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
91b663f57316e5d21f13386e193c34792608dc8f
29,467
cpp
C++
src/SyntaxTree.cpp
gitmodimo/cppgraphqlgen
bee89894653ad12f574f941d27c156354b1d497c
[ "MIT" ]
52
2018-08-12T15:36:12.000Z
2019-05-04T09:22:34.000Z
src/SyntaxTree.cpp
gitmodimo/cppgraphqlgen
bee89894653ad12f574f941d27c156354b1d497c
[ "MIT" ]
30
2018-09-10T18:05:16.000Z
2019-05-02T00:43:01.000Z
src/SyntaxTree.cpp
gitmodimo/cppgraphqlgen
bee89894653ad12f574f941d27c156354b1d497c
[ "MIT" ]
13
2018-08-20T03:40:22.000Z
2019-04-19T08:15:46.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "graphqlservice/GraphQLParse.h" #include "graphqlservice/internal/Grammar.h" #include "graphqlservice/internal/SyntaxTree.h" #include <tao/pegtl/contrib/unescape.hpp> #include <functional> #include <iterator> #include <memory> #include <numeric> #include <optional> #include <sstream> #include <utility> using namespace std::literals; namespace graphql { namespace peg { void ast_node::unescaped_view(std::string_view unescaped) noexcept { _unescaped = std::make_unique<unescaped_t>(unescaped); } std::string_view ast_node::unescaped_view() const { if (!_unescaped) { if (is_type<block_quote_content_lines>()) { // Trim leading and trailing empty lines const auto isNonEmptyLine = [](const std::unique_ptr<ast_node>& child) noexcept { return child->is_type<block_quote_line>(); }; const auto itrEndRev = std::make_reverse_iterator( std::find_if(children.cbegin(), children.cend(), isNonEmptyLine)); const auto itrRev = std::find_if(children.crbegin(), itrEndRev, isNonEmptyLine); std::vector<std::optional<std::pair<std::string_view, std::string_view>>> lines( std::distance(itrRev, itrEndRev)); std::transform(itrRev, itrEndRev, lines.rbegin(), [](const std::unique_ptr<ast_node>& child) noexcept { return (child->is_type<block_quote_line>() && !child->children.empty() && child->children.front()->is_type<block_quote_empty_line>() && child->children.back()->is_type<block_quote_line_content>()) ? std::make_optional(std::make_pair(child->children.front()->string_view(), child->children.back()->unescaped_view())) : std::nullopt; }); // Calculate the common indent const auto commonIndent = std::accumulate(lines.cbegin(), lines.cend(), std::optional<size_t> {}, [](auto value, const auto& line) noexcept { if (line) { const auto indent = line->first.size(); if (!value || indent < *value) { value = indent; } } return value; }); const auto trimIndent = commonIndent ? *commonIndent : 0; std::string joined; if (!lines.empty()) { joined.reserve(std::accumulate(lines.cbegin(), lines.cend(), size_t {}, [trimIndent](auto value, const auto& line) noexcept { if (line) { value += line->first.size() - trimIndent; value += line->second.size(); } return value; }) + lines.size() - 1); bool firstLine = true; for (const auto& line : lines) { if (!firstLine) { joined.append(1, '\n'); } if (line) { joined.append(line->first.substr(trimIndent)); joined.append(line->second); } firstLine = false; } } _unescaped = std::make_unique<unescaped_t>(std::move(joined)); } else if (children.size() > 1) { std::string joined; joined.reserve(std::accumulate(children.cbegin(), children.cend(), size_t(0), [](size_t total, const std::unique_ptr<ast_node>& child) { return total + child->string_view().size(); })); for (const auto& child : children) { joined.append(child->string_view()); } _unescaped = std::make_unique<unescaped_t>(std::move(joined)); } else if (!children.empty()) { _unescaped = std::make_unique<unescaped_t>(children.front()->string_view()); } else if (has_content() && is_type<escaped_unicode>()) { const auto content = string_view(); memory_input<> in(content.data(), content.size(), "escaped unicode"); std::string utf8; utf8.reserve((content.size() + 1) / 2); unescape::unescape_j::apply(in, utf8); _unescaped = std::make_unique<unescaped_t>(std::move(utf8)); } else { _unescaped = std::make_unique<unescaped_t>(std::string_view {}); } } return std::visit( [](const auto& value) noexcept { return std::string_view { value }; }, *_unescaped); } void ast_node::remove_content() noexcept { basic_node_t::remove_content(); _unescaped.reset(); } using namespace tao::graphqlpeg; template <typename Rule> struct ast_selector : std::false_type { }; template <> struct ast_selector<operation_type> : std::true_type { }; template <> struct ast_selector<list_value> : std::true_type { }; template <> struct ast_selector<object_field_name> : std::true_type { }; template <> struct ast_selector<object_field> : std::true_type { }; template <> struct ast_selector<object_value> : std::true_type { }; template <> struct ast_selector<variable_value> : std::true_type { }; template <> struct ast_selector<integer_value> : std::true_type { }; template <> struct ast_selector<float_value> : std::true_type { }; template <> struct ast_selector<escaped_unicode> : std::true_type { }; template <> struct ast_selector<escaped_char> : std::true_type { static void transform(std::unique_ptr<ast_node>& n) { if (n->has_content()) { const char ch = n->string_view().front(); switch (ch) { case '"': n->unescaped_view("\""sv); return; case '\\': n->unescaped_view("\\"sv); return; case '/': n->unescaped_view("/"sv); return; case 'b': n->unescaped_view("\b"sv); return; case 'f': n->unescaped_view("\f"sv); return; case 'n': n->unescaped_view("\n"sv); return; case 'r': n->unescaped_view("\r"sv); return; case 't': n->unescaped_view("\t"sv); return; default: break; } } throw parse_error("invalid escaped character sequence", n->begin()); } }; template <> struct ast_selector<string_quote_character> : std::true_type { static void transform(std::unique_ptr<ast_node>& n) { n->unescaped_view(n->string_view()); } }; template <> struct ast_selector<block_escape_sequence> : std::true_type { static void transform(std::unique_ptr<ast_node>& n) { n->unescaped_view(R"bq(""")bq"sv); } }; template <> struct ast_selector<block_quote_content_lines> : std::true_type { }; template <> struct ast_selector<block_quote_empty_line> : std::true_type { }; template <> struct ast_selector<block_quote_line> : std::true_type { }; template <> struct ast_selector<block_quote_line_content> : std::true_type { }; template <> struct ast_selector<block_quote_character> : std::true_type { static void transform(std::unique_ptr<ast_node>& n) { n->unescaped_view(n->string_view()); } }; template <> struct ast_selector<string_value> : std::true_type { }; template <> struct ast_selector<true_keyword> : std::true_type { }; template <> struct ast_selector<false_keyword> : std::true_type { }; template <> struct ast_selector<null_keyword> : std::true_type { }; template <> struct ast_selector<enum_value> : std::true_type { }; template <> struct ast_selector<field_name> : std::true_type { }; template <> struct ast_selector<argument_name> : std::true_type { }; template <> struct ast_selector<argument> : std::true_type { }; template <> struct ast_selector<arguments> : std::true_type { }; template <> struct ast_selector<directive_name> : std::true_type { }; template <> struct ast_selector<directive> : std::true_type { }; template <> struct ast_selector<directives> : std::true_type { }; template <> struct ast_selector<variable> : std::true_type { }; template <> struct ast_selector<scalar_name> : std::true_type { }; template <> struct ast_selector<named_type> : std::true_type { }; template <> struct ast_selector<list_type> : std::true_type { }; template <> struct ast_selector<nonnull_type> : std::true_type { }; template <> struct ast_selector<default_value> : std::true_type { }; template <> struct ast_selector<operation_definition> : std::true_type { }; template <> struct ast_selector<fragment_definition> : std::true_type { }; template <> struct ast_selector<schema_definition> : std::true_type { }; template <> struct ast_selector<scalar_type_definition> : std::true_type { }; template <> struct ast_selector<object_type_definition> : std::true_type { }; template <> struct ast_selector<interface_type_definition> : std::true_type { }; template <> struct ast_selector<union_type_definition> : std::true_type { }; template <> struct ast_selector<enum_type_definition> : std::true_type { }; template <> struct ast_selector<input_object_type_definition> : std::true_type { }; template <> struct ast_selector<directive_definition> : std::true_type { }; template <> struct ast_selector<schema_extension> : std::true_type { }; template <> struct ast_selector<scalar_type_extension> : std::true_type { }; template <> struct ast_selector<object_type_extension> : std::true_type { }; template <> struct ast_selector<interface_type_extension> : std::true_type { }; template <> struct ast_selector<union_type_extension> : std::true_type { }; template <> struct ast_selector<enum_type_extension> : std::true_type { }; template <> struct ast_selector<input_object_type_extension> : std::true_type { }; template <typename Rule> struct schema_selector : ast_selector<Rule> { }; template <> struct schema_selector<description> : std::true_type { }; template <> struct schema_selector<object_name> : std::true_type { }; template <> struct schema_selector<interface_name> : std::true_type { }; template <> struct schema_selector<union_name> : std::true_type { }; template <> struct schema_selector<enum_name> : std::true_type { }; template <> struct schema_selector<root_operation_definition> : std::true_type { }; template <> struct schema_selector<interface_type> : std::true_type { }; template <> struct schema_selector<input_field_definition> : std::true_type { }; template <> struct schema_selector<input_fields_definition> : std::true_type { }; template <> struct schema_selector<arguments_definition> : std::true_type { }; template <> struct schema_selector<field_definition> : std::true_type { }; template <> struct schema_selector<fields_definition> : std::true_type { }; template <> struct schema_selector<union_type> : std::true_type { }; template <> struct schema_selector<enum_value_definition> : std::true_type { }; template <> struct schema_selector<repeatable_keyword> : std::true_type { }; template <> struct schema_selector<directive_location> : std::true_type { }; template <> struct schema_selector<operation_type_definition> : std::true_type { }; template <typename Rule> struct executable_selector : ast_selector<Rule> { }; template <> struct executable_selector<variable_name> : std::true_type { }; template <> struct executable_selector<alias_name> : std::true_type { }; template <> struct executable_selector<alias> : parse_tree::fold_one { }; template <> struct executable_selector<operation_name> : std::true_type { }; template <> struct executable_selector<fragment_name> : std::true_type { }; template <> struct executable_selector<field> : std::true_type { }; template <> struct executable_selector<fragment_spread> : std::true_type { }; template <> struct executable_selector<inline_fragment> : std::true_type { }; template <> struct executable_selector<selection_set> : std::true_type { }; template <> struct executable_selector<type_condition> : std::true_type { }; template <typename Rule> struct ast_action : nothing<Rule> { }; struct [[nodiscard]] depth_guard { explicit depth_guard(size_t& depth) noexcept : _depth(depth) { ++_depth; } ~depth_guard() { --_depth; } depth_guard(depth_guard&&) noexcept = delete; depth_guard(const depth_guard&) = delete; depth_guard& operator=(depth_guard&&) noexcept = delete; depth_guard& operator=(const depth_guard&) = delete; private: size_t& _depth; }; template <> struct ast_action<selection_set> : maybe_nothing { template <typename Rule, apply_mode A, rewind_mode M, template <typename...> class Action, template <typename...> class Control, typename ParseInput, typename... States> [[nodiscard]] static bool match(ParseInput& in, States&&... st) { depth_guard guard(in.selectionSetDepth); if (in.selectionSetDepth > in.depthLimit()) { std::ostringstream oss; oss << "Exceeded nested depth limit: " << in.depthLimit() << " for https://spec.graphql.org/October2021/#SelectionSet"; throw parse_error(oss.str(), in); } return tao::graphqlpeg::template match<Rule, A, M, Action, Control>(in, st...); } }; template <typename Rule> struct ast_control : normal<Rule> { static const char* error_message; template <typename Input, typename... State> [[noreturn]] static void raise(const Input& in, State&&...) { throw parse_error(error_message, in); } }; template <> const char* ast_control<one<'}'>>::error_message = "Expected }"; template <> const char* ast_control<one<']'>>::error_message = "Expected ]"; template <> const char* ast_control<one<')'>>::error_message = "Expected )"; template <> const char* ast_control<quote_token>::error_message = "Expected \""; template <> const char* ast_control<block_quote_token>::error_message = "Expected \"\"\""; template <> const char* ast_control<variable_name_content>::error_message = "Expected https://spec.graphql.org/October2021/#Variable"; template <> const char* ast_control<escaped_unicode_content>::error_message = "Expected https://spec.graphql.org/October2021/#EscapedUnicode"; template <> const char* ast_control<string_escape_sequence_content>::error_message = "Expected https://spec.graphql.org/October2021/#EscapedCharacter"; template <> const char* ast_control<string_quote_content>::error_message = "Expected https://spec.graphql.org/October2021/#StringCharacter"; template <> const char* ast_control<block_quote_content>::error_message = "Expected https://spec.graphql.org/October2021/#BlockStringCharacter"; template <> const char* ast_control<fractional_part_content>::error_message = "Expected https://spec.graphql.org/October2021/#FractionalPart"; template <> const char* ast_control<exponent_part_content>::error_message = "Expected https://spec.graphql.org/October2021/#ExponentPart"; template <> const char* ast_control<argument_content>::error_message = "Expected https://spec.graphql.org/October2021/#Argument"; template <> const char* ast_control<arguments_content>::error_message = "Expected https://spec.graphql.org/October2021/#Arguments"; template <> const char* ast_control<list_value_content>::error_message = "Expected https://spec.graphql.org/October2021/#ListValue"; template <> const char* ast_control<object_field_content>::error_message = "Expected https://spec.graphql.org/October2021/#ObjectField"; template <> const char* ast_control<object_value_content>::error_message = "Expected https://spec.graphql.org/October2021/#ObjectValue"; template <> const char* ast_control<input_value_content>::error_message = "Expected https://spec.graphql.org/October2021/#Value"; template <> const char* ast_control<default_value_content>::error_message = "Expected https://spec.graphql.org/October2021/#DefaultValue"; template <> const char* ast_control<list_type_content>::error_message = "Expected https://spec.graphql.org/October2021/#ListType"; template <> const char* ast_control<type_name_content>::error_message = "Expected https://spec.graphql.org/October2021/#Type"; template <> const char* ast_control<variable_content>::error_message = "Expected https://spec.graphql.org/October2021/#VariableDefinition"; template <> const char* ast_control<variable_definitions_content>::error_message = "Expected https://spec.graphql.org/October2021/#VariableDefinitions"; template <> const char* ast_control<directive_content>::error_message = "Expected https://spec.graphql.org/October2021/#Directive"; template <> const char* ast_control<field_content>::error_message = "Expected https://spec.graphql.org/October2021/#Field"; template <> const char* ast_control<type_condition_content>::error_message = "Expected https://spec.graphql.org/October2021/#TypeCondition"; template <> const char* ast_control<fragement_spread_or_inline_fragment_content>::error_message = "Expected https://spec.graphql.org/October2021/#FragmentSpread or " "https://spec.graphql.org/October2021/#InlineFragment"; template <> const char* ast_control<selection_set_content>::error_message = "Expected https://spec.graphql.org/October2021/#SelectionSet"; template <> const char* ast_control<operation_definition_operation_type_content>::error_message = "Expected https://spec.graphql.org/October2021/#OperationDefinition"; template <> const char* ast_control<fragment_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#FragmentDefinition"; template <> const char* ast_control<root_operation_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#RootOperationTypeDefinition"; template <> const char* ast_control<schema_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#SchemaDefinition"; template <> const char* ast_control<scalar_type_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#ScalarTypeDefinition"; template <> const char* ast_control<arguments_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#ArgumentsDefinition"; template <> const char* ast_control<field_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#FieldDefinition"; template <> const char* ast_control<fields_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#FieldsDefinition"; template <> const char* ast_control<implements_interfaces_content>::error_message = "Expected https://spec.graphql.org/October2021/#ImplementsInterfaces"; template <> const char* ast_control<object_type_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#ObjectTypeDefinition"; template <> const char* ast_control<interface_type_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#InterfaceTypeDefinition"; template <> const char* ast_control<union_member_types_content>::error_message = "Expected https://spec.graphql.org/October2021/#UnionMemberTypes"; template <> const char* ast_control<union_type_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#UnionTypeDefinition"; template <> const char* ast_control<enum_value_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#EnumValueDefinition"; template <> const char* ast_control<enum_values_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#EnumValuesDefinition"; template <> const char* ast_control<enum_type_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#EnumTypeDefinition"; template <> const char* ast_control<input_field_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#InputValueDefinition"; template <> const char* ast_control<input_fields_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#InputFieldsDefinition"; template <> const char* ast_control<input_object_type_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#InputObjectTypeDefinition"; template <> const char* ast_control<directive_definition_content>::error_message = "Expected https://spec.graphql.org/October2021/#DirectiveDefinition"; template <> const char* ast_control<schema_extension_content>::error_message = "Expected https://spec.graphql.org/October2021/#SchemaExtension"; template <> const char* ast_control<scalar_type_extension_content>::error_message = "Expected https://spec.graphql.org/October2021/#ScalarTypeExtension"; template <> const char* ast_control<object_type_extension_content>::error_message = "Expected https://spec.graphql.org/October2021/#ObjectTypeExtension"; template <> const char* ast_control<interface_type_extension_content>::error_message = "Expected https://spec.graphql.org/October2021/#InterfaceTypeExtension"; template <> const char* ast_control<union_type_extension_content>::error_message = "Expected https://spec.graphql.org/October2021/#UnionTypeExtension"; template <> const char* ast_control<enum_type_extension_content>::error_message = "Expected https://spec.graphql.org/October2021/#EnumTypeExtension"; template <> const char* ast_control<input_object_type_extension_content>::error_message = "Expected https://spec.graphql.org/October2021/#InputObjectTypeExtension"; template <> const char* ast_control<mixed_document_content>::error_message = "Expected https://spec.graphql.org/October2021/#Document"; template <> const char* ast_control<executable_document_content>::error_message = "Expected executable https://spec.graphql.org/October2021/#Document"; template <> const char* ast_control<schema_document_content>::error_message = "Expected schema type https://spec.graphql.org/October2021/#Document"; namespace graphql_parse_tree { namespace internal { using ast_state = parse_tree::internal::state<ast_node>; template <template <typename...> class Selector> struct make_control { template <typename Rule, bool, bool> struct state_handler; template <typename Rule> using type = state_handler<Rule, parse_tree::internal::is_selected_node<Rule, Selector>, parse_tree::internal::is_leaf<8, typename Rule::subs_t, Selector>>; }; template <template <typename...> class Selector> template <typename Rule> struct make_control<Selector>::state_handler<Rule, false, true> : ast_control<Rule> { }; template <template <typename...> class Selector> template <typename Rule> struct make_control<Selector>::state_handler<Rule, false, false> : ast_control<Rule> { static constexpr bool enable = true; template <typename ParseInput> static void start(const ParseInput& /*unused*/, ast_state& state) { state.emplace_back(); } template <typename ParseInput> static void success(const ParseInput& /*unused*/, ast_state& state) { auto n = std::move(state.back()); state.pop_back(); for (auto& c : n->children) { state.back()->children.emplace_back(std::move(c)); } } template <typename ParseInput> static void failure(const ParseInput& /*unused*/, ast_state& state) { state.pop_back(); } }; template <template <typename...> class Selector> template <typename Rule, bool B> struct make_control<Selector>::state_handler<Rule, true, B> : ast_control<Rule> { template <typename ParseInput> static void start(const ParseInput& in, ast_state& state) { state.emplace_back(); state.back()->template start<Rule>(in); } template <typename ParseInput> static void success(const ParseInput& in, ast_state& state) { auto n = std::move(state.back()); state.pop_back(); n->template success<Rule>(in); parse_tree::internal::transform<Selector<Rule>>(in, n); if (n) { state.back()->children.emplace_back(std::move(n)); } } template <typename ParseInput> static void failure(const ParseInput& /*unused*/, ast_state& state) { state.pop_back(); } }; } // namespace internal template <typename Rule, template <typename...> class Action, template <typename...> class Selector, typename ParseInput> [[nodiscard]] std::unique_ptr<ast_node> parse(ParseInput&& in) { internal::ast_state state; if (!tao::graphqlpeg::parse<Rule, Action, internal::make_control<Selector>::template type>( std::forward<ParseInput>(in), state)) { return nullptr; } if (state.stack.size() != 1) { throw std::logic_error("Unexpected error parsing GraphQL"); } return std::move(state.back()); } } // namespace graphql_parse_tree template <class ParseInput> class [[nodiscard]] depth_limit_input : public ParseInput { public: template <typename... Args> explicit depth_limit_input(size_t depthLimit, Args&&... args) noexcept : ParseInput(std::forward<Args>(args)...) , _depthLimit(depthLimit) { } size_t depthLimit() const noexcept { return _depthLimit; } size_t selectionSetDepth = 0; private: const size_t _depthLimit; }; using ast_file = depth_limit_input<file_input<>>; using ast_memory = depth_limit_input<memory_input<>>; struct [[nodiscard]] ast_string { std::vector<char> input; std::unique_ptr<ast_memory> memory {}; }; struct [[nodiscard]] ast_string_view { std::string_view input; std::unique_ptr<memory_input<>> memory {}; }; struct [[nodiscard]] ast_input { std::variant<ast_string, std::unique_ptr<ast_file>, ast_string_view> data; }; ast parseSchemaString(std::string_view input, size_t depthLimit) { ast result { std::make_shared<ast_input>( ast_input { ast_string { { input.cbegin(), input.cend() } } }), {} }; auto& data = std::get<ast_string>(result.input->data); try { // Try a smaller grammar with only schema type definitions first. data.memory = std::make_unique<ast_memory>(depthLimit, data.input.data(), data.input.size(), "GraphQL"s); result.root = graphql_parse_tree::parse<schema_document, ast_action, schema_selector>(*data.memory); } catch (const peg::parse_error&) { // Try again with the full document grammar so validation can handle the unexepected // executable definitions if this is a mixed document. data.memory = std::make_unique<ast_memory>(depthLimit, data.input.data(), data.input.size(), "GraphQL"s); result.root = graphql_parse_tree::parse<mixed_document, ast_action, schema_selector>(*data.memory); } return result; } ast parseSchemaFile(std::string_view filename, size_t depthLimit) { ast result; try { result.input = std::make_shared<ast_input>( ast_input { std::make_unique<ast_file>(depthLimit, filename) }); auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data); // Try a smaller grammar with only schema type definitions first. result.root = graphql_parse_tree::parse<schema_document, ast_action, schema_selector>(std::move(in)); } catch (const peg::parse_error&) { result.input = std::make_shared<ast_input>( ast_input { std::make_unique<ast_file>(depthLimit, filename) }); auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data); // Try again with the full document grammar so validation can handle the unexepected // executable definitions if this is a mixed document. result.root = graphql_parse_tree::parse<mixed_document, ast_action, schema_selector>(std::move(in)); } return result; } ast parseString(std::string_view input, size_t depthLimit) { ast result { std::make_shared<ast_input>( ast_input { ast_string { { input.cbegin(), input.cend() } } }), {} }; auto& data = std::get<ast_string>(result.input->data); try { // Try a smaller grammar with only executable definitions first. data.memory = std::make_unique<ast_memory>(depthLimit, data.input.data(), data.input.size(), "GraphQL"s); result.root = graphql_parse_tree::parse<executable_document, ast_action, executable_selector>( *data.memory); } catch (const peg::parse_error&) { // Try again with the full document grammar so validation can handle the unexepected type // definitions if this is a mixed document. data.memory = std::make_unique<ast_memory>(depthLimit, data.input.data(), data.input.size(), "GraphQL"s); result.root = graphql_parse_tree::parse<mixed_document, ast_action, executable_selector>( *data.memory); } return result; } ast parseFile(std::string_view filename, size_t depthLimit) { ast result; try { result.input = std::make_shared<ast_input>( ast_input { std::make_unique<ast_file>(depthLimit, filename) }); auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data); // Try a smaller grammar with only executable definitions first. result.root = graphql_parse_tree::parse<executable_document, ast_action, executable_selector>( std::move(in)); } catch (const peg::parse_error&) { result.input = std::make_shared<ast_input>( ast_input { std::make_unique<ast_file>(depthLimit, filename) }); auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data); // Try again with the full document grammar so validation can handle the unexepected type // definitions if this is a mixed document. result.root = graphql_parse_tree::parse<mixed_document, ast_action, executable_selector>( std::move(in)); } return result; } } // namespace peg peg::ast operator"" _graphql(const char* text, size_t size) { peg::ast result { std::make_shared<peg::ast_input>( peg::ast_input { peg::ast_string_view { { text, size } } }), {} }; auto& data = std::get<peg::ast_string_view>(result.input->data); try { // Try a smaller grammar with only executable definitions first. data.memory = std::make_unique<peg::memory_input<>>(data.input.data(), data.input.size(), "GraphQL"s); result.root = peg::graphql_parse_tree:: parse<peg::executable_document, peg::nothing, peg::executable_selector>(*data.memory); } catch (const peg::parse_error&) { // Try again with the full document grammar so validation can handle the unexepected type // definitions if this is a mixed document. data.memory = std::make_unique<peg::memory_input<>>(data.input.data(), data.input.size(), "GraphQL"s); result.root = peg::graphql_parse_tree:: parse<peg::mixed_document, peg::nothing, peg::executable_selector>(*data.memory); } return result; } } // namespace graphql
24.972034
100
0.729562
gitmodimo
91b92c801076aba030ae894cf64d8893ade60bd2
467
cpp
C++
Level2_PointersPassByConstructDestructScopeRes/ConstructnDestruct.cpp
Arunken/DevCPP
93f4e52284c8a4ce5d00acbe292002692eadfb39
[ "Apache-2.0" ]
null
null
null
Level2_PointersPassByConstructDestructScopeRes/ConstructnDestruct.cpp
Arunken/DevCPP
93f4e52284c8a4ce5d00acbe292002692eadfb39
[ "Apache-2.0" ]
null
null
null
Level2_PointersPassByConstructDestructScopeRes/ConstructnDestruct.cpp
Arunken/DevCPP
93f4e52284c8a4ce5d00acbe292002692eadfb39
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; class ConstructnDestruct { //public : //int a,b; //ConstructnDestruct *addr; public : ConstructnDestruct() { cout<<"Constructor invoked!!! "<<endl; } ~ConstructnDestruct() { cout<<"Destructor invoked"<<endl; } }; //ConstructnDestruct obj1; main() { cout<< "Inside the main method"<<endl; { ConstructnDestruct obj2; cout<<"here"<<endl; } cout<<"Last line of main method"<<endl; }
12.972222
41
0.633833
Arunken
91ba50090a5a6c176dc44310a9f402e000cf0fc5
2,777
cpp
C++
src/AglTextureUbyte.cpp
philiphubbard/Agl
7ee5c6911d4cf2199f1ebf56f28d01d3e051e789
[ "MIT" ]
1
2016-04-09T00:41:41.000Z
2016-04-09T00:41:41.000Z
src/AglTextureUbyte.cpp
philiphubbard/Agl
7ee5c6911d4cf2199f1ebf56f28d01d3e051e789
[ "MIT" ]
null
null
null
src/AglTextureUbyte.cpp
philiphubbard/Agl
7ee5c6911d4cf2199f1ebf56f28d01d3e051e789
[ "MIT" ]
null
null
null
// Copyright (c) 2013 Philip M. Hubbard // // 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. // // http://opensource.org/licenses/MIT // // AglTextureUbyte.cpp // #include "AglTextureUbyte.h" namespace Agl { class TextureUbyte::Imp { public: Imp() : width(0), height(0) {} GLsizei width; GLsizei height; }; TextureUbyte::TextureUbyte(GLenum target) : Texture(target), _m(new Imp) { } TextureUbyte::~TextureUbyte() { } void TextureUbyte::setData(GLubyte* data, GLsizei width, GLsizei height, GLint internalFormat, GLenum format, GLint rowLength, GLint skipPixels, GLint skipRows) { _m->width = width; _m->height = height; glBindTexture(target(), id()); glPixelStorei(GL_UNPACK_ROW_LENGTH, rowLength); glPixelStorei(GL_UNPACK_SKIP_PIXELS, skipPixels); glPixelStorei(GL_UNPACK_SKIP_ROWS, skipRows); // TODO: Replace with glTexStorage2D() and glTexSubImage2D(), when // the former becomes available on OS X. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, data); // Make certain Texture::isBound() does not incorrectly return true for // another texture. unbind(); } GLsizei TextureUbyte::width() const { return _m->width; } GLsizei TextureUbyte::height() const { return _m->height; } }
30.855556
81
0.651062
philiphubbard
91bb15200a33975b5c004971acaccceed920bcfc
97,774
cpp
C++
src/currency_core/blockchain_storage.cpp
UScrypto/boolberry-opencl
1369c7a2cb012983a2fac7e78438bd9a7185e867
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/currency_core/blockchain_storage.cpp
UScrypto/boolberry-opencl
1369c7a2cb012983a2fac7e78438bd9a7185e867
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/currency_core/blockchain_storage.cpp
UScrypto/boolberry-opencl
1369c7a2cb012983a2fac7e78438bd9a7185e867
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
// Copyright (c) 2012-2013 The Cryptonote developers // Copyright (c) 2012-2013 The Boolberry developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <algorithm> #include <cstdio> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include "include_base_utils.h" #include "currency_basic_impl.h" #include "blockchain_storage.h" #include "currency_format_utils.h" #include "currency_boost_serialization.h" #include "blockchain_storage_boost_serialization.h" #include "currency_config.h" #include "miner.h" #include "misc_language.h" #include "profile_tools.h" #include "file_io_utils.h" #include "common/boost_serialization_helper.h" #include "warnings.h" #include "crypto/hash.h" #include "miner_common.h" using namespace std; using namespace epee; using namespace currency; DISABLE_VS_WARNINGS(4267) //------------------------------------------------------------------ blockchain_storage::blockchain_storage(tx_memory_pool& tx_pool):m_tx_pool(tx_pool), m_current_block_cumul_sz_limit(0), m_is_in_checkpoint_zone(false), m_donations_account(AUTO_VAL_INIT(m_donations_account)), m_royalty_account(AUTO_VAL_INIT(m_royalty_account)), m_is_blockchain_storing(false), m_current_pruned_rs_height(0) { bool r = get_donation_accounts(m_donations_account, m_royalty_account); CHECK_AND_ASSERT_THROW_MES(r, "failed to load donation accounts"); } //------------------------------------------------------------------ bool blockchain_storage::have_tx(const crypto::hash &id) { CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_transactions.find(id) != m_transactions.end(); } //------------------------------------------------------------------ bool blockchain_storage::have_tx_keyimg_as_spent(const crypto::key_image &key_im) { CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_spent_keys.find(key_im) != m_spent_keys.end(); } //------------------------------------------------------------------ transaction *blockchain_storage::get_tx(const crypto::hash &id) { CRITICAL_REGION_LOCAL(m_blockchain_lock); auto it = m_transactions.find(id); if (it == m_transactions.end()) return NULL; return &it->second.tx; } //------------------------------------------------------------------ uint64_t blockchain_storage::get_current_blockchain_height() { CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_blocks.size(); } //------------------------------------------------------------------ void blockchain_storage::fill_addr_to_alias_dict() { for (const auto& a : m_aliases) { if (a.second.size()) { m_addr_to_alias[a.second.back().m_address] = a.first; } } } //------------------------------------------------------------------ bool blockchain_storage::init(const std::string& config_folder) { CRITICAL_REGION_LOCAL(m_blockchain_lock); m_config_folder = config_folder; LOG_PRINT_L0("Loading blockchain..."); const std::string filename = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_FILENAME; if(!tools::unserialize_obj_from_file(*this, filename)) { LOG_PRINT_L0("Can't load blockchain storage from file, generating genesis block."); block bl = boost::value_initialized<block>(); block_verification_context bvc = boost::value_initialized<block_verification_context>(); generate_genesis_block(bl); add_new_block(bl, bvc); CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed && bvc.m_added_to_main_chain, false, "Failed to add genesis block to blockchain"); } if(!m_blocks.size()) { LOG_PRINT_L0("Blockchain not loaded, generating genesis block."); block bl = boost::value_initialized<block>(); block_verification_context bvc = boost::value_initialized<block_verification_context>(); generate_genesis_block(bl); add_new_block(bl, bvc); CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "Failed to add genesis block to blockchain"); } uint64_t timestamp_diff = time(NULL) - m_blocks.back().bl.timestamp; if(!m_blocks.back().bl.timestamp) timestamp_diff = time(NULL) - 1341378000; fill_addr_to_alias_dict(); LOG_PRINT_GREEN("Blockchain initialized. last block: " << m_blocks.size()-1 << ", " << misc_utils::get_time_interval_string(timestamp_diff) << " time ago, current difficulty: " << get_difficulty_for_next_block(), LOG_LEVEL_0); return true; } //------------------------------------------------------------------ bool blockchain_storage::store_blockchain() { m_is_blockchain_storing = true; misc_utils::auto_scope_leave_caller scope_exit_handler = misc_utils::create_scope_leave_handler([&](){m_is_blockchain_storing=false;}); LOG_PRINT_L0("Storing blockchain..."); if (!tools::create_directories_if_necessary(m_config_folder)) { LOG_PRINT_L0("Failed to create data directory: " << m_config_folder); return false; } const std::string temp_filename = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_TEMP_FILENAME; // There is a chance that temp_filename and filename are hardlinks to the same file std::remove(temp_filename.c_str()); if(!tools::serialize_obj_to_file(*this, temp_filename)) { //achtung! LOG_ERROR("Failed to save blockchain data to file: " << temp_filename); return false; } const std::string filename = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_FILENAME; std::error_code ec = tools::replace_file(temp_filename, filename); if (ec) { LOG_ERROR("Failed to rename blockchain data file " << temp_filename << " to " << filename << ": " << ec.message() << ':' << ec.value()); return false; } LOG_PRINT_L0("Blockchain stored OK."); return true; } //------------------------------------------------------------------ bool blockchain_storage::deinit() { return store_blockchain(); } //------------------------------------------------------------------ bool blockchain_storage::pop_block_from_blockchain() { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(m_blocks.size() > 1, false, "pop_block_from_blockchain: can't pop from blockchain with size = " << m_blocks.size()); size_t h = m_blocks.size()-1; block_extended_info& bei = m_blocks[h]; pop_block_scratchpad_data(bei.bl, m_scratchpad); //crypto::hash id = get_block_hash(bei.bl); bool r = purge_block_data_from_blockchain(bei.bl, bei.bl.tx_hashes.size()); CHECK_AND_ASSERT_MES(r, false, "Failed to purge_block_data_from_blockchain for block " << get_block_hash(bei.bl) << " on height " << h); //remove from index auto bl_ind = m_blocks_index.find(get_block_hash(bei.bl)); CHECK_AND_ASSERT_MES(bl_ind != m_blocks_index.end(), false, "pop_block_from_blockchain: blockchain id not found in index"); m_blocks_index.erase(bl_ind); //pop block from core m_blocks.pop_back(); m_tx_pool.on_blockchain_dec(m_blocks.size()-1, get_top_block_id()); return true; } //------------------------------------------------------------------ void blockchain_storage::set_checkpoints(checkpoints&& chk_pts) { m_checkpoints = chk_pts; prune_ring_signatures_if_need(); } //------------------------------------------------------------------ bool blockchain_storage::prune_ring_signatures(uint64_t height, uint64_t& transactions_pruned, uint64_t& signatures_pruned) { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(height < m_blocks.size(), false, "prune_ring_signatures called with wrong parametr " << height << ", m_blocks.size() " << m_blocks.size()); for(const auto& h: m_blocks[height].bl.tx_hashes) { auto it = m_transactions.find(h); CHECK_AND_ASSERT_MES(it != m_transactions.end(), false, "failed to find transaction " << h << " in blockchain index, in block on height = " << height); CHECK_AND_ASSERT_MES(it->second.m_keeper_block_height == height, false, "failed to validate extra check, it->second.m_keeper_block_height = " << it->second.m_keeper_block_height << "is mot equal to height = " << height << " in blockchain index, for block on height = " << height); signatures_pruned += it->second.tx.signatures.size(); it->second.tx.signatures.clear(); ++transactions_pruned; } return true; } //------------------------------------------------------------------ bool blockchain_storage::prune_ring_signatures_if_need() { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(m_blocks.size() && m_checkpoints.get_top_checkpoint_height() && m_checkpoints.get_top_checkpoint_height() > m_current_pruned_rs_height) { LOG_PRINT_CYAN("Starting pruning ring signatues...", LOG_LEVEL_0); uint64_t tx_count = 0, sig_count = 0; for(uint64_t height = m_current_pruned_rs_height; height < m_blocks.size() && height <= m_checkpoints.get_top_checkpoint_height(); height++) { bool res = prune_ring_signatures(height, tx_count, sig_count); CHECK_AND_ASSERT_MES(res, false, "filed to prune_ring_signatures for height = " << height); } m_current_pruned_rs_height = m_checkpoints.get_top_checkpoint_height(); LOG_PRINT_CYAN("Transaction pruning finished: " << sig_count << " signatures released in " << tx_count << " transactions.", LOG_LEVEL_0); } return true; } //------------------------------------------------------------------ bool blockchain_storage::reset_and_set_genesis_block(const block& b) { CRITICAL_REGION_LOCAL(m_blockchain_lock); m_transactions.clear(); m_spent_keys.clear(); m_blocks.clear(); m_blocks_index.clear(); m_alternative_chains.clear(); m_outputs.clear(); m_scratchpad.clear(); block_verification_context bvc = boost::value_initialized<block_verification_context>(); add_new_block(b, bvc); return bvc.m_added_to_main_chain && !bvc.m_verifivation_failed; } //------------------------------------------------------------------ //TODO: not the best way, add later update method instead of full copy bool blockchain_storage::copy_scratchpad(std::vector<crypto::hash>& scr) { CRITICAL_REGION_LOCAL(m_blockchain_lock); scr = m_scratchpad; return true; } //------------------------------------------------------------------ bool blockchain_storage::copy_scratchpad(std::string& dst) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if (m_scratchpad.size()) { dst.append(reinterpret_cast<const char*>(&m_scratchpad[0]), m_scratchpad.size() * 32); } return true; } //------------------------------------------------------------------ bool blockchain_storage::purge_transaction_keyimages_from_blockchain(const transaction& tx, bool strict_check) { CRITICAL_REGION_LOCAL(m_blockchain_lock); struct purge_transaction_visitor: public boost::static_visitor<bool> { blockchain_storage& m_bcs; key_images_container& m_spent_keys; bool m_strict_check; purge_transaction_visitor(blockchain_storage& bcs, key_images_container& spent_keys, bool strict_check): m_bcs(bcs), m_spent_keys(spent_keys), m_strict_check(strict_check){} bool operator()(const txin_to_key& inp) const { //const crypto::key_image& ki = inp.k_image; auto r = m_spent_keys.find(inp.k_image); if(r != m_spent_keys.end()) { m_spent_keys.erase(r); }else { CHECK_AND_ASSERT_MES(!m_strict_check, false, "purge_block_data_from_blockchain: key image in transaction not found"); } if(inp.key_offsets.size() == 1) { //direct spend detected if(!m_bcs.update_spent_tx_flags_for_input(inp.amount, inp.key_offsets[0], false)) { //internal error LOG_PRINT_L0("Failed to update_spent_tx_flags_for_input"); return false; } } return true; } bool operator()(const txin_gen& inp) const { return true; } bool operator()(const txin_to_script& tx) const { return false; } bool operator()(const txin_to_scripthash& tx) const { return false; } }; BOOST_FOREACH(const txin_v& in, tx.vin) { bool r = boost::apply_visitor(purge_transaction_visitor(*this, m_spent_keys, strict_check), in); CHECK_AND_ASSERT_MES(!strict_check || r, false, "failed to process purge_transaction_visitor"); } return true; } //------------------------------------------------------------------ bool blockchain_storage::purge_transaction_from_blockchain(const crypto::hash& tx_id) { CRITICAL_REGION_LOCAL(m_blockchain_lock); auto tx_index_it = m_transactions.find(tx_id); CHECK_AND_ASSERT_MES(tx_index_it != m_transactions.end(), false, "purge_block_data_from_blockchain: transaction not found in blockchain index!!"); transaction& tx = tx_index_it->second.tx; purge_transaction_keyimages_from_blockchain(tx, true); bool r = unprocess_blockchain_tx_extra(tx); CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra"); if(!is_coinbase(tx)) { currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc); bool r = m_tx_pool.add_tx(tx, tvc, true); CHECK_AND_ASSERT_MES(r, false, "purge_block_data_from_blockchain: failed to add transaction to transaction pool"); } bool res = pop_transaction_from_global_index(tx, tx_id); m_transactions.erase(tx_index_it); LOG_PRINT_L1("Removed transaction from blockchain history:" << tx_id << ENDL); return res; } //------------------------------------------------------------------ bool blockchain_storage::purge_block_data_from_blockchain(const block& bl, size_t processed_tx_count) { CRITICAL_REGION_LOCAL(m_blockchain_lock); bool res = true; CHECK_AND_ASSERT_MES(processed_tx_count <= bl.tx_hashes.size(), false, "wrong processed_tx_count in purge_block_data_from_blockchain"); for(size_t count = 0; count != processed_tx_count; count++) { res = purge_transaction_from_blockchain(bl.tx_hashes[(processed_tx_count -1)- count]) && res; } res = purge_transaction_from_blockchain(get_transaction_hash(bl.miner_tx)) && res; return res; } //------------------------------------------------------------------ crypto::hash blockchain_storage::get_top_block_id(uint64_t& height) { CRITICAL_REGION_LOCAL(m_blockchain_lock); height = get_current_blockchain_height()-1; return get_top_block_id(); } //------------------------------------------------------------------ crypto::hash blockchain_storage::get_top_block_id() { CRITICAL_REGION_LOCAL(m_blockchain_lock); crypto::hash id = null_hash; if(m_blocks.size()) { get_block_hash(m_blocks.back().bl, id); } return id; } //------------------------------------------------------------------ bool blockchain_storage::get_top_block(block& b) { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(m_blocks.size(), false, "Wrong blockchain state, m_blocks.size()=0!"); b = m_blocks.back().bl; return true; } //------------------------------------------------------------------ bool blockchain_storage::get_short_chain_history(std::list<crypto::hash>& ids) { CRITICAL_REGION_LOCAL(m_blockchain_lock); size_t i = 0; size_t current_multiplier = 1; size_t sz = m_blocks.size(); if(!sz) return true; size_t current_back_offset = 1; bool genesis_included = false; while(current_back_offset < sz) { ids.push_back(get_block_hash(m_blocks[sz-current_back_offset].bl)); if(sz-current_back_offset == 0) genesis_included = true; if(i < 10) { ++current_back_offset; }else { current_back_offset += current_multiplier *= 2; } ++i; } if(!genesis_included) ids.push_back(get_block_hash(m_blocks[0].bl)); return true; } //------------------------------------------------------------------ crypto::hash blockchain_storage::get_block_id_by_height(uint64_t height) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(height >= m_blocks.size()) return null_hash; return get_block_hash(m_blocks[height].bl); } //------------------------------------------------------------------ bool blockchain_storage::get_block_by_hash(const crypto::hash &h, block &blk) { CRITICAL_REGION_LOCAL(m_blockchain_lock); // try to find block in main chain blocks_by_id_index::const_iterator it = m_blocks_index.find(h); if (m_blocks_index.end() != it) { blk = m_blocks[it->second].bl; return true; } // try to find block in alternative chain blocks_ext_by_hash::const_iterator it_alt = m_alternative_chains.find(h); if (m_alternative_chains.end() != it_alt) { blk = it_alt->second.bl; return true; } return false; } //------------------------------------------------------------------ bool blockchain_storage::get_block_by_height(uint64_t h, block &blk) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(h >= m_blocks.size() ) return false; blk = m_blocks[h].bl; return true; } //------------------------------------------------------------------ void blockchain_storage::get_all_known_block_ids(std::list<crypto::hash> &main, std::list<crypto::hash> &alt, std::list<crypto::hash> &invalid) { CRITICAL_REGION_LOCAL(m_blockchain_lock); BOOST_FOREACH(blocks_by_id_index::value_type &v, m_blocks_index) main.push_back(v.first); BOOST_FOREACH(blocks_ext_by_hash::value_type &v, m_alternative_chains) alt.push_back(v.first); BOOST_FOREACH(blocks_ext_by_hash::value_type &v, m_invalid_blocks) invalid.push_back(v.first); } //------------------------------------------------------------------ wide_difficulty_type blockchain_storage::get_difficulty_for_next_block() { CRITICAL_REGION_LOCAL(m_blockchain_lock); std::vector<uint64_t> timestamps; std::vector<wide_difficulty_type> commulative_difficulties; size_t offset = m_blocks.size() - std::min(m_blocks.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT)); if(!offset) ++offset;//skip genesis block for(; offset < m_blocks.size(); offset++) { timestamps.push_back(m_blocks[offset].bl.timestamp); commulative_difficulties.push_back(m_blocks[offset].cumulative_difficulty); } return next_difficulty(timestamps, commulative_difficulties); } //------------------------------------------------------------------ bool blockchain_storage::rollback_blockchain_switching(std::list<block>& original_chain, size_t rollback_height) { CRITICAL_REGION_LOCAL(m_blockchain_lock); //remove failed subchain for(size_t i = m_blocks.size()-1; i >=rollback_height; i--) { bool r = pop_block_from_blockchain(); CHECK_AND_ASSERT_MES(r, false, "PANIC!!! failed to remove block while chain switching during the rollback!"); } //return back original chain BOOST_FOREACH(auto& bl, original_chain) { block_verification_context bvc = boost::value_initialized<block_verification_context>(); bool r = handle_block_to_main_chain(bl, bvc); CHECK_AND_ASSERT_MES(r && bvc.m_added_to_main_chain, false, "PANIC!!! failed to add (again) block while chain switching during the rollback!"); } LOG_PRINT_L0("Rollback success."); return true; } //------------------------------------------------------------------ bool blockchain_storage::switch_to_alternative_blockchain(std::list<blocks_ext_by_hash::iterator>& alt_chain) { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(alt_chain.size(), false, "switch_to_alternative_blockchain: empty chain passed"); size_t split_height = alt_chain.front()->second.height; CHECK_AND_ASSERT_MES(m_blocks.size() > split_height, false, "switch_to_alternative_blockchain: blockchain size is lower than split height"); //disconnecting old chain std::list<block> disconnected_chain; for(size_t i = m_blocks.size()-1; i >=split_height; i--) { block b = m_blocks[i].bl; bool r = pop_block_from_blockchain(); CHECK_AND_ASSERT_MES(r, false, "failed to remove block on chain switching"); disconnected_chain.push_front(b); } //connecting new alternative chain for(auto alt_ch_iter = alt_chain.begin(); alt_ch_iter != alt_chain.end(); alt_ch_iter++) { auto ch_ent = *alt_ch_iter; block_verification_context bvc = boost::value_initialized<block_verification_context>(); bool r = handle_block_to_main_chain(ch_ent->second.bl, bvc); if(!r || !bvc.m_added_to_main_chain) { LOG_PRINT_L0("Failed to switch to alternative blockchain"); rollback_blockchain_switching(disconnected_chain, split_height); add_block_as_invalid(ch_ent->second, get_block_hash(ch_ent->second.bl)); LOG_PRINT_L0("The block was inserted as invalid while connecting new alternative chain, block_id: " << get_block_hash(ch_ent->second.bl)); m_alternative_chains.erase(ch_ent); for(auto alt_ch_to_orph_iter = ++alt_ch_iter; alt_ch_to_orph_iter != alt_chain.end(); alt_ch_to_orph_iter++) { //block_verification_context bvc = boost::value_initialized<block_verification_context>(); add_block_as_invalid((*alt_ch_iter)->second, (*alt_ch_iter)->first); m_alternative_chains.erase(*alt_ch_to_orph_iter); } return false; } } //pushing old chain as alternative chain BOOST_FOREACH(auto& old_ch_ent, disconnected_chain) { block_verification_context bvc = boost::value_initialized<block_verification_context>(); bool r = handle_alternative_block(old_ch_ent, get_block_hash(old_ch_ent), bvc); if(!r) { LOG_ERROR("Failed to push ex-main chain blocks to alternative chain "); rollback_blockchain_switching(disconnected_chain, split_height); return false; } } //removing all_chain entries from alternative chain BOOST_FOREACH(auto ch_ent, alt_chain) { m_alternative_chains.erase(ch_ent); } LOG_PRINT_GREEN("REORGANIZE SUCCESS! on height: " << split_height << ", new blockchain size: " << m_blocks.size(), LOG_LEVEL_0); return true; } //------------------------------------------------------------------ wide_difficulty_type blockchain_storage::get_next_difficulty_for_alternative_chain(const std::list<blocks_ext_by_hash::iterator>& alt_chain, block_extended_info& bei) { std::vector<uint64_t> timestamps; std::vector<wide_difficulty_type> commulative_difficulties; if(alt_chain.size()< DIFFICULTY_BLOCKS_COUNT) { CRITICAL_REGION_LOCAL(m_blockchain_lock); size_t main_chain_stop_offset = alt_chain.size() ? alt_chain.front()->second.height : bei.height; size_t main_chain_count = DIFFICULTY_BLOCKS_COUNT - std::min(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT), alt_chain.size()); main_chain_count = std::min(main_chain_count, main_chain_stop_offset); size_t main_chain_start_offset = main_chain_stop_offset - main_chain_count; if(!main_chain_start_offset) ++main_chain_start_offset; //skip genesis block for(; main_chain_start_offset < main_chain_stop_offset; ++main_chain_start_offset) { timestamps.push_back(m_blocks[main_chain_start_offset].bl.timestamp); commulative_difficulties.push_back(m_blocks[main_chain_start_offset].cumulative_difficulty); } CHECK_AND_ASSERT_MES((alt_chain.size() + timestamps.size()) <= DIFFICULTY_BLOCKS_COUNT, false, "Internal error, alt_chain.size()["<< alt_chain.size() << "] + vtimestampsec.size()[" << timestamps.size() << "] NOT <= DIFFICULTY_WINDOW[]" << DIFFICULTY_BLOCKS_COUNT ); BOOST_FOREACH(auto it, alt_chain) { timestamps.push_back(it->second.bl.timestamp); commulative_difficulties.push_back(it->second.cumulative_difficulty); } }else { timestamps.resize(std::min(alt_chain.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT))); commulative_difficulties.resize(std::min(alt_chain.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT))); size_t count = 0; size_t max_i = timestamps.size()-1; BOOST_REVERSE_FOREACH(auto it, alt_chain) { timestamps[max_i - count] = it->second.bl.timestamp; commulative_difficulties[max_i - count] = it->second.cumulative_difficulty; count++; if(count >= DIFFICULTY_BLOCKS_COUNT) break; } } return next_difficulty(timestamps, commulative_difficulties); } //------------------------------------------------------------------ bool blockchain_storage::prevalidate_miner_transaction(const block& b, uint64_t height) { CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs"); CHECK_AND_ASSERT_MES(b.miner_tx.vin[0].type() == typeid(txin_gen), false, "coinbase transaction in the block has the wrong type"); if(boost::get<txin_gen>(b.miner_tx.vin[0]).height != height) { LOG_PRINT_RED_L0("The miner transaction in block has invalid height: " << boost::get<txin_gen>(b.miner_tx.vin[0]).height << ", expected: " << height); return false; } CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW, false, "coinbase transaction transaction have wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW); //check outs overflow if(!check_outs_overflow(b.miner_tx)) { LOG_PRINT_RED_L0("miner transaction have money overflow in block " << get_block_hash(b)); return false; } return true; } //------------------------------------------------------------------ bool blockchain_storage::lookfor_donation(const transaction& tx, uint64_t& donation, uint64_t& royalty) { crypto::public_key coin_base_tx_pub_key = null_pkey; bool r = parse_and_validate_tx_extra(tx, coin_base_tx_pub_key); CHECK_AND_ASSERT_MES(r, false, "Failed to validate coinbase extra"); if(tx.vout.size() >= 2) { //check donations value size_t i = tx.vout.size()-2; CHECK_AND_ASSERT_MES(tx.vout[i].target.type() == typeid(txout_to_key), false, "wrong type id in transaction out" ); if(is_out_to_acc(m_donations_account, boost::get<txout_to_key>(tx.vout[i].target), coin_base_tx_pub_key, i) ) { donation = tx.vout[i].amount; } } if(tx.vout.size() >= 1) { size_t i = tx.vout.size()-1; CHECK_AND_ASSERT_MES(tx.vout[i].target.type() == typeid(txout_to_key), false, "wrong type id in transaction out" ); if(donation) { //donations already found, check royalty if(is_out_to_acc(m_royalty_account, boost::get<txout_to_key>(tx.vout[i].target), coin_base_tx_pub_key, i) ) { royalty = tx.vout[i].amount; } }else { //only donations, without royalty if(is_out_to_acc(m_donations_account, boost::get<txout_to_key>(tx.vout[i].target), coin_base_tx_pub_key, i) ) { donation = tx.vout[i].amount; } } } return true; } //------------------------------------------------------------------ bool blockchain_storage::get_required_donations_value_for_next_block(uint64_t& don_am) { TRY_ENTRY(); CRITICAL_REGION_LOCAL(m_blockchain_lock); uint64_t sz = get_current_blockchain_height(); if(sz < CURRENCY_DONATIONS_INTERVAL || sz%CURRENCY_DONATIONS_INTERVAL) { LOG_ERROR("internal error: validate_donations_value at wrong height: " << get_current_blockchain_height()); return false; } std::vector<bool> donation_votes; for(size_t i = m_blocks.size() - CURRENCY_DONATIONS_INTERVAL; i!= m_blocks.size(); i++) donation_votes.push_back(!(m_blocks[i].bl.flags&BLOCK_FLAGS_SUPPRESS_DONATION)); don_am = get_donations_anount_for_day(m_blocks.back().already_donated_coins, donation_votes); return true; CATCH_ENTRY_L0("blockchain_storage::validate_donations_value", false); } //------------------------------------------------------------------ bool blockchain_storage::validate_donations_value(uint64_t donation, uint64_t royalty) { CRITICAL_REGION_LOCAL(m_blockchain_lock); uint64_t expected_don_total = 0; if(!get_required_donations_value_for_next_block(expected_don_total)) return false; CHECK_AND_ASSERT_MES(donation + royalty == expected_don_total, false, "Wrong donations amount: " << donation + royalty << ", expected " << expected_don_total); uint64_t expected_donation = 0; uint64_t expected_royalty = 0; get_donation_parts(expected_don_total, expected_royalty, expected_donation); CHECK_AND_ASSERT_MES(expected_royalty == royalty && expected_donation == donation, false, "wrong donation parts: " << donation << "/" << royalty << ", expected: " << expected_donation << "/" << expected_royalty); return true; } //------------------------------------------------------------------ bool blockchain_storage::validate_miner_transaction(const block& b, size_t cumulative_block_size, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins, uint64_t already_donated_coins, uint64_t& donation_total) { CRITICAL_REGION_LOCAL(m_blockchain_lock); //validate reward uint64_t money_in_use = 0; uint64_t royalty = 0; uint64_t donation = 0; //donations should be last one //size_t outs_total = b.miner_tx.vout.size(); BOOST_FOREACH(auto& o, b.miner_tx.vout) { money_in_use += o.amount; } uint64_t h = get_block_height(b); //once a day, without if(h && !(h%CURRENCY_DONATIONS_INTERVAL) /*&& h > 21600*/) { bool r = lookfor_donation(b.miner_tx, donation, royalty); CHECK_AND_ASSERT_MES(r, false, "Failed to lookfor_donation"); r = validate_donations_value(donation, royalty); CHECK_AND_ASSERT_MES(r, false, "Failed to validate donations value"); money_in_use -= donation + royalty; } std::vector<size_t> last_blocks_sizes; get_last_n_blocks_sizes(last_blocks_sizes, CURRENCY_REWARD_BLOCKS_WINDOW); uint64_t max_donation = 0; if(!get_block_reward(misc_utils::median(last_blocks_sizes), cumulative_block_size, already_generated_coins, already_donated_coins, base_reward, max_donation)) { LOG_PRINT_L0("block size " << cumulative_block_size << " is bigger than allowed for this blockchain"); return false; } if(base_reward + fee < money_in_use) { LOG_ERROR("coinbase transaction spend too much money (" << print_money(money_in_use) << "). Block reward is " << print_money(base_reward + fee) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")"); return false; } if(base_reward + fee != money_in_use) { LOG_ERROR("coinbase transaction doesn't use full amount of block reward: spent: " << print_money(money_in_use) << ", block reward " << print_money(base_reward + fee) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")"); return false; } donation_total = royalty + donation; return true; } //------------------------------------------------------------------ bool blockchain_storage::get_backward_blocks_sizes(size_t from_height, std::vector<size_t>& sz, size_t count) { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(from_height < m_blocks.size(), false, "Internal error: get_backward_blocks_sizes called with from_height=" << from_height << ", blockchain height = " << m_blocks.size()); size_t start_offset = (from_height+1) - std::min((from_height+1), count); for(size_t i = start_offset; i != from_height+1; i++) sz.push_back(m_blocks[i].block_cumulative_size); return true; } //------------------------------------------------------------------ bool blockchain_storage::get_last_n_blocks_sizes(std::vector<size_t>& sz, size_t count) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(!m_blocks.size()) return true; return get_backward_blocks_sizes(m_blocks.size() -1, sz, count); } //------------------------------------------------------------------ uint64_t blockchain_storage::get_current_comulative_blocksize_limit() { return m_current_block_cumul_sz_limit; } //------------------------------------------------------------------ bool blockchain_storage::create_block_template(block& b, const account_public_address& miner_address, wide_difficulty_type& diffic, uint64_t& height, const blobdata& ex_nonce, bool vote_for_donation, const alias_info& ai) { size_t median_size; uint64_t already_generated_coins; uint64_t already_donated_coins; uint64_t donation_amount_for_this_block = 0; CRITICAL_REGION_BEGIN(m_blockchain_lock); b.major_version = CURRENT_BLOCK_MAJOR_VERSION; b.minor_version = CURRENT_BLOCK_MINOR_VERSION; b.prev_id = get_top_block_id(); b.timestamp = time(NULL); b.flags = 0; if(!vote_for_donation) b.flags = BLOCK_FLAGS_SUPPRESS_DONATION; height = m_blocks.size(); diffic = get_difficulty_for_next_block(); if(!(height%CURRENCY_DONATIONS_INTERVAL)) get_required_donations_value_for_next_block(donation_amount_for_this_block); CHECK_AND_ASSERT_MES(diffic, false, "difficulty owverhead."); median_size = m_current_block_cumul_sz_limit / 2; already_generated_coins = m_blocks.back().already_generated_coins; already_donated_coins = m_blocks.back().already_donated_coins; CRITICAL_REGION_END(); size_t txs_size; uint64_t fee; if (!m_tx_pool.fill_block_template(b, median_size, already_generated_coins, already_donated_coins, txs_size, fee)) { return false; } /* two-phase miner transaction generation: we don't know exact block size until we prepare block, but we don't know reward until we know block size, so first miner transaction generated with fake amount of money, and with phase we know think we know expected block size */ //make blocks coin-base tx looks close to real coinbase tx to get truthful blob size bool r = construct_miner_tx(height, median_size, already_generated_coins, already_donated_coins, txs_size, fee, miner_address, m_donations_account.m_account_address, m_royalty_account.m_account_address, b.miner_tx, ex_nonce, 11, donation_amount_for_this_block, ai); CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, first chance"); #ifdef _DEBUG std::list<size_t> try_val; try_val.push_back(get_object_blobsize(b.miner_tx)); #endif size_t cumulative_size = txs_size + get_object_blobsize(b.miner_tx); for (size_t try_count = 0; try_count != 10; ++try_count) { r = construct_miner_tx(height, median_size, already_generated_coins, already_donated_coins, cumulative_size, fee, miner_address, m_donations_account.m_account_address, m_royalty_account.m_account_address, b.miner_tx, ex_nonce, 11, donation_amount_for_this_block, ai); #ifdef _DEBUG try_val.push_back(get_object_blobsize(b.miner_tx)); #endif CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, second chance"); size_t coinbase_blob_size = get_object_blobsize(b.miner_tx); if (coinbase_blob_size > cumulative_size - txs_size) { cumulative_size = txs_size + coinbase_blob_size; continue; } if (coinbase_blob_size < cumulative_size - txs_size) { size_t delta = cumulative_size - txs_size - coinbase_blob_size; b.miner_tx.extra.insert(b.miner_tx.extra.end(), delta, 0); //here could be 1 byte difference, because of extra field counter is varint, and it can become from 1-byte len to 2-bytes len. if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) { CHECK_AND_ASSERT_MES(cumulative_size + 1 == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " + 1 is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx)); b.miner_tx.extra.resize(b.miner_tx.extra.size() - 1); if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) { //fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_size LOG_PRINT_RED("Miner tx creation have no luck with delta_extra size = " << delta << " and " << delta - 1 , LOG_LEVEL_2); cumulative_size += delta - 1; continue; } LOG_PRINT_GREEN("Setting extra for block: " << b.miner_tx.extra.size() << ", try_count=" << try_count, LOG_LEVEL_1); } } CHECK_AND_ASSERT_MES(cumulative_size == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx)); return true; } LOG_ERROR("Failed to create_block_template with " << 10 << " tries"); return false; } //------------------------------------------------------------------ bool blockchain_storage::print_transactions_statistics() { CRITICAL_REGION_LOCAL(m_blockchain_lock); LOG_PRINT_L0("Started to collect transaction statistics, pleas wait..."); size_t total_count = 0; size_t coinbase_count = 0; size_t total_full_blob = 0; size_t total_cropped_blob = 0; for(auto tx_entry: m_transactions) { ++total_count; if(is_coinbase(tx_entry.second.tx)) ++coinbase_count; else { total_full_blob += get_object_blobsize<transaction>(tx_entry.second.tx); transaction tx = tx_entry.second.tx; tx.signatures.clear(); total_cropped_blob += get_object_blobsize<transaction>(tx); } } LOG_PRINT_L0("Done" << ENDL << "total transactions: " << total_count << ENDL << "coinbase transactions: " << coinbase_count << ENDL << "avarage size of transaction: " << total_full_blob/(total_count-coinbase_count) << ENDL << "avarage size of transaction without ring signatures: " << total_cropped_blob/(total_count-coinbase_count) << ENDL ); return true; } //------------------------------------------------------------------ bool blockchain_storage::complete_timestamps_vector(uint64_t start_top_height, std::vector<uint64_t>& timestamps) { if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) return true; CRITICAL_REGION_LOCAL(m_blockchain_lock); size_t need_elements = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW - timestamps.size(); CHECK_AND_ASSERT_MES(start_top_height < m_blocks.size(), false, "internal error: passed start_height = " << start_top_height << " not less then m_blocks.size()=" << m_blocks.size()); size_t stop_offset = start_top_height > need_elements ? start_top_height - need_elements:0; do { timestamps.push_back(m_blocks[start_top_height].bl.timestamp); if(start_top_height == 0) break; --start_top_height; }while(start_top_height != stop_offset); return true; } //------------------------------------------------------------------ bool blockchain_storage::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc) { if(m_checkpoints.is_height_passed_zone(get_block_height(b), get_current_blockchain_height()-1)) { LOG_PRINT_RED_L0("Block with id: " << id << "[" << get_block_height(b) << "]" << ENDL << " for alternative chain, is under checkpoint zone, declined"); bvc.m_verifivation_failed = true; return false; } TRY_ENTRY(); CRITICAL_REGION_LOCAL(m_blockchain_lock); //block is not related with head of main chain //first of all - look in alternative chains container auto it_main_prev = m_blocks_index.find(b.prev_id); auto it_prev = m_alternative_chains.find(b.prev_id); if(it_prev != m_alternative_chains.end() || it_main_prev != m_blocks_index.end()) { //we have new block in alternative chain //build alternative subchain, front -> mainchain, back -> alternative head blocks_ext_by_hash::iterator alt_it = it_prev; //m_alternative_chains.find() std::list<blocks_ext_by_hash::iterator> alt_chain; std::vector<crypto::hash> alt_scratchppad; std::map<uint64_t, crypto::hash> alt_scratchppad_patch; std::vector<uint64_t> timestamps; while(alt_it != m_alternative_chains.end()) { alt_chain.push_front(alt_it); timestamps.push_back(alt_it->second.bl.timestamp); alt_it = m_alternative_chains.find(alt_it->second.bl.prev_id); } if(alt_chain.size()) { //make sure that it has right connection to main chain CHECK_AND_ASSERT_MES(m_blocks.size() > alt_chain.front()->second.height, false, "main blockchain wrong height"); crypto::hash h = null_hash; get_block_hash(m_blocks[alt_chain.front()->second.height - 1].bl, h); CHECK_AND_ASSERT_MES(h == alt_chain.front()->second.bl.prev_id, false, "alternative chain have wrong connection to main chain"); complete_timestamps_vector(alt_chain.front()->second.height - 1, timestamps); //build alternative scratchpad for(auto& ach: alt_chain) { if(!push_block_scratchpad_data(ach->second.scratch_offset, ach->second.bl, alt_scratchppad, alt_scratchppad_patch)) { LOG_PRINT_RED_L0("Block with id: " << id << ENDL << " for alternative chain, have invalid data"); bvc.m_verifivation_failed = true; return false; } } }else { CHECK_AND_ASSERT_MES(it_main_prev != m_blocks_index.end(), false, "internal error: broken imperative condition it_main_prev != m_blocks_index.end()"); complete_timestamps_vector(it_main_prev->second, timestamps); } //check timestamp correct if(!check_block_timestamp(timestamps, b)) { LOG_PRINT_RED_L0("Block with id: " << id << ENDL << " for alternative chain, have invalid timestamp: " << b.timestamp); //add_block_as_invalid(b, id);//do not add blocks to invalid storage before proof of work check was passed bvc.m_verifivation_failed = true; return false; } block_extended_info bei = boost::value_initialized<block_extended_info>(); bei.bl = b; bei.height = alt_chain.size() ? it_prev->second.height + 1 : it_main_prev->second + 1; uint64_t connection_height = alt_chain.size() ? alt_chain.front()->second.height:bei.height; CHECK_AND_ASSERT_MES(connection_height, false, "INTERNAL ERROR: Wrong connection_height==0 in handle_alternative_block"); bei.scratch_offset = m_blocks[connection_height].scratch_offset + alt_scratchppad.size(); CHECK_AND_ASSERT_MES(bei.scratch_offset, false, "INTERNAL ERROR: Wrong bei.scratch_offset==0 in handle_alternative_block"); //lets collect patchs from main line std::map<uint64_t, crypto::hash> main_line_patches; for(uint64_t i = connection_height; i != m_blocks.size(); i++) { std::vector<crypto::hash> block_addendum; bool res = get_block_scratchpad_addendum(m_blocks[i].bl, block_addendum); CHECK_AND_ASSERT_MES(res, false, "Failed to get_block_scratchpad_addendum for alt block"); get_scratchpad_patch(m_blocks[i].scratch_offset, 0, block_addendum.size(), block_addendum, main_line_patches); } //apply only that patches that lay under alternative scratchpad offset for(auto ml: main_line_patches) { if(ml.first < m_blocks[connection_height].scratch_offset) alt_scratchppad_patch[ml.first] = crypto::xor_pod(alt_scratchppad_patch[ml.first], ml.second); } wide_difficulty_type current_diff = get_next_difficulty_for_alternative_chain(alt_chain, bei); CHECK_AND_ASSERT_MES(current_diff, false, "!!!!!!! DIFFICULTY OVERHEAD !!!!!!!"); crypto::hash proof_of_work = null_hash; // POW #ifdef ENABLE_HASHING_DEBUG size_t call_no = 0; std::stringstream ss; #endif get_block_longhash(bei.bl, proof_of_work, bei.height, [&](uint64_t index) -> crypto::hash { uint64_t offset = index%bei.scratch_offset; crypto::hash res; if(offset >= m_blocks[connection_height].scratch_offset) { res = alt_scratchppad[offset - m_blocks[connection_height].scratch_offset]; }else { res = m_scratchpad[offset]; } auto it = alt_scratchppad_patch.find(offset); if(it != alt_scratchppad_patch.end()) {//apply patch res = crypto::xor_pod(res, it->second); } #ifdef ENABLE_HASHING_DEBUG ss << "[" << call_no << "][" << index << "%" << bei.scratch_offset <<"(" << index%bei.scratch_offset << ")]" << res << ENDL; ++call_no; #endif return res; }); #ifdef ENABLE_HASHING_DEBUG LOG_PRINT_L3("ID: " << get_block_hash(bei.bl) << "[" << bei.height << "]" << ENDL << "POW:" << proof_of_work << ENDL << ss.str()); #endif if(!check_hash(proof_of_work, current_diff)) { LOG_PRINT_RED_L0("Block with id: " << id << ENDL << " for alternative chain, have not enough proof of work: " << proof_of_work << ENDL << " expected difficulty: " << current_diff); bvc.m_verifivation_failed = true; return false; } // if(!m_checkpoints.is_in_checkpoint_zone(bei.height)) { m_is_in_checkpoint_zone = false; }else { m_is_in_checkpoint_zone = true; if(!m_checkpoints.check_block(bei.height, id)) { LOG_ERROR("CHECKPOINT VALIDATION FAILED"); bvc.m_verifivation_failed = true; return false; } } if(!prevalidate_miner_transaction(b, bei.height)) { LOG_PRINT_RED_L0("Block with id: " << string_tools::pod_to_hex(id) << " (as alternative) have wrong miner transaction."); bvc.m_verifivation_failed = true; return false; } bei.cumulative_difficulty = alt_chain.size() ? it_prev->second.cumulative_difficulty: m_blocks[it_main_prev->second].cumulative_difficulty; bei.cumulative_difficulty += current_diff; #ifdef _DEBUG auto i_dres = m_alternative_chains.find(id); CHECK_AND_ASSERT_MES(i_dres == m_alternative_chains.end(), false, "insertion of new alternative block returned as it already exist"); #endif auto i_res = m_alternative_chains.insert(blocks_ext_by_hash::value_type(id, bei)); CHECK_AND_ASSERT_MES(i_res.second, false, "insertion of new alternative block returned as it already exist"); alt_chain.push_back(i_res.first); //check if difficulty bigger then in main chain if(m_blocks.back().cumulative_difficulty < bei.cumulative_difficulty) { //do reorganize! LOG_PRINT_GREEN("###### REORGANIZE on height: " << alt_chain.front()->second.height << " of " << m_blocks.size() -1 << " with cum_difficulty " << m_blocks.back().cumulative_difficulty << ENDL << " alternative blockchain size: " << alt_chain.size() << " with cum_difficulty " << bei.cumulative_difficulty, LOG_LEVEL_0); bool r = switch_to_alternative_blockchain(alt_chain); if(r) bvc.m_added_to_main_chain = true; else bvc.m_verifivation_failed = true; return r; } LOG_PRINT_BLUE("----- BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << bei.height << ENDL << "id:\t" << id << ENDL << "PoW:\t" << proof_of_work << ENDL << "difficulty:\t" << current_diff, LOG_LEVEL_0); return true; }else { //block orphaned bvc.m_marked_as_orphaned = true; LOG_PRINT_RED_L0("Block recognized as orphaned and rejected, id = " << id); } return true; CATCH_ENTRY_L0("blockchain_storage::handle_alternative_block", false); } //------------------------------------------------------------------ bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks, std::list<transaction>& txs) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(start_offset >= m_blocks.size()) return false; for(size_t i = start_offset; i < start_offset + count && i < m_blocks.size();i++) { blocks.push_back(m_blocks[i].bl); std::list<crypto::hash> missed_ids; get_transactions(m_blocks[i].bl.tx_hashes, txs, missed_ids); CHECK_AND_ASSERT_MES(!missed_ids.size(), false, "have missed transactions in own block in main blockchain"); } return true; } //------------------------------------------------------------------ bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(start_offset >= m_blocks.size()) return false; for(size_t i = start_offset; i < start_offset + count && i < m_blocks.size();i++) blocks.push_back(m_blocks[i].bl); return true; } //------------------------------------------------------------------ bool blockchain_storage::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp) { CRITICAL_REGION_LOCAL(m_blockchain_lock); rsp.current_blockchain_height = get_current_blockchain_height(); std::list<block> blocks; get_blocks(arg.blocks, blocks, rsp.missed_ids); BOOST_FOREACH(const auto& bl, blocks) { std::list<crypto::hash> missed_tx_id; std::list<transaction> txs; get_transactions(bl.tx_hashes, txs, rsp.missed_ids); CHECK_AND_ASSERT_MES(!missed_tx_id.size(), false, "Internal error: have missed missed_tx_id.size()=" << missed_tx_id.size() << ENDL << "for block id = " << get_block_hash(bl)); rsp.blocks.push_back(block_complete_entry()); block_complete_entry& e = rsp.blocks.back(); //pack block e.block = t_serializable_object_to_blob(bl); //pack transactions BOOST_FOREACH(transaction& tx, txs) e.txs.push_back(t_serializable_object_to_blob(tx)); } //get another transactions, if need std::list<transaction> txs; get_transactions(arg.txs, txs, rsp.missed_ids); //pack aside transactions BOOST_FOREACH(const auto& tx, txs) rsp.txs.push_back(t_serializable_object_to_blob(tx)); return true; } //------------------------------------------------------------------ bool blockchain_storage::get_transactions_daily_stat(uint64_t& daily_cnt, uint64_t& daily_volume) { CRITICAL_REGION_LOCAL(m_blockchain_lock); daily_cnt = daily_volume = 0; for(size_t i = (m_blocks.size() > CURRENCY_BLOCK_PER_DAY ? m_blocks.size() - CURRENCY_BLOCK_PER_DAY:0 ); i!=m_blocks.size(); i++) { for(auto& h: m_blocks[i].bl.tx_hashes) { ++daily_cnt; auto tx_it = m_transactions.find(h); CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "Wrong transaction hash "<< h <<" in block on height " << i ); uint64_t am = 0; bool r = get_inputs_money_amount(tx_it->second.tx, am); CHECK_AND_ASSERT_MES(r, false, "failed to get_inputs_money_amount"); daily_volume += am; } } return true; } //------------------------------------------------------------------ bool blockchain_storage::check_keyimages(const std::list<crypto::key_image>& images, std::list<bool>& images_stat) { //true - unspent, false - spent CRITICAL_REGION_LOCAL(m_blockchain_lock); for (auto& ki : images) { images_stat.push_back(m_spent_keys.count(ki)?false:true); } return true; } //------------------------------------------------------------------ uint64_t blockchain_storage::get_current_hashrate(size_t aprox_count) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(m_blocks.size() <= aprox_count) return 0; wide_difficulty_type w_hr = (m_blocks.back().cumulative_difficulty - m_blocks[m_blocks.size() - aprox_count].cumulative_difficulty)/ (m_blocks.back().bl.timestamp - m_blocks[m_blocks.size() - aprox_count].bl.timestamp); return w_hr.convert_to<uint64_t>(); } //------------------------------------------------------------------ bool blockchain_storage::extport_scratchpad_to_file(const std::string& path) { CRITICAL_REGION_LOCAL(m_blockchain_lock); export_scratchpad_file_header fh; memset(&fh, 0, sizeof(fh)); fh.current_hi.prevhash = currency::get_block_hash(m_blocks.back().bl); fh.current_hi.height = m_blocks.size()-1; fh.scratchpad_size = m_scratchpad.size()*4; try { std::string tmp_path = path + ".tmp"; std::ofstream fstream; fstream.exceptions(std::ifstream::failbit | std::ifstream::badbit); fstream.open(tmp_path, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc); fstream.write((const char*)&fh, sizeof(fh)); fstream.write((const char*)&m_scratchpad[0], m_scratchpad.size()*32); fstream.close(); boost::filesystem::remove(path); boost::filesystem::rename(tmp_path, path); LOG_PRINT_L0("Scratchpad exported to " << path << ", " << (m_scratchpad.size()*32)/1024 << "kbytes" ); return true; } catch(const std::exception& e) { LOG_PRINT_L0("Failed to store scratchpad, error: " << e.what()); return false; } catch(...) { LOG_PRINT_L0("Failed to store scratchpad, unknown error" ); return false; } return true; } //------------------------------------------------------------------ bool blockchain_storage::get_alternative_blocks(std::list<block>& blocks) { CRITICAL_REGION_LOCAL(m_blockchain_lock); BOOST_FOREACH(const auto& alt_bl, m_alternative_chains) { blocks.push_back(alt_bl.second.bl); } return true; } //------------------------------------------------------------------ size_t blockchain_storage::get_alternative_blocks_count() { CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_alternative_chains.size(); } //------------------------------------------------------------------ bool blockchain_storage::add_out_to_get_random_outs(std::vector<std::pair<crypto::hash, size_t> >& amount_outs, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs, uint64_t amount, size_t i, uint64_t mix_count, bool use_only_forced_to_mix) { CRITICAL_REGION_LOCAL(m_blockchain_lock); transactions_container::iterator tx_it = m_transactions.find(amount_outs[i].first); CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "internal error: transaction with id " << amount_outs[i].first << ENDL << ", used in mounts global index for amount=" << amount << ": i=" << i << "not found in transactions index"); CHECK_AND_ASSERT_MES(tx_it->second.tx.vout.size() > amount_outs[i].second, false, "internal error: in global outs index, transaction out index=" << amount_outs[i].second << " more than transaction outputs = " << tx_it->second.tx.vout.size() << ", for tx id = " << amount_outs[i].first); transaction& tx = tx_it->second.tx; CHECK_AND_ASSERT_MES(tx.vout[amount_outs[i].second].target.type() == typeid(txout_to_key), false, "unknown tx out type"); CHECK_AND_ASSERT_MES(tx_it->second.m_spent_flags.size() == tx.vout.size(), false, "internal error"); //do not use outputs that obviously spent for mixins if(tx_it->second.m_spent_flags[amount_outs[i].second]) return false; //check if transaction is unlocked if(!is_tx_spendtime_unlocked(tx.unlock_time)) return false; //use appropriate mix_attr out uint8_t mix_attr = boost::get<txout_to_key>(tx.vout[amount_outs[i].second].target).mix_attr; if(mix_attr == CURRENCY_TO_KEY_OUT_FORCED_NO_MIX) return false; //COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS call means that ring signature will have more than one entry. else if(use_only_forced_to_mix && mix_attr == CURRENCY_TO_KEY_OUT_RELAXED) return false; //relaxed not allowed else if(mix_attr != CURRENCY_TO_KEY_OUT_RELAXED && mix_attr > mix_count) return false;//mix_attr set to specific minimum, and mix_count is less then desired count COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry& oen = *result_outs.outs.insert(result_outs.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry()); oen.global_amount_index = i; oen.out_key = boost::get<txout_to_key>(tx.vout[amount_outs[i].second].target).key; return true; } //------------------------------------------------------------------ size_t blockchain_storage::find_end_of_allowed_index(const std::vector<std::pair<crypto::hash, size_t> >& amount_outs) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(!amount_outs.size()) return 0; size_t i = amount_outs.size(); do { --i; transactions_container::iterator it = m_transactions.find(amount_outs[i].first); CHECK_AND_ASSERT_MES(it != m_transactions.end(), 0, "internal error: failed to find transaction from outputs index with tx_id=" << amount_outs[i].first); if(it->second.m_keeper_block_height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW <= get_current_blockchain_height() ) return i+1; } while (i != 0); return 0; } //------------------------------------------------------------------ bool blockchain_storage::get_random_outs_for_amounts(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response& res) { CRITICAL_REGION_LOCAL(m_blockchain_lock); BOOST_FOREACH(uint64_t amount, req.amounts) { COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs = *res.outs.insert(res.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount()); result_outs.amount = amount; auto it = m_outputs.find(amount); if(it == m_outputs.end()) { LOG_ERROR("COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS: not outs for amount " << amount << ", wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist"); continue;//actually this is strange situation, wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist } std::vector<std::pair<crypto::hash, size_t> >& amount_outs = it->second; //it is not good idea to use top fresh outs, because it increases possibility of transaction canceling on split //lets find upper bound of not fresh outs size_t up_index_limit = find_end_of_allowed_index(amount_outs); CHECK_AND_ASSERT_MES(up_index_limit <= amount_outs.size(), false, "internal error: find_end_of_allowed_index returned wrong index=" << up_index_limit << ", with amount_outs.size = " << amount_outs.size()); if(amount_outs.size() > req.outs_count) { std::set<size_t> used; size_t try_count = 0; for(uint64_t j = 0; j != req.outs_count && try_count < up_index_limit;) { size_t i = crypto::rand<size_t>()%up_index_limit; if(used.count(i)) continue; bool added = add_out_to_get_random_outs(amount_outs, result_outs, amount, i, req.outs_count, req.use_forced_mix_outs); used.insert(i); if(added) ++j; ++try_count; } }else { for(size_t i = 0; i != up_index_limit; i++) add_out_to_get_random_outs(amount_outs, result_outs, amount, i, req.outs_count, req.use_forced_mix_outs); } } return true; } //------------------------------------------------------------------ bool blockchain_storage::update_spent_tx_flags_for_input(uint64_t amount, uint64_t global_index, bool spent) { CRITICAL_REGION_LOCAL(m_blockchain_lock); auto it = m_outputs.find(amount); CHECK_AND_ASSERT_MES(it != m_outputs.end(), false, "Amount " << amount << " have not found during update_spent_tx_flags_for_input()"); CHECK_AND_ASSERT_MES(global_index < it->second.size(), false, "Global index" << global_index << " for amount " << amount << " bigger value than amount's vector size()=" << it->second.size()); auto tx_it = m_transactions.find(it->second[global_index].first); CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "Can't find transaction id: " << it->second[global_index].first << ", refferenced in amount=" << amount << ", global index=" << global_index); CHECK_AND_ASSERT_MES(it->second[global_index].second < tx_it->second.m_spent_flags.size() , false, "Wrong input offset: " << it->second[global_index].second << " in transaction id: " << it->second[global_index].first << ", refferenced in amount=" << amount << ", global index=" << global_index); tx_it->second.m_spent_flags[it->second[global_index].second] = spent; return true; } //------------------------------------------------------------------ bool blockchain_storage::resync_spent_tx_flags() { LOG_PRINT_L0("Started re-building spent tx outputs data..."); CRITICAL_REGION_LOCAL(m_blockchain_lock); for(auto& tx: m_transactions) { if(is_coinbase(tx.second.tx)) continue; for(auto& in: tx.second.tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, txin_to_key, in_to_key, false); if(in_to_key.key_offsets.size() != 1) continue; //direct spending if(!update_spent_tx_flags_for_input(in_to_key.amount, in_to_key.key_offsets[0], true)) return false; } } LOG_PRINT_L0("Finished re-building spent tx outputs data"); return true; } //------------------------------------------------------------------ bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(!qblock_ids.size() /*|| !req.m_total_height*/) { LOG_ERROR("Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << /*", m_height=" << req.m_total_height <<*/ ", dropping connection"); return false; } //check genesis match if(qblock_ids.back() != get_block_hash(m_blocks[0].bl)) { LOG_ERROR("Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block missmatch: " << ENDL << "id: " << qblock_ids.back() << ", " << ENDL << "expected: " << get_block_hash(m_blocks[0].bl) << "," << ENDL << " dropping connection"); return false; } /* Figure out what blocks we should request to get state_normal */ size_t i = 0; auto bl_it = qblock_ids.begin(); auto block_index_it = m_blocks_index.find(*bl_it); for(; bl_it != qblock_ids.end(); bl_it++, i++) { block_index_it = m_blocks_index.find(*bl_it); if(block_index_it != m_blocks_index.end()) break; } if(bl_it == qblock_ids.end()) { LOG_ERROR("Internal error handling connection, can't find split point"); return false; } if(block_index_it == m_blocks_index.end()) { //this should NEVER happen, but, dose of paranoia in such cases is not too bad LOG_ERROR("Internal error handling connection, can't find split point"); return false; } //we start to put block ids INCLUDING last known id, just to make other side be sure starter_offset = block_index_it->second; return true; } //------------------------------------------------------------------ wide_difficulty_type blockchain_storage::block_difficulty(size_t i) { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(i < m_blocks.size(), false, "wrong block index i = " << i << " at blockchain_storage::block_difficulty()"); if(i == 0) return m_blocks[i].cumulative_difficulty; return m_blocks[i].cumulative_difficulty - m_blocks[i-1].cumulative_difficulty; } //------------------------------------------------------------------ void blockchain_storage::print_blockchain(uint64_t start_index, uint64_t end_index) { std::stringstream ss; CRITICAL_REGION_LOCAL(m_blockchain_lock); if(start_index >=m_blocks.size()) { LOG_PRINT_L0("Wrong starter index set: " << start_index << ", expected max index " << m_blocks.size()-1); return; } for(size_t i = start_index; i != m_blocks.size() && i != end_index; i++) { ss << "height " << i << ", timestamp " << m_blocks[i].bl.timestamp << ", cumul_dif " << m_blocks[i].cumulative_difficulty << ", cumul_size " << m_blocks[i].block_cumulative_size << "\nid\t\t" << get_block_hash(m_blocks[i].bl) << "\ndifficulty\t\t" << block_difficulty(i) << ", nonce " << m_blocks[i].bl.nonce << ", tx_count " << m_blocks[i].bl.tx_hashes.size() << ENDL; } LOG_PRINT_L1("Current blockchain:" << ENDL << ss.str()); LOG_PRINT_L0("Blockchain printed with log level 1"); } //------------------------------------------------------------------ void blockchain_storage::print_blockchain_index() { std::stringstream ss; CRITICAL_REGION_LOCAL(m_blockchain_lock); BOOST_FOREACH(const blocks_by_id_index::value_type& v, m_blocks_index) ss << "id\t\t" << v.first << " height" << v.second << ENDL << ""; LOG_PRINT_L0("Current blockchain index:" << ENDL << ss.str()); } //------------------------------------------------------------------ void blockchain_storage::print_blockchain_outs(const std::string& file) { std::stringstream ss; CRITICAL_REGION_LOCAL(m_blockchain_lock); BOOST_FOREACH(const outputs_container::value_type& v, m_outputs) { const std::vector<std::pair<crypto::hash, size_t> >& vals = v.second; if(vals.size()) { ss << "amount: " << v.first << ENDL; for(size_t i = 0; i != vals.size(); i++) ss << "\t" << vals[i].first << ": " << vals[i].second << ENDL; } } if(file_io_utils::save_string_to_file(file, ss.str())) { LOG_PRINT_L0("Current outputs index writen to file: " << file); }else { LOG_PRINT_L0("Failed to write current outputs index to file: " << file); } } //------------------------------------------------------------------ bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(!find_blockchain_supplement(qblock_ids, resp.start_height)) return false; resp.total_height = get_current_blockchain_height(); size_t count = 0; for(size_t i = resp.start_height; i != m_blocks.size() && count < BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT; i++, count++) resp.m_block_ids.push_back(get_block_hash(m_blocks[i].bl)); return true; } //------------------------------------------------------------------ bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, std::list<std::pair<block, std::list<transaction> > >& blocks, uint64_t& total_height, uint64_t& start_height, size_t max_count) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(!find_blockchain_supplement(qblock_ids, start_height)) return false; total_height = get_current_blockchain_height(); size_t count = 0; for(size_t i = start_height; i != m_blocks.size() && count < max_count; i++, count++) { blocks.resize(blocks.size()+1); blocks.back().first = m_blocks[i].bl; std::list<crypto::hash> mis; get_transactions(m_blocks[i].bl.tx_hashes, blocks.back().second, mis); CHECK_AND_ASSERT_MES(!mis.size(), false, "internal error, transaction from block not found"); } return true; } //------------------------------------------------------------------ bool blockchain_storage::add_block_as_invalid(const block& bl, const crypto::hash& h) { block_extended_info bei = AUTO_VAL_INIT(bei); bei.bl = bl; return add_block_as_invalid(bei, h); } //------------------------------------------------------------------ bool blockchain_storage::add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h) { CRITICAL_REGION_LOCAL(m_blockchain_lock); auto i_res = m_invalid_blocks.insert(std::map<crypto::hash, block_extended_info>::value_type(h, bei)); CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid by tx returned status existed"); LOG_PRINT_L0("BLOCK ADDED AS INVALID: " << h << ENDL << ", prev_id=" << bei.bl.prev_id << ", m_invalid_blocks count=" << m_invalid_blocks.size()); return true; } //------------------------------------------------------------------ bool blockchain_storage::have_block(const crypto::hash& id) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(m_blocks_index.count(id)) return true; if(m_alternative_chains.count(id)) return true; /*if(m_orphaned_blocks.get<by_id>().count(id)) return true;*/ /*if(m_orphaned_by_tx.count(id)) return true;*/ if(m_invalid_blocks.count(id)) return true; return false; } //------------------------------------------------------------------ bool blockchain_storage::handle_block_to_main_chain(const block& bl, block_verification_context& bvc) { crypto::hash id = get_block_hash(bl); return handle_block_to_main_chain(bl, id, bvc); } //------------------------------------------------------------------ bool blockchain_storage::push_transaction_to_global_outs_index(const transaction& tx, const crypto::hash& tx_id, std::vector<uint64_t>& global_indexes) { CRITICAL_REGION_LOCAL(m_blockchain_lock); size_t i = 0; BOOST_FOREACH(const auto& ot, tx.vout) { outputs_container::mapped_type& amount_index = m_outputs[ot.amount]; amount_index.push_back(std::pair<crypto::hash, size_t>(tx_id, i)); global_indexes.push_back(amount_index.size()-1); ++i; } return true; } //------------------------------------------------------------------ size_t blockchain_storage::get_total_transactions() { CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_transactions.size(); } //------------------------------------------------------------------ bool blockchain_storage::get_outs(uint64_t amount, std::list<crypto::public_key>& pkeys) { CRITICAL_REGION_LOCAL(m_blockchain_lock); auto it = m_outputs.find(amount); if(it == m_outputs.end()) return true; BOOST_FOREACH(const auto& out_entry, it->second) { auto tx_it = m_transactions.find(out_entry.first); CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "transactions outs global index consistency broken: wrong tx id in index"); CHECK_AND_ASSERT_MES(tx_it->second.tx.vout.size() > out_entry.second, false, "transactions outs global index consistency broken: index in tx_outx more then size"); CHECK_AND_ASSERT_MES(tx_it->second.tx.vout[out_entry.second].target.type() == typeid(txout_to_key), false, "transactions outs global index consistency broken: index in tx_outx more then size"); pkeys.push_back(boost::get<txout_to_key>(tx_it->second.tx.vout[out_entry.second].target).key); } return true; } //------------------------------------------------------------------ bool blockchain_storage::pop_transaction_from_global_index(const transaction& tx, const crypto::hash& tx_id) { CRITICAL_REGION_LOCAL(m_blockchain_lock); size_t i = tx.vout.size()-1; BOOST_REVERSE_FOREACH(const auto& ot, tx.vout) { auto it = m_outputs.find(ot.amount); CHECK_AND_ASSERT_MES(it != m_outputs.end(), false, "transactions outs global index consistency broken"); CHECK_AND_ASSERT_MES(it->second.size(), false, "transactions outs global index: empty index for amount: " << ot.amount); CHECK_AND_ASSERT_MES(it->second.back().first == tx_id , false, "transactions outs global index consistency broken: tx id missmatch"); CHECK_AND_ASSERT_MES(it->second.back().second == i, false, "transactions outs global index consistency broken: in transaction index missmatch"); it->second.pop_back(); //do not let to exist empty m_outputs entries - this will broke scratchpad selector if(!it->second.size()) m_outputs.erase(it); --i; } return true; } //------------------------------------------------------------------ bool blockchain_storage::unprocess_blockchain_tx_extra(const transaction& tx) { if(is_coinbase(tx)) { tx_extra_info ei = AUTO_VAL_INIT(ei); bool r = parse_and_validate_tx_extra(tx, ei); CHECK_AND_ASSERT_MES(r, false, "failed to validate transaction extra on unprocess_blockchain_tx_extra"); if(ei.m_alias.m_alias.size()) { r = pop_alias_info(ei.m_alias); CHECK_AND_ASSERT_MES(r, false, "failed to pop_alias_info"); } } return true; } //------------------------------------------------------------------ bool blockchain_storage::get_alias_info(const std::string& alias, alias_info_base& info) { CRITICAL_REGION_LOCAL(m_blockchain_lock); auto it = m_aliases.find(alias); if(it != m_aliases.end()) { if(it->second.size()) { info = it->second.back(); return true; } } return false; } //------------------------------------------------------------------ uint64_t blockchain_storage::get_aliases_count() { CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_aliases.size(); } //------------------------------------------------------------------ uint64_t blockchain_storage::get_scratchpad_size() { CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_scratchpad.size()*32; } //------------------------------------------------------------------ bool blockchain_storage::get_all_aliases(std::list<alias_info>& aliases) { CRITICAL_REGION_LOCAL(m_blockchain_lock); for(auto a: m_aliases) { if(a.second.size()) { aliases.push_back(alias_info()); aliases.back().m_alias = a.first; static_cast<alias_info_base&>(aliases.back()) = a.second.back(); } } return true; } //------------------------------------------------------------------ std::string blockchain_storage::get_alias_by_address(const account_public_address& addr) { auto it = m_addr_to_alias.find(addr); if (it != m_addr_to_alias.end()) return it->second; return ""; } //------------------------------------------------------------------ bool blockchain_storage::pop_alias_info(const alias_info& ai) { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(ai.m_alias.size(), false, "empty name in pop_alias_info"); aliases_container::mapped_type& alias_history = m_aliases[ai.m_alias]; CHECK_AND_ASSERT_MES(alias_history.size(), false, "empty name list in pop_alias_info"); auto it = m_addr_to_alias.find(alias_history.back().m_address); if (it != m_addr_to_alias.end()) { m_addr_to_alias.erase(it); } else { LOG_ERROR("In m_addr_to_alias not found " << get_account_address_as_str(alias_history.back().m_address)); } alias_history.pop_back(); if (alias_history.size()) { m_addr_to_alias[alias_history.back().m_address] = ai.m_alias; } return true; } //------------------------------------------------------------------ bool blockchain_storage::put_alias_info(const alias_info& ai) { CRITICAL_REGION_LOCAL(m_blockchain_lock); CHECK_AND_ASSERT_MES(ai.m_alias.size(), false, "empty name in put_alias_info"); aliases_container::mapped_type& alias_history = m_aliases[ai.m_alias]; if(ai.m_sign == null_sig) {//adding new alias, check sat name is free CHECK_AND_ASSERT_MES(!alias_history.size(), false, "alias " << ai.m_alias << " already in use"); alias_history.push_back(ai); m_addr_to_alias[alias_history.back().m_address] = ai.m_alias; }else { //update procedure CHECK_AND_ASSERT_MES(alias_history.size(), false, "alias " << ai.m_alias << " can't be update becouse it doesn't exists"); std::string signed_buff; make_tx_extra_alias_entry(signed_buff, ai, true); bool r = crypto::check_signature(get_blob_hash(signed_buff), alias_history.back().m_address.m_spend_public_key, ai.m_sign); CHECK_AND_ASSERT_MES(r, false, "Failed to check signature, alias update failed"); //update granted auto it = m_addr_to_alias.find(alias_history.back().m_address); if (it != m_addr_to_alias.end()) m_addr_to_alias.erase(it); else LOG_ERROR("Wromg m_addr_to_alias state: address not found " << get_account_address_as_str(alias_history.back().m_address)); alias_history.push_back(ai); m_addr_to_alias[alias_history.back().m_address] = ai.m_alias; } return true; } //------------------------------------------------------------------ bool blockchain_storage::process_blockchain_tx_extra(const transaction& tx) { //check transaction extra tx_extra_info ei = AUTO_VAL_INIT(ei); bool r = parse_and_validate_tx_extra(tx, ei); CHECK_AND_ASSERT_MES(r, false, "failed to validate transaction extra"); if(is_coinbase(tx) && ei.m_alias.m_alias.size()) { r = put_alias_info(ei.m_alias); CHECK_AND_ASSERT_MES(r, false, "failed to put_alias_info"); } return true; } //------------------------------------------------------------------ bool blockchain_storage::add_transaction_from_block(const transaction& tx, const crypto::hash& tx_id, const crypto::hash& bl_id, uint64_t bl_height) { CRITICAL_REGION_LOCAL(m_blockchain_lock); bool r = process_blockchain_tx_extra(tx); CHECK_AND_ASSERT_MES(r, false, "failed to process_blockchain_tx_extra"); struct add_transaction_input_visitor: public boost::static_visitor<bool> { blockchain_storage& m_bcs; key_images_container& m_spent_keys; const crypto::hash& m_tx_id; const crypto::hash& m_bl_id; add_transaction_input_visitor(blockchain_storage& bcs, key_images_container& spent_keys, const crypto::hash& tx_id, const crypto::hash& bl_id): m_bcs(bcs), m_spent_keys(spent_keys), m_tx_id(tx_id), m_bl_id(bl_id) {} bool operator()(const txin_to_key& in) const { const crypto::key_image& ki = in.k_image; auto r = m_spent_keys.insert(ki); if(!r.second) { //double spend detected LOG_PRINT_L0("tx with id: " << m_tx_id << " in block id: " << m_bl_id << " have input marked as spent with key image: " << ki << ", block declined"); return false; } if(in.key_offsets.size() == 1) { //direct spend detected if(!m_bcs.update_spent_tx_flags_for_input(in.amount, in.key_offsets[0], true)) { //internal error LOG_PRINT_L0("Failed to update_spent_tx_flags_for_input"); return false; } } return true; } bool operator()(const txin_gen& tx) const{return true;} bool operator()(const txin_to_script& tx) const{return false;} bool operator()(const txin_to_scripthash& tx) const{return false;} }; BOOST_FOREACH(const txin_v& in, tx.vin) { if(!boost::apply_visitor(add_transaction_input_visitor(*this, m_spent_keys, tx_id, bl_id), in)) { LOG_ERROR("critical internal error: add_transaction_input_visitor failed. but key_images should be already checked"); purge_transaction_keyimages_from_blockchain(tx, false); bool r = unprocess_blockchain_tx_extra(tx); CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra"); return false; } } transaction_chain_entry ch_e; ch_e.m_keeper_block_height = bl_height; ch_e.m_spent_flags.resize(tx.vout.size(), false); ch_e.tx = tx; auto i_r = m_transactions.insert(std::pair<crypto::hash, transaction_chain_entry>(tx_id, ch_e)); if(!i_r.second) { LOG_ERROR("critical internal error: tx with id: " << tx_id << " in block id: " << bl_id << " already in blockchain"); purge_transaction_keyimages_from_blockchain(tx, true); bool r = unprocess_blockchain_tx_extra(tx); CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra"); return false; } r = push_transaction_to_global_outs_index(tx, tx_id, i_r.first->second.m_global_output_indexes); CHECK_AND_ASSERT_MES(r, false, "failed to return push_transaction_to_global_outs_index tx id " << tx_id); LOG_PRINT_L2("Added transaction to blockchain history:" << ENDL << "tx_id: " << tx_id << ENDL << "inputs: " << tx.vin.size() << ", outs: " << tx.vout.size() << ", spend money: " << print_money(get_outs_money_amount(tx)) << "(fee: " << (is_coinbase(tx) ? "0[coinbase]" : print_money(get_tx_fee(tx))) << ")"); return true; } //------------------------------------------------------------------ bool blockchain_storage::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs) { CRITICAL_REGION_LOCAL(m_blockchain_lock); auto it = m_transactions.find(tx_id); if(it == m_transactions.end()) { LOG_PRINT_RED_L0("warning: get_tx_outputs_gindexs failed to find transaction with id = " << tx_id); return false; } CHECK_AND_ASSERT_MES(it->second.m_global_output_indexes.size(), false, "internal error: global indexes for transaction " << tx_id << " is empty"); indexs = it->second.m_global_output_indexes; return true; } //------------------------------------------------------------------ bool blockchain_storage::check_tx_inputs(const transaction& tx, uint64_t& max_used_block_height, crypto::hash& max_used_block_id) { CRITICAL_REGION_LOCAL(m_blockchain_lock); bool res = check_tx_inputs(tx, &max_used_block_height); if(!res) return false; CHECK_AND_ASSERT_MES(max_used_block_height < m_blocks.size(), false, "internal error: max used block index=" << max_used_block_height << " is not less then blockchain size = " << m_blocks.size()); get_block_hash(m_blocks[max_used_block_height].bl, max_used_block_id); return true; } //------------------------------------------------------------------ bool blockchain_storage::have_tx_keyimges_as_spent(const transaction &tx) { BOOST_FOREACH(const txin_v& in, tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, in_to_key, true); if(have_tx_keyimg_as_spent(in_to_key.k_image)) return true; } return false; } //------------------------------------------------------------------ bool blockchain_storage::check_tx_inputs(const transaction& tx, uint64_t* pmax_used_block_height) { crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx); return check_tx_inputs(tx, tx_prefix_hash, pmax_used_block_height); } //------------------------------------------------------------------ bool blockchain_storage::check_tx_inputs(const transaction& tx, const crypto::hash& tx_prefix_hash, uint64_t* pmax_used_block_height) { size_t sig_index = 0; if(pmax_used_block_height) *pmax_used_block_height = 0; BOOST_FOREACH(const auto& txin, tx.vin) { CHECK_AND_ASSERT_MES(txin.type() == typeid(txin_to_key), false, "wrong type id in tx input at blockchain_storage::check_tx_inputs"); const txin_to_key& in_to_key = boost::get<txin_to_key>(txin); CHECK_AND_ASSERT_MES(in_to_key.key_offsets.size(), false, "empty in_to_key.key_offsets in transaction with id " << get_transaction_hash(tx)); if(have_tx_keyimg_as_spent(in_to_key.k_image)) { LOG_PRINT_L1("Key image already spent in blockchain: " << string_tools::pod_to_hex(in_to_key.k_image)); return false; } std::vector<crypto::signature> sig_stub; const std::vector<crypto::signature>* psig = &sig_stub; if (!m_is_in_checkpoint_zone) { CHECK_AND_ASSERT_MES(sig_index < tx.signatures.size(), false, "wrong transaction: not signature entry for input with index= " << sig_index); psig = &tx.signatures[sig_index]; } if (!check_tx_input(in_to_key, tx_prefix_hash, *psig, pmax_used_block_height)) { LOG_PRINT_L0("Failed to check ring signature for tx " << get_transaction_hash(tx)); return false; } sig_index++; } if (!m_is_in_checkpoint_zone) { CHECK_AND_ASSERT_MES(tx.signatures.size() == sig_index, false, "tx signatures count differs from inputs"); } return true; } //------------------------------------------------------------------ bool blockchain_storage::is_tx_spendtime_unlocked(uint64_t unlock_time) { if(unlock_time < CURRENCY_MAX_BLOCK_NUMBER) { //interpret as block index if(get_current_blockchain_height()-1 + CURRENCY_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time) return true; else return false; }else { //interpret as time uint64_t current_time = static_cast<uint64_t>(time(NULL)); if(current_time + CURRENCY_LOCKED_TX_ALLOWED_DELTA_SECONDS >= unlock_time) return true; else return false; } return false; } //------------------------------------------------------------------ bool blockchain_storage::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, uint64_t* pmax_related_block_height) { CRITICAL_REGION_LOCAL(m_blockchain_lock); struct outputs_visitor { std::vector<const crypto::public_key *>& m_results_collector; blockchain_storage& m_bch; outputs_visitor(std::vector<const crypto::public_key *>& results_collector, blockchain_storage& bch):m_results_collector(results_collector), m_bch(bch) {} bool handle_output(const transaction& tx, const tx_out& out) { //check tx unlock time if(!m_bch.is_tx_spendtime_unlocked(tx.unlock_time)) { LOG_PRINT_L0("One of outputs for one of inputs have wrong tx.unlock_time = " << tx.unlock_time); return false; } if(out.target.type() != typeid(txout_to_key)) { LOG_PRINT_L0("Output have wrong type id, which=" << out.target.which()); return false; } m_results_collector.push_back(&boost::get<txout_to_key>(out.target).key); return true; } }; //check ring signature std::vector<const crypto::public_key *> output_keys; outputs_visitor vi(output_keys, *this); if(!scan_outputkeys_for_indexes(txin, vi, pmax_related_block_height)) { LOG_PRINT_L0("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size()); return false; } if(txin.key_offsets.size() != output_keys.size()) { LOG_PRINT_L0("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size()); return false; } if(m_is_in_checkpoint_zone) return true; CHECK_AND_ASSERT_MES(sig.size() == output_keys.size(), false, "internal error: tx signatures count=" << sig.size() << " mismatch with outputs keys count for inputs=" << output_keys.size()); return crypto::check_ring_signature(tx_prefix_hash, txin.k_image, output_keys, sig.data()); } //------------------------------------------------------------------ uint64_t blockchain_storage::get_adjusted_time() { //TODO: add collecting median time return time(NULL); } //------------------------------------------------------------------ bool blockchain_storage::check_block_timestamp_main(const block& b) { if(b.timestamp > get_adjusted_time() + CURRENCY_BLOCK_FUTURE_TIME_LIMIT) { LOG_PRINT_L0("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + 2 hours"); return false; } std::vector<uint64_t> timestamps; size_t offset = m_blocks.size() <= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW ? 0: m_blocks.size()- BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW; for(;offset!= m_blocks.size(); ++offset) timestamps.push_back(m_blocks[offset].bl.timestamp); return check_block_timestamp(std::move(timestamps), b); } //------------------------------------------------------------------ bool blockchain_storage::check_block_timestamp(std::vector<uint64_t> timestamps, const block& b) { if(timestamps.size() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) return true; uint64_t median_ts = epee::misc_utils::median(timestamps); if(b.timestamp < median_ts) { LOG_PRINT_L0("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", less than median of last " << BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW << " blocks, " << median_ts); return false; } return true; } //------------------------------------------------------------------ bool blockchain_storage::get_block_for_scratchpad_alt(uint64_t connection_height, uint64_t block_index, std::list<blockchain_storage::blocks_ext_by_hash::iterator>& alt_chain, block & b) { CRITICAL_REGION_LOCAL(m_blockchain_lock); if(block_index >= connection_height) { //take it from alt chain for(auto it: alt_chain) { if(it->second.height == block_index) { b = it->second.bl; return true; } } CHECK_AND_ASSERT_MES(false, false, "Failed to find alternative block with height=" << block_index); }else { b = m_blocks[block_index].bl; } return true; } //------------------------------------------------------------------ bool blockchain_storage::prune_aged_alt_blocks() { CRITICAL_REGION_LOCAL(m_blockchain_lock); uint64_t current_height = get_current_blockchain_height(); for(auto it = m_alternative_chains.begin(); it != m_alternative_chains.end();) { if( current_height > it->second.height && current_height - it->second.height > CURRENCY_ALT_BLOCK_LIVETIME_COUNT) m_alternative_chains.erase(it++); else ++it; } return true; } //------------------------------------------------------------------ bool blockchain_storage::handle_block_to_main_chain(const block& bl, const crypto::hash& id, block_verification_context& bvc) { TIME_MEASURE_START(block_processing_time); CRITICAL_REGION_LOCAL(m_blockchain_lock); if(bl.prev_id != get_top_block_id()) { LOG_PRINT_L0("Block with id: " << id << ENDL << "have wrong prev_id: " << bl.prev_id << ENDL << "expected: " << get_top_block_id()); return false; } if(!check_block_timestamp_main(bl)) { LOG_PRINT_L0("Block with id: " << id << ENDL << "have invalid timestamp: " << bl.timestamp); //add_block_as_invalid(bl, id);//do not add blocks to invalid storage befor proof of work check was passed bvc.m_verifivation_failed = true; return false; } //check proof of work TIME_MEASURE_START(target_calculating_time); wide_difficulty_type current_diffic = get_difficulty_for_next_block(); CHECK_AND_ASSERT_MES(current_diffic, false, "!!!!!!!!! difficulty overhead !!!!!!!!!"); TIME_MEASURE_FINISH(target_calculating_time); TIME_MEASURE_START(longhash_calculating_time); crypto::hash proof_of_work = null_hash; proof_of_work = get_block_longhash(bl, m_blocks.size(), [&](uint64_t index) -> crypto::hash& { return m_scratchpad[index%m_scratchpad.size()]; }); if(!check_hash(proof_of_work, current_diffic)) { LOG_PRINT_L0("Block with id: " << id << ENDL << "have not enough proof of work: " << proof_of_work << ENDL << "nexpected difficulty: " << current_diffic ); bvc.m_verifivation_failed = true; return false; } if(m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height())) { m_is_in_checkpoint_zone = true; if(!m_checkpoints.check_block(get_current_blockchain_height(), id)) { LOG_ERROR("CHECKPOINT VALIDATION FAILED"); bvc.m_verifivation_failed = true; return false; } }else m_is_in_checkpoint_zone = false; TIME_MEASURE_FINISH(longhash_calculating_time); if(!prevalidate_miner_transaction(bl, m_blocks.size())) { LOG_PRINT_L0("Block with id: " << id << " failed to pass prevalidation"); bvc.m_verifivation_failed = true; return false; } size_t coinbase_blob_size = get_object_blobsize(bl.miner_tx); size_t cumulative_block_size = coinbase_blob_size; //process transactions if(!add_transaction_from_block(bl.miner_tx, get_transaction_hash(bl.miner_tx), id, get_current_blockchain_height())) { LOG_PRINT_L0("Block with id: " << id << " failed to add transaction to blockchain storage"); bvc.m_verifivation_failed = true; return false; } size_t tx_processed_count = 0; uint64_t fee_summary = 0; BOOST_FOREACH(const crypto::hash& tx_id, bl.tx_hashes) { transaction tx; size_t blob_size = 0; uint64_t fee = 0; if(!m_tx_pool.take_tx(tx_id, tx, blob_size, fee)) { LOG_PRINT_L0("Block with id: " << id << "have at least one unknown transaction with id: " << tx_id); purge_block_data_from_blockchain(bl, tx_processed_count); //add_block_as_invalid(bl, id); bvc.m_verifivation_failed = true; return false; } //If we under checkpoints, ring signatures should be pruned if(m_is_in_checkpoint_zone) { tx.signatures.clear(); } if(!check_tx_inputs(tx)) { LOG_PRINT_L0("Block with id: " << id << "have at least one transaction (id: " << tx_id << ") with wrong inputs."); currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc); bool add_res = m_tx_pool.add_tx(tx, tvc, true); CHECK_AND_ASSERT_MES2(add_res, "handle_block_to_main_chain: failed to add transaction back to transaction pool"); purge_block_data_from_blockchain(bl, tx_processed_count); add_block_as_invalid(bl, id); LOG_PRINT_L0("Block with id " << id << " added as invalid becouse of wrong inputs in transactions"); bvc.m_verifivation_failed = true; return false; } if(!add_transaction_from_block(tx, tx_id, id, get_current_blockchain_height())) { LOG_PRINT_L0("Block with id: " << id << " failed to add transaction to blockchain storage"); currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc); bool add_res = m_tx_pool.add_tx(tx, tvc, true); CHECK_AND_ASSERT_MES2(add_res, "handle_block_to_main_chain: failed to add transaction back to transaction pool"); purge_block_data_from_blockchain(bl, tx_processed_count); bvc.m_verifivation_failed = true; return false; } fee_summary += fee; cumulative_block_size += blob_size; ++tx_processed_count; } uint64_t base_reward = 0; uint64_t already_generated_coins = m_blocks.size() ? m_blocks.back().already_generated_coins:0; uint64_t already_donated_coins = m_blocks.size() ? m_blocks.back().already_donated_coins:0; uint64_t donation_total = 0; if(!validate_miner_transaction(bl, cumulative_block_size, fee_summary, base_reward, already_generated_coins, already_donated_coins, donation_total)) { LOG_PRINT_L0("Block with id: " << id << " have wrong miner transaction"); purge_block_data_from_blockchain(bl, tx_processed_count); bvc.m_verifivation_failed = true; return false; } block_extended_info bei = boost::value_initialized<block_extended_info>(); bei.bl = bl; bei.scratch_offset = m_scratchpad.size(); bei.block_cumulative_size = cumulative_block_size; bei.cumulative_difficulty = current_diffic; bei.already_generated_coins = already_generated_coins + base_reward; bei.already_donated_coins = already_donated_coins + donation_total; if(m_blocks.size()) bei.cumulative_difficulty += m_blocks.back().cumulative_difficulty; bei.height = m_blocks.size(); auto ind_res = m_blocks_index.insert(std::pair<crypto::hash, size_t>(id, bei.height)); if(!ind_res.second) { LOG_ERROR("block with id: " << id << " already in block indexes"); purge_block_data_from_blockchain(bl, tx_processed_count); bvc.m_verifivation_failed = true; return false; } //append to scratchpad if(!push_block_scratchpad_data(bl, m_scratchpad)) { LOG_ERROR("Internal error for block id: " << id << ": failed to put_block_scratchpad_data"); purge_block_data_from_blockchain(bl, tx_processed_count); bvc.m_verifivation_failed = true; return false; } #ifdef ENABLE_HASHING_DEBUG LOG_PRINT_L3("SCRATCHPAD_SHOT FOR H=" << bei.height+1 << ENDL << dump_scratchpad(m_scratchpad)); #endif m_blocks.push_back(bei); update_next_comulative_size_limit(); TIME_MEASURE_FINISH(block_processing_time); LOG_PRINT_L1("+++++ BLOCK SUCCESSFULLY ADDED" << ENDL << "id:\t" << id << ENDL << "PoW:\t" << proof_of_work << ENDL << "HEIGHT " << bei.height << ", difficulty:\t" << current_diffic << ENDL << "block reward: " << print_money(fee_summary + base_reward) << "(" << print_money(base_reward) << " + " << print_money(fee_summary) << ")" << ( (bei.height%CURRENCY_DONATIONS_INTERVAL)?std::string(""):std::string("donation: ") + print_money(donation_total) ) << ", coinbase_blob_size: " << coinbase_blob_size << ", cumulative size: " << cumulative_block_size << ", " << block_processing_time << "("<< target_calculating_time << "/" << longhash_calculating_time << ")ms"); bvc.m_added_to_main_chain = true; m_tx_pool.on_blockchain_inc(bei.height, id); //LOG_PRINT_L0("BLOCK: " << ENDL << "" << dump_obj_as_json(bei.bl)); return true; } //------------------------------------------------------------------ bool blockchain_storage::update_next_comulative_size_limit() { std::vector<size_t> sz; get_last_n_blocks_sizes(sz, CURRENCY_REWARD_BLOCKS_WINDOW); uint64_t median = misc_utils::median(sz); if(median <= CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE) median = CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE; m_current_block_cumul_sz_limit = median*2; return true; } //------------------------------------------------------------------ bool blockchain_storage::add_new_block(const block& bl_, block_verification_context& bvc) { //copy block here to let modify block.target block bl = bl_; crypto::hash id = get_block_hash(bl); CRITICAL_REGION_LOCAL(m_tx_pool);//to avoid deadlock lets lock tx_pool for whole add/reorganize process CRITICAL_REGION_LOCAL1(m_blockchain_lock); if(have_block(id)) { LOG_PRINT_L3("block with id = " << id << " already exists"); bvc.m_already_exists = true; return false; } //check that block refers to chain tail if(!(bl.prev_id == get_top_block_id())) { //chain switching or wrong block bvc.m_added_to_main_chain = false; bool r = handle_alternative_block(bl, id, bvc); return r; //never relay alternative blocks } return handle_block_to_main_chain(bl, id, bvc); }
41.482393
297
0.663049
UScrypto
91beb4ae0b8f9ec855d9a00590a37a36cd0602a0
6,099
cpp
C++
src/sampling.cpp
Algebraicphylogenetics/Empar
1c2b4eec4ac0917c65786acf36de4b906d95715c
[ "MIT" ]
null
null
null
src/sampling.cpp
Algebraicphylogenetics/Empar
1c2b4eec4ac0917c65786acf36de4b906d95715c
[ "MIT" ]
null
null
null
src/sampling.cpp
Algebraicphylogenetics/Empar
1c2b4eec4ac0917c65786acf36de4b906d95715c
[ "MIT" ]
null
null
null
/* * sampling.cpp * * Created by Ania M. Kedzierska on 11/11/11. * Copyright 2011 Politecnic University of Catalonia, Center for Genomic Regulation. This is program can be redistributed, modified or else as given by the terms of the GNU General Public License. * */ #include <iostream> #include <cstdlib> #include "random.h" #include "sampling.h" #include "miscelania.h" #include "em.h" #include <stdexcept> #include "boost/math/distributions/chi_squared.hpp" Counts data; // Produces random parameters without length restriction. void random_parameters(Model &Mod, Parameters &Par){ long k; if (Par.nalpha != Mod.nalpha) { throw std::out_of_range( "Number of states in model does not match parameters"); } for(k=0; k < Par.nedges; k++) { Mod.random_edge(Par.tm[k]); } Mod.random_root(Par.r); } // Produces random parameters of given lengths (as given inside Par). // The lengths are given as a vector matching the list of edges. // The generated parameters are biologically meaningful ( DLC as in Chang, 1966), i.e. every diagonal entry is the largest in its column. void random_parameters_length(Tree &T, Model &Mod, Parameters &Par){ long k; if (Par.nalpha != Mod.nalpha) { throw std::length_error("Number of states in model does not match parameters"); } if (T.nedges != Par.nedges) { throw std::length_error( "Number of edges in tree does not match parameters"); } for(k=0; k < Par.nedges; k++) { Mod.random_edge_bio_length((T.edges[k]).br, Par.tm[k]); } Mod.random_root(Par.r); } // Simulates the data used for testing. Stores the data in data and the parameters in Parsim. Counts random_fake_counts(Tree &T, double N, Parameters &Parsim) { long i; // Fills in simulated counts data.N = 0; data.c.resize(T.nstleaves); // assigns memory for (i=0; i < T.nstleaves; i++) { data.c[i] = N*joint_prob_leaves(T, Parsim, i); data.N = data.N + data.c[i]; } // Copies species names. data.species.resize(T.nleaves); // assigns memory for (i=0; i < T.nleaves; i++) { data.species[i] = T.names[i]; } // Fills in the rest of the struct. data.nalpha = 4; data.nspecies = T.nleaves; data.nstates = T.nstleaves; return data; } // Puts a random state on st, following the given model and parameters. void random_state(Tree &T, Model &Mod, Parameters &Par, State &st) { long i, e; bool updated; if (st.len != T.nnodes) { std::cout << "Tree and state are not compatible." << std::endl; } // reset the state to a negative value. for(i=0; i < st.len; i++) st.s[i] = -1; // random state on the root. st.s[T.nleaves] = discrete(Par.r); updated = true; while(updated) { updated = false; // run over the edges, and update any states necessary for(e=0; e < T.nedges; e++) { // if there is something to be updated if (st.s[T.edges[e].s] >= 0 && st.s[T.edges[e].t] < 0) { updated = true; st.s[T.edges[e].t] = discrete(Par.tm[e][st.s[T.edges[e].s]]); } } } } // Simulates counts for the full observable and hidden state matrix F. void random_full_counts(Tree &T, Model &Mod, Parameters &Par, long length, Matrix &F) { long i, j, k; long a, b; State st, sth, stl; create_state(st, T.nnodes, T.nalpha); create_state(sth, T.nhidden, T.nalpha); create_state(stl, T.nleaves, T.nalpha); for(i=0; i < T.nstleaves; i++) { for(j=0; j < T.nsthidden; j++) { F.m[i][j] = 0; } } for (k=0; k < length; k++) { random_state(T, Mod, Par, st); // the first nleaves nodes are the leaves for (i=0; i < T.nleaves; i++) { stl.s[i] = st.s[i]; } for (i=T.nleaves; i < T.nnodes; i++) { sth.s[i - T.nleaves] = st.s[i]; } a = state2index(stl); b = state2index(sth); F.m[a][b] = F.m[a][b] + 1.; } } // Simulates an alignment for a given tree, model and parameters. void random_data(Tree &T, Model &Mod, Parameters &Par, long length, Alignment &align) { if (T.nedges != Par.nedges) { std::cout << "Error: Tree and Parameters are not compatible" << std::endl; } long i, j; State st; create_state(st, T.nnodes, T.nalpha); // The 4 DNA bases: align.nalpha = 4; align.alpha.resize(align.nalpha); align.alpha[0] = 'A'; align.alpha[1] = 'C'; align.alpha[2] = 'G'; align.alpha[3] = 'T'; align.nspecies = T.nleaves; align.len = length; align.seq.resize(align.nspecies); align.name.resize(align.nspecies); for (i=0; i < align.nspecies; i++) { (align.seq[i]).resize(length); align.name[i] = T.names[i]; } for (i=0; i < length; i++) { random_state(T, Mod, Par, st); for (j=0; j < align.nspecies; j++) { // the first nleaves nodes are the leaves align.seq[j][i] = st.s[j]; } } } // Checks if a matrix tm belongs to a given model( for matrices generated during sampling). bool check_model_matrix(Model &Mod, TMatrix &tm) { long i, j, k, l; long a, b; for(i=0; i < Mod.nalpha; i++) { for(j=0; j < Mod.nalpha; j++) { for(k=0; k < Mod.nalpha; k++) { for(l=0; l < Mod.nalpha; l++) { a = Mod.matrix_structure(i, j); b = Mod.matrix_structure(k, l); if (a == b && tm[i][j] != tm[k][l]) { return false; } } } } } return true; } bool check_DLC_matrix(TMatrix &tm) { long i0; for (unsigned long i=0; i < tm[0].size(); i++) { i0 = max_in_col(tm, i); if (i0 != (long)i) return false; } return true; } bool check_matrix_length(double len, TMatrix &tm) { double clen; double eps = 1e-10; clen = branch_length(tm, tm.size()); if (boost::math::isnan(clen)) return false; if (fabs(clen - len) > eps) return false; else return true; } bool check_matrix_stochastic(TMatrix &tm) { double sum; double eps = 1e-10; for(unsigned long i=0; i < tm.size(); i++) { sum = 0; for(unsigned long j=0; j < tm[i].size(); j++) { if (tm[i][j] < 0) return false; sum = sum + tm[i][j]; } if (fabs(sum - 1) > eps) return false; } return true; }
24.493976
198
0.608296
Algebraicphylogenetics
91c0c554e64ab6821ac74d4128dec9d00830a099
1,761
cc
C++
nlp-automl/src/model/CreateDatasetRecordRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
nlp-automl/src/model/CreateDatasetRecordRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
nlp-automl/src/model/CreateDatasetRecordRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/nlp-automl/model/CreateDatasetRecordRequest.h> using AlibabaCloud::Nlp_automl::Model::CreateDatasetRecordRequest; CreateDatasetRecordRequest::CreateDatasetRecordRequest() : RpcServiceRequest("nlp-automl", "2019-11-11", "CreateDatasetRecord") { setMethod(HttpRequest::Method::Post); } CreateDatasetRecordRequest::~CreateDatasetRecordRequest() {} std::string CreateDatasetRecordRequest::getDatasetRecord()const { return datasetRecord_; } void CreateDatasetRecordRequest::setDatasetRecord(const std::string& datasetRecord) { datasetRecord_ = datasetRecord; setBodyParameter("DatasetRecord", datasetRecord); } long CreateDatasetRecordRequest::getDatasetId()const { return datasetId_; } void CreateDatasetRecordRequest::setDatasetId(long datasetId) { datasetId_ = datasetId; setBodyParameter("DatasetId", std::to_string(datasetId)); } long CreateDatasetRecordRequest::getProjectId()const { return projectId_; } void CreateDatasetRecordRequest::setProjectId(long projectId) { projectId_ = projectId; setBodyParameter("ProjectId", std::to_string(projectId)); }
27.952381
84
0.767178
aliyun
91c4cbd4d21cadea7cd6e77cfe1d4d540c861c9b
1,181
cpp
C++
c++/leetcode/0953-Verifying_an_Alien_Dictionary-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/0953-Verifying_an_Alien_Dictionary-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/0953-Verifying_an_Alien_Dictionary-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
// 953 Verifying an Alien Dictionary // https://leetcode.com/problems/verifying-an-alien-dictionary // version: 1; create time: 2020-01-14 22:54:25; class Solution { public: bool isAlienSorted(vector<string>& words, string order) { int order_index[26]; for (int i = 0; i < 26; ++i) { const auto c = order[i]; order_index[c - 'a'] = i; } const int n = words.size(); const auto is_sorted = [&](const string& w0, const string& w1) { const int m = std::min(w0.size(), w1.size()); for (int j = 0; j < m; ++j) { const int idx0 = w0[j] - 'a'; const int idx1 = w1[j] - 'a'; if (order_index[idx0] > order_index[idx1]) { return false; } else if (order_index[idx0] < order_index[idx1]) { return true; } } return w0.size() <= w1.size(); }; if (n <= 1) return true; for (int i = 1; i < n; ++i) { if (!is_sorted(words[i-1], words[i])) { return false; } } return true; } };
31.918919
72
0.458933
levendlee
91c72ac9ce76c638fd476ad637785c2dc856d710
9,391
cpp
C++
dwarf/SB/Core/x/xMovePoint.cpp
stravant/bfbbdecomp
2126be355a6bb8171b850f829c1f2731c8b5de08
[ "OLDAP-2.7" ]
1
2021-01-05T11:28:55.000Z
2021-01-05T11:28:55.000Z
dwarf/SB/Core/x/xMovePoint.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
null
null
null
dwarf/SB/Core/x/xMovePoint.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
1
2022-03-30T15:15:08.000Z
2022-03-30T15:15:08.000Z
typedef struct xLinkAsset; typedef struct xMovePoint; typedef struct xMovePointAsset; typedef struct xEnt; typedef struct xBaseAsset; typedef struct xVec3; typedef struct xEnv; typedef struct xSerial; typedef struct xCoef; typedef struct xSpline3; typedef struct xCoef3; typedef struct xScene; typedef struct xMemPool; typedef struct xBase; typedef int32(*type_0)(xBase*, xBase*, uint32, float32*, xBase*); typedef xBase*(*type_1)(uint32); typedef int8*(*type_2)(xBase*); typedef int8*(*type_3)(uint32); typedef void(*type_6)(xMemPool*, void*); typedef float32 type_4[4]; typedef uint8 type_5[2]; typedef float32 type_7[4]; typedef xVec3 type_8[2]; struct xLinkAsset { uint16 srcEvent; uint16 dstEvent; uint32 dstAssetID; float32 param[4]; uint32 paramWidgetAssetID; uint32 chkAssetID; }; struct xMovePoint : xBase { xMovePointAsset* asset; xVec3* pos; xMovePoint** nodes; xMovePoint* prev; uint32 node_wt_sum; uint8 on; uint8 pad[2]; float32 delay; xSpline3* spl; }; struct xMovePointAsset : xBaseAsset { xVec3 pos; uint16 wt; uint8 on; uint8 bezIndex; uint8 flg_props; uint8 pad; uint16 numPoints; float32 delay; float32 zoneRadius; float32 arenaRadius; }; struct xEnt { }; struct xBaseAsset { uint32 id; uint8 baseType; uint8 linkCount; uint16 baseFlags; }; struct xVec3 { float32 x; float32 y; float32 z; }; struct xEnv { }; struct xSerial { }; struct xCoef { float32 a[4]; }; struct xSpline3 { uint16 type; uint16 flags; uint32 N; uint32 allocN; xVec3* points; float32* time; xVec3* p12; xVec3* bctrl; float32* knot; xCoef3* coef; uint32 arcSample; float32* arcLength; }; struct xCoef3 { xCoef x; xCoef y; xCoef z; }; struct xScene { uint32 sceneID; uint16 flags; uint16 num_ents; uint16 num_trigs; uint16 num_stats; uint16 num_dyns; uint16 num_npcs; uint16 num_act_ents; uint16 num_nact_ents; float32 gravity; float32 drag; float32 friction; uint16 num_ents_allocd; uint16 num_trigs_allocd; uint16 num_stats_allocd; uint16 num_dyns_allocd; uint16 num_npcs_allocd; xEnt** trigs; xEnt** stats; xEnt** dyns; xEnt** npcs; xEnt** act_ents; xEnt** nact_ents; xEnv* env; xMemPool mempool; xBase*(*resolvID)(uint32); int8*(*base2Name)(xBase*); int8*(*id2Name)(uint32); }; struct xMemPool { void* FreeList; uint16 NextOffset; uint16 Flags; void* UsedList; void(*InitCB)(xMemPool*, void*); void* Buffer; uint16 Size; uint16 NumRealloc; uint32 Total; }; struct xBase { uint32 id; uint8 baseType; uint8 linkCount; uint16 baseFlags; xLinkAsset* link; int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*); }; uint32 gActiveHeap; xVec3* xMovePointGetPos(xMovePoint* m); float32 xMovePointGetNext(xMovePoint* m, xMovePoint* prev, xMovePoint** next, xVec3* hdng); void xMovePointSplineDestroy(xMovePoint* m); void xMovePointSplineSetup(xMovePoint* m); void xMovePointSetup(xMovePoint* m, xScene* sc); void xMovePointReset(xMovePoint* m); void xMovePointLoad(xMovePoint* ent, xSerial* s); void xMovePointSave(xMovePoint* ent, xSerial* s); void xMovePointInit(xMovePoint* m, xMovePointAsset* asset); // xMovePointGetPos__FPC10xMovePoint // Start address: 0x1f2870 xVec3* xMovePointGetPos(xMovePoint* m) { // Line 271, Address: 0x1f2870, Func Offset: 0 // Func End, Address: 0x1f2878, Func Offset: 0x8 } // xMovePointGetNext__FPC10xMovePointPC10xMovePointPP10xMovePointP5xVec3 // Start address: 0x1f2880 float32 xMovePointGetNext(xMovePoint* m, xMovePoint* prev, xMovePoint** next, xVec3* hdng) { int32 rnd; uint16 idx; xMovePoint* previousOption; // Line 208, Address: 0x1f2880, Func Offset: 0 // Line 214, Address: 0x1f28a8, Func Offset: 0x28 // Line 216, Address: 0x1f28b8, Func Offset: 0x38 // Line 217, Address: 0x1f28c4, Func Offset: 0x44 // Line 222, Address: 0x1f28c8, Func Offset: 0x48 // Line 223, Address: 0x1f28e4, Func Offset: 0x64 // Line 226, Address: 0x1f28f0, Func Offset: 0x70 // Line 227, Address: 0x1f2908, Func Offset: 0x88 // Line 230, Address: 0x1f2910, Func Offset: 0x90 // Line 227, Address: 0x1f2914, Func Offset: 0x94 // Line 230, Address: 0x1f2918, Func Offset: 0x98 // Line 233, Address: 0x1f2920, Func Offset: 0xa0 // Line 241, Address: 0x1f2928, Func Offset: 0xa8 // Line 244, Address: 0x1f2930, Func Offset: 0xb0 // Line 247, Address: 0x1f2938, Func Offset: 0xb8 // Line 250, Address: 0x1f2940, Func Offset: 0xc0 // Line 252, Address: 0x1f2960, Func Offset: 0xe0 // Line 255, Address: 0x1f296c, Func Offset: 0xec // Line 256, Address: 0x1f2974, Func Offset: 0xf4 // Line 258, Address: 0x1f2980, Func Offset: 0x100 // Line 259, Address: 0x1f298c, Func Offset: 0x10c // Line 261, Address: 0x1f2990, Func Offset: 0x110 // Line 262, Address: 0x1f2998, Func Offset: 0x118 // Line 264, Address: 0x1f2a88, Func Offset: 0x208 // Line 265, Address: 0x1f2a90, Func Offset: 0x210 // Func End, Address: 0x1f2ab0, Func Offset: 0x230 } // xMovePointSplineDestroy__FP10xMovePoint // Start address: 0x1f2ab0 void xMovePointSplineDestroy(xMovePoint* m) { // Line 174, Address: 0x1f2ab0, Func Offset: 0 // Line 176, Address: 0x1f2abc, Func Offset: 0xc // Line 178, Address: 0x1f2ac0, Func Offset: 0x10 // Func End, Address: 0x1f2ac8, Func Offset: 0x18 } // xMovePointSplineSetup__FP10xMovePoint // Start address: 0x1f2ad0 void xMovePointSplineSetup(xMovePoint* m) { xMovePoint* w0; xMovePoint* w2; xMovePoint* w3; xVec3 points[2]; xVec3 p1; xVec3 p2; // Line 123, Address: 0x1f2ad0, Func Offset: 0 // Line 130, Address: 0x1f2ad4, Func Offset: 0x4 // Line 123, Address: 0x1f2ad8, Func Offset: 0x8 // Line 130, Address: 0x1f2ae4, Func Offset: 0x14 // Line 137, Address: 0x1f2b00, Func Offset: 0x30 // Line 139, Address: 0x1f2b04, Func Offset: 0x34 // Line 141, Address: 0x1f2b08, Func Offset: 0x38 // Line 139, Address: 0x1f2b0c, Func Offset: 0x3c // Line 141, Address: 0x1f2b10, Func Offset: 0x40 // Line 144, Address: 0x1f2b28, Func Offset: 0x58 // Line 146, Address: 0x1f2b38, Func Offset: 0x68 // Line 147, Address: 0x1f2b3c, Func Offset: 0x6c // Line 146, Address: 0x1f2b40, Func Offset: 0x70 // Line 147, Address: 0x1f2b44, Func Offset: 0x74 // Line 148, Address: 0x1f2b5c, Func Offset: 0x8c // Line 149, Address: 0x1f2b78, Func Offset: 0xa8 // Line 150, Address: 0x1f2b90, Func Offset: 0xc0 // Line 157, Address: 0x1f2b98, Func Offset: 0xc8 // Line 158, Address: 0x1f2bd0, Func Offset: 0x100 // Line 159, Address: 0x1f2bec, Func Offset: 0x11c // Line 160, Address: 0x1f2c08, Func Offset: 0x138 // Line 161, Address: 0x1f2c24, Func Offset: 0x154 // Line 162, Address: 0x1f2c40, Func Offset: 0x170 // Line 163, Address: 0x1f2c5c, Func Offset: 0x18c // Line 167, Address: 0x1f2c78, Func Offset: 0x1a8 // Line 168, Address: 0x1f2c98, Func Offset: 0x1c8 // Line 169, Address: 0x1f2ca4, Func Offset: 0x1d4 // Line 170, Address: 0x1f2ca8, Func Offset: 0x1d8 // Func End, Address: 0x1f2cb8, Func Offset: 0x1e8 } // xMovePointSetup__FP10xMovePointP6xScene // Start address: 0x1f2cc0 void xMovePointSetup(xMovePoint* m, xScene* sc) { uint32* id; uint16 idx; // Line 98, Address: 0x1f2cc0, Func Offset: 0 // Line 106, Address: 0x1f2ce4, Func Offset: 0x24 // Line 107, Address: 0x1f2cec, Func Offset: 0x2c // Line 109, Address: 0x1f2cf0, Func Offset: 0x30 // Line 113, Address: 0x1f2d08, Func Offset: 0x48 // Line 119, Address: 0x1f2d18, Func Offset: 0x58 // Line 118, Address: 0x1f2d20, Func Offset: 0x60 // Line 113, Address: 0x1f2d24, Func Offset: 0x64 // Line 116, Address: 0x1f2d2c, Func Offset: 0x6c // Line 118, Address: 0x1f2d4c, Func Offset: 0x8c // Line 119, Address: 0x1f2d5c, Func Offset: 0x9c // Line 120, Address: 0x1f2d70, Func Offset: 0xb0 // Func End, Address: 0x1f2d90, Func Offset: 0xd0 } // xMovePointReset__FP10xMovePoint // Start address: 0x1f2d90 void xMovePointReset(xMovePoint* m) { // Line 85, Address: 0x1f2d90, Func Offset: 0 // Line 90, Address: 0x1f2d9c, Func Offset: 0xc // Line 93, Address: 0x1f2da8, Func Offset: 0x18 // Line 94, Address: 0x1f2db4, Func Offset: 0x24 // Line 95, Address: 0x1f2dc0, Func Offset: 0x30 // Func End, Address: 0x1f2dd0, Func Offset: 0x40 } // xMovePointLoad__FP10xMovePointP7xSerial // Start address: 0x1f2dd0 void xMovePointLoad(xMovePoint* ent, xSerial* s) { // Line 78, Address: 0x1f2dd0, Func Offset: 0 // Func End, Address: 0x1f2dd8, Func Offset: 0x8 } // xMovePointSave__FP10xMovePointP7xSerial // Start address: 0x1f2de0 void xMovePointSave(xMovePoint* ent, xSerial* s) { // Line 59, Address: 0x1f2de0, Func Offset: 0 // Func End, Address: 0x1f2de8, Func Offset: 0x8 } // xMovePointInit__FP10xMovePointP15xMovePointAsset // Start address: 0x1f2df0 void xMovePointInit(xMovePoint* m, xMovePointAsset* asset) { // Line 24, Address: 0x1f2df0, Func Offset: 0 // Line 28, Address: 0x1f2e04, Func Offset: 0x14 // Line 30, Address: 0x1f2e0c, Func Offset: 0x1c // Line 31, Address: 0x1f2e10, Func Offset: 0x20 // Line 34, Address: 0x1f2e1c, Func Offset: 0x2c // Line 35, Address: 0x1f2e24, Func Offset: 0x34 // Line 36, Address: 0x1f2e2c, Func Offset: 0x3c // Line 38, Address: 0x1f2e34, Func Offset: 0x44 // Line 39, Address: 0x1f2e3c, Func Offset: 0x4c // Line 41, Address: 0x1f2e4c, Func Offset: 0x5c // Line 44, Address: 0x1f2e58, Func Offset: 0x68 // Line 45, Address: 0x1f2e5c, Func Offset: 0x6c // Line 46, Address: 0x1f2e60, Func Offset: 0x70 // Func End, Address: 0x1f2e74, Func Offset: 0x84 }
26.908309
91
0.728676
stravant
91ca9f6c30220237d286d7ad387f085e03f7dc47
9,163
cpp
C++
Plugins/UnLua/Source/UnLua/Private/Registries/ClassRegistry.cpp
xiejiangzhi/UnLua
86ad978f939016caed1d11f803bb79bc73dbdfc1
[ "MIT" ]
1
2022-03-24T02:56:59.000Z
2022-03-24T02:56:59.000Z
Plugins/UnLua/Source/UnLua/Private/Registries/ClassRegistry.cpp
xiejiangzhi/UnLua
86ad978f939016caed1d11f803bb79bc73dbdfc1
[ "MIT" ]
null
null
null
Plugins/UnLua/Source/UnLua/Private/Registries/ClassRegistry.cpp
xiejiangzhi/UnLua
86ad978f939016caed1d11f803bb79bc73dbdfc1
[ "MIT" ]
null
null
null
// Tencent is pleased to support the open source community by making UnLua available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // 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 "Registries/ClassRegistry.h" #include "LuaEnv.h" #include "Binding.h" #include "LowLevel.h" #include "LuaCore.h" #include "UELib.h" #include "ReflectionUtils/ClassDesc.h" extern int32 UObject_Identical(lua_State* L); extern int32 UObject_Delete(lua_State* L); namespace UnLua { TMap<UStruct*, FClassDesc*> FClassRegistry::Classes; TMap<FName, FClassDesc*> FClassRegistry::Name2Classes; FClassRegistry::FClassRegistry(FLuaEnv* Env) : Env(Env) { } TSharedPtr<FClassRegistry> FClassRegistry::Find(const lua_State* L) { const auto Env = FLuaEnv::FindEnv(L); if (Env == nullptr) return nullptr; return Env->GetClassRegistry(); } FClassDesc* FClassRegistry::Find(const char* TypeName) { const FName Key = TypeName; FClassDesc** Ret = Name2Classes.Find(Key); return Ret ? *Ret : nullptr; } FClassDesc* FClassRegistry::Find(const UStruct* Type) { FClassDesc** Ret = Classes.Find(Type); return Ret ? *Ret : nullptr; } FClassDesc* FClassRegistry::RegisterReflectedType(const char* MetatableName) { FClassDesc* Ret = Find(MetatableName); if (Ret) { Classes.FindOrAdd(Ret->AsStruct(), Ret); return Ret; } const char* TypeName = MetatableName[0] == 'U' || MetatableName[0] == 'A' || MetatableName[0] == 'F' ? MetatableName + 1 : MetatableName; const auto Type = LoadReflectedType(TypeName); if (!Type) return nullptr; const auto StructType = Cast<UStruct>(Type); if (StructType) { Ret = RegisterInternal(StructType, UTF8_TO_TCHAR(MetatableName)); return Ret; } const auto EnumType = Cast<UEnum>(Type); if (EnumType) { // TODO: check(false); } return nullptr; } FClassDesc* FClassRegistry::RegisterReflectedType(UStruct* Type) { FClassDesc** Exists = Classes.Find(Type); if (Exists) return *Exists; const auto MetatableName = LowLevel::GetMetatableName(Type); Exists = Name2Classes.Find(FName(MetatableName)); if (Exists) { Classes.Add(Type, *Exists); return *Exists; } const auto Ret = RegisterInternal(Type, MetatableName); return Ret; } bool FClassRegistry::StaticUnregister(const UObjectBase* Type) { FClassDesc* ClassDesc; if (!Classes.RemoveAndCopyValue((UStruct*)Type, ClassDesc)) return false; ClassDesc->UnLoad(); for (auto Pair : FLuaEnv::AllEnvs) { auto Registry = Pair.Value->GetClassRegistry(); Registry->Unregister(ClassDesc); } return true; } bool FClassRegistry::PushMetatable(lua_State* L, const char* MetatableName) { int Type = luaL_getmetatable(L, MetatableName); if (Type == LUA_TTABLE) return true; lua_pop(L, 1); if (FindExportedNonReflectedClass(MetatableName)) return false; FClassDesc* ClassDesc = RegisterReflectedType(MetatableName); if (!ClassDesc) return false; luaL_newmetatable(L, MetatableName); lua_pushstring(L, "__index"); lua_pushcfunction(L, Class_Index); lua_rawset(L, -3); lua_pushstring(L, "__newindex"); lua_pushcfunction(L, Class_NewIndex); lua_rawset(L, -3); uint64 TypeHash = (uint64)ClassDesc->AsStruct(); lua_pushstring(L, "TypeHash"); lua_pushnumber(L, TypeHash); lua_rawset(L, -3); UScriptStruct* ScriptStruct = ClassDesc->AsScriptStruct(); if (ScriptStruct) { lua_pushlightuserdata(L, ClassDesc); lua_pushstring(L, "Copy"); lua_pushvalue(L, -2); lua_pushcclosure(L, ScriptStruct_Copy, 1); lua_rawset(L, -4); lua_pushstring(L, "CopyFrom"); lua_pushvalue(L, -2); lua_pushcclosure(L, ScriptStruct_CopyFrom, 1); lua_rawset(L, -4); lua_pushstring(L, "__eq"); lua_pushvalue(L, -2); lua_pushcclosure(L, ScriptStruct_Compare, 1); lua_rawset(L, -4); lua_pushstring(L, "__gc"); lua_pushvalue(L, -2); lua_pushcclosure(L, ScriptStruct_Delete, 1); lua_rawset(L, -4); lua_pushstring(L, "__call"); lua_pushvalue(L, -2); lua_pushcclosure(L, ScriptStruct_New, 1); // closure lua_rawset(L, -4); lua_pop(L, 1); } else { UClass* Class = ClassDesc->AsClass(); if (Class != UObject::StaticClass() && Class != UClass::StaticClass()) { lua_pushstring(L, "ClassDesc"); lua_pushlightuserdata(L, ClassDesc); lua_rawset(L, -3); lua_pushstring(L, "StaticClass"); lua_pushlightuserdata(L, ClassDesc); lua_pushcclosure(L, Class_StaticClass, 1); lua_rawset(L, -3); lua_pushstring(L, "Cast"); lua_pushcfunction(L, Class_Cast); lua_rawset(L, -3); lua_pushstring(L, "__eq"); lua_pushcfunction(L, UObject_Identical); lua_rawset(L, -3); lua_pushstring(L, "__gc"); lua_pushcfunction(L, UObject_Delete); lua_rawset(L, -3); } } lua_pushvalue(L, -1); // set metatable to self lua_setmetatable(L, -2); TArray<FClassDesc*> ClassDescChain; ClassDesc->GetInheritanceChain(ClassDescChain); TArray<IExportedClass*> ExportedClasses; for (int32 i = ClassDescChain.Num() - 1; i > -1; --i) { auto ExportedClass = FindExportedReflectedClass(*ClassDescChain[i]->GetName()); if (ExportedClass) ExportedClass->Register(L); } UELib::SetTableForClass(L, MetatableName); return true; } bool FClassRegistry::TrySetMetatable(lua_State* L, const char* MetatableName) { if (!PushMetatable(L, MetatableName)) return false; lua_setmetatable(L, -2); return true; } FClassDesc* FClassRegistry::Register(const char* MetatableName) { const auto L = Env->GetMainState(); if (!PushMetatable(L, MetatableName)) return nullptr; // TODO: refactor lua_pop(L, 1); FName Key = FName(UTF8_TO_TCHAR(MetatableName)); return Name2Classes.FindChecked(Key); } FClassDesc* FClassRegistry::Register(const UStruct* Class) { const auto MetatableName = LowLevel::GetMetatableName(Class); return Register(TCHAR_TO_UTF8(*MetatableName)); } void FClassRegistry::Cleanup() { for (const auto Pair : Name2Classes) delete Pair.Value; Name2Classes.Empty(); Classes.Empty(); } UField* FClassRegistry::LoadReflectedType(const char* InName) { FString Name = UTF8_TO_TCHAR(InName); // find candidates in memory UField* Ret = FindObject<UClass>(ANY_PACKAGE, *Name); if (!Ret) Ret = FindObject<UScriptStruct>(ANY_PACKAGE, *Name); if (!Ret) Ret = FindObject<UEnum>(ANY_PACKAGE, *Name); // load candidates if not found if (!Ret) Ret = LoadObject<UClass>(nullptr, *Name); if (!Ret) Ret = LoadObject<UScriptStruct>(nullptr, *Name); if (!Ret) Ret = LoadObject<UEnum>(nullptr, *Name); return Ret; } FClassDesc* FClassRegistry::RegisterInternal(UStruct* Type, const FString& Name) { check(Type); check(!Classes.Contains(Type)); FClassDesc* ClassDesc = new FClassDesc(Type, Name); Classes.Add(Type, ClassDesc); Name2Classes.Add(FName(*Name), ClassDesc); return ClassDesc; } void FClassRegistry::Unregister(const FClassDesc* ClassDesc) { const auto L = Env->GetMainState(); const auto MetatableName = ClassDesc->GetName(); lua_pushnil(L); lua_setfield(L, LUA_REGISTRYINDEX, TCHAR_TO_UTF8(*MetatableName)); } }
30.141447
145
0.58889
xiejiangzhi
91cadaf1f75cbf8a4c49b75247976a88e84dacc1
827
cpp
C++
soj/3845.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
soj/3845.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
soj/3845.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> int p[300]; int Parent(int n) {     if (p[n]==-1)         return n;     return p[n]=Parent(p[n]); } void Swap(int &a,int &b) {     int temp=a;     a=b;     b=temp; } int main() {     int n,m;     int a,b;     int i,count;     while (scanf("%d%d",&n,&m)==2)     {         memset(p,-1,sizeof(p));         while (m--)         {             scanf("%d%d",&a,&b);             a=Parent(a);             b=Parent(b);             if (a==b)                 continue;             if (b==1)                 Swap(a,b);             p[b]=a;         }         count=0;         for (i=1;i<=n;i++)         {             if (Parent(i)!=1)             {                 printf("%d\n",i);                 count++;             }         }         if (!count)             printf("0\n");     }     return 0; }
15.903846
34
0.336155
huangshenno1
91cd45520970a6e49e6d13c3fd9db0d37fbe06a9
7,968
cpp
C++
libs/ofxCloudPlatform/src/VisionDebug.cpp
SAIC/ofxCloudPlatform
4a97b38cb9be1faf245b9421789e9b43b5645356
[ "MIT" ]
1
2017-11-17T01:20:54.000Z
2017-11-17T01:20:54.000Z
libs/ofxCloudPlatform/src/VisionDebug.cpp
SAIC/ofxCloudPlatform
4a97b38cb9be1faf245b9421789e9b43b5645356
[ "MIT" ]
3
2017-09-30T18:30:08.000Z
2019-11-21T09:14:42.000Z
libs/ofxCloudPlatform/src/VisionDebug.cpp
SAIC/ofxCloudPlatform
4a97b38cb9be1faf245b9421789e9b43b5645356
[ "MIT" ]
1
2017-11-06T12:14:43.000Z
2017-11-06T12:14:43.000Z
// // Copyright (c) 2016 Christopher Baker <https://christopherbaker.net> // // SPDX-License-Identifier: MIT // #include "ofx/CloudPlatform/VisionDebug.h" #include "ofGraphics.h" namespace ofx { namespace CloudPlatform { void VisionDebug::draw(const std::string& label, float value, float x, float y, float width, float height) { draw(label, ofToString(value, 2), x, y, width, height); } void VisionDebug::draw(const std::string& label, const std::string& value, float x, float y, float width, float height) { ofPushStyle(); ofFill(); ofSetColor(0, 200); ofDrawRectangle(x, y, width, height); // ofFill(); // ofSetColor(127, 200); // ofDrawRectangle(x, y, width * value, height); ofSetColor(255); ofDrawBitmapStringHighlight(label + "(" + value + ")", x + 5, y + 14); ofNoFill(); ofSetColor(255, 200); ofDrawRectangle(x, y, width, height); ofPopStyle(); } void VisionDebug::draw(const std::string& label, const Likelihood& likelihood, float x, float y, float width, float height) { draw(label + ": " + likelihood.name(), likelihood.value(), x, y, width, height); } void VisionDebug::draw(const FaceAnnotation::Landmark& landmark) { ofColor background= ofColor(0, 80); ofColor foreground = ofColor(0, 0); if (glm::distance(glm::vec3(ofGetMouseX(), ofGetMouseY(), 0), landmark.position()) < 5) { foreground = ofColor(255); background = ofColor(0); } ofDrawBitmapStringHighlight(landmark.name(), landmark.position(), foreground, background); ofNoFill(); ofDrawEllipse(landmark.position().x, landmark.position().y, 10, 10); } void VisionDebug::draw(const FaceAnnotation& annotation) { ofRectangle r = annotation.boundingPoly().getBoundingBox(); annotation.boundingPoly().draw(); annotation.fdBoundingPoly().draw(); for (auto& landmark : annotation.landmarks()) { draw(landmark); } // /// \sa rollAngle() // float _rollAngle; // // /// \sa panAngle() // float _panAngle; // // /// \sa tiltAngle() // float _tiltAngle; if (r.inside(ofGetMouseX(), ofGetMouseY())) { ofPushMatrix(); ofPushStyle(); ofTranslate(ofGetMouseX(), ofGetMouseY()); int height = 25; int yPosition = 10; draw(" JOY", annotation.joyLikelihood(), 10, yPosition+=height); draw(" SORROW", annotation.sorrowLikelihood(), 10, yPosition+=height); draw(" ANGER", annotation.angerLikelihood(), 10, yPosition+=height); draw(" SURPRISE", annotation.surpriseLikelihood(), 10, yPosition+=height); draw("UNDEREXPOSED", annotation.underExposedLikelihood(), 10, yPosition+=height); draw(" BLURRED", annotation.blurredLikelihood(), 10, yPosition+=height); draw(" HEADWARE", annotation.headwearLikelihood(), 10, yPosition+=height); yPosition += height; draw(" Detection confidence: ", annotation.detectionConfidence(), 10, yPosition+=height); draw(" Landmarking confidence: ", annotation.landmarkingConfidence(), 10, yPosition+=height); ofPopStyle(); ofPopMatrix(); } } void VisionDebug::draw(const EntityAnnotation& annotation) { ofRectangle r = annotation.boundingPoly().getBoundingBox(); annotation.boundingPoly().draw(); int height = 25; int yPosition = 10; draw("DESCRIPTION", annotation.description(), 10, yPosition+=height); draw(" LOCALE", annotation.locale(), 10, yPosition+=height); draw(" MID", annotation.mid(), 10, yPosition+=height); draw(" SCORE", annotation.score(), 10, yPosition+=height); draw(" TOPICALITY", annotation.topicality(), 10, yPosition+=height); ofDrawBitmapStringHighlight(annotation.description(), r.x + 14, r.y + 14); } void VisionDebug::draw(const SafeSearchAnnotation& annotation) { ofPushMatrix(); ofPushStyle(); ofTranslate(ofGetMouseX(), ofGetMouseY()); int height = 25; int yPosition = 10; draw(" ADULT", annotation.adult(), 10, yPosition+=height); draw(" SPOOF", annotation.spoof(), 10, yPosition+=height); draw(" MEDICAL", annotation.medical(), 10, yPosition+=height); draw(" RACY", annotation.racy(), 10, yPosition+=height); draw("VIOLENCE", annotation.violence(), 10, yPosition+=height); ofPopStyle(); ofPopMatrix(); } void VisionDebug::draw(const ImagePropertiesAnnotation& annotation) { } void VisionDebug::draw(const std::vector<FaceAnnotation>& annotations) { for (auto& annotation: annotations) draw(annotation); } void VisionDebug::draw(const std::vector<EntityAnnotation>& annotations) { for (auto& annotation: annotations) draw(annotation); } void VisionDebug::draw(const AnnotateImageResponse& response) { draw(response.faceAnnotations()); draw(response.landmarkAnnotations()); draw(response.logoAnnotations()); draw(response.labelAnnotations()); draw(response.textAnnotations()); draw(response.safeSearchAnnotation()); draw(response.imagePropertiesAnnotation()); } void VisionDebug::draw(const std::vector<AnnotateImageResponse>& responses) { for (auto& response: responses) draw(response); } void VisionDebug::draw(const AnnotateImageResponse& response, VisionRequestItem::Feature::Type filterType) { switch (filterType) { case VisionRequestItem::Feature::Type::TYPE_UNSPECIFIED: std::cout << "TYPE_UNSPECIFIED" << std::endl; break; case VisionRequestItem::Feature::Type::FACE_DETECTION: std::cout << "FACE_DETECTION" << std::endl; draw(response.faceAnnotations()); break; case VisionRequestItem::Feature::Type::LANDMARK_DETECTION: std::cout << "LANDMARK_DETECTION" << std::endl; draw(response.landmarkAnnotations()); break; case VisionRequestItem::Feature::Type::LOGO_DETECTION: std::cout << "LOGO_DETECTION" << std::endl; draw(response.logoAnnotations()); break; case VisionRequestItem::Feature::Type::LABEL_DETECTION: std::cout << "LABEL_DETECTION" << std::endl; draw(response.labelAnnotations()); break; case VisionRequestItem::Feature::Type::TEXT_DETECTION: std::cout << "TEXT_DETECTION" << std::endl; draw(response.textAnnotations()); break; case VisionRequestItem::Feature::Type::DOCUMENT_TEXT_DETECTION: std::cout << "DOCUMENT_TEXT_DETECTION" << std::endl; break; case VisionRequestItem::Feature::Type::SAFE_SEARCH_DETECTION: std::cout << "SAFE_SEARCH_DETECTION" << std::endl; draw(response.safeSearchAnnotation()); break; case VisionRequestItem::Feature::Type::IMAGE_PROPERTIES: std::cout << "IMAGE_PROPERTIES" << std::endl; draw(response.imagePropertiesAnnotation()); break; case VisionRequestItem::Feature::Type::CROP_HINTS: std::cout << "CROP_HINTS" << std::endl; break; case VisionRequestItem::Feature::Type::WEB_DETECTION: std::cout << "WEB_DETECTION" << std::endl; break; } } void VisionDebug::draw(const std::vector<AnnotateImageResponse>& responses, VisionRequestItem::Feature::Type filterType) { for (auto& response: responses) draw(response, filterType); } } } // namespace ofx::CloudPlatform
29.511111
101
0.609438
SAIC
91d09f0224cfc20a62bfa40aae3eb3567ed85850
8,847
cxx
C++
PWG/muondep/AliMuonCompactManuStatus.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWG/muondep/AliMuonCompactManuStatus.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWG/muondep/AliMuonCompactManuStatus.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
#include "AliMuonCompactManuStatus.h" #include "AliAnalysisTriggerScalers.h" #include "AliCDBManager.h" #include "AliMUONCDB.h" #include "AliMUONCalibrationData.h" #include "AliMUONPadStatusMaker.h" #include "AliMUONRecoParam.h" #include "AliMUONRejectList.h" #include "AliMpCDB.h" #include "AliMpConstants.h" #include "AliMpDDLStore.h" #include "AliMpDetElement.h" #include "AliMpManuIterator.h" #include "AliMuonCompactMapping.h" #include <cassert> /// \ingroup compact const UInt_t AliMuonCompactManuStatus::MANUBADPEDMASK = ( 1 << 0 ); const UInt_t AliMuonCompactManuStatus::MANUBADHVMASK = ( 1 << 1 ); const UInt_t AliMuonCompactManuStatus::MANUBADLVMASK = (1 << 2 ); const UInt_t AliMuonCompactManuStatus::MANUBADOCCMASK = ( 1 << 3 ); const UInt_t AliMuonCompactManuStatus::MANUOUTOFCONFIGMASK = ( 1 << 4 ); const UInt_t AliMuonCompactManuStatus::MANUREJECTMASK = ( 1 << 5 ); std::string AliMuonCompactManuStatus::CauseAsString(UInt_t cause) { std::string rv = ""; if ( cause & MANUBADPEDMASK ) rv += "_ped"; if ( cause & MANUBADHVMASK ) rv += "_hv"; if ( cause & MANUBADLVMASK ) rv += "_lv"; if ( cause & MANUBADOCCMASK ) rv += "_occ"; if ( cause & MANUOUTOFCONFIGMASK ) rv += "_config"; if ( cause & MANUREJECTMASK ) rv += "_reject"; return rv; } void AliMuonCompactManuStatus::Print(const std::vector<UInt_t>& manuStatus, bool all) { AliMuonCompactMapping* cm = AliMuonCompactMapping::GetCompactMapping(); for ( std::vector<UInt_t>::size_type i = 0; i < manuStatus.size(); ++i ) { Int_t absManuId = cm->AbsManuId(i); Int_t detElemId = cm->GetDetElemIdFromAbsManuId(absManuId); Int_t manuId = cm->GetManuIdFromAbsManuId(absManuId); Int_t busPatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId,manuId); if ( manuStatus[i] || all ) { std::cout << Form("status[%04lu]=%6x (DE %04d BP %04d MANU %04d) %s",i,manuStatus[i],detElemId,busPatchId,manuId,CauseAsString(manuStatus[i]).c_str()) << std::endl; } } } std::vector<UInt_t> AliMuonCompactManuStatus::BuildFromOCDB(Int_t runNumber, const char* ocdbPath) { std::vector<UInt_t> vManuStatus(16828,0); AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(ocdbPath); man->SetRun(runNumber); if (!AliMpDDLStore::Instance()) { AliMpCDB::LoadAll(); } AliMuonCompactMapping* cm = AliMuonCompactMapping::GetCompactMapping(ocdbPath,runNumber); AliMUONCalibrationData cd(runNumber,true); AliMUONRejectList* rl = cd.RejectList(); assert(rl->IsBinary()); AliMUONPadStatusMaker statusMaker(cd); AliMUONRecoParam* recoParam = AliMUONCDB::LoadRecoParam(); statusMaker.SetLimits(*recoParam); AliMpManuIterator it; Int_t detElemId, manuId; // Int_t pedCheck = ( // AliMUONPadStatusMaker::kPedMeanZero | // AliMUONPadStatusMaker::kPedMeanTooLow | // AliMUONPadStatusMaker::kPedMeanTooHigh | // AliMUONPadStatusMaker::kPedSigmaTooLow | // AliMUONPadStatusMaker::kPedSigmaTooHigh ); // // Int_t hvCheck = ( // AliMUONPadStatusMaker::kHVError | // AliMUONPadStatusMaker::kHVTooLow | // AliMUONPadStatusMaker::kHVTooHigh | // AliMUONPadStatusMaker::kHVChannelOFF | // AliMUONPadStatusMaker::kHVSwitchOFF ); // // Int_t occCheck = ( // AliMUONPadStatusMaker::kManuOccupancyTooHigh // ); // // Int_t lvCheck = ( AliMUONPadStatusMaker::kLVTooLow ); Int_t pedCheck = 62; // should really use the enum above, but can't do that until there is an AliRoot tag with that mod, otherwise I break AliPhysics... Int_t hvCheck = 31; Int_t occCheck = 4; Int_t lvCheck = 8; Int_t ntotal(0); Int_t nbad(0); Int_t nbadped=0; Int_t nbadocc=0; Int_t nbadhv=0; Int_t nbadlv=0; Int_t nmissing=0; Int_t nreco=0; Int_t nrejected=0; while ( it.Next(detElemId,manuId) ) { AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); Int_t busPatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId,manuId); UInt_t manuStatus = 0; Int_t manubadped=0; Int_t manubadocc=0; Int_t manubadhv=0; Int_t manubadlv=0; Int_t manumissing=0; Int_t manureject=0; for ( Int_t manuChannel = 0; manuChannel < AliMpConstants::ManuNofChannels(); ++manuChannel ) { if ( de->IsConnectedChannel(manuId,manuChannel) ) { ++ntotal; UInt_t status = statusMaker.PadStatus(detElemId, manuId, manuChannel); //if (!status) continue; if ( status & AliMUONPadStatusMaker::BuildStatus(pedCheck,0,0,0) ) { ++manubadped; } if ( status & AliMUONPadStatusMaker::BuildStatus(0,hvCheck,0,0) ) { ++manubadhv; } if ( status & AliMUONPadStatusMaker::BuildStatus(0,0,lvCheck,0) ) { ++manubadlv; } if ( status & AliMUONPadStatusMaker::BuildStatus(0,0,0,occCheck) ) { ++manubadocc; } if ( status & AliMUONPadStatusMaker::BuildStatus(128 /*AliMUONPadStatusMaker::kMissing*/,0,0,0) ) { ++manumissing; } Float_t proba = TMath::Max(rl->DetectionElementProbability(detElemId),rl->BusPatchProbability(busPatchId)); proba = TMath::Max(proba,rl->ManuProbability(detElemId,manuId)); proba = TMath::Max(proba,rl->ChannelProbability(detElemId,manuId,manuChannel)); if ( proba > 0 ) { ++manureject; } } if ( manubadped>=0.9*de->NofChannelsInManu(manuId) ) { manuStatus |= MANUBADPEDMASK; } if ( manubadhv ) { manuStatus |= MANUBADHVMASK; } if ( manubadlv ) { manuStatus |= MANUBADLVMASK; } if ( manubadocc ) { manuStatus |= MANUBADOCCMASK; } if ( manumissing) { manuStatus |= MANUOUTOFCONFIGMASK; } if ( manureject >= 0.9*de->NofChannelsInManu(manuId) ) { manuStatus |= MANUREJECTMASK; } Int_t manuAbsIndex = cm->FindManuAbsIndex(detElemId,manuId); vManuStatus[manuAbsIndex] = manuStatus; } } assert(ntotal==1064008); man->ClearCache(); return vManuStatus; } void AliMuonCompactManuStatus::WriteToBinaryFile(const char* runlist, const char* outputfile, const char* ocdbPath) { AliAnalysisTriggerScalers ts(runlist,ocdbPath); std::vector<int> vrunlist = ts.GetRunList(); // FIXME: should need to bring in all the AliAnalysisTriggerScalers class just to read the runlist... std::ofstream out(outputfile,std::ios::binary); std::vector<int>::size_type nruns = vrunlist.size(); out.write((char*)&nruns,sizeof(int)); out.write((char*)&vrunlist[0],nruns*sizeof(int)); for ( std::vector<int>::size_type i = 0; i < vrunlist.size(); ++i ) { Int_t runNumber = vrunlist[i]; std::vector<UInt_t> manuStatus = BuildFromOCDB(runNumber,ocdbPath); out.write((char*)&manuStatus[0], manuStatus.size()*sizeof(int)); assert(manuStatus.size()==16828); std::cout << Form("RUN %6d",runNumber) << std::endl; // gObjectTable->Print(); } out.close(); } void AliMuonCompactManuStatus::ReadManuStatus(const char* inputfile, std::map<int,std::vector<UInt_t> >& manuStatusForRuns) { std::ifstream in(inputfile,std::ios::binary); int nruns; in.read((char*)&nruns,sizeof(int)); std::cout << "nruns=" << nruns << std::endl; std::vector<int> vrunlist; vrunlist.resize(nruns,0); std::vector<int> manuStatus; in.read((char*)&vrunlist[0],sizeof(int)*nruns); for ( std::vector<int>::size_type i = 0; i < vrunlist.size(); ++i ) { Int_t runNumber = vrunlist[i]; std::cout << runNumber << " "; manuStatus.resize(16828,0); in.read((char*)&manuStatus[0],sizeof(int)*manuStatus.size()); for ( std::vector<int>::size_type j = 0; j < manuStatus.size(); ++j ) { manuStatusForRuns[runNumber].push_back(manuStatus[j]); } } std::cout << std::endl; }
31.151408
176
0.594552
maroozm
91d1ad6ada1817bead4703de39514f46188fc341
20,599
cpp
C++
Systronix_M24C32.cpp
systronix/Systronix_M24C32
3d9e2e11fd17d7d54978a6dff50076561b9943dc
[ "MIT" ]
null
null
null
Systronix_M24C32.cpp
systronix/Systronix_M24C32
3d9e2e11fd17d7d54978a6dff50076561b9943dc
[ "MIT" ]
null
null
null
Systronix_M24C32.cpp
systronix/Systronix_M24C32
3d9e2e11fd17d7d54978a6dff50076561b9943dc
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <Systronix_M24C32.h> //---------------------------< D E F A U L T C O N S R U C T O R >------------------------------------------ // // default constructor assumes lowest base address // Systronix_M24C32::Systronix_M24C32 (void) { _base = EEP_BASE_MIN; error.total_error_count = 0; // clear the error counter } //---------------------------< D E S T R U C T O R >---------------------------------------------------------- // // destructor // Systronix_M24C32::~Systronix_M24C32 (void) { // Anything to do here? Leave I2C as master? Set flag? } //---------------------------< S E T U P >-------------------------------------------------------------------- // // TODO: merge with begin()? This function doesn't actually do anything, it just sets some private values. It's // redundant and some params must be effectively specified again in begin (Wire net and pins are not independent). what parameters are specified again? [wsk] // uint8_t Systronix_M24C32::setup (uint8_t base, i2c_t3 wire, char* name) { if ((EEP_BASE_MIN > base) || (EEP_BASE_MAX < base)) { i2c_common.tally_transaction (SILLY_PROGRAMMER, &error); return FAIL; } _base = base; _wire = wire; _wire_name = wire_name = name; // protected and public return SUCCESS; } //---------------------------< B E G I N >-------------------------------------------------------------------- // // I2C_PINS_18_19 or I2C_PINS_29_30 // void Systronix_M24C32::begin (i2c_pins pins, i2c_rate rate) { _wire.begin (I2C_MASTER, 0x00, pins, I2C_PULLUP_EXT, rate); // join I2C as master // Serial.printf ("275 lib begin %s\r\n", _wire_name); _wire.setDefaultTimeout (200000); // 200ms } //---------------------------< D E F A U L T B E G I N >---------------------------------------------------- // // // void Systronix_M24C32::begin (void) { _wire.begin(); // initialize I2C as master } //---------------------------< B A S E _ G E T >-------------------------------------------------------------- // // return the I2C base address for this instance // uint8_t Systronix_M24C32::base_get(void) { return _base; } //---------------------------< I N I T >---------------------------------------------------------------------- // // determines if there is a MB85RC256V at _base address by attempting to get an address ack from the device // uint8_t Systronix_M24C32::init (void) { error.exists = true; // necessary to presume that the device exists if (SUCCESS != ping_eeprom()) { error.exists = false; // only place in this file where this can be set false return FAIL; } return SUCCESS; } //---------------------------< S E T _ A D D R 1 6 >---------------------------------------------------------- // // byte order is important. In Teensy memory, a uint16_t is stored least-significant byte in the lower of two // addresses. The eep_addr union allows access to a single eep address as a struct of two bytes (high and // low), as an array of two bytes [0] and [1], or as a uint16_t. // // Given the address 0x123, this function stores it in the eep_addr union as: // eep.control.addr_as_u16: 0x2301 (use get_eep_addr16() to retrieve a properly ordered address) // eep.control.addr_as_struct.low: 0x23 // eep.control.addr_as_struct.high: 0x01 // eep.control.addr_as_array[0]: 0x01 // eep.control.addr_as_array[1]: 0x23 // uint8_t Systronix_M24C32::set_addr16 (uint16_t addr) { if (addr & (ADDRESS_MAX+1)) { i2c_common.tally_transaction (SILLY_PROGRAMMER, &error); return DENIED; // memory address out of bounds } control.addr.as_u16 = __builtin_bswap16 (addr); // byte swap and set the address return SUCCESS; } //---------------------------< G E T _ F R A M _ A D D R 1 6 >------------------------------------------------ // // byte order is important. In Teensy memory, a uint16_t is stored least-significant byte in the lower of two // addresses. The eep_addr union allows access to a single eep address as a struct of two bytes (high and // low), as an array of two bytes [0] and [1], or as a uint16_t. // // Returns eep address as a uint16_t in proper byte order // // See set_addr16() for additional explanation. // uint16_t Systronix_M24C32::get_addr16 (void) { return __builtin_bswap16 (control.addr.as_u16); } //---------------------------< I N C _ A D D R 1 6 >---------------------------------------------------------- // // byte order is important. In Teensy memory, a uint16_t is stored least-significant byte in the lower of two // addresses. The eep_addr union allows access to a single eep address as a struct of two bytes (high and // low), as an array of two bytes [0] and [1], or as a uint16_t. // // This function simplifies keeping track of the current eep address pointer when using current_address_read() // which uses the eep's internal address pointer. Increments the address by one and makes sure that the address // properly wraps from 0x0FFF to 0x0000 instead of going to 0x1000. // // See set_addr16() for additional explanation. // void Systronix_M24C32::inc_addr16 (void) { uint16_t addr = __builtin_bswap16 (control.addr.as_u16); control.addr.as_u16 = __builtin_bswap16 ((++addr & ADDRESS_MAX)); } //---------------------------< A D V _ A D D R 1 6 >---------------------------------------------------------- // // This function advances the current eep address pointer by rd_wr_len when using page_read() or page_write() // to track the eep's internal address pointer. Advances the address and makes sure that the address // properly wraps from 0x0FFF to 0x0000 instead of going to 0x1000. // void Systronix_M24C32::adv_addr16 (void) { uint16_t addr = __builtin_bswap16 (control.addr.as_u16); control.addr.as_u16 = __builtin_bswap16 ((addr + control.rd_wr_len) & ADDRESS_MAX); } //---------------------------< P I N G _ E E P R O M >-------------------------------------------------------- // // send slave address to eeprom to determine if the device exists or is busy. // uint8_t Systronix_M24C32::ping_eeprom (void) { uint8_t ret_val; if (!error.exists) // exit immediately if device does not exist return ABSENT; _wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address ret_val = _wire.endTransmission(); // xmit slave address if (SUCCESS != ret_val) return FAIL; // device did not ack the address return SUCCESS; // device acked the address } //---------------------------< P I N G _ E E P R O M _ T I M E D >-------------------------------------------- // // repeatedly send slave address to eeprom to determine when the device becomes unbusy. Timeout and return FAIL // if device still busy after twait mS; default is 5mS; M24C32-X parts (1.6V-5.5V tW is 10mS max) // uint8_t Systronix_M24C32::ping_eeprom_timed (uint32_t t_wait) { uint8_t ret_val; // uint32_t start_time = millis (); uint32_t end_time = millis () + t_wait; while (millis () <= end_time) { // spin _wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address ret_val = _wire.endTransmission(); // xmit slave address if (SUCCESS == ret_val) return SUCCESS; } return FAIL; // device did not ack the address within the allotted time } //---------------------------< B Y T E _ W R I T E >---------------------------------------------------------- // TODO: make this work // i2c_t3 error returns // beginTransmission: none, void function sets txBufferLength to 1 // write: two address bytes; txBufferLength = 3; return 0 if txBuffer overflow (tx buffer is 259 bytes) // write: a byte; txBufferLength = 4; return zero if overflow // endTransmission: does the write; returns: // 0=success // 1=data too long (as a result of Wire.write() causing an overflow) // 2=recv addr NACK // 3=recv data NACK // 4=other error // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. write the byte to be transmitted into control.wr_byte // 3. call this function // uint8_t Systronix_M24C32::byte_write (void) { uint8_t ret_val; if (!error.exists) // exit immediately if device does not exist return ABSENT; if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS { // it didn't i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } _wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer control.bytes_written += _wire.write (control.wr_byte); // add data byte to the tx buffer if (3 != control.bytes_written) { i2c_common.tally_transaction (WR_INCOMPLETE, &error); // only here 0 is error value since we expected to write more than 0 bytes return FAIL; } ret_val = _wire.endTransmission(); // xmit memory address and data byte if (SUCCESS != ret_val) { i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } i2c_common.tally_transaction (SUCCESS, &error); return SUCCESS; } //---------------------------< I N T 1 6 _ W R I T E >-------------------------------------------------------- // TODO: make this work // writes the two bytes of an int16_t or uint16_t to eep beginning at address in control.addr; ls byte is first. // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. write the 16-bit value to be transmitted into control.wr_int16 (there is no control.wr_uint16) // 3. call this function // uint8_t Systronix_M24C32::int16_write (void) { if (!error.exists) // exit immediately if device does not exist return ABSENT; control.wr_buf_ptr = (uint8_t*)(&control.wr_int16); // point to the int16 member of the control struct control.rd_wr_len = sizeof(uint16_t); // set the write length return page_write (); // do the write and done } //---------------------------< I N T 3 2 _ W R I T E >-------------------------------------------------------- // TODO: make this work // writes the four bytes of an int32_t or uint32_t to eep beginning at address in control.addr; ls byte is first. // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. write the 32-bit value to be transmitted into control.wr_int32 (there is no control.wr_uint32) // 3. call this function // uint8_t Systronix_M24C32::int32_write (void) { if (!error.exists) // exit immediately if device does not exist return ABSENT; control.wr_buf_ptr = (uint8_t*)(&control.wr_int32); // point to the int32 member of the control struct control.rd_wr_len = sizeof(uint32_t); // set the write length return page_write (); // do the write and done } //---------------------------< P A G E _ W R I T E >---------------------------------------------------------- // TODO make this work // writes an array of control.rd_wr_len number of bytes to eep beginning at address in control.addr. 32 bytes // per page write max // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. set control.wr_buf_ptr to point at the array of bytes to be transmitted // 3. set control.rd_wr_len to the number of bytes to be transmitted // 4. call this function // uint8_t Systronix_M24C32::page_write (void) { uint8_t ret_val; if (!error.exists) // exit immediately if device does not exist return ABSENT; if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS { // it didn't i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } _wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer control.bytes_written += _wire.write (control.wr_buf_ptr, control.rd_wr_len); // copy source to wire tx buffer data if (control.bytes_written < (2 + control.rd_wr_len)) // did we try to write too many bytes to the i2c_t3 tx buf? { i2c_common.tally_transaction (WR_INCOMPLETE, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } ret_val = _wire.endTransmission(); // xmit memory address followed by data if (SUCCESS != ret_val) { i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } adv_addr16 (); // advance our copy of the address i2c_common.tally_transaction (SUCCESS, &error); return SUCCESS; } //---------------------------< C U R R E N T _ A D D R E S S _ R E A D >-------------------------------------- // // Read a byte from the eep's current address pointer; the eep's address pointer is bumped to the next // location after the read. We presume that the eep's address pointer was previously set with byte_read(). // This function attempts to track the eep's internal pointer by incrementing control.addr. // // During the internal write cycle, SDA is disabled; the device will ack a slave address but does not respond to any requests. // // To use this function: // 1. perform some operation that correctly sets the eep's internal address pointer // 2. call this function // 3. retrieve the byte read from control.rd_byte // // This function does not use ping_eeprom_timed () because other functions call this function and the ping in // middle of all of that confuses the eeprom or perhaps the i2c_t3 library uint8_t Systronix_M24C32::current_address_read (void) { uint8_t ret_val; if (!error.exists) // exit immediately if device does not exist return ABSENT; control.bytes_received = _wire.requestFrom(_base, 1, I2C_STOP); if (1 != control.bytes_received) // if we got more than or less than 1 byte { ret_val = _wire.status(); // to get error value i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } control.rd_byte = _wire.readByte(); // get the byte inc_addr16 (); // bump our copy of the address i2c_common.tally_transaction (SUCCESS, &error); return SUCCESS; } //---------------------------< B Y T E _ R E A D >------------------------------------------------------------ // // Read a byte from a specified address. // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. call this function // 3. retrieve the byte read from control.rd_byte // uint8_t Systronix_M24C32::byte_read (void) { uint8_t ret_val; if (!error.exists) // exit immediately if device does not exist return ABSENT; if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS { // it didn't i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } _wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer if (2 != control.bytes_written) // did we get correct number of bytes into the i2c_t3 tx buf? { i2c_common.tally_transaction (WR_INCOMPLETE, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } ret_val = _wire.endTransmission(); // xmit memory address; will fail if device is busy if (SUCCESS != ret_val) { i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } return current_address_read (); // use current_address_read() to fetch the byte } //---------------------------< I N T 1 6 _ R E A D >---------------------------------------------------------- // // reads the two bytes of an int16_t or uint16_t from eep beginning at address in control.addr; ls byte is first. // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. call this function // 3. retrieve the 16-bit value from control.rd_int16 // uint8_t Systronix_M24C32::int16_read (void) { if (!error.exists) // exit immediately if device does not exist return ABSENT; control.rd_buf_ptr = (uint8_t*)(&control.rd_int16); control.rd_wr_len = sizeof(uint16_t); // set the read length return page_read (); // do the read and done } //---------------------------< I N T 3 2 _ R E A D >---------------------------------------------------------- // // reads the four bytes of an int32_t or uint32_t from eep beginning at address in control.addr; ls byte is first. // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. call this function // 3. retrieve the 32-bit value from control.rd_int32 // uint8_t Systronix_M24C32::int32_read (void) { if (!error.exists) // exit immediately if device does not exist return ABSENT; control.rd_buf_ptr = (uint8_t*)(&control.rd_int32); control.rd_wr_len = sizeof(uint32_t); // set the read length return page_read (); // do the read and done } //---------------------------< P A G E _ R E A D >------------------------------------------------------------ // // Reads control.rd_wr_len bytes from eep beginning at control.addr. The number of bytes that can be read in // a single operation is limited by the I2C_RX_BUFFER_LENGTH #define in i2c_t3.h. Setting control.rd_wr_len to // 256 is a convenient max (max size of the i2c_t3 buffer). // // To use this function: // 1. use set_addr16 (addr) to set the address in the control.addr union // 2. set control.rd_wr_len to the number of bytes to be read // 3. set control.rd_buf_ptr to point to the place where the data are to be stored // 4. call this function // uint8_t Systronix_M24C32::page_read (void) { uint8_t ret_val; size_t i; uint8_t* ptr = control.rd_buf_ptr; // a copy so we don't disturb the original if (!error.exists) // exit immediately if device does not exist return ABSENT; if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS { // it didn't i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } _wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer if (2 != control.bytes_written) // did we get correct number of bytes into the i2c_t3 tx buf? { i2c_common.tally_transaction (WR_INCOMPLETE, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } ret_val = _wire.endTransmission (I2C_NOSTOP); // xmit memory address if (SUCCESS != ret_val) { i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } control.bytes_received = _wire.requestFrom(_base, control.rd_wr_len, I2C_STOP); // read the bytes if (control.bytes_received != control.rd_wr_len) { ret_val = _wire.status(); // to get error value i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter return FAIL; // calling function decides what to do with the error } for (i=0;i<control.rd_wr_len; i++) // copy wire rx buffer data to destination *ptr++ = _wire.readByte(); adv_addr16 (); // advance our copy of the address i2c_common.tally_transaction (SUCCESS, &error); return SUCCESS; }
37.317029
157
0.633332
systronix
91d36b2b3e1678b846e48debdafd83129345c2d7
15,648
cpp
C++
tests/csimsbw/csimsbw.cpp
nickerso/csim-v2
c414d194f341cf00b0520ba3de4a2d7a37792768
[ "Apache-2.0" ]
null
null
null
tests/csimsbw/csimsbw.cpp
nickerso/csim-v2
c414d194f341cf00b0520ba3de4a2d7a37792768
[ "Apache-2.0" ]
null
null
null
tests/csimsbw/csimsbw.cpp
nickerso/csim-v2
c414d194f341cf00b0520ba3de4a2d7a37792768
[ "Apache-2.0" ]
1
2022-02-04T05:59:23.000Z
2022-02-04T05:59:23.000Z
#include "gtest/gtest.h" #include <string> #include <cmath> #include "csimsbw.h" #include "csim/error_codes.h" // generated with test resource locations #include "test_resources.h" #define ABS_TOL 1.0e-7 #define LOOSE_TOL 1.0e-1 #define VERY_LOOSE_TOL 0.5 TEST(SBW, say_hello) { char* hello; int length; int code = csim_sayHello(&hello, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 11); EXPECT_EQ(std::string(hello), "Hello World"); csim_freeVector(hello); } TEST(SBW, model_string) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE), &modelString, &length); EXPECT_EQ(code, 0); int expectedLength = 9422 + strlen(" xml:base=\"\"") + strlen(TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE)); EXPECT_EQ(length, expectedLength); EXPECT_NE(std::string(modelString), ""); csim_freeVector(modelString); } TEST(SBW, model_with_imports_string) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); EXPECT_EQ(code, 0); int expectedLength = 4629 + strlen(" xml:base=\"\"") + strlen(TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE)); EXPECT_EQ(length, expectedLength); EXPECT_NE(std::string(modelString), ""); csim_freeVector(modelString); } TEST(SBW, load_model) { char* modelString; int length; // need to allow users to apply changes to the raw XML (from SED-ML for example) int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE), &modelString, &length); EXPECT_EQ(code, 0); code = csim_loadCellml(modelString); EXPECT_EQ(code, 0); csim_freeVector(modelString); } TEST(SBW, load_model_with_imports) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); EXPECT_EQ(code, 0); code = csim_loadCellml(modelString); EXPECT_EQ(code, 0); csim_freeVector(modelString); } TEST(SBW, get_variables) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); char** variables; code = csim_getVariables(&variables, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 19); // test a few random variable IDs EXPECT_EQ(std::string(variables[0]), "actual_sin/sin"); EXPECT_EQ(std::string(variables[2]), "deriv_approx_sin/sin"); EXPECT_EQ(std::string(variables[5]), "main/deriv_approx_initial_value"); EXPECT_EQ(std::string(variables[9]), "main/x"); EXPECT_EQ(std::string(variables[15]), "parabolic_approx_sin/kPi_32"); EXPECT_EQ(std::string(variables[10]), "parabolic_approx_sin/C"); csim_freeMatrix((void**)variables, length); } TEST(SBW, get_variables_with_imports) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); char** variables; code = csim_getVariables(&variables, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 5); // test a few random variable IDs EXPECT_EQ(std::string(variables[1]), "main/sin1"); EXPECT_EQ(std::string(variables[3]), "main/sin3"); EXPECT_EQ(std::string(variables[4]), "main/x"); csim_freeMatrix((void**)variables, length); } TEST(SBW, get_initial_values) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; code = csim_getValues(&values, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 19); // test a few random variable values EXPECT_NEAR(values[0], 0.0, ABS_TOL); EXPECT_NEAR(values[5], 0.0, ABS_TOL); EXPECT_NEAR(values[10], 0.75, ABS_TOL); csim_freeVector(values); } TEST(SBW, get_initial_values_import) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; code = csim_getValues(&values, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 5); // test a few random variable values EXPECT_NEAR(values[1], 0.0, ABS_TOL); EXPECT_NEAR(values[3], 0.0, ABS_TOL); EXPECT_NEAR(values[4], 0.0, ABS_TOL); csim_freeVector(values); } TEST(SBW, set_value) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; // get the initial values code = csim_getValues(&values, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 19); // test a few random variable values EXPECT_NEAR(values[0], 0.0, ABS_TOL); EXPECT_NEAR(values[5], 0.0, ABS_TOL); EXPECT_NEAR(values[10], 0.75, ABS_TOL); csim_freeVector(values); // and now we should be able to set the value of the input variables code = csim_setValue("main/deriv_approx_initial_value", 123.456); EXPECT_EQ(code, 0); code = csim_setValue("parabolic_approx_sin/C", 987.654); EXPECT_EQ(code, 0); code = csim_getValues(&values, &length); EXPECT_NEAR(values[5], 123.456, ABS_TOL); EXPECT_NEAR(values[10], 987.654, ABS_TOL); csim_freeVector(values); } TEST(SBW, set_value_import) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; code = csim_getValues(&values, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 5); // test a few random variable values EXPECT_NEAR(values[1], 0.0, ABS_TOL); EXPECT_NEAR(values[3], 0.0, ABS_TOL); EXPECT_NEAR(values[4], 0.0, ABS_TOL); csim_freeVector(values); // try setting a variable (there are no inputs in this model) code = csim_setValue("main/sin1", 123.4); EXPECT_NE(code, 0); } TEST(SBW, one_step) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; // get the initial values code = csim_getValues(&values, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 19); csim_freeVector(values); code = csim_setTolerances(1.0, 1.0, 10); code = csim_oneStep(1.5); EXPECT_EQ(code, 0); // check the outputs code = csim_getValues(&values, &length); EXPECT_NEAR(values[9], 1.5, ABS_TOL); // main/x EXPECT_NEAR(values[0], sin(1.5), ABS_TOL); // actual_sin/sin EXPECT_NEAR(values[2], sin(1.5), LOOSE_TOL); // deriv_approx_sin/sin csim_freeVector(values); } TEST(SBW, one_step_import) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; code = csim_setTolerances(1.0, 1.0, 10); code = csim_oneStep(1.5); EXPECT_EQ(code, 0); // check the outputs code = csim_getValues(&values, &length); EXPECT_NEAR(values[4], 1.5, ABS_TOL); // main/x EXPECT_NEAR(values[1], sin(1.5), ABS_TOL); // main/sin1 (actual sine) EXPECT_NEAR(values[2], sin(1.5), LOOSE_TOL); // main/sin2 (deriv approx) EXPECT_NEAR(values[3], sin(1.5), LOOSE_TOL); // main/sin3 (parabolic approx) csim_freeVector(values); } TEST(SBW, reset) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; // simulate a bit code = csim_setTolerances(1.0, 1.0, 10); code = csim_oneStep(1.5); // reset and check the outputs are back to the same code = csim_reset(); EXPECT_EQ(code, 0); code = csim_getValues(&values, &length); EXPECT_NEAR(values[0], 0.0, ABS_TOL); EXPECT_NEAR(values[5], 0.0, ABS_TOL); EXPECT_NEAR(values[10], 0.75, ABS_TOL); csim_freeVector(values); } TEST(SBW, reset_import) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double* values; code = csim_setTolerances(1.0, 1.0, 10); code = csim_oneStep(1.5); // reset and check the outputs code = csim_reset(); EXPECT_EQ(code, 0); code = csim_getValues(&values, &length); EXPECT_NEAR(values[1], 0.0, ABS_TOL); EXPECT_NEAR(values[3], 0.0, ABS_TOL); EXPECT_NEAR(values[4], 0.0, ABS_TOL); csim_freeVector(values); } TEST(SBW, simulate_import) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double** values; int nData; code = csim_setTolerances(1.0, 1.0, 10); code = csim_simulate(0.0, 0.0, 7.0, 8, &values, &nData, &length); EXPECT_EQ(code, 0); EXPECT_EQ(length, 5); EXPECT_EQ(nData, 9); // 8+1 // check the outputs EXPECT_NEAR(values[8][4], 7.0, ABS_TOL); // main/x EXPECT_NEAR(values[4][1], sin(3.5), ABS_TOL); // main/sin1 (actual sine) EXPECT_NEAR(values[8][1], sin(7.0), ABS_TOL); // main/sin1 (actual sine) EXPECT_NEAR(values[4][2], sin(3.5), LOOSE_TOL); // main/sin2 (deriv approx) EXPECT_NEAR(values[8][2], sin(7.0), LOOSE_TOL); // main/sin2 (deriv approx) EXPECT_NEAR(values[4][3], sin(3.5), LOOSE_TOL); // main/sin3 (parabolic approx) EXPECT_NEAR(values[8][3], sin(7.0), VERY_LOOSE_TOL); // main/sin3 (parabolic approx) csim_freeMatrix((void**)values, length); } TEST(SBW, simulate_import_delayed_start) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double** values; int nData; code = csim_setTolerances(1.0, 1.0, 10); code = csim_simulate(0.0, 3.5, 7.0, 4, &values, &length, &nData); EXPECT_EQ(code, 0); EXPECT_EQ(length, 5); EXPECT_EQ(nData, 5); // 4+1 // check the outputs - need looser tolerances due to that big step at the start. EXPECT_NEAR(values[0][4], 3.5, ABS_TOL); // main/x EXPECT_NEAR(values[4][4], 7.0, ABS_TOL); // main/x EXPECT_NEAR(values[0][1], sin(3.5), ABS_TOL); // main/sin1 (actual sine) EXPECT_NEAR(values[4][1], sin(7.0), ABS_TOL); // main/sin1 (actual sine) EXPECT_NEAR(values[0][2], sin(3.5), LOOSE_TOL); // main/sin2 (deriv approx) EXPECT_NEAR(values[4][2], sin(7.0), VERY_LOOSE_TOL); // main/sin2 (deriv approx) EXPECT_NEAR(values[0][3], sin(3.5), LOOSE_TOL); // main/sin3 (parabolic approx) EXPECT_NEAR(values[4][3], sin(7.0), VERY_LOOSE_TOL); // main/sin3 (parabolic approx) csim_freeMatrix((void**)values, length); } TEST(SBW, get_voi) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); // no point continuing if this fails ASSERT_EQ(code, 0); code = csim_loadCellml(modelString); ASSERT_EQ(code, 0); csim_freeVector(modelString); double voi = csim_getVariableOfIntegration(); EXPECT_NEAR(voi, 0.0, ABS_TOL); int nData; double** values; code = csim_setTolerances(1.0, 1.0, 10); code = csim_simulate(0.0, 3.5, 7.0, 4, &values, &length, &nData); csim_freeMatrix((void**)values, nData); voi = csim_getVariableOfIntegration(); EXPECT_NEAR(voi, 7.0, ABS_TOL); code = csim_simulate(0.0, 3.5, 7.0, 4, &values, &length, &nData); csim_freeMatrix((void**)values, nData); voi = csim_getVariableOfIntegration(); EXPECT_NEAR(voi, 7.0, ABS_TOL); code = csim_oneStep(1.0); voi = csim_getVariableOfIntegration(); EXPECT_NEAR(voi, 8.0, ABS_TOL); code = csim_oneStep(2.345); voi = csim_getVariableOfIntegration(); EXPECT_NEAR(voi, 10.345, ABS_TOL); code = csim_reset(); voi = csim_getVariableOfIntegration(); EXPECT_NEAR(voi, 0.0, ABS_TOL); code = csim_oneStep(2.345); voi = csim_getVariableOfIntegration(); EXPECT_NEAR(voi, 2.345, ABS_TOL); }
35.243243
88
0.64807
nickerso
91d37878541358051b949781050b06f103150bc5
2,035
hpp
C++
test/unit/module/real/math/log1p/regular/log1p.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
test/unit/module/real/math/log1p/regular/log1p.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
test/unit/module/real/math/log1p/regular/log1p.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include <eve/function/log1p.hpp> #include <eve/constant/mzero.hpp> #include <eve/constant/nan.hpp> #include <eve/constant/inf.hpp> #include <eve/constant/minf.hpp> #include <eve/constant/smallestposval.hpp> #include <eve/constant/mindenormal.hpp> #include <eve/constant/eps.hpp> #include <eve/constant/log_2.hpp> #include <eve/constant/zero.hpp> #include <eve/platform.hpp> #include <cmath> TTS_CASE_TPL("Check eve::log1p return type", EVE_TYPE) { TTS_EXPR_IS(eve::log1p(T(0)), T); } TTS_CASE_TPL("Check eve::log1p behavior", EVE_TYPE) { using v_t = eve::element_type_t<T>; if constexpr(eve::platform::supports_invalids) { TTS_IEEE_EQUAL(eve::log1p(eve::inf(eve::as<T>())) , eve::inf(eve::as<T>()) ); TTS_IEEE_EQUAL(eve::log1p(eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) ); TTS_IEEE_EQUAL(eve::log1p(eve::mone(eve::as<T>())) , eve::minf(eve::as<T>())); TTS_IEEE_EQUAL(eve::log1p(T( 0 )) , T( 0 ) ); } if constexpr(eve::platform::supports_denormals) { TTS_IEEE_EQUAL(eve::log1p(eve::mindenormal(eve::as<T>())), T(std::log1p(eve::mindenormal(eve::as<v_t>())))); } auto epsi = eve::eps(eve::as<T>()); TTS_ULP_EQUAL(eve::log1p(epsi) , epsi , 0.5 ); TTS_ULP_EQUAL(eve::log1p(epsi) , epsi , 0.5 ); TTS_ULP_EQUAL(eve::log1p(T(1)) , eve::log_2(eve::as<T>()) , 0.5 ); TTS_ULP_EQUAL(eve::log1p(T(0)) , T(0) , 0.5 ); TTS_ULP_EQUAL(eve::log1p(eve::smallestposval(eve::as<T>())), eve::smallestposval(eve::as<T>()), 0.5 ); TTS_ULP_EQUAL(eve::log1p(epsi) , epsi , 0.5 ); }
39.134615
112
0.531695
orao
91d3ddf033fc0c541188798026484102568c5723
1,241
hpp
C++
boost/graph/python/distributed/dinic_max_flow.hpp
erwinvaneijk/bgl-python
6731d1e0e9681e99f1ad0a876b2adb8139d93027
[ "BSL-1.0" ]
18
2015-06-19T08:44:21.000Z
2021-07-23T11:09:05.000Z
boost/graph/python/distributed/dinic_max_flow.hpp
erwinvaneijk/bgl-python
6731d1e0e9681e99f1ad0a876b2adb8139d93027
[ "BSL-1.0" ]
null
null
null
boost/graph/python/distributed/dinic_max_flow.hpp
erwinvaneijk/bgl-python
6731d1e0e9681e99f1ad0a876b2adb8139d93027
[ "BSL-1.0" ]
3
2015-07-13T07:50:49.000Z
2020-10-26T15:08:03.000Z
// Copyright 2005 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Douglas Gregor // Andrew Lumsdaine #include <boost/graph/distributed/dinic_max_flow.hpp> #include <boost/python.hpp> namespace boost { namespace graph { namespace python { namespace distributed { using boost::python::object; template<typename Graph> int dinic_max_flow (const Graph& g, typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, vector_property_map< int, typename property_map<Graph, edge_index_t>::const_type>& capacity, vector_property_map< int, typename property_map<Graph, edge_index_t>::const_type>* in_flow) { typedef typename property_map<Graph, edge_index_t>::const_type EdgeIndexMap; typedef vector_property_map<int, EdgeIndexMap> FlowMap; FlowMap flow = in_flow? *in_flow : FlowMap(num_edges(g), get(edge_index, g)); return boost::graph::distributed::dinic_max_flow(g, s, t, capacity, flow); } } } } } // end namespace boost::graph::python::distributed
31.820513
79
0.745367
erwinvaneijk
91d9e9e4de5c0d8d813ac48f2bf8192fa77c23b2
1,417
cpp
C++
mapchannel.cpp
chuanstudyup/TrackReplay
fdce9ee21c0fd9394968616f277cced7f23d7b7e
[ "Apache-2.0" ]
null
null
null
mapchannel.cpp
chuanstudyup/TrackReplay
fdce9ee21c0fd9394968616f277cced7f23d7b7e
[ "Apache-2.0" ]
null
null
null
mapchannel.cpp
chuanstudyup/TrackReplay
fdce9ee21c0fd9394968616f277cced7f23d7b7e
[ "Apache-2.0" ]
null
null
null
#include "mapchannel.h" MapChannel::MapChannel(QObject *parent) : QObject(parent) { } void MapChannel::getMousePoint(double lng, double lat) { emit mousePointChanged(lng,lat); } void MapChannel::addPoint(double lng, double lat) { emit addPointClicked(lng,lat); } void MapChannel::movePoint(int id, double lng, double lat) { emit movePointClicked(id,lng,lat); } void MapChannel::transTask(int type, int len) { emit taskCome(type,len); } void MapChannel::transPoints(int id, double lng, double lat) { emit pointsCome(id,lng,lat); } void MapChannel::updateBoatPos(double lng, double lat, double course) { emit boatPosUpdated(lng,lat,course); } void MapChannel::reloadMap() { emit reloadMapClicked(); } void MapChannel::setOrigin(double lng, double lat) { emit setOriginPoint(lng,lat); } void MapChannel::clearWaypoints() { emit clearWaypointsClicked(); } void MapChannel::clearAll() { emit clearAllClicked(); } void MapChannel::addFencePoint(double lng, double lat) { emit addFencePointClicked(lng,lat); } void MapChannel::addFence() { emit addFenceClicked(); } void MapChannel::clearFence() { emit clearFenceClicked(); } void MapChannel::panTo(double lng, double lat) { emit panToClicked(lng,lat); } void MapChannel::clearTrack() { emit clearTrackClicked(); }
17.280488
70
0.673253
chuanstudyup
91e12885a97b0b802781587e02307494b2d4d364
8,984
cpp
C++
contrib/samples/win32/mfc/CanalDiagnostic/MainFrm.cpp
nanocortex/vscp
0b1a51a35a886921179a8112c592547f84c9771a
[ "CC-BY-3.0" ]
null
null
null
contrib/samples/win32/mfc/CanalDiagnostic/MainFrm.cpp
nanocortex/vscp
0b1a51a35a886921179a8112c592547f84c9771a
[ "CC-BY-3.0" ]
null
null
null
contrib/samples/win32/mfc/CanalDiagnostic/MainFrm.cpp
nanocortex/vscp
0b1a51a35a886921179a8112c592547f84c9771a
[ "CC-BY-3.0" ]
null
null
null
// MainFrm.cpp : implementation of the CMainFrame class // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version // 2 of the License, or (at your option) any later version. // canald.cpp // // This file is part of the CANAL (https://www.vscp.org) // // Copyright (C) 2000-2010 Ake Hedman, eurosource, <akhe@eurosource.se> // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this file see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // // $RCSfile: MainFrm.cpp,v $ // $Date: 2005/01/05 12:16:20 $ // $Author: akhe $ // $Revision: 1.2 $ #include "stdafx.h" #include "CanalDiagnostic.h" #include "MainFrm.h" #include "Splash.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd) ON_WM_INITMENUPOPUP() ON_WM_MENUSELECT() ON_UPDATE_COMMAND_UI(ID_INDICATOR_DATE, OnUpdateDate) ON_UPDATE_COMMAND_UI(ID_INDICATOR_TIME, OnUpdateTime) ON_COMMAND_EX(CG_ID_VIEW_CANALCONTROL, OnBarCheck) ON_UPDATE_COMMAND_UI(CG_ID_VIEW_CANALCONTROL, OnUpdateControlBarMenu) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; ///////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { // CG: The following block was inserted by 'Status Bar' component. { m_nStatusPane1Width = -1; m_bMenuSelect = FALSE; } // TODO: add member initialization code here } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } // TODO: Delete these three lines if you don't want the toolbar to // be dockable m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); // TODO: Add a menu item that will toggle the visibility of the // dialog bar named "Canal Control": // 1. In ResourceView, open the menu resource that is used by // the CMainFrame class // 2. Select the View submenu // 3. Double-click on the blank item at the bottom of the submenu // 4. Assign the new item an ID: CG_ID_VIEW_CANALCONTROL // 5. Assign the item a Caption: Canal Control // TODO: Change the value of CG_ID_VIEW_CANALCONTROL to an appropriate value: // 1. Open the file resource.h // CG: The following block was inserted by the 'Dialog Bar' component { // Initialize dialog bar m_wndCanalControl if (!m_wndCanalControl.Create(this, CG_IDD_CANALCONTROL, CBRS_TOP | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_HIDE_INPLACE, CG_ID_VIEW_CANALCONTROL)) { TRACE0("Failed to create dialog bar m_wndCanalControl\n"); return -1; // fail to create } m_wndCanalControl.EnableDocking(CBRS_ALIGN_TOP | CBRS_ALIGN_BOTTOM); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndCanalControl); } // CG: The following line was added by the Splash Screen component. CSplashWnd::ShowSplashScreen(this); /* // CG: The following block was inserted by 'Status Bar' component. { // Find out the size of the static variable 'indicators' defined // by AppWizard and copy it int nOrigSize = sizeof(indicators) / sizeof(UINT); UINT* pIndicators = new UINT[nOrigSize + 2]; memcpy(pIndicators, indicators, sizeof(indicators)); // Call the Status Bar Component's status bar creation function if (!InitStatusBar(pIndicators, nOrigSize, 60)) { TRACE0("Failed to initialize Status Bar\n"); return -1; } delete[] pIndicators; } */ return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CMDIFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CMDIFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CMDIFrameWnd::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame message handlers void CMainFrame::OnMenuSelect(UINT nItemID, UINT nFlags, HMENU hSysMenu) { CMDIFrameWnd::OnMenuSelect(nItemID, nFlags, hSysMenu); // CG: The following block was inserted by 'Status Bar' component. { // Restore first pane of the statusbar? if (nFlags == 0xFFFF && hSysMenu == 0 && m_nStatusPane1Width != -1) { m_bMenuSelect = FALSE; m_wndStatusBar.SetPaneInfo(0, m_nStatusPane1ID, m_nStatusPane1Style, m_nStatusPane1Width); m_nStatusPane1Width = -1; // Set it to illegal value } else { m_bMenuSelect = TRUE; } } } void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu) { CMDIFrameWnd::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu); // CG: The following block was inserted by 'Status Bar' component. { // store width of first pane and its style if (m_nStatusPane1Width == -1 && m_bMenuSelect) { m_wndStatusBar.GetPaneInfo(0, m_nStatusPane1ID, m_nStatusPane1Style, m_nStatusPane1Width); m_wndStatusBar.SetPaneInfo(0, m_nStatusPane1ID, SBPS_NOBORDERS|SBPS_STRETCH, 16384); } } } void CMainFrame::OnUpdateDate(CCmdUI* pCmdUI) { // CG: This function was inserted by 'Status Bar' component. // Get current date and format it CTime time = CTime::GetCurrentTime(); CString strDate = time.Format(_T("%A, %y %B %d, ")); // BLOCK: compute the width of the date string CSize size; { HGDIOBJ hOldFont = NULL; HFONT hFont = (HFONT)m_wndStatusBar.SendMessage(WM_GETFONT); CClientDC dc(NULL); if (hFont != NULL) hOldFont = dc.SelectObject(hFont); size = dc.GetTextExtent(strDate); if (hOldFont != NULL) dc.SelectObject(hOldFont); } // Update the pane to reflect the current date UINT nID, nStyle; int nWidth; m_wndStatusBar.GetPaneInfo(m_nDatePaneNo, nID, nStyle, nWidth); m_wndStatusBar.SetPaneInfo(m_nDatePaneNo, nID, nStyle, size.cx); pCmdUI->SetText(strDate); pCmdUI->Enable(TRUE); } void CMainFrame::OnUpdateTime(CCmdUI* pCmdUI) { // CG: This function was inserted by 'Status Bar' component. // Get current date and format it CTime time = CTime::GetCurrentTime(); CString strTime = time.Format(_T("%X")); // BLOCK: compute the width of the date string CSize size; { HGDIOBJ hOldFont = NULL; HFONT hFont = (HFONT)m_wndStatusBar.SendMessage(WM_GETFONT); CClientDC dc(NULL); if (hFont != NULL) hOldFont = dc.SelectObject(hFont); size = dc.GetTextExtent(strTime); if (hOldFont != NULL) dc.SelectObject(hOldFont); } // Update the pane to reflect the current time UINT nID, nStyle; int nWidth; m_wndStatusBar.GetPaneInfo(m_nTimePaneNo, nID, nStyle, nWidth); m_wndStatusBar.SetPaneInfo(m_nTimePaneNo, nID, nStyle, size.cx); pCmdUI->SetText(strTime); pCmdUI->Enable(TRUE); } BOOL CMainFrame::InitStatusBar(UINT *pIndicators, int nSize, int nSeconds) { // CG: This function was inserted by 'Status Bar' component. // Create an index for the DATE pane m_nDatePaneNo = nSize++; pIndicators[m_nDatePaneNo] = ID_INDICATOR_DATE; // Create an index for the TIME pane m_nTimePaneNo = nSize++; nSeconds = 1; pIndicators[m_nTimePaneNo] = ID_INDICATOR_TIME; // TODO: Select an appropriate time interval for updating // the status bar when idling. m_wndStatusBar.SetTimer(0x1000, nSeconds * 1000, NULL); return m_wndStatusBar.SetIndicators(pIndicators, nSize); }
28.340694
80
0.693232
nanocortex
91e17bb80960d5c92bc8e5315b1ef9fdc1b2de76
247
cc
C++
tests/CompileTests/ElsaTestCases/t0165.cc
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
tests/CompileTests/ElsaTestCases/t0165.cc
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
tests/CompileTests/ElsaTestCases/t0165.cc
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
// t0165.cc // specialization of nsCOMPtr template <class T> class nsCOMPtr { // nsCOMPtr === nsCOMPtr<T> }; // specialization template <> class nsCOMPtr<int> { // nsCOMPtr === nsCOMPtr<int> nsCOMPtr(nsCOMPtr<int> &blah); };
16.466667
32
0.62753
maurizioabba
91e244ff538141f09e993278a6868a5bb3f05a19
3,089
hpp
C++
include/nac/pak.hpp
nacitar/old-projects
e5af376f868124b9828196df1f55adb682969f3d
[ "MIT" ]
1
2016-05-04T04:22:42.000Z
2016-05-04T04:22:42.000Z
include/nac/pak.hpp
nacitar/old-projects
e5af376f868124b9828196df1f55adb682969f3d
[ "MIT" ]
null
null
null
include/nac/pak.hpp
nacitar/old-projects
e5af376f868124b9828196df1f55adb682969f3d
[ "MIT" ]
6
2016-05-04T04:23:02.000Z
2020-11-30T22:32:43.000Z
#ifndef __PAK_HPP__ #define __PAK_HPP__ #include <nx/type.hpp> #include <string> #include <vector> #include <fstream> /* Every PAK file has a header, 16 bytes long 4 Ident (IDPAKHEADER) 4 directory offset 4 directory length All files in the PAK has a directory entry, consisting of 56 relative filename 4 file data position 4 file data length This data exists back-to-back in the file, the position could be anywhere, it is stored in the directory offset field of the pak file header. So, the directory can be anywhere, but it is one contiguous list wherever it is. The number of entries can be obtained from the header's directory length divided by 64, as each entry is 64 bytes long. */ // .PAK File Header struct nxPakHeader { nxMem pSignature[4]; nxMemInt32 pOffset; nxMemInt32 pLength; }; // .PAK Directory Header struct nxPakDirectory { nxMem pName[56]; nxMemInt32 pFilePos; nxMemInt32 pFileLen; }; enum nxArchiveType { NX_UNKNOWN=0, NX_PAK }; class nxArchiveData { protected: std::ifstream*ifsIn; nxULong uOffset; nxULong uSize; nxArchiveType aType; public: nxArchiveData(std::ifstream*ifs=NULL,const nxULong& offset=0,const nxULong& size=0, const nxArchiveType& type=NX_UNKNOWN) : ifsIn(ifs), uOffset(offset), uSize(size), aType(type) { } bool GetData(std::vector<char>&vcData) const { if (ifsIn && *ifsIn && ifsIn->seekg(uOffset,std::ios::beg)) { vcData.resize(uSize); if (ifsIn->read(&vcData.front(),uSize)) return true; } return false; } inline const nxULong& GetSize(void) const { return uSize; } inline const nxArchiveType&GetType(void) const { return aType; } }; typedef std::map<std::string,nxArchiveData> nxArchiveMap; class nxPak { std::ifstream ifsIn; protected: nxArchiveMap mpFiles; inline void Clear(void); public: bool Open(const std::string&strFile); inline const nxArchiveMap& GetFileMap(void) const { return mpFiles; } }; inline void nxPak::Clear(void) { ifsIn.close(); ifsIn.clear(); mpFiles.clear(); } bool nxPak::Open(const std::string&strFile) { Clear(); ifsIn.open(strFile.c_str(),std::ios::binary); if (!ifsIn) return false; nxPakHeader objHead; ifsIn.read((char*)&objHead,sizeof(nxPakHeader)); //check signature and that the offset is valid if (ifsIn && //read OK nxMemCmp((const nxMem*)objHead.pSignature,(const nxMem*)"PACK",4) == 0 && //right signature ifsIn.seekg(nxLMemToNum32<nxUInt32>(objHead.pOffset),std::ios::beg)) //valid offset { nxUInt32 uFiles = nxLMemToNum32<nxUInt32>(objHead.pLength) / sizeof(nxPakDirectory); nxPakDirectory objDir; while (uFiles--) { ifsIn.read((char*)&objDir,sizeof(nxPakDirectory)); if (!ifsIn) { Clear(); return false; } mpFiles[(const char*)objDir.pName] = nxArchiveData(&ifsIn,nxLMemToNum32<nxULong>(objDir.pFilePos),nxLMemToNum32<nxULong>(objDir.pFileLen), NX_PAK); } return true; } Clear(); return false; } #endif // __PAK_HPP__
24.91129
151
0.685335
nacitar
91e5830dd89a08350dc8a29643b5503b1c61bedd
2,699
cpp
C++
GLdraw/GLScreenshot.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
57
2015-05-07T18:07:11.000Z
2022-03-18T18:44:39.000Z
GLdraw/GLScreenshot.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
7
2018-12-10T21:46:52.000Z
2022-01-20T19:49:11.000Z
GLdraw/GLScreenshot.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
36
2015-01-10T18:36:45.000Z
2022-01-20T19:49:24.000Z
#include <KrisLibrary/Logger.h> #include "GLScreenshot.h" #include "GL.h" #include "GLError.h" #include <stdio.h> //#define GDI_AVAILABLE #if defined _WIN32 && defined GDI_AVAILABLE #include <ole2.h> #include <image/gdi.h> #endif //_WIN32 && GDI_AVAILABLE #include <image/ppm.h> #include <memory.h> void flipRGBImage(unsigned char* image,int width,int height) { int stride = width*3; unsigned char* row = new unsigned char[stride]; for(int i=0;i<height/2;i++) { //swap rows i,height-i memcpy(row,image+i*stride,stride); memcpy(image+i*stride,image+(height-i-1)*stride,stride); memcpy(image+(height-i-1)*stride,row,stride); } delete [] row; } bool GLSaveScreenshot(const char* filename) { #if (defined WIN32 && defined GDI_AVAILABLE) // These are important to get screen captures to work correctly glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLint vp[4]; glGetIntegerv(GL_VIEWPORT,vp); int x=vp[0]; int y=vp[1]; int width = vp[2]; int height = vp[3]; //row-major array, bottom corner is first row Image image; image.initialize(width,height,Image::R8G8B8); //glReadBuffer(GL_FRONT); glReadBuffer(GL_BACK); glReadPixels(x,y,width,height,GL_RGB,GL_UNSIGNED_BYTE,image.data); bool errors = CheckGLErrors("SaveScreenshot",false); if(errors) return false; //LOG4CXX_INFO(KrisLibrary::logger(),"Flipping RGB image...\n"); flipRGBImage(image.data,width,height); //LOG4CXX_INFO(KrisLibrary::logger(),"Done, now exporting...\n"); return ExportImageGDIPlus(filename,image); //LOG4CXX_INFO(KrisLibrary::logger(),"Done, saving screenshot.\n"); /* ImageOperator op(image); ImageOperator op2; op2.initialize(640,480); op.stretchBlitBilinear(op2); Image image2; op2.output(image2,Image::R8G8B8); ExportImageGDIPlus(filename,image2); */ #else LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, saving screenshot in PPM format...\n"); return GLSaveScreenshotPPM(filename); #endif } bool GLSaveScreenshotPPM(const char* filename) { // These are important to get screen captures to work correctly glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLint vp[4]; glGetIntegerv(GL_VIEWPORT,vp); int x=vp[0]; int y=vp[1]; int width = vp[2]; int height = vp[3]; unsigned char* data = new unsigned char[width*height*3]; glReadBuffer(GL_BACK); glReadPixels(x,y,width,height,GL_RGB,GL_UNSIGNED_BYTE,data); bool errors = CheckGLErrors("SaveScreenshot",false); if(errors) { delete [] data; return false; } flipRGBImage(data,width,height); bool res = WritePPM_RGB_Binary(data,width,height,filename); delete [] data; return res; }
27.824742
89
0.715821
smeng9
91eb3e744eea84991fb9e428fa2eaa64d4a37026
2,114
cpp
C++
src/listener.cpp
inani47/beginner_tutorials
7b5b3ec6ab32b22ad77273087ad4b1d2aa9c5041
[ "BSD-2-Clause" ]
null
null
null
src/listener.cpp
inani47/beginner_tutorials
7b5b3ec6ab32b22ad77273087ad4b1d2aa9c5041
[ "BSD-2-Clause" ]
null
null
null
src/listener.cpp
inani47/beginner_tutorials
7b5b3ec6ab32b22ad77273087ad4b1d2aa9c5041
[ "BSD-2-Clause" ]
1
2018-10-27T06:17:24.000Z
2018-10-27T06:17:24.000Z
/* * BSD 2-Clause License * * Copyright (c) 2017, Pranav Inani * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file listner.cpp * * @brief Subscribes to the topic chatter * * In this implementation it receives messages * from talker.cpp on the topic chatter * * * * @author Pranav Inani * @copyright 2017 */ #include "ros/ros.h" #include "std_msgs/String.h" /** * @brief call back function for a subscriber node * @param msg is the string received from talker on topic chatter * @return none */ void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data.c_str()); } int main(int argc, char **argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback); ros::spin(); return 0; }
33.03125
81
0.733207
inani47
91ebfc21408addb761be14b571a2954e3516c58e
8,845
cpp
C++
src/frm/frmBackup.cpp
dpage/pgadmin3
6784e6281831a083fe5a0bbd49eac90e1a6ac547
[ "Artistic-1.0" ]
2
2021-07-16T21:45:41.000Z
2021-08-14T15:54:17.000Z
src/frm/frmBackup.cpp
dpage/pgadmin3
6784e6281831a083fe5a0bbd49eac90e1a6ac547
[ "Artistic-1.0" ]
null
null
null
src/frm/frmBackup.cpp
dpage/pgadmin3
6784e6281831a083fe5a0bbd49eac90e1a6ac547
[ "Artistic-1.0" ]
2
2017-11-18T15:00:24.000Z
2021-08-14T15:54:30.000Z
////////////////////////////////////////////////////////////////////////// // // pgAdmin III - PostgreSQL Tools // RCS-ID: $Id$ // Copyright (C) 2002 - 2010, The pgAdmin Development Team // This software is released under the Artistic Licence // // frmBackup.cpp - Backup database dialogue // ////////////////////////////////////////////////////////////////////////// // wxWindows headers #include <wx/wx.h> #include <wx/settings.h> // App headers #include "pgAdmin3.h" #include "frmMain.h" #include "frmBackup.h" #include "sysLogger.h" #include "pgSchema.h" #include "pgTable.h" // Icons #include "images/backup.xpm" #define nbNotebook CTRL_NOTEBOOK("nbNotebook") #define txtFilename CTRL_TEXT("txtFilename") #define btnFilename CTRL_BUTTON("btnFilename") #define rbxFormat CTRL_RADIOBOX("rbxFormat") #define chkBlobs CTRL_CHECKBOX("chkBlobs") #define chkOid CTRL_CHECKBOX("chkOid") #define chkInsert CTRL_CHECKBOX("chkInsert") #define chkDisableDollar CTRL_CHECKBOX("chkDisableDollar") #define sbxPlainOptions CTRL_STATICBOX("sbxPlainOptions") #define chkOnlyData CTRL_CHECKBOX("chkOnlyData") #define chkOnlySchema CTRL_CHECKBOX("chkOnlySchema") #define chkNoOwner CTRL_CHECKBOX("chkNoOwner") #define chkCreateDb CTRL_CHECKBOX("chkCreateDb") #define chkDropDb CTRL_CHECKBOX("chkDropDb") #define chkDisableTrigger CTRL_CHECKBOX("chkDisableTrigger") #define chkVerbose CTRL_CHECKBOX("chkVerbose") BEGIN_EVENT_TABLE(frmBackup, ExternProcessDialog) EVT_TEXT(XRCID("txtFilename"), frmBackup::OnChange) EVT_BUTTON(XRCID("btnFilename"), frmBackup::OnSelectFilename) EVT_RADIOBOX(XRCID("rbxFormat"), frmBackup::OnChangePlain) EVT_CHECKBOX(XRCID("chkOnlyData"), frmBackup::OnChangePlain) EVT_CHECKBOX(XRCID("chkOnlySchema"), frmBackup::OnChangePlain) EVT_CHECKBOX(XRCID("chkNoOwner"), frmBackup::OnChangePlain) EVT_CLOSE( ExternProcessDialog::OnClose) END_EVENT_TABLE() frmBackup::frmBackup(frmMain *form, pgObject *obj) : ExternProcessDialog(form) { object=obj; wxLogInfo(wxT("Creating a backup dialogue for %s %s"), object->GetTypeName().c_str(), object->GetFullName().c_str()); wxWindowBase::SetFont(settings->GetSystemFont()); LoadResource(form, wxT("frmBackup")); RestorePosition(); SetTitle(wxString::Format(_("Backup %s %s"), object->GetTranslatedTypeName().c_str(), object->GetFullIdentifier().c_str())); canBlob = (obj->GetMetaType() == PGM_DATABASE); chkBlobs->SetValue(canBlob); chkDisableDollar->Enable(obj->GetConnection()->BackendMinimumVersion(7, 5)); if (!object->GetDatabase()->GetServer()->GetPasswordIsStored()) environment.Add(wxT("PGPASSWORD=") + object->GetDatabase()->GetServer()->GetPassword()); // Icon SetIcon(wxIcon(backup_xpm)); // fix translation problem wxString dollarLabel=wxGetTranslation(_("Disable $$ quoting")); dollarLabel.Replace(wxT("$$"), wxT("$")); chkDisableDollar->SetLabel(dollarLabel); chkDisableDollar->SetSize(chkDisableDollar->GetBestSize()); txtMessages = CTRL_TEXT("txtMessages"); txtMessages->SetMaxLength(0L); btnOK->Disable(); wxCommandEvent ev; OnChangePlain(ev); } frmBackup::~frmBackup() { wxLogInfo(wxT("Destroying a backup dialogue")); SavePosition(); } wxString frmBackup::GetHelpPage() const { wxString page; page = wxT("pg/app-pgdump"); return page; } void frmBackup::OnSelectFilename(wxCommandEvent &ev) { wxString title, prompt; if (rbxFormat->GetSelection() == 2) // plain { title = _("Select output file"); prompt = _("Query files (*.sql)|*.sql|All files (*.*)|*.*"); } else { title = _("Select backup filename"); prompt = _("Backup files (*.backup)|*.backup|All files (*.*)|*.*"); } wxFileDialog file(this, title, wxGetHomeDir(), txtFilename->GetValue(), prompt, wxSAVE); if (file.ShowModal() == wxID_OK) { txtFilename->SetValue(file.GetPath()); OnChange(ev); } } void frmBackup::OnChange(wxCommandEvent &ev) { if (!process && !done) btnOK->Enable(!txtFilename->GetValue().IsEmpty()); } void frmBackup::OnChangePlain(wxCommandEvent &ev) { bool isPlain = (rbxFormat->GetSelection() == 2); sbxPlainOptions->Enable(isPlain); chkBlobs->Enable(canBlob && !isPlain); chkOnlyData->Enable(isPlain && !chkOnlySchema->GetValue()); if (isPlain) isPlain = !chkOnlyData->GetValue(); chkOnlySchema->Enable(isPlain); chkNoOwner->Enable(isPlain); chkDropDb->Enable(isPlain); chkCreateDb->Enable(isPlain); chkDisableTrigger->Enable(chkOnlyData->GetValue()); } wxString frmBackup::GetCmd(int step) { wxString cmd = getCmdPart1(); return cmd + getCmdPart2(); } wxString frmBackup::GetDisplayCmd(int step) { wxString cmd = getCmdPart1(); return cmd + getCmdPart2(); } wxString frmBackup::getCmdPart1() { extern wxString backupExecutable; wxString cmd=backupExecutable; pgServer *server=object->GetDatabase()->GetServer(); cmd += wxT(" -i") wxT(" -h ") + server->GetName() + wxT(" -p ") + NumToStr((long)server->GetPort()) + wxT(" -U ") + server->GetUsername(); return cmd; } wxString frmBackup::getCmdPart2() { extern wxString backupExecutable; wxString cmd; // if (server->GetSSL()) // pg_dump doesn't support ssl switch (rbxFormat->GetSelection()) { case 0: // compressed { cmd.Append(wxT(" -F c")); if (chkBlobs->GetValue()) cmd.Append(wxT(" -b")); break; } case 1: // tar { cmd.Append(wxT(" -F t")); if (chkBlobs->GetValue()) cmd.Append(wxT(" -b")); break; } case 2: { cmd.Append(wxT(" -F p")); if (chkOnlyData->GetValue()) { cmd.Append(wxT(" -a")); if (chkDisableTrigger->GetValue()) cmd.Append(wxT(" --disable-triggers")); } else { if (chkOnlySchema->GetValue()) cmd.Append(wxT(" -s")); if (chkOnlySchema->GetValue()) cmd.Append(wxT(" -s")); if (chkNoOwner->GetValue()) cmd.Append(wxT(" -O")); if (chkCreateDb->GetValue()) cmd.Append(wxT(" -C")); if (chkDropDb->GetValue()) cmd.Append(wxT(" -c")); } break; } } if (chkOid->GetValue()) cmd.Append(wxT(" -o")); if (chkInsert->GetValue()) cmd.Append(wxT(" -D")); if (chkDisableDollar->GetValue()) cmd.Append(wxT(" --disable-dollar-quoting")); if (chkVerbose->GetValue()) cmd.Append(wxT(" -v")); cmd.Append(wxT(" -f \"") + txtFilename->GetValue() + wxT("\"")); if (object->GetMetaType() == PGM_SCHEMA) #ifdef WIN32 cmd.Append(wxT(" -n \\\"") + ((pgSchema*)object)->GetIdentifier() + wxT("\\\"")); #else cmd.Append(wxT(" -n '") + ((pgSchema*)object)->GetQuotedIdentifier() + wxT("'")); #endif else if (object->GetMetaType() == PGM_TABLE) { // The syntax changed in 8.2 :-( if (pgAppMinimumVersion(backupExecutable + wxT(" --version"), 8, 2)) { #ifdef WIN32 cmd.Append(wxT(" -t \"\\\"") + ((pgTable*)object)->GetSchema()->GetIdentifier() + wxT("\\\".\\\"") + ((pgTable*)object)->GetIdentifier() + wxT("\\\"\"")); #else cmd.Append(wxT(" -t '") + ((pgTable*)object)->GetSchema()->GetQuotedIdentifier() + wxT(".") + ((pgTable*)object)->GetQuotedIdentifier() + wxT("'")); #endif } else { cmd.Append(wxT(" -t ") + ((pgTable*)object)->GetQuotedIdentifier()); cmd.Append(wxT(" -n ") + ((pgTable*)object)->GetSchema()->GetQuotedIdentifier()); } } cmd.Append(wxT(" ") + object->GetDatabase()->GetQuotedIdentifier()); return cmd; } void frmBackup::Go() { txtFilename->SetFocus(); Show(true); } backupFactory::backupFactory(menuFactoryList *list, wxMenu *mnu, wxToolBar *toolbar) : contextActionFactory(list) { mnu->Append(id, _("&Backup..."), _("Creates a backup of the current database to a local file")); } wxWindow *backupFactory::StartDialog(frmMain *form, pgObject *obj) { frmBackup *frm=new frmBackup(form, obj); frm->Go(); return 0; } bool backupFactory::CheckEnable(pgObject *obj) { extern wxString backupExecutable; return obj && obj->CanBackup() && !backupExecutable.IsEmpty(); }
28.440514
128
0.59299
dpage
91ecc0f918c51550b90273cd61737bfc91e6d7a6
519
cpp
C++
src/lib/io/mipi_tx.cpp
kinglee1982/FaceRecognitionTerminalDemo
5e197011a87403d2433f691b8390ec340432b2be
[ "Apache-2.0" ]
2
2020-12-21T13:15:59.000Z
2021-07-07T08:04:06.000Z
src/lib/io/mipi_tx.cpp
kinglee1982/FaceRecognitionTerminalDemo
5e197011a87403d2433f691b8390ec340432b2be
[ "Apache-2.0" ]
null
null
null
src/lib/io/mipi_tx.cpp
kinglee1982/FaceRecognitionTerminalDemo
5e197011a87403d2433f691b8390ec340432b2be
[ "Apache-2.0" ]
1
2022-03-24T01:08:42.000Z
2022-03-24T01:08:42.000Z
#include "mipi_tx.h" #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include "hi_mipi_tx.h" #include "rp-lcd-mipi-8inch-800x1280.h" Mipi_Tx::Mipi_Tx() {} Mipi_Tx *Mipi_Tx::getInstance() { static Mipi_Tx self; return &self; } bool Mipi_Tx::startMipiTx(VO_INTF_SYNC_E voIntfSync) { start_mipi_8inch_800x1280_mipiTx(voIntfSync); return true; } bool Mipi_Tx::startDeviceWithUserSyncInfo(VO_DEV voDev) { start_mipi_8inch_800x1280_userSyncInfo(voDev); return true; }
19.961538
58
0.716763
kinglee1982
91ed58a6dc446a8afb77af133372d237d2d746b1
912
cpp
C++
Sorting and Searching/array_division.cpp
vjerin/CSES-Problem-Set
68070812fa1d27e4653f58dcdabed56188a45110
[ "Apache-2.0" ]
null
null
null
Sorting and Searching/array_division.cpp
vjerin/CSES-Problem-Set
68070812fa1d27e4653f58dcdabed56188a45110
[ "Apache-2.0" ]
10
2020-10-02T10:28:22.000Z
2020-10-09T18:30:56.000Z
Sorting and Searching/array_division.cpp
vjerin/CSES-Problem-Set
68070812fa1d27e4653f58dcdabed56188a45110
[ "Apache-2.0" ]
10
2020-10-02T11:16:32.000Z
2020-10-08T18:31:18.000Z
#include <bits/stdc++.h> #define int long long #define MOD 1000000007 using namespace std; void solve() { int n, k; cin >> n >> k; int x[n]; int sum = 0; for(int i = 0; i < n; i++) { cin >> x[i]; sum += x[i]; } int l = sum / k, h = sum; int m, ans = l; while(l <= h) { // cout << l << " " << h << endl; m = (l + h) / 2; int count = k, i = 0; while(count--) { int s = 0; while(i < n) { s += x[i]; if(s > m) { break; } i++; } } if(i != n) { l = m + 1; } else { ans = m; h = m - 1; } } cout << ans << endl; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
16.581818
41
0.326754
vjerin
91ef65ef4bbd6f4410d4498335a0703839a5517b
3,829
inl
C++
src/core/reflection/include/meta_struct.inl
Caravetta/Engine
6e2490a68727dc731b466335499f3204490acc5f
[ "MIT" ]
2
2018-05-21T02:12:50.000Z
2019-04-23T20:56:00.000Z
src/core/reflection/include/meta_struct.inl
Caravetta/Engine
6e2490a68727dc731b466335499f3204490acc5f
[ "MIT" ]
12
2018-05-30T13:15:25.000Z
2020-02-02T21:29:42.000Z
src/core/reflection/include/meta_struct.inl
Caravetta/Engine
6e2490a68727dc731b466335499f3204490acc5f
[ "MIT" ]
2
2018-06-14T19:03:29.000Z
2018-12-30T07:37:22.000Z
#include "crc32.h" #include "reflection_system.h" namespace Engine { #define GET_FIELD_OFFSET( __struct, __field ) (uint32_t) (uintptr_t) &( ((__struct*)NULL)->*__field) template<class T> void Meta_Struct::create( Meta_Struct const*& meta_struct, const char* name, const char* base_name ) { Meta_Struct* tmp_struct = Meta_Struct::create(); meta_struct = tmp_struct; Meta_Struct::create<T>(name, base_name, &T::populate_meta_struct_func, tmp_struct); } template<class T> void Meta_Struct::create( const char* name, const char* base_name, populate_meta_struct_func func, Meta_Struct* info ) { info->__size = sizeof(T); info->__name = name; bool base_populate = false; if ( base_name ) { info->__base_struct = Reflection::get_meta_struct(base_name); info->__base_struct->add_derived_struct(info); } const Meta_Struct* base_struct = info->__base_struct; while ( base_populate == false && base_struct ) { if ( base_struct ) { base_populate = base_struct->__populate_func && base_struct->__populate_func == func; base_struct = base_struct->__base_struct; } else { base_name = NULL; } } if ( base_populate == false ) { info->__populate_func = func; } if ( info->__populate_func ) { info->__populate_func( *info ); } } template<class Struct_T, class Field_T> void Meta_Struct::add_field( Field_T Struct_T::* field, const char* name, uint32_t flags ) { Meta_Field* new_field = allocate_field(); new_field->__name = name; new_field->__name_crc = crc32(name); new_field->__size = sizeof(Field_T); new_field->__offset = GET_FIELD_OFFSET(Struct_T, field); } template<class Class_T, class Base_T> Meta_Struct_Registrar<Class_T, Base_T>::Meta_Struct_Registrar( const char* name ) : Meta_Base_Registrar( name ) { Meta_Base_Registrar::add_to_list(Registrar_Base_Types::META_STRUCT_TYPE, this); } template<class Class_T, class Base_T> Meta_Struct_Registrar<Class_T, Base_T>::~Meta_Struct_Registrar( void ) { meta_unregister(); Meta_Base_Registrar::remove_from_list(Registrar_Base_Types::META_STRUCT_TYPE, this); } template<class Class_T, class Base_T> void Meta_Struct_Registrar<Class_T, Base_T>::meta_register( void ) { if ( Class_T::__s_meta_struct == NULL ) { Base_T::__s_meta_struct.meta_register(); Meta_Base_Registrar::add_type_to_registry(Class_T::create_meta_struct()); } } template<class Class_T, class Base_T> void Meta_Struct_Registrar<Class_T, Base_T>::meta_unregister( void ) { if ( Class_T::__s_meta_struct != NULL ) { Meta_Base_Registrar::remove_type_from_registry(Class_T::__s_meta_struct); Class_T::__s_meta_struct = NULL; } } template<class Class_T> Meta_Struct_Registrar<Class_T, void>::Meta_Struct_Registrar( const char* name ) : Meta_Base_Registrar( name ) { Meta_Base_Registrar::add_to_list(Registrar_Base_Types::META_STRUCT_TYPE, this); } template<class Class_T> Meta_Struct_Registrar<Class_T, void>::~Meta_Struct_Registrar( void ) { meta_unregister(); Meta_Base_Registrar::remove_from_list(Registrar_Base_Types::META_STRUCT_TYPE, this); } template<class Class_T> void Meta_Struct_Registrar<Class_T, void>::meta_register( void ) { if ( Class_T::__s_meta_struct == NULL ) { Meta_Base_Registrar::add_type_to_registry((Meta_Base*)Class_T::create_meta_struct()); } } template<class Class_T> void Meta_Struct_Registrar<Class_T, void>::meta_unregister( void ) { if ( Class_T::__s_meta_struct != NULL ) { Meta_Base_Registrar::remove_type_from_registry(Class_T::__s_meta_struct); Class_T::__s_meta_struct = NULL; } } } // end namespace Engine
30.149606
118
0.702533
Caravetta
91f41160c9460d2c15cc16e05173d23c1ac4c4ec
1,240
cpp
C++
openscenario/openscenario_interpreter/src/syntax/private.cpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/src/syntax/private.cpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/src/syntax/private.cpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2021 Tier IV, Inc. 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 <openscenario_interpreter/syntax/private.hpp> #include <openscenario_interpreter/utility/demangle.hpp> namespace openscenario_interpreter { inline namespace syntax { nlohmann::json & operator<<(nlohmann::json & json, const Private & datum) { json["entityRef"] = datum.entity_ref; json["PrivateAction"] = nlohmann::json::array(); for (const auto & private_action : datum.private_actions) { nlohmann::json action; action["type"] = makeTypename(private_action.type()); json["PrivateAction"].push_back(action); } return json; } } // namespace syntax } // namespace openscenario_interpreter
32.631579
75
0.740323
autocore-ai
91f8143416a80a857972acd1a1917719b6d7f0bd
13,256
cc
C++
chromium/ui/views/animation/ink_drop_animation_unittest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
chromium/ui/views/animation/ink_drop_animation_unittest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
2
2017-03-09T09:00:50.000Z
2017-09-21T15:48:20.000Z
chromium/ui/views/animation/ink_drop_animation_unittest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.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. #ifndef UI_VIEWS_ANIMATION_INK_DROP_ANIMATION_UNITTEST_H_ #define UI_VIEWS_ANIMATION_INK_DROP_ANIMATION_UNITTEST_H_ #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/size_f.h" #include "ui/views/animation/ink_drop_animation.h" #include "ui/views/animation/ink_drop_state.h" #include "ui/views/animation/test/ink_drop_animation_test_api.h" namespace views { namespace test { namespace { // Transforms a copy of |point| with |transform| and returns it. gfx::Point TransformPoint(const gfx::Transform& transform, const gfx::Point& point) { gfx::Point transformed_point = point; transform.TransformPoint(&transformed_point); return transformed_point; } } // namespace class InkDropAnimationTest : public testing::Test { public: InkDropAnimationTest() {} ~InkDropAnimationTest() override {} protected: scoped_ptr<InkDropAnimation> CreateInkDropAnimation() const; private: DISALLOW_COPY_AND_ASSIGN(InkDropAnimationTest); }; // Returns a new InkDropAnimation with default parameters. scoped_ptr<InkDropAnimation> InkDropAnimationTest::CreateInkDropAnimation() const { return make_scoped_ptr( new InkDropAnimation(gfx::Size(10, 10), 2, gfx::Size(8, 8), 1)); } TEST_F(InkDropAnimationTest, InitialStateAfterConstruction) { scoped_ptr<InkDropAnimation> ink_drop_animation = CreateInkDropAnimation(); EXPECT_EQ(views::InkDropState::HIDDEN, ink_drop_animation->ink_drop_state()); } TEST_F(InkDropAnimationTest, AnimateToActionPending) { scoped_ptr<InkDropAnimation> ink_drop_animation = CreateInkDropAnimation(); ink_drop_animation->AnimateToState(views::InkDropState::ACTION_PENDING); EXPECT_EQ(views::InkDropState::ACTION_PENDING, ink_drop_animation->ink_drop_state()); } TEST_F(InkDropAnimationTest, AnimateToQuickAction) { scoped_ptr<InkDropAnimation> ink_drop_animation = CreateInkDropAnimation(); ink_drop_animation->AnimateToState(views::InkDropState::QUICK_ACTION); EXPECT_EQ(views::InkDropState::QUICK_ACTION, ink_drop_animation->ink_drop_state()); } TEST_F(InkDropAnimationTest, AnimateToSlowActionPending) { scoped_ptr<InkDropAnimation> ink_drop_animation = CreateInkDropAnimation(); ink_drop_animation->AnimateToState(views::InkDropState::SLOW_ACTION_PENDING); EXPECT_EQ(views::InkDropState::SLOW_ACTION_PENDING, ink_drop_animation->ink_drop_state()); } TEST_F(InkDropAnimationTest, AnimateToSlowAction) { scoped_ptr<InkDropAnimation> ink_drop_animation = CreateInkDropAnimation(); ink_drop_animation->AnimateToState(views::InkDropState::SLOW_ACTION); EXPECT_EQ(views::InkDropState::SLOW_ACTION, ink_drop_animation->ink_drop_state()); } TEST_F(InkDropAnimationTest, AnimateToActivated) { scoped_ptr<InkDropAnimation> ink_drop_animation = CreateInkDropAnimation(); ink_drop_animation->AnimateToState(views::InkDropState::ACTIVATED); EXPECT_EQ(views::InkDropState::ACTIVATED, ink_drop_animation->ink_drop_state()); } TEST_F(InkDropAnimationTest, AnimateToDeactivated) { scoped_ptr<InkDropAnimation> ink_drop_animation = CreateInkDropAnimation(); ink_drop_animation->AnimateToState(views::InkDropState::DEACTIVATED); EXPECT_EQ(views::InkDropState::DEACTIVATED, ink_drop_animation->ink_drop_state()); } TEST_F(InkDropAnimationTest, TransformedPointsUsingTransformsFromCalculateCircleTransforms) { const int kHalfDrawnSize = 5; const int kDrawnSize = 2 * kHalfDrawnSize; const int kHalfTransformedSize = 100; const int kTransformedSize = 2 * kHalfTransformedSize; // Constant points in the drawn space that will be transformed. const gfx::Point center(kHalfDrawnSize, kHalfDrawnSize); const gfx::Point mid_left(0, kHalfDrawnSize); const gfx::Point mid_right(kDrawnSize, kHalfDrawnSize); const gfx::Point top_mid(kHalfDrawnSize, 0); const gfx::Point bottom_mid(kHalfDrawnSize, kDrawnSize); scoped_ptr<InkDropAnimation> ink_drop_animation( new InkDropAnimation(gfx::Size(kDrawnSize, kDrawnSize), 2, gfx::Size(kHalfDrawnSize, kHalfDrawnSize), 1)); InkDropAnimationTestApi test_api(ink_drop_animation.get()); InkDropAnimationTestApi::InkDropTransforms transforms; test_api.CalculateCircleTransforms( gfx::Size(kTransformedSize, kTransformedSize), &transforms); // Transform variables to reduce verbosity of actual verification code. const gfx::Transform kTopLeftTransform = transforms[InkDropAnimationTestApi::PaintedShape::TOP_LEFT_CIRCLE]; const gfx::Transform kTopRightTransform = transforms[InkDropAnimationTestApi::PaintedShape::TOP_RIGHT_CIRCLE]; const gfx::Transform kBottomRightTransform = transforms[InkDropAnimationTestApi::PaintedShape::BOTTOM_RIGHT_CIRCLE]; const gfx::Transform kBottomLeftTransform = transforms[InkDropAnimationTestApi::PaintedShape::BOTTOM_LEFT_CIRCLE]; const gfx::Transform kHorizontalTransform = transforms[InkDropAnimationTestApi::PaintedShape::HORIZONTAL_RECT]; const gfx::Transform kVerticalTransform = transforms[InkDropAnimationTestApi::PaintedShape::VERTICAL_RECT]; // Top left circle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kTopLeftTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedSize, 0), TransformPoint(kTopLeftTransform, mid_left)); EXPECT_EQ(gfx::Point(kHalfTransformedSize, 0), TransformPoint(kTopLeftTransform, mid_right)); EXPECT_EQ(gfx::Point(0, -kHalfTransformedSize), TransformPoint(kTopLeftTransform, top_mid)); EXPECT_EQ(gfx::Point(0, kHalfTransformedSize), TransformPoint(kTopLeftTransform, bottom_mid)); // Top right circle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kTopRightTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedSize, 0), TransformPoint(kTopRightTransform, mid_left)); EXPECT_EQ(gfx::Point(kHalfTransformedSize, 0), TransformPoint(kTopRightTransform, mid_right)); EXPECT_EQ(gfx::Point(0, -kHalfTransformedSize), TransformPoint(kTopRightTransform, top_mid)); EXPECT_EQ(gfx::Point(0, kHalfTransformedSize), TransformPoint(kTopRightTransform, bottom_mid)); // Bottom right circle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kBottomRightTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedSize, 0), TransformPoint(kBottomRightTransform, mid_left)); EXPECT_EQ(gfx::Point(kHalfTransformedSize, 0), TransformPoint(kBottomRightTransform, mid_right)); EXPECT_EQ(gfx::Point(0, -kHalfTransformedSize), TransformPoint(kBottomRightTransform, top_mid)); EXPECT_EQ(gfx::Point(0, kHalfTransformedSize), TransformPoint(kBottomRightTransform, bottom_mid)); // Bottom left circle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kBottomLeftTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedSize, 0), TransformPoint(kBottomLeftTransform, mid_left)); EXPECT_EQ(gfx::Point(kHalfTransformedSize, 0), TransformPoint(kBottomLeftTransform, mid_right)); EXPECT_EQ(gfx::Point(0, -kHalfTransformedSize), TransformPoint(kBottomLeftTransform, top_mid)); EXPECT_EQ(gfx::Point(0, kHalfTransformedSize), TransformPoint(kBottomLeftTransform, bottom_mid)); // Horizontal rectangle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kHorizontalTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedSize, 0), TransformPoint(kHorizontalTransform, mid_left)); EXPECT_EQ(gfx::Point(kHalfTransformedSize, 0), TransformPoint(kHorizontalTransform, mid_right)); EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kHorizontalTransform, top_mid)); EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kHorizontalTransform, bottom_mid)); // Vertical rectangle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kVerticalTransform, center)); EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kVerticalTransform, mid_left)); EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kVerticalTransform, mid_right)); EXPECT_EQ(gfx::Point(0, -kHalfTransformedSize), TransformPoint(kVerticalTransform, top_mid)); EXPECT_EQ(gfx::Point(0, kHalfTransformedSize), TransformPoint(kVerticalTransform, bottom_mid)); } TEST_F(InkDropAnimationTest, TransformedPointsUsingTransformsFromCalculateRectTransforms) { const int kHalfDrawnSize = 5; const int kDrawnSize = 2 * kHalfDrawnSize; const int kTransformedRadius = 10; const int kHalfTransformedWidth = 100; const int kTransformedWidth = 2 * kHalfTransformedWidth; const int kHalfTransformedHeight = 100; const int kTransformedHeight = 2 * kHalfTransformedHeight; // Constant points in the drawn space that will be transformed. const gfx::Point center(kHalfDrawnSize, kHalfDrawnSize); const gfx::Point mid_left(0, kHalfDrawnSize); const gfx::Point mid_right(kDrawnSize, kHalfDrawnSize); const gfx::Point top_mid(kHalfDrawnSize, 0); const gfx::Point bottom_mid(kHalfDrawnSize, kDrawnSize); scoped_ptr<InkDropAnimation> ink_drop_animation( new InkDropAnimation(gfx::Size(kDrawnSize, kDrawnSize), 2, gfx::Size(kHalfDrawnSize, kHalfDrawnSize), 1)); InkDropAnimationTestApi test_api(ink_drop_animation.get()); InkDropAnimationTestApi::InkDropTransforms transforms; test_api.CalculateRectTransforms( gfx::Size(kTransformedWidth, kTransformedHeight), kTransformedRadius, &transforms); // Transform variables to reduce verbosity of actual verification code. const gfx::Transform kTopLeftTransform = transforms[InkDropAnimationTestApi::PaintedShape::TOP_LEFT_CIRCLE]; const gfx::Transform kTopRightTransform = transforms[InkDropAnimationTestApi::PaintedShape::TOP_RIGHT_CIRCLE]; const gfx::Transform kBottomRightTransform = transforms[InkDropAnimationTestApi::PaintedShape::BOTTOM_RIGHT_CIRCLE]; const gfx::Transform kBottomLeftTransform = transforms[InkDropAnimationTestApi::PaintedShape::BOTTOM_LEFT_CIRCLE]; const gfx::Transform kHorizontalTransform = transforms[InkDropAnimationTestApi::PaintedShape::HORIZONTAL_RECT]; const gfx::Transform kVerticalTransform = transforms[InkDropAnimationTestApi::PaintedShape::VERTICAL_RECT]; const int x_offset = kHalfTransformedWidth - kTransformedRadius; const int y_offset = kHalfTransformedWidth - kTransformedRadius; // Top left circle EXPECT_EQ(gfx::Point(-x_offset, -y_offset), TransformPoint(kTopLeftTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedWidth, -y_offset), TransformPoint(kTopLeftTransform, mid_left)); EXPECT_EQ(gfx::Point(-x_offset, -kHalfTransformedHeight), TransformPoint(kTopLeftTransform, top_mid)); // Top right circle EXPECT_EQ(gfx::Point(x_offset, -y_offset), TransformPoint(kTopRightTransform, center)); EXPECT_EQ(gfx::Point(kHalfTransformedWidth, -y_offset), TransformPoint(kTopRightTransform, mid_right)); EXPECT_EQ(gfx::Point(x_offset, -kHalfTransformedHeight), TransformPoint(kTopRightTransform, top_mid)); // Bottom right circle EXPECT_EQ(gfx::Point(x_offset, y_offset), TransformPoint(kBottomRightTransform, center)); EXPECT_EQ(gfx::Point(kHalfTransformedWidth, y_offset), TransformPoint(kBottomRightTransform, mid_right)); EXPECT_EQ(gfx::Point(x_offset, kHalfTransformedHeight), TransformPoint(kBottomRightTransform, bottom_mid)); // Bottom left circle EXPECT_EQ(gfx::Point(-x_offset, y_offset), TransformPoint(kBottomLeftTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedWidth, y_offset), TransformPoint(kBottomLeftTransform, mid_left)); EXPECT_EQ(gfx::Point(-x_offset, kHalfTransformedHeight), TransformPoint(kBottomLeftTransform, bottom_mid)); // Horizontal rectangle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kHorizontalTransform, center)); EXPECT_EQ(gfx::Point(-kHalfTransformedWidth, 0), TransformPoint(kHorizontalTransform, mid_left)); EXPECT_EQ(gfx::Point(kHalfTransformedWidth, 0), TransformPoint(kHorizontalTransform, mid_right)); EXPECT_EQ(gfx::Point(0, -y_offset), TransformPoint(kHorizontalTransform, top_mid)); EXPECT_EQ(gfx::Point(0, y_offset), TransformPoint(kHorizontalTransform, bottom_mid)); // Vertical rectangle EXPECT_EQ(gfx::Point(0, 0), TransformPoint(kVerticalTransform, center)); EXPECT_EQ(gfx::Point(-x_offset, 0), TransformPoint(kVerticalTransform, mid_left)); EXPECT_EQ(gfx::Point(x_offset, 0), TransformPoint(kVerticalTransform, mid_right)); EXPECT_EQ(gfx::Point(0, -kHalfTransformedHeight), TransformPoint(kVerticalTransform, top_mid)); EXPECT_EQ(gfx::Point(0, kHalfTransformedHeight), TransformPoint(kVerticalTransform, bottom_mid)); } } // namespace test } // namespace views #endif // UI_VIEWS_ANIMATION_INK_DROP_ANIMATION_UNITTEST_H_
43.462295
80
0.759128
wedataintelligence
91fba7fbcbec3c3c1017da674cf1f51386ef9ded
806
cpp
C++
Recursion and Backtracking/AllIndicesOfX.cpp
Ankitlenka26/IP2021
99322c9c84a8a9c9178a505afbffdcebd312b059
[ "MIT" ]
null
null
null
Recursion and Backtracking/AllIndicesOfX.cpp
Ankitlenka26/IP2021
99322c9c84a8a9c9178a505afbffdcebd312b059
[ "MIT" ]
null
null
null
Recursion and Backtracking/AllIndicesOfX.cpp
Ankitlenka26/IP2021
99322c9c84a8a9c9178a505afbffdcebd312b059
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<int> *allIndices(vector<int> arr, int x, int idx, int fsf) { if (idx == arr.size()) { vector<int> *res = new vector<int>(fsf); return res; } if (arr[idx] == x) { vector<int> *iarr = allIndices(arr, x, idx + 1, fsf + 1); iarr->at(fsf) = idx; return iarr; } else { vector<int> *iarr = allIndices(arr, x, idx + 1, fsf); return iarr; } } int main() { int n; cin >> n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } int x; cin >> x; vector<int> *ans = allIndices(arr, x, 0, 0); for (int i = 0; i < ans->size(); i++) { cout << ans->at(i) << endl; } return 0; }
17.521739
65
0.46402
Ankitlenka26
91fd3fe0219c586b1d4a975467d4a9e5a93d7ec9
5,625
cpp
C++
Src/Files/MXFileMap.cpp
L-Spiro/MhsX
9cc71fbbac93ba54a01839db129cd9b47a68f29e
[ "BSD-2-Clause" ]
19
2016-09-07T18:22:09.000Z
2022-03-25T23:05:39.000Z
Src/Files/MXFileMap.cpp
L-Spiro/MhsX
9cc71fbbac93ba54a01839db129cd9b47a68f29e
[ "BSD-2-Clause" ]
1
2021-09-30T14:24:54.000Z
2021-11-13T14:58:02.000Z
Src/Files/MXFileMap.cpp
L-Spiro/MhsX
9cc71fbbac93ba54a01839db129cd9b47a68f29e
[ "BSD-2-Clause" ]
5
2018-04-10T16:52:25.000Z
2021-05-11T02:40:17.000Z
#include "MXFileMap.h" #include "../System/MXSystem.h" #include <algorithm> // == Macros. #define MX_MAP_BUF_SIZE static_cast<UINT64>(mx::CSystem::GetSystemInfo().dwAllocationGranularity * 64) namespace mx { CFileMap::CFileMap() : m_hFile( INVALID_HANDLE_VALUE ), m_hMap( INVALID_HANDLE_VALUE ), m_pbMapBuffer( nullptr ), m_bIsEmpty( TRUE ), m_bWritable( TRUE ), m_ui64Size( 0 ), m_ui64MapStart( MAXUINT64 ), m_dwMapSize( 0 ) { } CFileMap::~CFileMap() { Close(); } // == Functions. // Creates a file mapping. Always opens for read, may also open for write. BOOL CFileMap::CreateMap( LPCSTR _lpcFile, BOOL _bOpenForWrite ) { Close(); m_hFile = ::CreateFileA( _lpcFile, _bOpenForWrite ? (GENERIC_READ | GENERIC_WRITE) : GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if ( m_hFile == INVALID_HANDLE_VALUE ) { return FALSE; } m_bWritable = _bOpenForWrite; return CreateFileMap(); } // Creates a file mapping. Always opens for read, may also open for write. BOOL CFileMap::CreateMap( LPCWSTR _lpwFile, BOOL _bOpenForWrite ) { Close(); m_hFile = ::CreateFileW( _lpwFile, _bOpenForWrite ? (GENERIC_READ | GENERIC_WRITE) : GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if ( m_hFile == INVALID_HANDLE_VALUE ) { return FALSE; } m_bWritable = _bOpenForWrite; return CreateFileMap(); } // Closes the opened file map. VOID CFileMap::Close() { if ( m_pbMapBuffer ) { ::UnmapViewOfFile( m_pbMapBuffer ); m_pbMapBuffer = nullptr; } if ( m_hMap != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_hMap ); m_hMap = INVALID_HANDLE_VALUE; } if ( m_hFile != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_hFile ); m_hFile = INVALID_HANDLE_VALUE; } m_bIsEmpty = TRUE; m_ui64Size = 0; m_ui64MapStart = MAXUINT64; m_dwMapSize = 0; } // Gets the size of the file. UINT64 CFileMap::Size() const { if ( !m_ui64Size ) { m_ui64Size = CFile::Size( m_hFile ); } return m_ui64Size; } // Reads from the opened file. DWORD CFileMap::Read( LPVOID _lpvBuffer, UINT64 _ui64From, DWORD _dwNumberOfBytesToRead ) const { _dwNumberOfBytesToRead = static_cast<DWORD>(std::min( static_cast<UINT64>(_dwNumberOfBytesToRead), Size() - _ui64From )); // Read in 8-megabyte chunks. PBYTE pbDst = static_cast<PBYTE>(_lpvBuffer); DWORD dwWritten = 0; while ( _dwNumberOfBytesToRead ) { DWORD dwReadAmount = std::min( static_cast<DWORD>(8 * 1024 * 1024), _dwNumberOfBytesToRead ); if ( !MapRegion( _ui64From, dwReadAmount ) ) { return dwWritten; } std::memcpy( pbDst, &m_pbMapBuffer[_ui64From-m_ui64MapStart], dwReadAmount ); _dwNumberOfBytesToRead -= dwReadAmount; _ui64From += dwReadAmount; pbDst += dwReadAmount; } return dwWritten; } // Writes to the opened file. DWORD CFileMap::Write( LPCVOID _lpvBuffer, UINT64 _ui64From, DWORD _dwNumberOfBytesToWrite ) { _dwNumberOfBytesToWrite = static_cast<DWORD>(std::min( static_cast<UINT64>(_dwNumberOfBytesToWrite), Size() - _ui64From )); // Write in 8-megabyte chunks. const BYTE * pbSrc = static_cast<const BYTE *>(_lpvBuffer); DWORD dwWritten = 0; while ( _dwNumberOfBytesToWrite ) { DWORD dwWriteAmount = std::min( static_cast<DWORD>(8 * 1024 * 1024), _dwNumberOfBytesToWrite ); if ( !MapRegion( _ui64From, dwWriteAmount ) ) { return dwWritten; } std::memcpy( &m_pbMapBuffer[_ui64From-m_ui64MapStart], pbSrc, dwWriteAmount ); _dwNumberOfBytesToWrite -= dwWriteAmount; _ui64From += dwWriteAmount; pbSrc += dwWriteAmount; } return dwWritten; } // Creates the file map. BOOL CFileMap::CreateFileMap() { if ( m_hFile == INVALID_HANDLE_VALUE ) { return FALSE; } // Can't open 0-sized files. Emulate the successful mapping of such a file. m_bIsEmpty = Size() == 0; if ( m_bIsEmpty ) { return TRUE; } m_hMap = ::CreateFileMappingW( m_hFile, NULL, m_bWritable ? PAGE_READWRITE : PAGE_READONLY, 0, 0, NULL ); if ( m_hMap == NULL ) { // For some reason ::CreateFileMapping() returns NULL rather than INVALID_HANDLE_VALUE. m_hMap = INVALID_HANDLE_VALUE; Close(); return FALSE; } m_ui64MapStart = MAXUINT64; m_dwMapSize = 0; return TRUE; } // Map a region of the file. BOOL CFileMap::MapRegion( UINT64 _ui64Offset, DWORD _dwSize ) const { if ( m_hMap == INVALID_HANDLE_VALUE ) { return FALSE; } UINT64 ui64Adjusted = AdjustBase( _ui64Offset ); DWORD dwNewSize = static_cast<DWORD>((_ui64Offset - ui64Adjusted) + _dwSize); dwNewSize = static_cast<DWORD>(std::min( static_cast<UINT64>(dwNewSize), Size() - ui64Adjusted )); if ( m_pbMapBuffer && ui64Adjusted == m_ui64MapStart && dwNewSize == m_dwMapSize ) { return TRUE; } if ( m_pbMapBuffer ) { // Unmap existing buffer. ::UnmapViewOfFile( m_pbMapBuffer ); m_pbMapBuffer = nullptr; m_ui64MapStart = MAXUINT64; m_dwMapSize = 0; } m_pbMapBuffer = static_cast<PBYTE>(::MapViewOfFile( m_hMap, (m_bWritable ? FILE_MAP_WRITE : 0) | FILE_MAP_READ, static_cast<DWORD>(ui64Adjusted >> 32), static_cast<DWORD>(ui64Adjusted), dwNewSize )); if ( !m_pbMapBuffer ) { return FALSE; } m_ui64MapStart = ui64Adjusted; m_dwMapSize = dwNewSize; return TRUE; } // Adjusts the input to the nearest mapping offset. UINT64 CFileMap::AdjustBase( UINT64 _ui64Offset ) const { if ( _ui64Offset < (MX_MAP_BUF_SIZE >> 1) ) { return 0; } if ( Size() <= MX_MAP_BUF_SIZE ) { return 0; } return ((_ui64Offset + (MX_MAP_BUF_SIZE >> 2)) & (~((MX_MAP_BUF_SIZE >> 1) - 1))) - (MX_MAP_BUF_SIZE >> 1); } } // namespace mx
29.605263
125
0.692622
L-Spiro
620288765be66bd87d59f31ce83df1017554225f
515
cc
C++
src/Plugin.cc
corelight/zeek-macho
85367ecec91eee906a13c244e01fb758db9a762a
[ "BSD-3-Clause" ]
5
2019-12-13T21:09:20.000Z
2020-04-03T05:47:37.000Z
src/Plugin.cc
corelight/zeek-macho
85367ecec91eee906a13c244e01fb758db9a762a
[ "BSD-3-Clause" ]
null
null
null
src/Plugin.cc
corelight/zeek-macho
85367ecec91eee906a13c244e01fb758db9a762a
[ "BSD-3-Clause" ]
2
2019-12-13T21:09:24.000Z
2020-02-16T13:46:05.000Z
#include "Plugin.h" #include "macho.h" namespace plugin { namespace Zeek_MACHO { Plugin plugin; } } using namespace plugin::Zeek_MACHO; plugin::Configuration Plugin::Configure() { AddComponent(new ::file_analysis::Component("MACHO", ::file_analysis::MACHO::Instantiate)); plugin::Configuration config; config.name = "Zeek::MACHO"; config.description = "MACH-O File Analyzer"; config.version.major = 0; config.version.minor = 1; config.version.patch = 0; return config; }
25.75
95
0.68932
corelight
62048ec0f66798a11c8ae21b2073fe539bef4a1a
3,216
cpp
C++
src/ExtentInsideNode.cpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
2
2020-02-16T07:46:47.000Z
2020-11-23T06:50:19.000Z
src/ExtentInsideNode.cpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
null
null
null
src/ExtentInsideNode.cpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
null
null
null
/*========================================================================== * Copyright (c) 2004 University of Massachusetts. All Rights Reserved. * * Use of the Lemur Toolkit for Language Modeling and Information Retrieval * is subject to the terms of the software license set forth in the LICENSE * file included with this software, and also available at * http://www.lemurproject.org/license.html * *========================================================================== */ // // ExtentInsideNode // // 28 July 2004 -- tds // #include "indri/ExtentInsideNode.hpp" #include "lemur/lemur-compat.hpp" #include "indri/Annotator.hpp" indri::infnet::ExtentInsideNode::ExtentInsideNode( const std::string& name, ListIteratorNode* inner, ListIteratorNode* outer ) : _inner(inner), _outer(outer), _name(name) { } void indri::infnet::ExtentInsideNode::prepare( lemur::api::DOCID_T documentID ) { // initialize the child / sibling pointer initpointer(); _extents.clear(); _lastExtent.begin = -1; _lastExtent.end = -1; if( !_inner || !_outer ) return; const indri::utility::greedy_vector<indri::index::Extent>& inExtents = _inner->extents(); const indri::utility::greedy_vector<indri::index::Extent>& outExtents = _outer->extents(); indri::utility::greedy_vector<indri::index::Extent>::const_iterator innerIter = inExtents.begin(); indri::utility::greedy_vector<indri::index::Extent>::const_iterator outerIter = outExtents.begin(); while( innerIter != inExtents.end() && outerIter != outExtents.end() ) { if( outerIter->contains( *innerIter ) ) { _extents.push_back( *innerIter ); innerIter++; } else if( outerIter->begin <= innerIter->begin ) { outerIter++; } else { innerIter++; } } } const indri::utility::greedy_vector<indri::index::Extent>& indri::infnet::ExtentInsideNode::extents() { return _extents; } lemur::api::DOCID_T indri::infnet::ExtentInsideNode::nextCandidateDocument() { return lemur_compat::max( _inner->nextCandidateDocument(), _outer->nextCandidateDocument() ); } const std::string& indri::infnet::ExtentInsideNode::getName() const { return _name; } void indri::infnet::ExtentInsideNode::annotate( class Annotator& annotator, lemur::api::DOCID_T documentID, indri::index::Extent &extent ) { if (! _lastExtent.contains(extent)) { // if the last extent we annotated contains this one, there is no work // to do. _lastExtent = extent; annotator.addMatches( _extents, this, documentID, extent ); indri::index::Extent range( extent.begin, extent.end ); indri::utility::greedy_vector<indri::index::Extent>::const_iterator iter; iter = std::lower_bound( _extents.begin(), _extents.end(), range, indri::index::Extent::begins_before_less() ); for( size_t i = iter-_extents.begin(); i<_extents.size() && _extents[i].begin <= extent.end; i++ ) { _inner->annotate( annotator, documentID, (indri::index::Extent &)_extents[i] ); _outer->annotate( annotator, documentID, (indri::index::Extent &)_extents[i] ); } } } void indri::infnet::ExtentInsideNode::indexChanged( indri::index::Index& index ) { _lastExtent.begin = -1; _lastExtent.end = -1; }
34.212766
140
0.666045
whuang022nccu
620ca58597396c4be1b5a8cc354ce29c2941f132
274
hpp
C++
include/server/http/compression_type.hpp
EricWang1hitsz/osrm-backend
ff1af413d6c78f8e454584fe978d5468d984d74a
[ "BSD-2-Clause" ]
4,526
2015-01-01T15:31:00.000Z
2022-03-31T17:33:49.000Z
include/server/http/compression_type.hpp
wsx9527/osrm-backend
1e70b645e480946dad313b67f6a7d331baecfe3c
[ "BSD-2-Clause" ]
4,497
2015-01-01T15:29:12.000Z
2022-03-31T19:19:35.000Z
include/server/http/compression_type.hpp
wsx9527/osrm-backend
1e70b645e480946dad313b67f6a7d331baecfe3c
[ "BSD-2-Clause" ]
3,023
2015-01-01T18:40:53.000Z
2022-03-30T13:30:46.000Z
#ifndef COMPRESSION_TYPE_HPP #define COMPRESSION_TYPE_HPP namespace osrm { namespace server { namespace http { enum compression_type { no_compression, gzip_rfc1952, deflate_rfc1951 }; } } // namespace server } // namespace osrm #endif // COMPRESSION_TYPE_HPP
12.454545
30
0.755474
EricWang1hitsz
620d975f95ed00e1af3139341fe73dce7c471020
1,459
cc
C++
src/arc036/b.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/arc036/b.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/arc036/b.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#ifdef _debug #define _GLIBCXX_DEBUG #endif #include <bits/stdc++.h> using namespace std; typedef long long ll; int peek(int start, vector<ll> &h, vector<ll> &down) { ll m = h[start]; int index = start + 1; while(index < (int)h.size()) { if(m > h[index]) { m = h[index]; index++; } else { // m <= h[index]; break; } } for(int i = start; i < index; i++) down[i] = index - 1; return index; } int peek_up(int start, vector<ll> &h, vector<ll> &up) { ll m = h[start]; int index = start - 1; while(index >= 0) { if(m > h[index]) { m = h[index]; index--; } else { // m <= h[index]; break; } } for(int i = start; i > index; i--) up[i] = index + 1; return index; } ll solve(int n, vector<ll> h) { vector<ll> up(n), down(n); for(int i = 0; i < n;) { i = peek(i, h, down); } for(int i = n - 1; i >= 0;) { i = peek_up(i, h, up); } /* for(int i = 0; i < n; i++) cout << i << " " << h[i] << " " << down[i] << " " << up[i] << endl; */ ll res = 0ll; for(int i = 0; i < n; i++) res = max(down[i] - up[i] + 1, res); return res; } #ifndef _debug int main() { int n; cin >> n; vector<ll> h(n); for(int i = 0; i < n; i++) cin >> h[i]; cout << solve(n, h) << endl; return 0; } #endif
21.144928
75
0.42769
nryotaro
620f8d9df58ef05e0fa03a8ff474ac4aa81876ca
499
cpp
C++
007-Reverse-Integer/solution.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
3
2019-05-27T06:47:32.000Z
2020-12-22T05:57:10.000Z
007-Reverse-Integer/solution.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
null
null
null
007-Reverse-Integer/solution.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
5
2020-04-01T10:26:04.000Z
2022-02-05T18:21:01.000Z
#include "solution.hpp" #include <limits.h> static auto x = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams cin.tie(NULL); return 0; }(); int Solution::reverse(int x) { int y = 0; int sign = x > 0 ? 1 : -1; x *= sign; int tmp, new_y; while (x) { tmp = x / 10; if (y > INT_MAX / 10) return 0; y *= 10; new_y = x - tmp * 10; if (y > INT_MAX - new_y) return 0; y += new_y; x = tmp; } return y * sign; }
16.096774
35
0.513026
johnhany
62105e35a225e3ba313c25872bce921d49d03304
5,362
hh
C++
jpeg.hh
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
9
2019-09-17T10:33:58.000Z
2021-07-29T10:03:42.000Z
jpeg.hh
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
null
null
null
jpeg.hh
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
1
2019-10-05T04:31:22.000Z
2019-10-05T04:31:22.000Z
// Copyright Stephan T. Lavavej, http://nuwen.net . // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://boost.org/LICENSE_1_0.txt . #ifndef PHAM_JPEG_HH #define PHAM_JPEG_HH #include "compiler.hh" #ifdef NUWEN_PLATFORM_MSVC #pragma once #endif #include "typedef.hh" #include "external_begin.hh" #include <stdexcept> #include <boost/format.hpp> #include <boost/tuple/tuple.hpp> #include <boost/utility.hpp> #include <jerror.h> #include <jpeglib.h> #include "external_end.hh" namespace nuwen { inline boost::tuple<ul_t, ul_t, vuc_t> decompress_jpeg_insecurely(const vuc_t& input, ul_t max_width = 2048, ul_t max_height = 2048); } namespace pham { inline void output_message(jpeg_common_struct * const p) { if (p->client_data) { p->err->format_message(p, static_cast<char *>(p->client_data)); p->client_data = NULL; } } inline void do_nothing(jpeg_decompress_struct *) { } const nuwen::uc_t fake_eoi_marker[] = { 0xFF, JPEG_EOI }; inline JPEG_boolean fill_input_buffer(jpeg_decompress_struct * const p) { // Obnoxiously, WARNMS is a macro that contains an old-style cast. p->err->msg_code = JWRN_JPEG_EOF; p->err->emit_message(reinterpret_cast<jpeg_common_struct *>(p), -1); p->src->next_input_byte = fake_eoi_marker; p->src->bytes_in_buffer = 2; return JPEG_TRUE; } inline void skip_input_data(jpeg_decompress_struct * const p, const long n) { // POISON_OK if (n > 0) { if (static_cast<nuwen::ul_t>(n) < p->src->bytes_in_buffer) { p->src->next_input_byte += n; p->src->bytes_in_buffer -= n; } else { p->src->next_input_byte = NULL; p->src->bytes_in_buffer = 0; } } } namespace jpeg { class decompressor_destroyer : public boost::noncopyable { public: explicit decompressor_destroyer(jpeg_decompress_struct& d) : m_p(&d) { } ~decompressor_destroyer() { jpeg_destroy_decompress(m_p); } private: jpeg_decompress_struct * const m_p; }; } } inline boost::tuple<nuwen::ul_t, nuwen::ul_t, nuwen::vuc_t> nuwen::decompress_jpeg_insecurely( const vuc_t& input, const ul_t max_width, const ul_t max_height) { using namespace std; using namespace boost; using namespace pham; using namespace pham::jpeg; if (input.empty()) { throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Empty input."); } jpeg_error_mgr error_manager; jpeg_decompress_struct decompressor; decompressor.err = jpeg_std_error(&error_manager); vc_t warning_message(JMSG_LENGTH_MAX, 0); decompressor.client_data = &warning_message[0]; decompressor.err->output_message = output_message; // Obnoxiously, jpeg_create_decompress is a macro that contains an old-style cast. jpeg_CreateDecompress(&decompressor, JPEG_LIB_VERSION, sizeof decompressor); jpeg_source_mgr source_manager; source_manager.next_input_byte = &input[0]; source_manager.bytes_in_buffer = input.size(); source_manager.init_source = do_nothing; source_manager.fill_input_buffer = fill_input_buffer; source_manager.skip_input_data = skip_input_data; source_manager.resync_to_restart = jpeg_resync_to_restart; // Default method. source_manager.term_source = do_nothing; decompressor.src = &source_manager; decompressor_destroyer destroyer(decompressor); jpeg_read_header(&decompressor, JPEG_TRUE); const ul_t width = decompressor.image_width; const ul_t height = decompressor.image_height; if (width == 0) { throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Zero width."); } if (height == 0) { throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Zero height."); } if (width > max_width) { throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Huge width."); } if (height > max_height) { throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Huge height."); } if (decompressor.num_components != 3) { throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Unexpected number of components."); } jpeg_start_decompress(&decompressor); tuple<ul_t, ul_t, vuc_t> ret(width, height, vuc_t(width * height * decompressor.num_components, 0)); uc_t * scanptr = &ret.get<2>()[0]; // No scaling is being used. while (decompressor.output_scanline < height) { if (jpeg_read_scanlines(&decompressor, &scanptr, 1) != 1) { throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - jpeg_read_scanlines() failed."); } scanptr += width * decompressor.num_components; } jpeg_finish_decompress(&decompressor); if (decompressor.client_data == NULL) { throw runtime_error(str(format( "RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - libjpeg warned \"%1%\".") % &warning_message[0])); } return ret; } #endif // Idempotency
31.727811
137
0.666729
nurettin
62127681cd9acbe8377127c01db5943dc704cf63
2,246
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Particles/FLUID_PARTICLES.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Particles/FLUID_PARTICLES.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Particles/FLUID_PARTICLES.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2011, Wen Zheng. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Vectors/VECTOR.h> #include <PhysBAM_Dynamics/Particles/PARTICLES_FORWARD.h> #include <PhysBAM_Dynamics/Particles/FLUID_PARTICLES.h> namespace PhysBAM{ //##################################################################### // Constructor //##################################################################### template<class TV> FLUID_PARTICLES<TV>:: FLUID_PARTICLES() :F(0,0),momentum_residual(0,0),color(0,0),volume(0,0),volume_residual(0,0),on_boundary(0,0),type(0,0),normal(0,0),node(0,0),age(0,0),phi(0,0) { Store_Id(); Store_Velocity(); array_collection->Add_Array(ATTRIBUTE_ID_FORCE,&F); //array_collection->Add_Array(ATTRIBUTE_ID_MOMENTUM_RESIDUAL,&momentum_residual); array_collection->Add_Array(ATTRIBUTE_ID_COLOR,&color); array_collection->Add_Array(ATTRIBUTE_ID_VOLUME,&volume); array_collection->Add_Array(ATTRIBUTE_ID_VOLUME_RESIDUAL,&volume_residual); array_collection->Add_Array(ATTRIBUTE_ID_ON_BOUNDARY,&on_boundary); array_collection->Add_Array(ATTRIBUTE_ID_TYPE,&type); //array_collection->Add_Array(ATTRIBUTE_ID_NORMAL,&normal); array_collection->Add_Array(ATTRIBUTE_ID_NODE,&node); array_collection->Add_Array(ATTRIBUTE_ID_AGE,&age); //array_collection->Add_Array(ATTRIBUTE_ID_PHI,&phi); } //##################################################################### // Constructor //##################################################################### template<class TV> FLUID_PARTICLES<TV>:: ~FLUID_PARTICLES() {} //##################################################################### template class FLUID_PARTICLES<VECTOR<float,1> >; template class FLUID_PARTICLES<VECTOR<float,2> >; template class FLUID_PARTICLES<VECTOR<float,3> >; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class FLUID_PARTICLES<VECTOR<double,1> >; template class FLUID_PARTICLES<VECTOR<double,2> >; template class FLUID_PARTICLES<VECTOR<double,3> >; #endif }
48.826087
145
0.610864
schinmayee
6215da75e5af5b8ace5786fc03f34f5472061835
10,498
cpp
C++
examples/tessellation/tessellation.cpp
harskish/Vulkan
25be6e4fda8b0d16875a55a1a476209305d4a983
[ "MIT" ]
318
2016-05-30T18:53:13.000Z
2022-03-23T19:09:57.000Z
examples/tessellation/tessellation.cpp
harskish/Vulkan
25be6e4fda8b0d16875a55a1a476209305d4a983
[ "MIT" ]
47
2016-06-04T20:53:27.000Z
2020-12-21T17:14:21.000Z
examples/tessellation/tessellation.cpp
harskish/Vulkan
25be6e4fda8b0d16875a55a1a476209305d4a983
[ "MIT" ]
35
2016-06-08T11:05:02.000Z
2021-07-26T17:26:36.000Z
/* * Vulkan Example - Tessellation shader PN triangles * * Based on http://alex.vlachos.com/graphics/CurvedPNTriangles.pdf * Shaders based on http://onrendering.blogspot.de/2011/12/tessellation-on-gpu-curved-pn-triangles.html * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkanExampleBase.h" // Vertex layout for this example vks::model::VertexLayout vertexLayout{ { vks::model::VERTEX_COMPONENT_POSITION, vks::model::VERTEX_COMPONENT_NORMAL, vks::model::VERTEX_COMPONENT_UV } }; class VulkanExample : public vkx::ExampleBase { using Parent = vkx::ExampleBase; public: bool splitScreen = true; bool wireframe = true; struct { vks::texture::Texture2D colorMap; } textures; struct { vks::model::Model object; } meshes; vks::Buffer uniformDataTC, uniformDataTE; struct UboTC { float tessLevel = 3.0f; } uboTC; struct UboTE { glm::mat4 projection; glm::mat4 model; float tessAlpha = 1.0f; } uboTE; struct { vk::Pipeline solid; vk::Pipeline wire; vk::Pipeline solidPassThrough; vk::Pipeline wirePassThrough; } pipelines; vk::PipelineLayout pipelineLayout; vk::DescriptorSet descriptorSet; vk::DescriptorSetLayout descriptorSetLayout; VulkanExample() { camera.setRotation({ -350.0f, 60.0f, 0.0f }); camera.setTranslation({ -3.0f, 2.3f, -6.5f }); title = "Vulkan Example - Tessellation shader (PN Triangles)"; } void getEnabledFeatures() override { // Example uses tessellation shaders if (deviceFeatures.tessellationShader) { enabledFeatures.tessellationShader = VK_TRUE; } else { throw std::runtime_error("Selected GPU does not support tessellation shaders!"); } // Fill mode non solid is required for wireframe display if (deviceFeatures.fillModeNonSolid) { enabledFeatures.fillModeNonSolid = VK_TRUE; } else { wireframe = false; } } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class device.destroyPipeline(pipelines.solid); device.destroyPipeline(pipelines.wire); device.destroyPipeline(pipelines.solidPassThrough); device.destroyPipeline(pipelines.wirePassThrough); device.destroyPipelineLayout(pipelineLayout); device.destroyDescriptorSetLayout(descriptorSetLayout); meshes.object.destroy(); device.destroyBuffer(uniformDataTC.buffer); device.freeMemory(uniformDataTC.memory); device.destroyBuffer(uniformDataTE.buffer); device.freeMemory(uniformDataTE.memory); textures.colorMap.destroy(); } void updateDrawCommandBuffer(const vk::CommandBuffer& cmdBuffer) override { vk::Viewport viewport = vks::util::viewport(splitScreen ? (float)size.width / 2.0f : (float)size.width, (float)size.height, 0.0f, 1.0f); cmdBuffer.setViewport(0, viewport); cmdBuffer.setScissor(0, vks::util::rect2D(size)); cmdBuffer.setLineWidth(1.0f); cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSet, nullptr); vk::DeviceSize offsets = 0; cmdBuffer.bindVertexBuffers(0, meshes.object.vertices.buffer, offsets); cmdBuffer.bindIndexBuffer(meshes.object.indices.buffer, 0, vk::IndexType::eUint32); if (splitScreen) { cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, wireframe ? pipelines.wirePassThrough : pipelines.solidPassThrough); cmdBuffer.drawIndexed(meshes.object.indexCount, 1, 0, 0, 0); viewport.x = float(size.width) / 2; } cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, wireframe ? pipelines.wire : pipelines.solid); cmdBuffer.drawIndexed(meshes.object.indexCount, 1, 0, 0, 0); } void loadAssets() override { meshes.object.loadFromFile(context, getAssetPath() + "models/lowpoly/deer.dae", vertexLayout, 1.0f); textures.colorMap.loadFromFile(context, getAssetPath() + "textures/deer.ktx", vk::Format::eBc3UnormBlock); } void setupDescriptorPool() { std::vector<vk::DescriptorPoolSize> poolSizes = { vk::DescriptorPoolSize(vk::DescriptorType::eUniformBuffer, 3), vk::DescriptorPoolSize(vk::DescriptorType::eCombinedImageSampler, 1), }; descriptorPool = device.createDescriptorPool({ {}, 2, (uint32_t)poolSizes.size(), poolSizes.data() }); } void setupDescriptorSetLayout() { std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings{ { 0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eTessellationControl }, { 1, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eTessellationEvaluation }, { 2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment }, }; descriptorSetLayout = device.createDescriptorSetLayout({ {}, static_cast<uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() }); pipelineLayout = device.createPipelineLayout(vk::PipelineLayoutCreateInfo{ {}, 1, &descriptorSetLayout }); } void setupDescriptorSet() { descriptorSet = device.allocateDescriptorSets({ descriptorPool, 1, &descriptorSetLayout })[0]; vk::DescriptorImageInfo texDescriptor = vk::DescriptorImageInfo(textures.colorMap.sampler, textures.colorMap.view, vk::ImageLayout::eGeneral); std::vector<vk::WriteDescriptorSet> writeDescriptorSets{ // Binding 0 : Tessellation control shader ubo { descriptorSet, 0, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &uniformDataTC.descriptor }, // Binding 1 : Tessellation evaluation shader ubo { descriptorSet, 1, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &uniformDataTE.descriptor }, // Binding 2 : Color map { descriptorSet, 2, 0, 1, vk::DescriptorType::eCombinedImageSampler, &texDescriptor }, }; device.updateDescriptorSets(writeDescriptorSets, nullptr); } void preparePipelines() { vks::pipelines::GraphicsPipelineBuilder builder{ device, pipelineLayout, renderPass }; builder.inputAssemblyState.topology = vk::PrimitiveTopology::ePatchList; builder.dynamicState.dynamicStateEnables.push_back(vk::DynamicState::eLineWidth); builder.vertexInputState.appendVertexLayout(vertexLayout); vk::PipelineTessellationStateCreateInfo tessellationState{ {}, 3 }; builder.pipelineCreateInfo.pTessellationState = &tessellationState; // Tessellation pipelines // Load shaders builder.loadShader(getAssetPath() + "shaders/tessellation/base.vert.spv", vk::ShaderStageFlagBits::eVertex); builder.loadShader(getAssetPath() + "shaders/tessellation/base.frag.spv", vk::ShaderStageFlagBits::eFragment); builder.loadShader(getAssetPath() + "shaders/tessellation/pntriangles.tesc.spv", vk::ShaderStageFlagBits::eTessellationControl); builder.loadShader(getAssetPath() + "shaders/tessellation/pntriangles.tese.spv", vk::ShaderStageFlagBits::eTessellationEvaluation); // Tessellation pipelines // Solid pipelines.solid = builder.create(context.pipelineCache); // Wireframe builder.rasterizationState.polygonMode = vk::PolygonMode::eLine; pipelines.wire = builder.create(context.pipelineCache); // Pass through pipelines // Load pass through tessellation shaders (Vert and frag are reused) device.destroyShaderModule(builder.shaderStages[2].module); device.destroyShaderModule(builder.shaderStages[3].module); builder.shaderStages.resize(2); builder.loadShader(getAssetPath() + "shaders/tessellation/passthrough.tesc.spv", vk::ShaderStageFlagBits::eTessellationControl); builder.loadShader(getAssetPath() + "shaders/tessellation/passthrough.tese.spv", vk::ShaderStageFlagBits::eTessellationEvaluation); // Solid builder.rasterizationState.polygonMode = vk::PolygonMode::eFill; pipelines.solidPassThrough = builder.create(context.pipelineCache); // Wireframe builder.rasterizationState.polygonMode = vk::PolygonMode::eLine; pipelines.wirePassThrough = builder.create(context.pipelineCache); } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Tessellation evaluation shader uniform buffer uniformDataTE = context.createUniformBuffer(uboTE); // Tessellation control shader uniform buffer uniformDataTC = context.createUniformBuffer(uboTC); updateUniformBuffers(); } void updateUniformBuffers() { // Tessellation eval uboTE.projection = glm::perspective(glm::radians(45.0f), (float)(size.width * ((splitScreen) ? 0.5f : 1.0f)) / (float)size.height, 0.1f, 256.0f); uboTE.model = camera.matrices.view; uniformDataTE.copy(uboTE); // Tessellation control uniform block uniformDataTC.copy(uboTC); } void prepare() override { ExampleBase::prepare(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } void viewChanged() override { updateUniformBuffers(); } virtual void OnUpdateUIOverlay() { if (ui.header("Settings")) { if (ui.inputFloat("Tessellation level", &uboTC.tessLevel, 0.25f, 2)) { updateUniformBuffers(); } if (deviceFeatures.fillModeNonSolid) { if (ui.checkBox("Wireframe", &wireframe)) { updateUniformBuffers(); buildCommandBuffers(); } if (ui.checkBox("Splitscreen", &splitScreen)) { updateUniformBuffers(); buildCommandBuffers(); } } } } }; RUN_EXAMPLE(VulkanExample)
41.494071
153
0.672795
harskish
621dd17616a19e6c168e308708aae90df1cc581d
2,342
cpp
C++
tests/flvstream_unittest.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
28
2017-04-30T13:56:13.000Z
2022-03-20T06:54:37.000Z
tests/flvstream_unittest.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
72
2017-04-25T03:42:58.000Z
2021-12-04T06:35:28.000Z
tests/flvstream_unittest.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
12
2017-04-16T06:25:24.000Z
2021-07-07T13:28:27.000Z
#include <gtest/gtest.h> #include "flv.h" #include "amf0.h" class FLVStreamFixture : public ::testing::Test { public: FLVStreamFixture() { } void SetUp() { } void TearDown() { } ~FLVStreamFixture() { } }; TEST_F(FLVStreamFixture, readMetaData_commonCase) { std::string buf; buf += amf0::Value("onMetaData").serialize(); buf += amf0::Value::object( { { "videodatarate", 100 }, { "audiodatarate", 50 } }).serialize(); bool success; int bitrate; std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size()); ASSERT_TRUE(success); ASSERT_EQ(150, bitrate); } TEST_F(FLVStreamFixture, readMetaData_notOnMetaData) { std::string buf; buf += amf0::Value("hoge").serialize(); buf += amf0::Value::object( { { "videodatarate", 100 }, { "audiodatarate", 50 } }).serialize(); bool success; int bitrate; std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size()); ASSERT_FALSE(success); } TEST_F(FLVStreamFixture, readMetaData_onlyVideo) { std::string buf; buf += amf0::Value("onMetaData").serialize(); buf += amf0::Value::object( { { "videodatarate", 100 }, }).serialize(); bool success; int bitrate; std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size()); ASSERT_TRUE(success); ASSERT_EQ(100, bitrate); } TEST_F(FLVStreamFixture, readMetaData_onlyAudio) { std::string buf; buf += amf0::Value("onMetaData").serialize(); buf += amf0::Value::object( { { "audiodatarate", 50 }, }).serialize(); bool success; int bitrate; std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size()); ASSERT_TRUE(success); ASSERT_EQ(50, bitrate); } TEST_F(FLVStreamFixture, readMetaData_neitherRateIsSupplied) { std::string buf; buf += amf0::Value("onMetaData").serialize(); buf += amf0::Value::object({}).serialize(); bool success; int bitrate; std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size()); ASSERT_FALSE(success); }
21.099099
100
0.60205
plonk
62261d6120f78d8884b5feef2b8fd8606c40a360
559
hh
C++
example/include/core/capture/real_sense/Image.hh
thingthing/smart-agent
f4c41432b1bab3283b00237b0208676acb0a00b1
[ "MIT" ]
null
null
null
example/include/core/capture/real_sense/Image.hh
thingthing/smart-agent
f4c41432b1bab3283b00237b0208676acb0a00b1
[ "MIT" ]
null
null
null
example/include/core/capture/real_sense/Image.hh
thingthing/smart-agent
f4c41432b1bab3283b00237b0208676acb0a00b1
[ "MIT" ]
null
null
null
#ifndef _IMAGE_HH_ #define _IMAGE_HH_ class Image { public: Image(const uint8_t* rgb_image, size_t height, size_t width, double fx, double fy, double cx, double cy, const float *disto) : _rgb(rgb_image), _height(height), _width(width), _fx(fx), _fy(fy), _cx(cx), _cy(cy), _disto(disto) {} ~Image() {} private: Image(); public: const uint8_t *_rgb; size_t _height; size_t _width; //focal double _fx; double _fy; //Center point double _cx; double _cy; //Distortion matrice const float *_disto; }; #endif /*! _IMAGE_HH_ */
18.633333
65
0.67263
thingthing
622698bb9f169f8bf37060908f246b14927b1b47
11,535
cpp
C++
iceoryx_utils/test/moduletests/test_cxx_convert.cpp
Karsten1987/iceoryx
e5c23eaf5c351ef0095e43673282867b8d060026
[ "Apache-2.0" ]
2
2019-11-04T05:02:53.000Z
2019-11-04T05:19:20.000Z
iceoryx_utils/test/moduletests/test_cxx_convert.cpp
Karsten1987/iceoryx
e5c23eaf5c351ef0095e43673282867b8d060026
[ "Apache-2.0" ]
null
null
null
iceoryx_utils/test/moduletests/test_cxx_convert.cpp
Karsten1987/iceoryx
e5c23eaf5c351ef0095e43673282867b8d060026
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 by Robert Bosch GmbH. 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 "test.hpp" #include "iceoryx_utils/cxx/convert.hpp" #include <cstdint> using namespace ::testing; using NumberType = iox::cxx::convert::NumberType; class convert_test : public Test { public: void SetUp() { internal::CaptureStderr(); } virtual void TearDown() { std::string output = internal::GetCapturedStderr(); if (Test::HasFailure()) { std::cout << output << std::endl; } } }; TEST_F(convert_test, toString_Integer) { EXPECT_THAT(iox::cxx::convert::toString(123), Eq("123")); } TEST_F(convert_test, toString_Float) { EXPECT_THAT(iox::cxx::convert::toString(12.3f), Eq("12.3")); } TEST_F(convert_test, toString_LongLongUnsignedInt) { EXPECT_THAT(iox::cxx::convert::toString(123LLU), Eq("123")); } TEST_F(convert_test, toString_Char) { EXPECT_THAT(iox::cxx::convert::toString('x'), Eq("x")); } TEST_F(convert_test, toString_String) { EXPECT_THAT(iox::cxx::convert::toString(std::string("hello")), Eq("hello")); } TEST_F(convert_test, toString_StringConvertableClass) { struct A { operator std::string() const { return "fuu"; } }; EXPECT_THAT(iox::cxx::convert::toString(A()), Eq("fuu")); } TEST_F(convert_test, FromString_String) { std::string source = "hello"; std::string destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(source, Eq(destination)); } TEST_F(convert_test, fromString_Char_Success) { std::string source = "h"; char destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(source[0], Eq(destination)); } TEST_F(convert_test, fromString_Char_Fail) { std::string source = "hasd"; char destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, stringIsNumber_IsINTEGER) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("123921301", NumberType::INTEGER), Eq(true)); } TEST_F(convert_test, stringIsNumber_IsEmpty) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("", NumberType::INTEGER), Eq(false)); } TEST_F(convert_test, stringIsNumber_IsZero) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("0", NumberType::INTEGER), Eq(true)); } TEST_F(convert_test, stringIsNumber_INTEGERWithSign) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("-123", NumberType::INTEGER), Eq(true)); } TEST_F(convert_test, stringIsNumber_INTEGERWithSignPlacedWrongly) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("2-3", NumberType::UNSIGNED_INTEGER), Eq(false)); } TEST_F(convert_test, stringIsNumber_SimpleFLOAT) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("123.123", NumberType::FLOAT), Eq(true)); } TEST_F(convert_test, stringIsNumber_MultiDotFLOAT) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("12.3.123", NumberType::FLOAT), Eq(false)); } TEST_F(convert_test, stringIsNumber_FLOATWithSign) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("+123.123", NumberType::FLOAT), Eq(true)); } TEST_F(convert_test, stringIsNumber_NumberWithLetters) { EXPECT_THAT(iox::cxx::convert::stringIsNumber("+123a.123", NumberType::FLOAT), Eq(false)); } TEST_F(convert_test, fromString_FLOAT_Success) { std::string source = "123.01"; float destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_FLOAT_EQ(destination, 123.01f); } TEST_F(convert_test, fromString_FLOAT_Fail) { std::string source = "hasd"; float destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_Double_Success) { std::string source = "123.04"; double destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(static_cast<double>(123.04))); } TEST_F(convert_test, fromString_Double_Fail) { std::string source = "hasd"; double destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_LongDouble_Success) { std::string source = "123.01"; long double destination; long double verify = 123.01; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Ge(verify - 0.00001)); EXPECT_THAT(destination, Le(verify + 0.00001)); } TEST_F(convert_test, fromString_LongDouble_Fail) { std::string source = "hasd"; double destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_UNSIGNED_Int_Success) { std::string source = "123"; unsigned int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(123u)); } TEST_F(convert_test, fromString_UNSIGNED_Int_Fail) { std::string source = "-123"; unsigned int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_UNSIGNED_LongInt_Success) { std::string source = "123"; unsigned long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(123lu)); } TEST_F(convert_test, fromString_UNSIGNED_LongInt_Fail) { std::string source = "-a123"; unsigned long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_UNSIGNED_LongLongInt_Success) { std::string source = "123"; unsigned long long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(123llu)); } TEST_F(convert_test, fromString_UNSIGNED_LongLongInt_Fail) { std::string source = "-a123"; unsigned long long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_Int_Success) { std::string source = "123"; int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(123)); } TEST_F(convert_test, fromString_Int_Fail) { std::string source = "-+123"; int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_ShortInt_Success) { std::string source = "123"; short destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(123)); } TEST_F(convert_test, fromString_ShortInt_Fail) { std::string source = "-+123"; short destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_Bool_Success) { std::string source = "1"; bool destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(true)); } TEST_F(convert_test, fromString_Bool_Fail) { std::string source = "-+123"; bool destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_UShortInt_Success) { std::string source = "123"; unsigned short destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(123)); } TEST_F(convert_test, fromString_UShortInt_Fail) { std::string source = "-+123"; unsigned short destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_LongInt_Success) { std::string source = "-1123"; long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(-1123l)); } TEST_F(convert_test, fromString_LongInt_Fail) { std::string source = "-a123"; long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_LongLongInt_Success) { std::string source = "-123"; long long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); EXPECT_THAT(destination, Eq(-123ll)); } TEST_F(convert_test, fromString_LongLongInt_Fail) { std::string source = "-a123"; long long int destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_MinMaxShort) { std::string source = "32767"; std::int16_t destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "32768"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); source = "-32768"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "-32769"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_MinMaxUNSIGNED_Short) { std::string source = "65535"; std::uint16_t destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "65536"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); source = "0"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "-1"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_MinMaxInt) { std::string source = "2147483647"; std::int32_t destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "2147483648"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); source = "-2147483648"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "-2147483649"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); } TEST_F(convert_test, fromString_MinMaxUNSIGNED_Int) { std::string source = "4294967295"; std::uint32_t destination; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "4294967296"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); source = "0"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true)); source = "-1"; EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false)); }
30.196335
99
0.705678
Karsten1987
6229fd95e90e5a7f6062a97a2c0b9c8e009c4995
180
cc
C++
src/itensor/mps/localmpo_mps.h.cc
kyungminlee/PiTensor
f206fe5a384b52336e9f406c11dc492ff129791b
[ "MIT" ]
10
2019-01-25T03:21:49.000Z
2020-01-19T04:42:32.000Z
src/itensor/mps/localmpo_mps.h.cc
kyungminlee/PiTensor
f206fe5a384b52336e9f406c11dc492ff129791b
[ "MIT" ]
null
null
null
src/itensor/mps/localmpo_mps.h.cc
kyungminlee/PiTensor
f206fe5a384b52336e9f406c11dc492ff129791b
[ "MIT" ]
2
2018-04-10T05:11:30.000Z
2018-09-14T08:16:07.000Z
#include "../../pitensor.h" #include "itensor/mps/localmpo_mps.h" namespace py = pybind11; using namespace itensor; void pitensor::mps::localmpo_mps(pybind11::module& module) { }
22.5
60
0.738889
kyungminlee
622c4465d2aa95da144bc5be4ded2c438d6b31ac
10,927
cc
C++
components/security_state/content/content_utils_unittest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
components/security_state/content/content_utils_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
components/security_state/content/content_utils_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 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/security_state/content/content_utils.h" #include "base/command_line.h" #include "base/test/histogram_tester.h" #include "components/security_state/core/security_state.h" #include "components/security_state/core/switches.h" #include "content/public/browser/security_style_explanation.h" #include "content/public/browser/security_style_explanations.h" #include "net/cert/cert_status_flags.h" #include "net/ssl/ssl_cipher_suite_names.h" #include "net/ssl/ssl_connection_status_flags.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using security_state::GetSecurityStyle; // Tests that SecurityInfo flags for subresources with certificate // errors are reflected in the SecurityStyleExplanations produced by // GetSecurityStyle. TEST(SecurityStateContentUtilsTest, GetSecurityStyleForContentWithCertErrors) { content::SecurityStyleExplanations explanations; security_state::SecurityInfo security_info; security_info.cert_status = 0; security_info.scheme_is_cryptographic = true; security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_DISPLAYED_AND_RAN; GetSecurityStyle(security_info, &explanations); EXPECT_TRUE(explanations.ran_content_with_cert_errors); EXPECT_TRUE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_RAN; GetSecurityStyle(security_info, &explanations); EXPECT_TRUE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_DISPLAYED; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_TRUE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_NONE; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); } // Tests that SecurityStyleExplanations for subresources with cert // errors are *not* set when the main resource has major certificate // errors. If the main resource has certificate errors, it would be // duplicative/confusing to also report subresources with cert errors. TEST(SecurityStateContentUtilsTest, SubresourcesAndMainResourceWithMajorCertErrors) { content::SecurityStyleExplanations explanations; security_state::SecurityInfo security_info; security_info.cert_status = net::CERT_STATUS_DATE_INVALID; security_info.scheme_is_cryptographic = true; security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_DISPLAYED_AND_RAN; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_RAN; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_DISPLAYED; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_NONE; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); } // Tests that SecurityStyleExplanations for subresources with cert // errors are set when the main resource has only minor certificate // errors. Minor errors on the main resource should not hide major // errors on subresources. TEST(SecurityStateContentUtilsTest, SubresourcesAndMainResourceWithMinorCertErrors) { content::SecurityStyleExplanations explanations; security_state::SecurityInfo security_info; security_info.cert_status = net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION; security_info.scheme_is_cryptographic = true; security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_DISPLAYED_AND_RAN; GetSecurityStyle(security_info, &explanations); EXPECT_TRUE(explanations.ran_content_with_cert_errors); EXPECT_TRUE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_RAN; GetSecurityStyle(security_info, &explanations); EXPECT_TRUE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_DISPLAYED; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_TRUE(explanations.displayed_content_with_cert_errors); security_info.content_with_cert_errors_status = security_state::CONTENT_STATUS_NONE; GetSecurityStyle(security_info, &explanations); EXPECT_FALSE(explanations.ran_content_with_cert_errors); EXPECT_FALSE(explanations.displayed_content_with_cert_errors); } bool FindSecurityStyleExplanation( const std::vector<content::SecurityStyleExplanation>& explanations, const char* summary, content::SecurityStyleExplanation* explanation) { for (const auto& entry : explanations) { if (entry.summary == summary) { *explanation = entry; return true; } } return false; } // Test that connection explanations are formated as expected. Note the strings // are not translated and so will be the same in any locale. TEST(SecurityStateContentUtilsTest, ConnectionExplanation) { // Test a modern configuration with a key exchange group. security_state::SecurityInfo security_info; security_info.cert_status = net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION; security_info.scheme_is_cryptographic = true; net::SSLConnectionStatusSetCipherSuite( 0xcca8 /* TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 */, &security_info.connection_status); net::SSLConnectionStatusSetVersion(net::SSL_CONNECTION_VERSION_TLS1_2, &security_info.connection_status); security_info.key_exchange_group = 29; // X25519 { content::SecurityStyleExplanations explanations; GetSecurityStyle(security_info, &explanations); content::SecurityStyleExplanation explanation; ASSERT_TRUE(FindSecurityStyleExplanation( explanations.secure_explanations, "Secure Connection", &explanation)); EXPECT_EQ( "The connection to this site is encrypted and authenticated using a " "strong protocol (TLS 1.2), a strong key exchange (ECDHE_RSA with " "X25519), and a strong cipher (CHACHA20_POLY1305).", explanation.description); } // Some older cache entries may be missing the key exchange group, despite // having a cipher which should supply one. security_info.key_exchange_group = 0; { content::SecurityStyleExplanations explanations; GetSecurityStyle(security_info, &explanations); content::SecurityStyleExplanation explanation; ASSERT_TRUE(FindSecurityStyleExplanation( explanations.secure_explanations, "Secure Connection", &explanation)); EXPECT_EQ( "The connection to this site is encrypted and authenticated using a " "strong protocol (TLS 1.2), a strong key exchange (ECDHE_RSA), and a " "strong cipher (CHACHA20_POLY1305).", explanation.description); } // TLS 1.3 ciphers use the key exchange group exclusively. net::SSLConnectionStatusSetCipherSuite(0x1301 /* TLS_AES_128_GCM_SHA256 */, &security_info.connection_status); net::SSLConnectionStatusSetVersion(net::SSL_CONNECTION_VERSION_TLS1_3, &security_info.connection_status); security_info.key_exchange_group = 29; // X25519 { content::SecurityStyleExplanations explanations; GetSecurityStyle(security_info, &explanations); content::SecurityStyleExplanation explanation; ASSERT_TRUE(FindSecurityStyleExplanation( explanations.secure_explanations, "Secure Connection", &explanation)); EXPECT_EQ( "The connection to this site is encrypted and authenticated using a " "strong protocol (TLS 1.3), a strong key exchange (X25519), and a " "strong cipher (AES_128_GCM).", explanation.description); } } // Tests that a security level of HTTP_SHOW_WARNING produces a // content::SecurityStyle of UNAUTHENTICATED, with an explanation. TEST(SecurityStateContentUtilsTest, HTTPWarning) { security_state::SecurityInfo security_info; content::SecurityStyleExplanations explanations; security_info.security_level = security_state::HTTP_SHOW_WARNING; blink::WebSecurityStyle security_style = GetSecurityStyle(security_info, &explanations); EXPECT_EQ(blink::WebSecurityStyleUnauthenticated, security_style); EXPECT_EQ(1u, explanations.unauthenticated_explanations.size()); } // Tests that a security level of NONE when there is a password or // credit card field on HTTP produces a content::SecurityStyle of // UNAUTHENTICATED, with an info explanation for each. TEST(SecurityStateContentUtilsTest, HTTPWarningInFuture) { security_state::SecurityInfo security_info; content::SecurityStyleExplanations explanations; security_info.security_level = security_state::NONE; security_info.displayed_password_field_on_http = true; blink::WebSecurityStyle security_style = GetSecurityStyle(security_info, &explanations); EXPECT_EQ(blink::WebSecurityStyleUnauthenticated, security_style); EXPECT_EQ(1u, explanations.info_explanations.size()); explanations.info_explanations.clear(); security_info.displayed_credit_card_field_on_http = true; security_style = GetSecurityStyle(security_info, &explanations); EXPECT_EQ(blink::WebSecurityStyleUnauthenticated, security_style); EXPECT_EQ(1u, explanations.info_explanations.size()); // Check that when both password and credit card fields get displayed, only // one explanation is added. explanations.info_explanations.clear(); security_info.displayed_credit_card_field_on_http = true; security_info.displayed_password_field_on_http = true; security_style = GetSecurityStyle(security_info, &explanations); EXPECT_EQ(blink::WebSecurityStyleUnauthenticated, security_style); EXPECT_EQ(1u, explanations.info_explanations.size()); } } // namespace
44.238866
79
0.800037
google-ar
622d7f4740081bae21c38f9e4a9304521d17d46b
6,542
cpp
C++
0-frameworks/hcs/example/hetero_tasks/hetero_tasks.cpp
cjmcv/cuda
04fcf80bd32a2909a232cfe532e24bbe6932ac10
[ "Apache-2.0" ]
34
2018-01-06T13:32:00.000Z
2021-12-22T03:16:01.000Z
0-frameworks/hcs/example/hetero_tasks/hetero_tasks.cpp
cjmcv/cuda
04fcf80bd32a2909a232cfe532e24bbe6932ac10
[ "Apache-2.0" ]
null
null
null
0-frameworks/hcs/example/hetero_tasks/hetero_tasks.cpp
cjmcv/cuda
04fcf80bd32a2909a232cfe532e24bbe6932ac10
[ "Apache-2.0" ]
4
2019-03-11T14:55:13.000Z
2021-12-22T03:16:03.000Z
//#define HETERO_TASKS #ifdef HETERO_TASKS #include <thread> #include <cuda_runtime.h> #include "device_launch_parameters.h" #include "hcs/executor.hpp" #include "hcs/profiler.hpp" extern int CallGemmGPU(const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc, cudaStream_t stream = nullptr); void Div2(float *src, int len, float *dst) { for (int c = 0; c < 10; c++) { for (int i = 0; i < len; i++) { dst[i] = src[i] / 2 + 1; } } } float AccMean(float *arr, float *arr2, int len) { float ave = 0.0; for (int i = 0; i < len; i++) { ave = (i / (i + 1.0)) * ave + (arr[i] + arr2[i]) / (i + 1.0); } return ave; } class TestClass : public hcs::TaskAssistor { public: TestClass() { count_ = 0; } std::atomic<int> count_; }; // C in G out. void TaskHost(hcs::TaskAssistor *assistor, std::vector<hcs::Blob *> inputs, hcs::Blob *output) { if (inputs.size() != 1) { std::cout << "inputs.size() != 1" << std::endl; } //printf("<s-%d-TaskHost2Device, %d>", assistor->id(), assistor->stream()); // Fetch input. float* data = (float *)inputs[0]->GetHostData(); std::vector<int> shape = inputs[0]->shape(); // Fetch output. output->SyncParams(1, 1, shape[2], shape[3], hcs::ON_DEVICE, hcs::FLOAT32); float* out_data = (float *)output->GetHostData(); // Process. Div2(data, inputs[0]->len(), out_data); //printf("TaskHost(%d, %d)", inputs[0]->object_id_, assistor->stream()); } // G in C out void TaskDevice(hcs::TaskAssistor *assistor, std::vector<hcs::Blob *> inputs, hcs::Blob *output) { if (inputs.size() != 1) { std::cout << "inputs.size() != 1" << std::endl; } //printf("<s-%d-TaskDevice2Host, %d>", assistor->id(), assistor->stream()); // Fetch input. float* d_in_data = (float *)inputs[0]->GetDeviceData(); std::vector<int> shape = inputs[0]->shape(); // Fetch output. output->SyncParams(1, 1, shape[2], shape[3], hcs::ON_HOST, hcs::FLOAT32); float *d_buffer = (float *)output->GetDeviceData(); // Process. CallGemmGPU(shape[2], shape[2], shape[2], 1.0, d_in_data, shape[2], d_in_data, shape[2], 0, d_buffer, shape[2], assistor->stream()); //printf("TaskDevice(%d, %d)", inputs[0]->object_id_, assistor->stream()); } // 2C in C out void TaskHost2(hcs::TaskAssistor *assistor, std::vector<hcs::Blob *> inputs, hcs::Blob *output) { if (inputs.size() != 2) { std::cout << "inputs.size() != 2" << std::endl; } //printf("<s-%d-TaskHost, %d>", assistor->id(), assistor->stream()); // Fetch input. float* h_in_data = (float *)inputs[0]->GetHostData(); float* h_in2_data = (float *)inputs[1]->GetHostData(); std::vector<int> shape = inputs[0]->shape(); // Fetch output. output->SyncParams(1, 1, 1, 1, hcs::ON_HOST, hcs::FLOAT32); float* h_out_data = (float *)output->GetHostData(); // Process. *h_out_data = AccMean(h_in_data, h_in2_data, inputs[0]->len()); //printf("TaskHost2(%d, %d)", inputs[0]->object_id_, assistor->stream()); } void Task() { printf("<master thread: %d>", std::this_thread::get_id()); hcs::Blob input("in"); input.Create(1, 1, 1280, 1280, hcs::ON_HOST, hcs::FLOAT32); input.object_id_ = 1; float *data = (float *)input.GetHostData(); for (int i = 0; i < input.len(); i++) { data[i] = 2; } hcs::Graph graph; hcs::Node *A = graph.emplace()->name("A"); hcs::Node *B1C = graph.emplace(TaskHost)->name("B1C"); hcs::Node *B2G = graph.emplace(TaskDevice)->name("B2G"); hcs::Node *C1C = graph.emplace(TaskHost)->name("C1C"); hcs::Node *C2G = graph.emplace(TaskDevice)->name("C2G"); hcs::Node *D1C = graph.emplace(TaskHost)->name("D1C"); hcs::Node *D2G = graph.emplace(TaskDevice)->name("D2G"); hcs::Node *OUT = graph.emplace(TaskHost2)->name("OUT"); // | -- C1C -- C2G | // AC(input) -- B1C -- B2G -- O(acc) // | -- D1C -- D2G | A->precede(B1C); B1C->precede(B2G); B2G->precede(C1C); C1C->precede(C2G); B2G->precede(D1C); D1C->precede(D2G); D2G->precede(OUT); C2G->precede(OUT); int queue_size = 60; graph.Initialize(queue_size); hcs::Executor executor("HeteroTest"); TestClass ass; executor.Bind(&graph, hcs::PARALLEL_MULTI_STREAMS, &ass); // hcs::SERIAL hcs::PARALLEL hcs::PARALLEL_MULTI_STREAMS hcs::Profiler profiler(&executor, &graph); int config_flag = hcs::VIEW_STATUS_RUN_TIME | hcs::VIEW_NODE | hcs::VIEW_NODE_RUN_TIME;// | hcs::VIEW_STATUS; profiler.Config(config_flag, 200); profiler.Start(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); clock_t time; float serial_time = 0.0; float push_time = 0.0; float get_time = 0.0; //////////////////////// { hcs::Blob out_blob("out"); // warn. A->Enqueue(&input); executor.Run().wait(); OUT->Dequeue(&out_blob); time = clock(); A->Enqueue(&input); executor.Run().wait(); OUT->Dequeue(&out_blob); serial_time = (clock() - time) * 1000.0 / CLOCKS_PER_SEC; printf("Finish.\n"); } // Loop. int loop_cnt = 10; while (1) { if (loop_cnt <= 0) break; loop_cnt--; time = clock(); printf(">>>>>>>>>>>>>>>>> New Round <<<<<<<<<<<<<<<<.\n"); for (int i = 0; i < queue_size; i++) { input.object_id_ = i; A->Enqueue(&input); } executor.Run(); push_time = (clock() - time) * 1000.0 / CLOCKS_PER_SEC; time = clock(); int count = 0; while (count < queue_size) { hcs::Blob out_blob("out"); bool flag = OUT->Dequeue(&out_blob); if (flag == true) { count++; float *data = (float *)out_blob.GetHostData(); printf("< %d , <", out_blob.object_id_); for (int i = 0; i < 1; i++) {//out.num_element_ printf("%f, ", data[i]); } printf(">.\n"); } else { std::cout << count << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } get_time = (clock() - time) * 1000.0 / CLOCKS_PER_SEC; printf("%d-times: push %f, get %f, serial: %f. \n", queue_size, push_time / queue_size, get_time / queue_size, serial_time); } profiler.Stop(); graph.Clean(); input.Release(); } int main() { while (1) Task(); return 0; } #endif // HETERO_TASKS
28.567686
128
0.572608
cjmcv
622dadbe497fbff44ca9d45118bcd93a6ab74f1b
21,442
hpp
C++
source/RD/Engine/Engine.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:18.000Z
2021-12-26T12:48:18.000Z
source/RD/Engine/Engine.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
null
null
null
source/RD/Engine/Engine.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:25.000Z
2021-12-26T12:48:25.000Z
/** * @file Engine.hpp * @brief The engine header. * @details Version 20210203. * The OpenGL headers should be included in the following way: * #define GLEW_STATIC * #include <GL/glew.h> * #ifdef _WIN32 * #define GLFW_EXPOSE_NATIVE_WGL * #define GLFW_EXPOSE_NATIVE_WIN32 * #endif * #include <GLFW/glfw3.h> * #include <GLFW/glfw3native.h> * #include <glm/glm.hpp> * #include <glm/gtc/matrix_transform.hpp> * #include <glm/gtc/type_ptr.hpp> */ #pragma once #include <Core.hpp> // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Debug macros for GL // Example: DEBUG_GLCHECK( glBindTexture(GL_TEXTURE_2D, 0); ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #ifdef DEBUG #define DEBUG_GLCHECK(stmt) \ do { \ GLenum e = glGetError(); \ stmt; \ if(GL_NO_ERROR != (e = glGetError())) \ RD::Core::Console::Message(stderr,"%s:%d in %s() \"%s\": %s\n", __FILE__, __LINE__, __func__, #stmt, RD::Engine::GLErrorToString(e).c_str()); \ } while(0) #else #define DEBUG_GLCHECK(stmt) stmt #endif /* DEBUG */ /* Default module namespace */ namespace RD { namespace Engine { /** * @brief Convert GL error to corresponding string. * @param [in] error GL error enum. * @return String that names the GL error. */ std::string GLErrorToString(GLenum error); /** * @brief Get OpenGL information. * @param [out] versionGL GL version string. * @param [out] versionGLSL GLSL version string. * @param [out] vendor Vendor string. * @param [out] renderer Renderer string. */ void GetGLInfo(std::string* versionGL, std::string* versionGLSL, std::string* vendor, std::string* renderer); /* Camera Modes */ typedef enum{ CAMERA_MODE_PERSPECTIVE, CAMERA_MODE_ORTHOGRAPHIC } CameraMode; /** * @brief Class: Camera */ class Camera { public: CameraMode mode; ///< The camera mode. Either @ref CAMERA_MODE_ORTHOGRAPHIC or @ref CAMERA_MODE_PERSPECTIVE. double left; ///< The left border limit for orthographic projection. double right; ///< The right border limit for orthographic projection. double bottom; ///< The bottom border limit for orthographic projection. double top; ///< The top border limit for orthographic projection. double clipNear; ///< The near clipping pane for perspective projection. double clipFar; ///< The far clipping pane for perspective projection. double aspect; ///< The aspect ratio for perspective projection. double fov; ///< The field of view angle in radians for perspective projection. glm::dvec3 position; ///< The position in world space coordinates. glm::dvec3 view; ///< The view direction in world space coordinates. glm::dvec3 up; ///< The up direction in world space coordinates. /** * @brief Update the projection matrix. * @details Call this function if you changed the projection mode or projection parameters (left, right, bottom, top, fov, aspect, clipNear, clipFar). */ void UpdateProjectionMatrix(void); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // GENERAL // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * @brief Create a camera using a perspective projection. This is the default constructor. * @param [in] clipNear Near clipping pane border. Defaults to 0.01. * @param [in] clipFar Far clipping pane border. Defaults to 500.0. * @param [in] aspect The aspect ratio (width / height). Defaults to 8.0 / 5.0. * @param [in] fov The field of view in radians. Defaults to glm::radians(58.0). * @param [in] position The initial position. Defaults to glm::dvec3(0.0). * @param [in] view The initial view direction. Defaults to glm::dvec3(0.0, 0.0, -1.0). * @param [in] up The initial up direction. Defaults to glm::dvec3(0.0, 1.0, 0.0). * @details The private attribute @ref mode will be set to @ref CAMERA_MODE_PERSPECTIVE. */ Camera(double clipNear = 0.01, double clipFar = 500.0, double aspect = 8.0 / 5.0, double fov = glm::radians(70.0), glm::dvec3 position = glm::dvec3(0.0), glm::dvec3 view = glm::dvec3(0.0, 0.0, -1.0), glm::dvec3 up = glm::dvec3(0.0, 1.0, 0.0)); /** * @brief Create a camera using an orthographic projection. * @param [in] left Left border. * @param [in] right Right border. * @param [in] bottom Bottom border. * @param [in] top Top border. * @param [in] clipNear Near clipping pane border. * @param [in] clipFar Far clipping pane border. * @param [in] view The view direction vector. Defaults to glm::dvec3(0.0, 0.0, -1.0). * @param [in] up The up direction vector. Defaults to glm::dvec3(0.0, 1.0, 0.0). * @details The private attribute @ref mode will be set to @ref CAMERA_MODE_ORTHOGRAPHIC. */ Camera(double left, double right, double bottom, double top, double clipNear, double clipFar, glm::dvec3 view = glm::dvec3(0.0, 0.0, -1.0), glm::dvec3 up = glm::dvec3(0.0, 1.0, 0.0)); /** * @brief Default copy constructor. */ Camera(const Camera& camera) = default; /** * @brief Delete the camera. * @details @ref DeleteUniformBufferObject will NOT be called. */ ~Camera(); /** * @brief Assignment operator. * @param [in] rhs The right hand side value. * @details This will copy all private attributes from rhs to this camera instance. However, the UBO value will not be copied. */ Camera& operator=(const Camera& rhs); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // WORLD SPACE TRANSFORMATIONS // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * @brief Rotate camera in world space coordinates beginning from the current orientation. * @param [in] angle Angle in radians. * @param [in] axis Rotation axis. */ void Rotate(double angle, glm::dvec3 axis); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VIEW SPACE TRANSFORMATIONS // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * @brief Roll around the forward (view) direction. * @param [in] angle Roll angle in radians. */ void RollView(double angle); /** * @brief Pitch around the x-axis of the camera view frame. * @param [in] angle Pitch angle in radians. */ void PitchView(double angle); /** * @brief Yaw around the down direction of the camera view frame. * @param [in] angle Yaw angle in radians. */ void YawView(double angle); /** * @brief Move camera in the camera view frame. * @param [in] xyz Movement vector. */ void MoveView(glm::dvec3 xyz); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // GET TRANSFORMATION MATRICES // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * @brief Get the view matrix only. * @return The 4x4 view matrix. */ glm::dmat4 GetViewMatrix(void); /** * @brief Get the projection matrix only. * @return The 4x4 projection matrix depending on the @ref mode. */ glm::dmat4 GetProjectionMatrix(void); /** * @brief Get the projection-view matrix. * @return 4x4 projection-view matrix. */ glm::dmat4 GetProjectionViewMatrix(void); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Uniform Buffer Object Management // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * @brief Generate the uniform buffer object. * @param [in] bindingPoint The bining point for the uniform buffer object. Must be the same in the shader. * @details The shader must use the following uniform block: * layout (std140, binding = bindingPoint) uniform Camera{ * mat4 camProjectionView; * mat4 camProjectionViewTFree; * vec3 camPosition; * vec3 camViewDirection; * }; * @note The buffer will be initialized using the @ref UpdateUniformBufferObject member function. */ void GenerateUniformBufferObject(GLuint bindingPoint); /** * @brief Delete the uniform buffer object. */ void DeleteUniformBufferObject(void); /** * @brief Update the uniform buffer object. * @details This will update the complete uniform block buffer data. */ void UpdateUniformBufferObject(void); private: glm::dmat4 projectionMatrix; ///< The projection matrix. Use @ref UpdateProjectionMatrix to update the matrix. GLuint ubo; ///< The uniform buffer object. }; /* class: Camera */ /** * @brief Class: CouboidFrustumCuller * @details Check whether a cuboid is visible by the cameras frustum or not. * @note The cuboid must be aligned to the world space axes. */ class CuboidFrustumCuller { public: /** * @brief Create a cuboid frustum culler using the cameras projection view matrix. * @param [in] cameraProjectionViewMatrix The projection view matrix of the camera. */ explicit CuboidFrustumCuller(const glm::mat4& cameraProjectionViewMatrix); /** * @brief Delete the cuboid frustum culler. */ ~CuboidFrustumCuller(); /** * @brief Check if a cuboid is visible. * @param [in] blockLowestPosition The lowest position of the cuboid. * @param [in] blockDimension The dimension of the cuboid. * @return True if cuboid is visible, false otherwise. */ bool IsVisible(glm::vec3 blockLowestPosition, glm::vec3 blockDimension); private: GLfloat cullInfo[6][4]; ///< Culling information (generated by constructor). }; /* class: CuboidFrustumCuller */ /** * @brief Class: Shader * @details Handles vertex + geometry (optional) + fragment shader. */ class Shader { public: /** * @brief Create a shader object. */ Shader():id(0){} /** * @brief Get the GLSL-version string to be used to generate shader. * @return The version string, e.g. "450". * @details Make sure that the OpenGL context is initialized to obtain correct version information. */ static std::string GetShadingLanguageVersion(void); /** * @brief Generate the shader. * @param [in] fileName The filename of the GLSL shader file. * @return True if success, false otherwise. * @details A zero terminator will be added to the shader source. The GLSL version will be assigned automatically using the @ref GetShadingLanguageVersion function. */ bool Generate(std::string fileName); /** * @brief Generate the shader. * @param [in] fileName The filename of the GLSL shader file. * @param [in] version The version string number, e.g. "450". * @return True if success, false otherwise. * @details A zero terminator will be added to the shader source. */ bool Generate(std::string fileName, std::string version); /** * @brief Generate the shader. * @param [in] fileName The filename of the GLSL shader file. * @param [in] version The version string number, e.g. "450". * @param [in] replacement Text replacement data. * @return True if success, false otherwise. * @details A zero terminator will be added to the shader source. */ bool Generate(std::string fileName, std::string version, std::vector<std::pair<std::string, std::string>>& replacement); /** * @brief Generate the shader. * @param [in] fileData Binary file data. * @param [in] version The version string number, e.g. "450". * @return True if success, false otherwise. * @details A zero terminator will be added to the shader source. */ bool Generate(std::vector<uint8_t>& fileData, std::string version); /** * @brief Generate the shader. * @param [in] fileData Binary file data. * @param [in] version The version string number, e.g. "450". * @param [in] replacement Text replacement data. * @return True if success, false otherwise. * @details A zero terminator will be added to the shader source. */ bool Generate(std::vector<uint8_t>& fileData, std::string version, std::vector<std::pair<std::string, std::string>>& replacement); /** * @brief Delete the shader program. */ void Delete(void); /** * @brief Use the shader. */ inline void Use(void){ DEBUG_GLCHECK( glUseProgram(id); ); } /** * @brief Get the uniform location. * @param [in] name Name of the uniform. * @return Location of the uniform. */ inline GLint GetUniformLocation(const GLchar* name){ return glGetUniformLocation(id, name); } /* The uniforms */ inline void UniformMatrix4fv(const GLchar* name, GLboolean transpose, glm::mat4& matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(glGetUniformLocation(id, name), 1, transpose, glm::value_ptr(matrix)); ); } inline void UniformMatrix4fv(GLint location, GLboolean transpose, glm::mat4& matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(location, 1, transpose, glm::value_ptr(matrix)); ); } inline void UniformMatrix4fv(const GLchar* name, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(glGetUniformLocation(id, name), 1, transpose, matrix); ); } inline void UniformMatrix4fv(GLint location, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(location, 1, transpose, matrix); ); } inline void UniformMatrix3fv(const GLchar* name, GLboolean transpose, glm::mat3& matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(glGetUniformLocation(id, name), 1, transpose, glm::value_ptr(matrix)); ); } inline void UniformMatrix3fv(GLint location, GLboolean transpose, glm::mat3& matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(location, 1, transpose, glm::value_ptr(matrix)); ); } inline void UniformMatrix3fv(const GLchar* name, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(glGetUniformLocation(id, name), 1, transpose, matrix); ); } inline void UniformMatrix3fv(GLint location, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(location, 1, transpose, matrix); ); } inline void UniformMatrix2fv(const GLchar* name, GLboolean transpose, glm::mat2& matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(glGetUniformLocation(id, name), 1, transpose, glm::value_ptr(matrix)); ); } inline void UniformMatrix2fv(GLint location, GLboolean transpose, glm::mat2& matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(location, 1, transpose, glm::value_ptr(matrix)); ); } inline void UniformMatrix2fv(const GLchar* name, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(glGetUniformLocation(id, name), 1, transpose, matrix); ); } inline void UniformMatrix2fv(GLint location, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(location, 1, transpose, matrix); ); } inline void Uniform4f(const GLchar* name, glm::vec4& value){ DEBUG_GLCHECK( glUniform4f(glGetUniformLocation(id, name), value.x, value.y, value.z, value.w); ); } inline void Uniform4f(GLint location, glm::vec4& value){ DEBUG_GLCHECK( glUniform4f(location, value.x, value.y, value.z, value.w); ); } inline void Uniform4fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform4fv(glGetUniformLocation(id, name), count, value); ); } inline void Uniform4fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform4fv(location, count, value); ); } inline void Uniform3f(const GLchar* name, glm::vec3& value){ DEBUG_GLCHECK( glUniform3f(glGetUniformLocation(id, name), value.x, value.y, value.z); ); } inline void Uniform3f(GLint location, glm::vec3& value){ DEBUG_GLCHECK( glUniform3f(location, value.x, value.y, value.z); ); } inline void Uniform3fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform3fv(glGetUniformLocation(id, name), count, value); ); } inline void Uniform3fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform3fv(location, count, value); ); } inline void Uniform2f(const GLchar* name, glm::vec2& value){ DEBUG_GLCHECK( glUniform2f(glGetUniformLocation(id, name), value.x, value.y); ); } inline void Uniform2f(GLint location, glm::vec2& value){ DEBUG_GLCHECK( glUniform2f(location, value.x, value.y); ); } inline void Uniform2fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform2fv(glGetUniformLocation(id, name), count, value); ); } inline void Uniform2fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform2fv(location, count, value); ); } inline void Uniform1f(const GLchar* name, GLfloat value){ DEBUG_GLCHECK( glUniform1f(glGetUniformLocation(id, name), value); ); } inline void Uniform1f(GLint location, GLfloat value){ DEBUG_GLCHECK( glUniform1f(location, value); ); } inline void Uniform1fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform1fv(glGetUniformLocation(id, name), count, value); ); } inline void Uniform1fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform1fv(location, count, value); ); } inline void Uniform4i(const GLchar* name, GLint value0, GLint value1, GLint value2, GLint value3){ DEBUG_GLCHECK( glUniform4i(glGetUniformLocation(id, name), value0, value1, value2, value3); ); } inline void Uniform4i(GLint location, GLint value0, GLint value1, GLint value2, GLint value3){ DEBUG_GLCHECK( glUniform4i(location, value0, value1, value2, value3); ); } inline void Uniform4iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform4iv(glGetUniformLocation(id, name), count, values); ); } inline void Uniform4iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform4iv(location, count, values); ); } inline void Uniform3i(const GLchar* name, GLint value0, GLint value1, GLint value2){ DEBUG_GLCHECK( glUniform3i(glGetUniformLocation(id, name), value0, value1, value2); ); } inline void Uniform3i(GLint location, GLint value0, GLint value1, GLint value2){ DEBUG_GLCHECK( glUniform3i(location, value0, value1, value2); ); } inline void Uniform3iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform3iv(glGetUniformLocation(id, name), count, values); ); } inline void Uniform3iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform3iv(location, count, values); ); } inline void Uniform2i(const GLchar* name, GLint value0, GLint value1){ DEBUG_GLCHECK( glUniform2i(glGetUniformLocation(id, name), value0, value1); ); } inline void Uniform2i(GLint location, GLint value0, GLint value1){ DEBUG_GLCHECK( glUniform2i(location, value0, value1); ); } inline void Uniform2iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform2iv(glGetUniformLocation(id, name), count, values); ); } inline void Uniform2iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform2iv(location, count, values); ); } inline void Uniform1i(const GLchar* name, GLint value){ DEBUG_GLCHECK( glUniform1i(glGetUniformLocation(id, name), value); ); } inline void Uniform1i(GLint location, GLint value){ DEBUG_GLCHECK( glUniform1i(location, value); ); } inline void Uniform1iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform1iv(glGetUniformLocation(id, name), count, values); ); } inline void Uniform1iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform1iv(location, count, values); ); } inline void UniformBlockBinding(const GLchar* name, GLuint value){ DEBUG_GLCHECK( glUniformBlockBinding(id, glGetUniformBlockIndex(id, name), value); ); } inline void UniformBlockBinding(GLint location, GLuint value){ DEBUG_GLCHECK( glUniformBlockBinding(id, location, value); ); } private: GLuint id; ///< The program ID. }; /* class: Shader */ } /* namespace: Engine */ } /* namespace: RD */
52.425428
251
0.623962
RobertDamerius
622e0dbff83d5e823a76f4fa0834f1b206977408
2,207
hh
C++
src/include/Token.hh
websurfer5/json-schema-enforcer
99211a602b1c8177d9f9e67cd7773015f74a4080
[ "Apache-2.0" ]
null
null
null
src/include/Token.hh
websurfer5/json-schema-enforcer
99211a602b1c8177d9f9e67cd7773015f74a4080
[ "Apache-2.0" ]
null
null
null
src/include/Token.hh
websurfer5/json-schema-enforcer
99211a602b1c8177d9f9e67cd7773015f74a4080
[ "Apache-2.0" ]
null
null
null
// Token.hh // // Copyright 2018 Jeffrey Kintscher <websurfer@surf2c.net> // // 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 __JSONSCHEMAENFORCER_TOKEN_HH #define __JSONSCHEMAENFORCER_TOKEN_HH #include "config.h" #include "stddefs.hh" #include <map> #include <string> namespace jsonschemaenforcer { class Token { public: Token(); Token(const Token& _token); Token(const std::string& _token_name, const std::string& _type, const std::string& _pattern, const std::string& _input_string, const std::string& _start_state, const std::string& _new_start_state, bool _pop_state, const std::string& _rule_body); Token& operator =(const Token& _token); bool operator ==(const Token& _token) const; inline bool operator !=(const Token& _token) const { return !(operator ==(_token)); }; void clear(); bool empty(); # define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \ void func_set(const vtype& _##vname); \ inline const vtype& func_get() const { return vname; }; \ inline bool has_##vname() const { return flag_name; }; # include "Token-vars.hh" # undef DEF_VAR // protected: # define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \ vtype vname; \ bool flag_name; # include "Token-vars.hh" # undef DEF_VAR }; typedef std::map<StdStringPair, Token> StdStringTokenMap; } #endif // __JSONSCHEMAENFORCER_TOKEN_HH
32.455882
100
0.643407
websurfer5
622e51fd945b9b7d4a4d3781848b739be83df8a4
728
cpp
C++
src/engines/ioda/src/ioda/C/String_c.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
1
2021-06-09T16:11:50.000Z
2021-06-09T16:11:50.000Z
src/engines/ioda/src/ioda/C/String_c.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
null
null
null
src/engines/ioda/src/ioda/C/String_c.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
3
2021-06-09T16:12:02.000Z
2021-11-14T09:19:25.000Z
/* * (C) Copyright 2020-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \addtogroup ioda_string * @{ * \file String_c.cpp * \brief @link ioda_string C bindings @endlink. Needed for reads. */ #include "ioda/C/String_c.h" #include <gsl/gsl-lite.hpp> extern "C" { IODA_DL void ioda_string_ret_t_destruct(ioda_string_ret_t* obj) { C_TRY; Expects(obj != nullptr); Expects(obj->strings != nullptr); for (size_t i = 0; i < obj->n; ++i) { if (obj->strings[i] != nullptr) { delete[] obj->strings[i]; } } delete[] obj->strings; delete obj; C_CATCH_AND_TERMINATE; } } /// @}
20.8
78
0.651099
NOAA-EMC
622ebf7562d5cf93bb2cde67f1a33f516bcb3d0c
7,017
hpp
C++
src/io.hpp
jewettaij/calc_writhe
018ee05d802b7bf51182a8f7cb70b67194a09aba
[ "MIT" ]
null
null
null
src/io.hpp
jewettaij/calc_writhe
018ee05d802b7bf51182a8f7cb70b67194a09aba
[ "MIT" ]
1
2021-03-24T20:59:10.000Z
2021-03-24T20:59:10.000Z
src/io.hpp
jewettaij/calc_writhe
018ee05d802b7bf51182a8f7cb70b67194a09aba
[ "MIT" ]
null
null
null
/// @file io.hpp /// @brief A series of (arguably unnecessary) functions that /// read strings and numbers from a file. /// @date 2007-4-13 #ifndef _IO_HPP #define _IO_HPP #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> #include <cstring> using namespace std; #include "err.hpp" /// When a syntax error occurs in a file, which file did it occur in? string g_filename; /// where in the file (did the error occur): long long g_line; /// comment indicator char g_comments_begin_with ='#'; /// comment terminator char g_comments_end_with = '\n'; /// @brief Does character c belong to aC? template<class C> inline bool BelongsToCstring(C c, C const *aC, C terminating_char) { assert(aC); while(*aC != terminating_char) { if (c == *aC) return true; ++aC; } return false; } /// @brief Skip over some characters if they are present at this location /// in the file. inline void Skip(istream &in, char const *aSkipTheseChars) { assert(aSkipTheseChars); if (! in) { stringstream err_msg; err_msg << "Error in input: \"" << g_filename <<"\"\n" " near line " << g_line <<": File ends prematurely." << endl; throw InputErr(err_msg.str().c_str()); } char c; while(in.get(c)) { if (c=='\n') g_line++; // <-- keep track of what line we are on else if (c == g_comments_begin_with) { // skip past this comment (do not assume single-line comments) do { in.get(c); if (in && (c=='\n')) g_line++; } while (in && (c != '\0') && (c != EOF) && (c!=g_comments_end_with)); } // Note: this code does not work with nested comments. fix this later.. if (in && (! BelongsToCstring(c, aSkipTheseChars, '\0'))) { in.putback(c); if (c=='\n') g_line--; break; } } } // Skip() /// @brief Read a token from the stream. /// (Tokens are words delimited by one of the characters /// in the "terminators" argument, which are typically whitespace.) inline void ReadString(istream &in, string &dest, char const *terminators) { assert(terminators); if (! in) { stringstream err_msg; err_msg << "Error in input: \"" << g_filename <<"\"\n" " near line " << g_line <<": File ends prematurely." << endl; throw InputErr(err_msg.str().c_str()); } char c; while(in.get(c)) { if (BelongsToCstring(c, terminators, '\0') || (c == g_comments_begin_with)) { in.putback(c); break; } else { dest.push_back(c); if (c=='\n') g_line++; //keep track of the number of newlines read so far. } } } // ReadString() /// @brief Read a number from this location in the file. template<class Scalar> bool ReadScalar(istream &in, Scalar& dest, char const *ac_terminators, string *ps_dest, string::const_iterator *pstopped_at=nullptr) { string s; ReadString(in, s, ac_terminators); // If requested, make a copy this string and return it to the caller if (ps_dest != nullptr) *ps_dest=s; if (pstopped_at != nullptr) *pstopped_at = ps_dest->begin(); if (s.size() != 0) { // I would prefer to use the standard ANSI C function: strtod() // to parse the string and convert it to a floating point variable. // But I have to copy this text into a c_string to get around strtod()'s // syntax. strtod() requires an argument of type "char *". I could // use s.c_str(), but this is a pointer of type "const char *". // So, I need to copy the contents of s.c_str() into a temporary array, // and then invoke strtod() on it. char *ac = new char [s.size() + 1]; strcpy(ac, s.c_str()); char *pstart = ac; char *pstop; #ifdef STRTOLD_UNSUPPORTED dest = strtod(pstart, &pstop); #else dest = strtold(pstart, &pstop);//Useful but not standard ANSI C #endif // Now pstop points past the last valid char // If requested, inform the caller where the parsing stopped if (pstopped_at != nullptr) *pstopped_at = ps_dest->begin() + (pstop - pstart); delete [] ac; return (pstop - pstart == s.size()); //did parsing terminate prematurely? } else return false; //no number was successfully read } //ReadScalar() /// @brief Read a number from this location in the file. /// @overloaded template<class Scalar> Scalar ReadScalar(istream &in, char const *ac_terminators) { Scalar dest; string s; if (! ReadScalar(in, dest, ac_terminators, &s)) { stringstream err_msg; err_msg << "Error in input: \"" << g_filename << "\"\n" " near line " << g_line; if (! s.empty()) cerr << ": \""<<s<<"\"\n"; err_msg << " Expected a number." << endl; throw InputErr(err_msg.str().c_str()); } return dest; } //ReadScalar() /// @brief Read an integer from this location in the file. bool ReadInt(istream &in, long long& dest, char const *ac_terminators, string *ps_dest, string::const_iterator *pstopped_at = nullptr) { string s; ReadString(in, s, ac_terminators); // If requested, make a copy this string and return it to the caller if (ps_dest != nullptr) *ps_dest=s; if (pstopped_at != nullptr) *pstopped_at = ps_dest->begin(); if (s != "") { // I would prefer to use the standard ANSI C function: strtod() // to parse the string and convert it to a floating point variable. // But I have to copy this text into a c_string to get around strtod()'s // syntax. strtod() requires an argument of type "char *". I could // use s.c_str(), but this is a pointer of type "const char *". // So, I need to copy the contents of s.c_str() into a temporary array, // and then invoke strtod() on it. char *ac = new char [s.size() + 1]; strcpy(ac, s.c_str()); char *pstart = ac; char *pstop; dest = strtol(pstart, &pstop, 10); // Now pstop points past the last valid char // If requested, inform the caller where the parsing stopped if (pstopped_at != nullptr) *pstopped_at = ps_dest->begin() + (pstop - pstart); delete [] ac; return (pstop - pstart == s.size()); //did parsing terminate prematurely? } else return false; //no number was successfully read } //ReadInt() /// @brief Read an integer from this location in the file. /// @overloaded long long ReadInt(istream &in, char const *ac_terminators) { long long dest; string s; if (! ReadInt(in, dest, ac_terminators, &s)) { stringstream err_msg; err_msg << "Error in input: \"" << g_filename << "\"\n" " near line " << g_line; if (! s.empty()) cerr << ": \""<<s<<"\"\n"; err_msg << " Expected an integer." << endl; throw InputErr(err_msg.str().c_str()); } return dest; } //ReadInt() #endif //#ifndef _IO_HPP
24.882979
77
0.601254
jewettaij
622f49a80f31a99c173edbdef5a20effd5e494c9
695
cpp
C++
client/client_main.cpp
aejaz83/asio_server
6b9bfbb9ca6954694ea08bfca0a9b1f4cf8741b4
[ "BSL-1.0" ]
null
null
null
client/client_main.cpp
aejaz83/asio_server
6b9bfbb9ca6954694ea08bfca0a9b1f4cf8741b4
[ "BSL-1.0" ]
null
null
null
client/client_main.cpp
aejaz83/asio_server
6b9bfbb9ca6954694ea08bfca0a9b1f4cf8741b4
[ "BSL-1.0" ]
null
null
null
/* * Author: Aehjaj Ahmed P * Date: 1-July-2019 */ #include <iostream> #include <boost/asio.hpp> #include "tcp_client.hpp" using boost::asio::ip::tcp; int main(int argc, char* argv[]){ try{ if(argc != 3){ std::cerr << "Usage: tcp_client <host> <port>\n"; return -1; } boost::asio::io_context io_context; // boost::asio::io_service::work work(io_context); tcp::resolver resolver(io_context); auto endpoints = resolver.resolve(argv[1], argv[2]); Tcp_Client client(io_context, endpoints); io_context.run(); } catch (std::exception& e){ std::cerr << "Exception: " << e.what() << std::endl; } return 0; }
23.166667
58
0.58705
aejaz83
623162bdc12f37fa04c30d884b5be1c9e6d218a7
6,540
cpp
C++
jni/WiEngine_binding/tmx/com_wiyun_engine_tmx_TMXTileMap.cpp
zchajax/WiEngine
ea2fa297f00aa5367bb5b819d6714ac84a8a8e25
[ "MIT" ]
39
2015-01-23T10:01:31.000Z
2021-06-10T03:01:18.000Z
jni/WiEngine_binding/tmx/com_wiyun_engine_tmx_TMXTileMap.cpp
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
1
2015-04-15T08:07:47.000Z
2015-04-15T08:07:47.000Z
jni/WiEngine_binding/tmx/com_wiyun_engine_tmx_TMXTileMap.cpp
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
20
2015-01-20T07:36:10.000Z
2019-09-15T01:02:19.000Z
#include "com_wiyun_engine_tmx_TMXTileMap.h" #include "wyTMXTileMap.h" #include "wyUtils_android.h" #include "wyLog.h" extern jfieldID g_fid_BaseObject_mPointer; JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeInit__I_3Lcom_wiyun_engine_opengl_Texture2D_2 (JNIEnv * env, jobject thiz, jint resId, jobjectArray tex) { jsize len = env->GetArrayLength(tex); wyTexture2D* textures[len]; for(int i = 0; i < len; i++) { jobject jt = (jobject)env->GetObjectArrayElement(tex, i); wyTexture2D* t = (wyTexture2D*)env->GetIntField(jt, g_fid_BaseObject_mPointer); textures[i] = t; } wyTMXTileMap* m = wyTMXTileMap::make(resId, textures, len); env->SetIntField(thiz, g_fid_BaseObject_mPointer, (jint)m); m->retain(); m->lazyRelease(); } JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeInit__Ljava_lang_String_2Z_3Lcom_wiyun_engine_opengl_Texture2D_2 (JNIEnv * env, jobject thiz, jstring path, jboolean isFile, jobjectArray tex) { jsize len = env->GetArrayLength(tex); wyTexture2D* textures[len]; for(int i = 0; i < len; i++) { jobject jt = (jobject)env->GetObjectArrayElement(tex, i); wyTexture2D* t = (wyTexture2D*)env->GetIntField(jt, g_fid_BaseObject_mPointer); textures[i] = t; } const char* p = (const char*)env->GetStringUTFChars(path, NULL); wyTMXTileMap* m = wyTMXTileMap::make(p, isFile, textures, len); env->ReleaseStringUTFChars(path, p); env->SetIntField(thiz, g_fid_BaseObject_mPointer, (jint)m); m->retain(); m->lazyRelease(); } JNIEXPORT jint JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeGetTMXLayer (JNIEnv * env, jobject thiz, jstring name) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); const char* n = env->GetStringUTFChars(name, NULL); wyTMXLayer* layer = map->getLayer(n); env->ReleaseStringUTFChars(name, n); return (jint)layer; } JNIEXPORT jint JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeGetTMXLayerAt (JNIEnv * env, jobject thiz, jint index) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); return (jint)map->getLayerAt(index); } JNIEXPORT jint JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeGetObjectGroup (JNIEnv * env, jobject thiz, jstring name) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); const char* n = env->GetStringUTFChars(name, NULL); wyTMXObjectGroup* group = map->getObjectGroup(n); env->ReleaseStringUTFChars(name, n); return (jint)group; } JNIEXPORT jstring JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getProperty (JNIEnv * env, jobject thiz, jstring key) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); const char* k = env->GetStringUTFChars(key, NULL); char* v = map->getProperty(k); jstring value = env->NewStringUTF(v); env->ReleaseStringUTFChars(key, k); return value; } JNIEXPORT jstring JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getTileProperties (JNIEnv * env, jobject thiz, jint gid, jstring key) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); const char* k = env->GetStringUTFChars(key, NULL); char* v = map->getTileProperty(gid, k); jstring value = env->NewStringUTF(v); env->ReleaseStringUTFChars(key, k); return value; } JNIEXPORT jint JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getMapWidth (JNIEnv * env, jobject thiz) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); return map->getMapWidth(); } JNIEXPORT jint JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getMapHeight (JNIEnv * env, jobject thiz) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); return map->getMapHeight(); } JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getTileWidth (JNIEnv * env, jobject thiz) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); return map->getTileWidth(); } JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getTileHeight (JNIEnv * env, jobject thiz) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); return map->getTileHeight(); } JNIEXPORT jint JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getOrientation (JNIEnv * env, jobject thiz) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); return map->getOrientation(); } JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_setDebugDrawObjects (JNIEnv * env, jobject thiz, jboolean flag) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); map->setDebugDrawObjects(flag); } JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeNodeToTMXSpace (JNIEnv * env, jobject thiz, jobject p, jobject out) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); wyPoint np = wyUtils_android::to_wyPoint(p); wyPoint nout = map->nodeToTMXSpace(np); wyUtils_android::to_WYPoint(nout, out); } JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeTMXToNodeSpace (JNIEnv * env, jobject thiz, jobject p, jobject out) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); wyPoint np = wyUtils_android::to_wyPoint(p); wyPoint nout = map->tmxToNodeSpace(np); wyUtils_android::to_WYPoint(nout, out); } JNIEXPORT jint JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_getAlpha (JNIEnv * env, jobject thiz) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); return map->getAlpha(); } JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_setAlpha (JNIEnv * env, jobject thiz, jint alpha) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); map->setAlpha(alpha); } JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeGetColor (JNIEnv * env, jobject thiz, jobject color) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); wyColor3B c = map->getColor(); wyUtils_android::to_WYColor3B(c, color); } JNIEXPORT void JNICALL Java_com_wiyun_engine_tmx_TMXTileMap_nativeSetColor (JNIEnv * env, jobject thiz, jint r, jint g, jint b) { wyTMXTileMap* map = (wyTMXTileMap*)env->GetIntField(thiz, g_fid_BaseObject_mPointer); map->setColor(wyc3b(r, g, b)); }
40.875
131
0.761927
zchajax
62343debc4ea5eca48577fbaf39775d7dfdd40b5
589
hpp
C++
Kernel/syscalls.hpp
foragerDev/GevOS
f21c8432dd63ab583d9132422bf313ebf60557e8
[ "Unlicense" ]
null
null
null
Kernel/syscalls.hpp
foragerDev/GevOS
f21c8432dd63ab583d9132422bf313ebf60557e8
[ "Unlicense" ]
null
null
null
Kernel/syscalls.hpp
foragerDev/GevOS
f21c8432dd63ab583d9132422bf313ebf60557e8
[ "Unlicense" ]
null
null
null
#ifndef SYSCALLS_HPP #define SYSCALLS_HPP #include "Exec/loader.hpp" #include "Filesystem/vfs.hpp" #include "Hardware/Drivers/keyboard.hpp" #include "Hardware/Drivers/pcspk.hpp" #include "Hardware/interrupts.hpp" #include "LibC/stdio.hpp" #include "LibC/types.hpp" #include "Mem/mm.hpp" #include "multitasking.hpp" #include "tty.hpp" extern "C" int shutdown(); class SyscallHandler : public InterruptHandler { public: SyscallHandler(InterruptManager* interruptManager, uint8_t InterruptNumber); ~SyscallHandler(); virtual uint32_t HandleInterrupt(uint32_t esp); }; #endif
22.653846
80
0.765705
foragerDev
6235100d8a62afc4deceb7f0ff0b06a387c102eb
2,782
cpp
C++
src/test/evo_utils_tests.cpp
thelazier/dash
22a24ab5b7b42d06a78d8fd092c3351bdf5aafdd
[ "MIT" ]
null
null
null
src/test/evo_utils_tests.cpp
thelazier/dash
22a24ab5b7b42d06a78d8fd092c3351bdf5aafdd
[ "MIT" ]
null
null
null
src/test/evo_utils_tests.cpp
thelazier/dash
22a24ab5b7b42d06a78d8fd092c3351bdf5aafdd
[ "MIT" ]
null
null
null
// Copyright (c) 2022 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/setup_common.h> #include <llmq/utils.h> #include <llmq/params.h> #include <chainparams.h> #include <validation.h> #include <boost/test/unit_test.hpp> /* TODO: rename this file and test to llmq_utils_test */ BOOST_AUTO_TEST_SUITE(evo_utils_tests) void Test() { using namespace llmq; const auto& consensus_params = Params().GetConsensus(); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeInstantSend, nullptr, false, false), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeInstantSend, nullptr, true, false), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeInstantSend, nullptr, true, true), false); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeDIP0024InstantSend, nullptr, false, false), false); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeDIP0024InstantSend, nullptr, true, false), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeDIP0024InstantSend, nullptr, true, true), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeChainLocks, nullptr, false, false), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeChainLocks, nullptr, false, false), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeChainLocks, nullptr, true, false), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypePlatform, nullptr, true, false), Params().IsTestChain()); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypePlatform, nullptr, true, true), Params().IsTestChain()); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypePlatform, nullptr, true, true), Params().IsTestChain()); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeMnhf, nullptr, true, false), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeMnhf, nullptr, true, true), true); BOOST_CHECK_EQUAL(CLLMQUtils::IsQuorumTypeEnabledInternal(consensus_params.llmqTypeMnhf, nullptr, true, true), true); } BOOST_FIXTURE_TEST_CASE(utils_IsQuorumTypeEnabled_tests_regtest, RegTestingSetup) { Test(); } BOOST_FIXTURE_TEST_CASE(utils_IsQuorumTypeEnabled_tests_mainnet, BasicTestingSetup) { Test(); } BOOST_AUTO_TEST_SUITE_END()
54.54902
144
0.81596
thelazier
62361cc16c9ad5370189225d5253bad12c1f6e7f
12,672
hpp
C++
src/cpp_lib/statistics/StatsTracker.hpp
hitbc/panSV
273b13bf496593325778d926f763bed6d2de5be2
[ "MIT" ]
null
null
null
src/cpp_lib/statistics/StatsTracker.hpp
hitbc/panSV
273b13bf496593325778d926f763bed6d2de5be2
[ "MIT" ]
null
null
null
src/cpp_lib/statistics/StatsTracker.hpp
hitbc/panSV
273b13bf496593325778d926f763bed6d2de5be2
[ "MIT" ]
1
2021-09-25T10:35:46.000Z
2021-09-25T10:35:46.000Z
/* * StatsTracker.hpp * * Created on: 2020年5月1日 * Author: fenghe */ #pragma once #include<iostream> #include <cstring> #include <cassert> #include <functional> #include <iosfwd> #include <map> #include <vector> extern "C" { #include "../clib/bam_file.h" } /****************PART ONE: Size Distribution***************************/ /// \brief Accumulate size observations and provide cdf/quantile/smoothed-pdf for the distribution /// struct SizeData { SizeData(unsigned initCount = 0, float initCprob = 0.) : count(initCount), cprob(initCprob) { } unsigned count; float cprob; }; typedef std::map<int, SizeData, std::greater<int>> map_type; struct SizeDistribution { SizeDistribution() : _isStatsComputed(false), _totalCount(0), _quantiles(_quantileNum, 0) { } /// \brief Implements the quantile function for this distribution int quantile(const float prob) const; /// \return The size at which all sizes equal or less are observed with probability \p prob float cdf(const int x) const;/// \return Probability of observing value <= \p x float pdf(const int x) const;/// \return Probability of observing value \p x, (with a smoothing window) unsigned totalObservations() const { return _totalCount; } void addObservation(const int size) { _isStatsComputed = false; _totalCount++; _sizeMap[size].count++; } void filterObservationsOverQuantile(const float prob);/// filter high value outliers: bool isStatSetMatch(const SizeDistribution &pss2);/// compare distributions to determine stats convergence int getSizeCount(int isize) const{ return _sizeMap[isize].count; } private: void calcStats() const; static const int _quantileNum = 1000; mutable bool _isStatsComputed; unsigned _totalCount; mutable std::vector<int> _quantiles; mutable map_type _sizeMap; }; //********************************PART TWO: Read PAIR DIRECTION**************************/ typedef int32_t pos_t; namespace PAIR_ORIENT { enum index_t { UNKNOWN, Fm, Fp, Rm, Rp, SIZE}; inline const char* label(const index_t i) { switch (i) { case Fm: return "Fm"; case Fp: return "Fp"; case Rm: return "Rm"; case Rp: return "Rp"; default: return "UNKNOWN"; } } inline index_t get_index(const pos_t pos1, const bool is_fwd_strand1, const pos_t pos2, const bool is_fwd_strand2) { const bool is_read1_left(pos1 < pos2); if (is_fwd_strand1 != is_fwd_strand2) { // special-case very short fragments as innies: // // a few bases of overhang are allowed to account for random matches of // the reverse read to the primer // if (std::abs(pos1 - pos2) <= 2) return Rp; const bool left_strand(is_read1_left ? is_fwd_strand1 : is_fwd_strand2); return (left_strand ? Rp : Rm); } else { return ((is_read1_left == is_fwd_strand1) ? Fp : Fm); } } /// inefficient label to id lookup, returns SIZE for unknown string: inline index_t get_index(const char *str) { for (int i(0); i < SIZE; ++i) { if (0 == strcmp(str, label(static_cast<index_t>(i)))) return static_cast<index_t>(i); } return SIZE; } } // END namespace PAIR_ORIENT /// pair orientation status wrapper: struct ReadPairOrient { ReadPairOrient() : _val(PAIR_ORIENT::UNKNOWN) { } PAIR_ORIENT::index_t val() const { return _val; } void setVal(const unsigned newVal) { assert(newVal < PAIR_ORIENT::SIZE); _val = static_cast<PAIR_ORIENT::index_t>(newVal); } private: PAIR_ORIENT::index_t _val; }; //********************************PART Three: ReadCounter**************************/ /// \brief Accumulate read statistics scanned for insert size estimation struct ReadCounter { ReadCounter() : _totalReadCount(0), _totalPairedReadCount(0), _totalUnpairedReadCount( 0), _totalPairedLowMapqReadCount(0), _totalHighConfidenceReadPairCount( 0) {} unsigned totalReadCount() const { return _totalReadCount;} unsigned totalPairedReadCount() const { return _totalPairedReadCount;} unsigned totalUnpairedReadCount() const {return _totalUnpairedReadCount;} unsigned totalPairedLowMapqReadCount() const {return _totalPairedLowMapqReadCount;} unsigned totalHighConfidenceReadPairCount() const { return _totalHighConfidenceReadPairCount;} void addReadCount() { _totalReadCount++;} void addPairedReadCount() { _totalPairedReadCount++;} void addUnpairedReadCount() { _totalUnpairedReadCount++;} void addPairedLowMapqReadCount() { _totalPairedLowMapqReadCount++;} void addHighConfidenceReadPairCount() { _totalHighConfidenceReadPairCount += 1;} friend std::ostream& operator<<(std::ostream &os, const ReadCounter &rs) { os << "\tTotal sampled reads: " + std::to_string(rs.totalReadCount()) + "\n" << "\tTotal sampled paired reads: " + std::to_string(rs.totalPairedReadCount()) + "\n" << "\tTotal sampled paired reads passing MAPQ filter: " + std::to_string( rs.totalPairedReadCount() - rs.totalPairedLowMapqReadCount()) + "\n" << "\tTotal sampled high-confidence read pairs passing all filters: " + std::to_string(rs.totalHighConfidenceReadPairCount()) + "\n"; return os; } private: ///////////////////////////////////// data: unsigned _totalReadCount; unsigned _totalPairedReadCount; unsigned _totalUnpairedReadCount; unsigned _totalPairedLowMapqReadCount; unsigned _totalHighConfidenceReadPairCount; }; //********************************PART Four: Unique Stats**************************/ /// Read pair insert stats can be computed for each sample or read group, this /// class represents the statistics for one group: /// struct UniqueStats { public: SizeDistribution fragStats; ReadPairOrient relOrients; ReadCounter readCounter; }; struct StatLabel { /// if isCopyPtrs then the strings are copied and alloced/de-alloced by /// the object, if false the client is responsible these pointers over /// the lifetime of the label: StatLabel(const char *bamLabelInit, const char *rgLabelInit, const bool isCopyPtrsInit = true) : isCopyPtrs(isCopyPtrsInit), bamLabel( (isCopyPtrs && (nullptr != bamLabelInit)) ? strdup(bamLabelInit) : bamLabelInit), rgLabel( (isCopyPtrs && (nullptr != rgLabelInit)) ? strdup(rgLabelInit) : rgLabelInit) { assert(nullptr != bamLabel); assert(nullptr != rgLabel); } StatLabel(const StatLabel &rhs) : isCopyPtrs(rhs.isCopyPtrs), bamLabel( isCopyPtrs ? strdup(rhs.bamLabel) : rhs.bamLabel), rgLabel( isCopyPtrs ? strdup(rhs.rgLabel) : rhs.rgLabel) { } StatLabel& operator=(const StatLabel &rhs) { if (this == &rhs) return *this; clear(); isCopyPtrs = rhs.isCopyPtrs; bamLabel = (isCopyPtrs ? strdup(rhs.bamLabel) : rhs.bamLabel); rgLabel = (isCopyPtrs ? strdup(rhs.rgLabel) : rhs.rgLabel); return *this; } public: ~StatLabel() { clear(); } /// sort allowing for nullptr string pointers in primary and secondary key: bool operator<(const StatLabel &rhs) const { const int scval(strcmp(bamLabel, rhs.bamLabel)); if (scval < 0) return true; if (scval == 0) { return (strcmp(rgLabel, rhs.rgLabel) < 0); } return false; } friend std::ostream& operator<<(std::ostream &os, const StatLabel &rgl) { os << "read group '" << rgl.rgLabel << "' in bam file '" << rgl.bamLabel; return os; } private: void clear() { if (isCopyPtrs) { if (nullptr != bamLabel) free(const_cast<char*>(bamLabel)); if (nullptr != rgLabel) free(const_cast<char*>(rgLabel)); } } bool isCopyPtrs; public: const char *bamLabel; const char *rgLabel; }; /// track pair orientation so that a consensus can be found for a read group struct OrientTracker { OrientTracker(const char *bamLabel, const char *rgLabel) : _isFinalized(false), _totalOrientCount(0), _rgLabel(bamLabel, rgLabel) { std::fill(_orientCount.begin(), _orientCount.end(), 0); } void addOrient(const PAIR_ORIENT::index_t ori) { static const unsigned maxOrientCount(100000); if (_totalOrientCount >= maxOrientCount) return; if (ori == PAIR_ORIENT::UNKNOWN) return; addOrientImpl(ori); } const ReadPairOrient& getConsensusOrient(const ReadCounter &readCounter) { finalize(readCounter); return _finalOrient; } unsigned getMinCount() { static const unsigned minCount(100); return minCount; } bool isOrientCountGood() { return (_totalOrientCount >= getMinCount()); } private: void addOrientImpl(const PAIR_ORIENT::index_t ori) { assert(!_isFinalized); assert(ori < PAIR_ORIENT::SIZE); _orientCount[ori]++; _totalOrientCount++; } void finalize(const ReadCounter &readCounter); bool _isFinalized; unsigned _totalOrientCount; const StatLabel _rgLabel; std::array<unsigned, PAIR_ORIENT::SIZE> _orientCount; ReadPairOrient _finalOrient; }; struct SimpleRead { SimpleRead(PAIR_ORIENT::index_t ort, unsigned sz) : _orient(ort), _insertSize(sz) { } PAIR_ORIENT::index_t _orient; unsigned _insertSize; }; struct ReadBuffer { ReadBuffer() : _abnormalRpCount(0), _observationRpCount(0) { } void updateBuffer(PAIR_ORIENT::index_t ort, unsigned sz) { _readInfo.emplace_back(ort, sz); if (ort == PAIR_ORIENT::Rp) { _observationRpCount++; if (sz >= 5000) _abnormalRpCount++; } } bool isBufferFull() const { return (_observationRpCount >= 1000); } bool isBufferNormal() const { if (_observationRpCount == 0) return false; return ((_abnormalRpCount / (float) _observationRpCount) < 0.01); } unsigned getAbnormalCount() { return _abnormalRpCount; } unsigned getObservationCount() { return _observationRpCount; } const std::vector<SimpleRead>& getBufferedReads() { return _readInfo; } void clearBuffer() { _abnormalRpCount = 0; _observationRpCount = 0; _readInfo.clear(); } private: unsigned _abnormalRpCount; unsigned _observationRpCount; std::vector<SimpleRead> _readInfo; }; #define statsCheckCnt 100000 enum RGT_RETURN { RGT_CONTINUE, RGT_BREAK, RGT_NORMAL }; struct StatsTracker { StatsTracker(const char *bamLabel = nullptr, const char *rgLabel = nullptr, const std::string &defaultStatsFilename = "") : _rgLabel(bamLabel, rgLabel), _orientInfo(bamLabel, rgLabel), _defaultStatsFilename( defaultStatsFilename) { } unsigned insertSizeObservations() const { return _stats.fragStats.totalObservations();} unsigned getMinObservationCount() const { static const unsigned minObservations(100); return minObservations; } bool isObservationCountGood() const { return (insertSizeObservations() >= getMinObservationCount()); } void checkInsertSizeCount() { if ((insertSizeObservations() % statsCheckCnt) == 0) _isChecked = true; } bool isInsertSizeChecked() const { return _isChecked; } void clearChecked() { _isChecked = false; } bool isInsertSizeConverged() const { return _isInsertSizeConverged; } bool isCheckedOrConverged() const { return (_isChecked || isInsertSizeConverged()); } void updateInsertSizeConvergenceTest() { // check convergence if (_oldInsertSize.totalObservations() > 0) { _isInsertSizeConverged = _oldInsertSize.isStatSetMatch( _stats.fragStats); } _oldInsertSize = _stats.fragStats; } ReadBuffer& getBuffer() { return _buffer; } void addBufferedData(); const OrientTracker& getOrientInfo() const { return _orientInfo; } const UniqueStats& getStats() const { assert(_isFinalized); return _stats; } /// getting a const ref of the stats forces finalization steps: void addReadCount() { _stats.readCounter.addReadCount();} void addPairedReadCount() { _stats.readCounter.addPairedReadCount();} void addUnpairedReadCount() { _stats.readCounter.addUnpairedReadCount();} void addPairedLowMapqReadCount() { _stats.readCounter.addPairedLowMapqReadCount();} void addHighConfidenceReadPairCount() { _stats.readCounter.addHighConfidenceReadPairCount();} /// Add one observation to the buffer /// If the buffer is full, AND if the fragment size distribution in the buffer looks normal, add the buffered data; /// otherwise, discard the buffer and move to the next region bool addObservation(PAIR_ORIENT::index_t ori, unsigned sz); void finalize(); void handleReadRecordBasic(bam1_t *b); RGT_RETURN handleReadRecordCheck(bam1_t *b); private: void addOrient(const PAIR_ORIENT::index_t ori) { assert(!_isFinalized); _orientInfo.addOrient(ori); } void addInsertSize(const int size) { assert(!_isFinalized); _stats.fragStats.addObservation(size); } bool _isFinalized = false; const StatLabel _rgLabel; OrientTracker _orientInfo; bool _isChecked = false; bool _isInsertSizeConverged = false; SizeDistribution _oldInsertSize; // previous fragment distribution is stored to determine convergence ReadBuffer _buffer; UniqueStats _stats; const std::string _defaultStatsFilename; };
29.746479
141
0.716461
hitbc
623661ec178cc62d5bcb82821a7df2c701681e03
2,113
hpp
C++
sandbox/usda/lexy/validate.hpp
fire/tinyusdz
2a98a12d0c6f34de8d7a219e5f82135e9beb4376
[ "MIT" ]
159
2020-04-14T15:59:35.000Z
2022-03-31T14:19:05.000Z
sandbox/usda/lexy/validate.hpp
fire/tinyusdz
2a98a12d0c6f34de8d7a219e5f82135e9beb4376
[ "MIT" ]
16
2020-05-21T06:00:40.000Z
2022-02-26T08:50:33.000Z
sandbox/usda/lexy/validate.hpp
fire/tinyusdz
2a98a12d0c6f34de8d7a219e5f82135e9beb4376
[ "MIT" ]
8
2020-07-01T04:13:42.000Z
2022-01-30T17:50:52.000Z
// Copyright (C) 2020 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef LEXY_VALIDATE_HPP_INCLUDED #define LEXY_VALIDATE_HPP_INCLUDED #include <lexy/callback.hpp> #include <lexy/dsl/base.hpp> #include <lexy/result.hpp> namespace lexy { template <typename Production, typename Input, typename Callback> class _validate_handler { public: constexpr explicit _validate_handler(const Input& input, const input_reader<Input>& reader, Callback cb) : _err_ctx(input, reader.cur()), _callback(cb) {} using result_type = result<void, typename Callback::return_type>; template <typename SubProduction> constexpr auto sub_handler(const input_reader<Input>& reader) { return _validate_handler<SubProduction, Input, Callback>(_err_ctx.input(), reader, _callback); } constexpr auto list_sink() { return noop.sink(); } template <typename Reader, typename Error> constexpr auto error(const Reader&, Error&& error) && { return lexy::invoke_as_result<result_type>(lexy::result_error, _callback, _err_ctx, LEXY_FWD(error)); } template <typename... Args> constexpr auto value(Args&&...) && { return result_type(lexy::result_value); } private: error_context<Production, Input> _err_ctx; LEXY_EMPTY_MEMBER Callback _callback; }; template <typename Production, typename Input, typename Callback> constexpr auto validate(const Input& input, Callback callback) { using rule = std::remove_const_t<decltype(Production::rule)>; using handler_t = _validate_handler<Production, Input, Callback>; auto reader = input.reader(); handler_t handler(input, reader, callback); return rule::template parser<final_parser>::parse(handler, reader); } } // namespace lexy #endif // LEXY_VALIDATE_HPP_INCLUDED
30.185714
95
0.667771
fire
9a8c2ad6d0efc11cc202d34e128a113821525368
2,940
cpp
C++
Engine/ac/dynobj/cc_agsdynamicobject.cpp
proteanblank/ags
025640c60dbf77d84d213d3994ebcc6600979476
[ "Artistic-2.0" ]
null
null
null
Engine/ac/dynobj/cc_agsdynamicobject.cpp
proteanblank/ags
025640c60dbf77d84d213d3994ebcc6600979476
[ "Artistic-2.0" ]
null
null
null
Engine/ac/dynobj/cc_agsdynamicobject.cpp
proteanblank/ags
025640c60dbf77d84d213d3994ebcc6600979476
[ "Artistic-2.0" ]
null
null
null
//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // http://www.opensource.org/licenses/artistic-license-2.0.php // //============================================================================= #include <string.h> #include "ac/dynobj/cc_agsdynamicobject.h" #include "ac/common.h" // quit() #include "util/memorystream.h" using namespace AGS::Common; // *** The script serialization routines for built-in types int AGSCCDynamicObject::Dispose(const char* /*address*/, bool /*force*/) { // cannot be removed from memory return 0; } int AGSCCDynamicObject::Serialize(const char *address, char *buffer, int bufsize) { // If the required space is larger than the provided buffer, // then return negated required space, notifying the caller that a larger buffer is necessary size_t req_size = CalcSerializeSize(); if (bufsize < 0 || req_size > static_cast<size_t>(bufsize)) return -(static_cast<int32_t>(req_size)); MemoryStream mems(reinterpret_cast<uint8_t*>(buffer), bufsize, kStream_Write); Serialize(address, &mems); return static_cast<int32_t>(mems.GetPosition()); } const char* AGSCCDynamicObject::GetFieldPtr(const char *address, intptr_t offset) { return address + offset; } void AGSCCDynamicObject::Read(const char *address, intptr_t offset, void *dest, int size) { memcpy(dest, address + offset, size); } uint8_t AGSCCDynamicObject::ReadInt8(const char *address, intptr_t offset) { return *(uint8_t*)(address + offset); } int16_t AGSCCDynamicObject::ReadInt16(const char *address, intptr_t offset) { return *(int16_t*)(address + offset); } int32_t AGSCCDynamicObject::ReadInt32(const char *address, intptr_t offset) { return *(int32_t*)(address + offset); } float AGSCCDynamicObject::ReadFloat(const char *address, intptr_t offset) { return *(float*)(address + offset); } void AGSCCDynamicObject::Write(const char *address, intptr_t offset, void *src, int size) { memcpy((void*)(address + offset), src, size); } void AGSCCDynamicObject::WriteInt8(const char *address, intptr_t offset, uint8_t val) { *(uint8_t*)(address + offset) = val; } void AGSCCDynamicObject::WriteInt16(const char *address, intptr_t offset, int16_t val) { *(int16_t*)(address + offset) = val; } void AGSCCDynamicObject::WriteInt32(const char *address, intptr_t offset, int32_t val) { *(int32_t*)(address + offset) = val; } void AGSCCDynamicObject::WriteFloat(const char *address, intptr_t offset, float val) { *(float*)(address + offset) = val; }
31.276596
97
0.679252
proteanblank
9a8c5628500474c3eb9bef147aaf32e1d349a862
935
cpp
C++
src/macro/macro203.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/macro/macro203.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/macro/macro203.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
#include "Macro.h" #include "DomainTree.h" #include "StandardFEM.h" extern DomainTree domain; int macro203(Macro &macro) { if (!macro) { macro.name = "erro"; macro.type = "chen"; macro.what = " Compute Error Norm "; macro.sensitivity[INTER] = true; macro.sensitivity[BATCH] = true; macro.db.selectDomain(); macro.db.frameButtonBox(); macro.db.addTextField("index = ",1); macro.db.addTextField("tol = ",0.001,6); macro.db.frameRadioBox(); // and other stuff return 0; } //-------------------------------------------------------------------------------------------------- int type, id, index; double tol; type = roundToInt(macro.p[0]); id = roundToInt(macro.p[1]) - 1; index = roundToInt(macro.p[2]); tol = macro.p[3]; standardFEM(domain(type,id)).computeElementErrors(index); return 0; }
18.333333
101
0.517647
chennachaos
9a8ced79843ca7f82f63b1cd0046cfb6efaa5937
1,105
hpp
C++
source/Input/Mapper.hpp
kurocha/input
619cbe901ebb2cfd9dd97235d30e596edc96aa14
[ "MIT", "Unlicense" ]
null
null
null
source/Input/Mapper.hpp
kurocha/input
619cbe901ebb2cfd9dd97235d30e596edc96aa14
[ "MIT", "Unlicense" ]
null
null
null
source/Input/Mapper.hpp
kurocha/input
619cbe901ebb2cfd9dd97235d30e596edc96aa14
[ "MIT", "Unlicense" ]
null
null
null
// // Mapper.hpp // This file is part of the "Input" project and released under the MIT License. // // Created by Samuel Williams on 23/2/2019. // Copyright, 2019, by Samuel Williams. All rights reserved. // #pragma once #include <unordered_map> namespace Input { template <typename ActionT> class Mapper { protected: using Actions = std::unordered_map<Key, ActionT>; Actions _actions; public: void bind(const Key & key, ActionT action) { _actions[key] = action; } void bind(DeviceT device, ButtonT button, ActionT action) { bind(Key(device, button), action); } // mapper.invoke(key, ->(action){}); template <typename BlockT> bool invoke(const Key & key, BlockT block) const { auto action = _actions.find(key); if (action != _actions.end()) { block(action); return true; } else { return false; } } template <typename BlockT> bool invoke(const Key & key) const { auto action = _actions.find(key); if (action != _actions.end()) { action(); return true; } else { return false; } } }; }
19.051724
80
0.630769
kurocha
9a8d5e604c6c9b2f1d4a8aecd6d8b8757fa165a7
4,853
cpp
C++
src/HashGenerator.cpp
kyberdrb/duplicate_finder
4971830082b0248d2f5b434f1cdb53eb3da39b6d
[ "CC0-1.0" ]
null
null
null
src/HashGenerator.cpp
kyberdrb/duplicate_finder
4971830082b0248d2f5b434f1cdb53eb3da39b6d
[ "CC0-1.0" ]
null
null
null
src/HashGenerator.cpp
kyberdrb/duplicate_finder
4971830082b0248d2f5b434f1cdb53eb3da39b6d
[ "CC0-1.0" ]
null
null
null
#include "HashGenerator.h" #include "openssl/sha.h" #include <array> #include <vector> #include <fstream> #include <iomanip> #include <sstream> // TODO maybe template this, or abstract this into virtual functions, according to the algorithm type - tested on SHA1 with SHA_CTX and with SHA256 with SHA256_CTX // - maybe later, when I will create a library for hashing which will be much simpler to use than the raw Crypto++ or OpenSSL libraries, like this for example: std::string sha256HashOfFile = Hasher::sha256sum(filePath); std::string HashGenerator::sha256_CPP_style(const std::string& filePath) { SHA256_CTX sha256_context; SHA256_Init(&sha256_context); std::ifstream file(filePath, std::ios::binary); const size_t CHUNK_SIZE = 1024; // preferring array instead of vector because the size of the buffer will stay the same throughout the entire hashAsText creation process //std::vector<char> chunkBuffer(CHUNK_SIZE, '\0'); std::array<char, CHUNK_SIZE> chunkBuffer{'\0'}; while ( file.read( chunkBuffer.data(), chunkBuffer.size() ) ) { auto bytesRead = file.gcount(); SHA256_Update(&sha256_context, chunkBuffer.data(), bytesRead); } // Evaluate the last partial chunk // `fin.read(...)` evaluates to false on the last partial block (or eof). You need to process partial reads outside of the while loop `gcount()!=0` - https://stackoverflow.com/questions/35905295/reading-a-file-in-chunks#comment59488065_35905524 if (file.gcount() != 0) { SHA256_Update(&sha256_context, chunkBuffer.data(), file.gcount()); } // preferring array instead of vector because the size of the buffer will stay the same throughout the entire hashAsText creation process //std::vector<uint8_t> hashAsText(SHA256_DIGEST_LENGTH, '\0'); std::array<uint8_t, SHA256_DIGEST_LENGTH> hash{'\0'}; SHA256_Final(hash.data(), &sha256_context); std::stringstream hashInHexadecimalFormat; for(auto chunk : hash) { hashInHexadecimalFormat << std::hex << std::setw(2) << std::setfill('0') << (uint32_t) chunk; } return hashInHexadecimalFormat.str(); } void HashGenerator::sha1_C_style_static_alloc(const char* filePath) { SHA_CTX sha1Context; SHA1_Init(&sha1Context); uint32_t bytesRead; uint8_t chunkBuffer[1024]; const size_t CHUNK_SIZE = 1024; FILE* file = fopen(filePath, "rb"); while( (bytesRead = fread(chunkBuffer, 1, CHUNK_SIZE, file) ) != 0 ) { SHA1_Update(&sha1Context, chunkBuffer, bytesRead); } uint8_t hash[SHA_DIGEST_LENGTH]; SHA1_Final(hash, &sha1Context); char hashInHexadecimalFormat[2 * SHA_DIGEST_LENGTH]; for(int32_t chunkPosition=0; chunkPosition < SHA_DIGEST_LENGTH; ++chunkPosition) { sprintf(&(hashInHexadecimalFormat[chunkPosition * 2]), "%02x", hash[chunkPosition] ); } printf("%s", hashInHexadecimalFormat); fclose(file); // no return because we would return a pointer to a local variable, which are discarded at the closing curly brace of this function; therefore we print the output to the terminal as a feedback and a side-effect } char* HashGenerator::sha1_C_style_dynamic_alloc(const char* filePath) { SHA_CTX* sha1Context = (SHA_CTX*) calloc(1, sizeof(SHA_CTX) ); SHA1_Init(sha1Context); uint32_t bytesRead; uint8_t* chunkBuffer = (uint8_t*) calloc(1024, sizeof(uint8_t) ); const size_t CHUNK_SIZE = 1024; FILE* file = fopen(filePath, "rb"); while( (bytesRead = fread(chunkBuffer, 1, CHUNK_SIZE, file) ) != 0 ) { SHA1_Update(sha1Context, chunkBuffer, bytesRead); } free(chunkBuffer); chunkBuffer = NULL; // sanitize dangling pointer uint8_t* hash = (uint8_t*) calloc(SHA_DIGEST_LENGTH, sizeof(uint8_t) ); SHA1_Final(hash, sha1Context); free(sha1Context); sha1Context = NULL; //char* hashInHexadecimalFormat = (char*) calloc(SHA_DIGEST_LENGTH * 2, sizeof(char)); // error: 'Corrupted size vs. prev_size' or 'malloc(): invalid next size (unsorted)' char* hashInHexadecimalFormat = (char*) calloc(SHA_DIGEST_LENGTH * 2 + 1, sizeof(char)); // add one extra position at the end of the buffer '+ 1' for the 'null terminator' '\0' that terminates the string, in order to prevent error 'Corrupted size vs. prev_size' and other errors and undefined behaviors - https://cppsecrets.com/users/931049711497106109971151165748485664103109971051084699111109/C00-Program-to-Find-Hash-of-File.php for(int32_t chunkPosition=0; chunkPosition < SHA_DIGEST_LENGTH; ++chunkPosition) { sprintf( &(hashInHexadecimalFormat[chunkPosition * 2] ), "%02x", hash[chunkPosition] ); } free(hash); hash = NULL; fclose(file); return hashInHexadecimalFormat; // remember to free the pointer in the caller code, i. e. free the pointer on the client side }
43.720721
437
0.712343
kyberdrb
9a901d305711cf12167bd8866b489ce1e756f783
4,969
cpp
C++
tuw_multi_robot_test/src/goal_generator.cpp
JakubHazik/tuw_multi_robot
9c5c8a2ed87e0bf6f9a573e38b4d5790dfc25aba
[ "BSD-3-Clause" ]
null
null
null
tuw_multi_robot_test/src/goal_generator.cpp
JakubHazik/tuw_multi_robot
9c5c8a2ed87e0bf6f9a573e38b4d5790dfc25aba
[ "BSD-3-Clause" ]
null
null
null
tuw_multi_robot_test/src/goal_generator.cpp
JakubHazik/tuw_multi_robot
9c5c8a2ed87e0bf6f9a573e38b4d5790dfc25aba
[ "BSD-3-Clause" ]
null
null
null
#include <ros/ros.h> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <cmath> #include <geometry_msgs/Pose.h> #include <geometry_msgs/PoseStamped.h> #include <nav_msgs/Odometry.h> #include <tf/transform_datatypes.h> #include <tf/transform_listener.h> #include <std_msgs/Bool.h> #include <tuw_multi_robot_msgs/RobotGoals.h> geometry_msgs::PoseStamped pose_odom_frame; void odomCallback(const nav_msgs::Odometry::ConstPtr& msg) { pose_odom_frame.header=msg->header; pose_odom_frame.pose=msg->pose.pose; } double distance2d(const double & x1, const double & y1, const double & x2, const double & y2) { return sqrt(pow(x1-x2,2)+pow(y1-y2,2)); } void parseWaypointsFile(ros::NodeHandle& nh, std::vector<geometry_msgs::PoseStamped>& goals_list, const std::string & _world_frame) { //csv file containing one waypoint/line in the formalism : x,y (meter),yaw (degree) //in frame map ROS_INFO("Going to parse"); std::string goals_file; if (nh.getParam("file", goals_file)) {ROS_INFO("Loaded %s as goals file", goals_file.c_str());} else {ROS_ERROR("No waypoints file specified");} std::ifstream data(goals_file.c_str(), std::ifstream::in); if (!data.is_open()){ROS_ERROR("Could not open input CSV file");} else { std::string line; while(std::getline(data,line)) { if (line.empty()){ROS_INFO( "Empty line");} geometry_msgs::PoseStamped next_point; std::stringstream lineStream(line); std::string cell; std::getline(lineStream,cell,','); next_point.pose.position.x = std::stof(cell); std::getline(lineStream,cell,','); next_point.pose.position.y = std::stof(cell); std::getline(lineStream,cell); next_point.pose.orientation = tf::createQuaternionMsgFromYaw(std::stof(cell)); next_point.header.frame_id = _world_frame; goals_list.push_back(next_point); } } ROS_INFO("Parsing completed"); } int main(int argc, char** argv){ ros::init(argc, argv, "goal_generator"); ros::NodeHandle nh("~"); std::vector<geometry_msgs::PoseStamped> goals_list; // ID of the robot associated with the goal generator std::string robot_id; nh.param<std::string>("robot_id", robot_id, "robot_0"); bool use_tf; nh.param<bool>("use_tf", use_tf, false); // Frames std::string odom_frame; nh.param<std::string>("odom_frame", odom_frame, "odom"); std::string world_frame; nh.param<std::string>("world_frame", world_frame, "map"); // Run in loop or not bool run_once; nh.param<bool>("run_once", run_once, true); parseWaypointsFile(nh, goals_list, world_frame); ros::Subscriber robotPoseSub = nh.subscribe("/" + robot_id + "/odom", 1, odomCallback); ros::Publisher goalPub = nh.advertise<tuw_multi_robot_msgs::RobotGoals>("/labelled_goal",1); // Transform tf::TransformListener tf_listener; geometry_msgs::PoseStamped pose_world_frame; // Create the goal structure tuw_multi_robot_msgs::RobotGoals labeled_goal; labeled_goal.robot_name=robot_id; ros::Rate loop_rate(2); unsigned goal_index=0; geometry_msgs::Pose goal = goals_list.at(goal_index).pose; labeled_goal.destinations.push_back(goal); bool goal_published=false; int n_time_publish=0; ros::spinOnce(); while(ros::ok()) { ros::spinOnce(); if(use_tf) { try { tf_listener.waitForTransform(pose_odom_frame.header.frame_id, world_frame, ros::Time::now(), ros::Duration(1.0)); pose_world_frame.header.stamp=ros::Time::now(); tf_listener.transformPose(world_frame, pose_odom_frame, pose_world_frame); } catch (tf::TransformException ex) { ROS_ERROR("%s",ex.what()); ros::Duration(1.0).sleep(); } } else { if(pose_odom_frame.header.frame_id != world_frame) { ROS_ERROR("Odometry frame (\"%s\") is not equal to the world frame (\"%s\"), please enable use_tf or publish in the right frame",odom_frame.c_str(),world_frame.c_str()); break; } } ROS_ERROR("%f",distance2d(goal.position.x,goal.position.y,pose_odom_frame.pose.position.x,pose_odom_frame.pose.position.y)); if(distance2d(goal.position.x,goal.position.y,pose_odom_frame.pose.position.x,pose_odom_frame.pose.position.y) < 1.0) { ros::Duration(2.0).sleep(); goal_index++; // If we reach the end of the list if(goal_index>=goals_list.size()) { if(run_once) break; else goal_index=0; } goal = goals_list.at(goal_index).pose; labeled_goal.destinations.at(0) = goal; goal_published=false; n_time_publish=0; } // Republish several times to be sure that the goal is sent if(!goal_published || n_time_publish<5) { goalPub.publish(labeled_goal); ROS_ERROR("Goal published"); goal_published=true; n_time_publish++; } loop_rate.sleep(); } return 0; }
29.229412
177
0.674784
JakubHazik
9a93b9f0558350f01e0429a0954ddcd5a9f2caa1
1,323
cpp
C++
src/wolf3d_shaders/ws_shaders.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
5
2019-09-14T14:08:46.000Z
2021-04-27T11:21:43.000Z
src/wolf3d_shaders/ws_shaders.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
null
null
null
src/wolf3d_shaders/ws_shaders.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
1
2019-10-19T04:19:46.000Z
2019-10-19T04:19:46.000Z
#include "ws.h" static void checkShader(GLuint handle) { GLint bResult; glGetShaderiv(handle, GL_COMPILE_STATUS, &bResult); if (bResult == GL_FALSE) { GLchar infoLog[1024]; glGetShaderInfoLog(handle, 1023, NULL, infoLog); Quit((char *)(std::string("shader compile failed: ") + infoLog).c_str()); } } GLuint ws_create_program(const GLchar *vs, const GLchar *ps, const std::vector<const char *> &attribs) { const GLchar *vertex_shader_with_version[2] = { "#version 120\n", vs }; const GLchar *fragment_shader_with_version[2] = { "#version 120\n", ps }; auto vertHandle = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertHandle, 2, vertex_shader_with_version, NULL); glCompileShader(vertHandle); checkShader(vertHandle); auto fragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragHandle, 2, fragment_shader_with_version, NULL); glCompileShader(fragHandle); checkShader(fragHandle); GLuint program = glCreateProgram(); glAttachShader(program, vertHandle); glAttachShader(program, fragHandle); int i = 0; for (auto attrib : attribs) { glBindAttribLocation(program, i, attrib); ++i; } glLinkProgram(program); return program; }
30.767442
103
0.664399
Daivuk
9a97c9bb78b98356e6c59f1881cc8cbd28877248
29,999
cc
C++
libs/core/tests/Logging/LogTest.cc
v8App/v8App
96c5278ae9078d508537f2e801b9ba0272ab1168
[ "MIT" ]
null
null
null
libs/core/tests/Logging/LogTest.cc
v8App/v8App
96c5278ae9078d508537f2e801b9ba0272ab1168
[ "MIT" ]
null
null
null
libs/core/tests/Logging/LogTest.cc
v8App/v8App
96c5278ae9078d508537f2e801b9ba0272ab1168
[ "MIT" ]
null
null
null
// Copyright 2020 The v8App Authors. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. #include "gtest/gtest.h" #include "gmock/gmock.h" #include "Logging/Log.h" #include "Logging/ILogSink.h" #include "Logging/LogMacros.h" #include "TestLogSink.h" namespace v8App { namespace Log { namespace LogTest { class LogDouble : public Log { public: static bool IsSinksEmpty() { return m_LogSinks.empty(); } static void TestInternalLog(LogMessage &inMessage, LogLevel inLevel, std::string File, std::string Function, int Line) { InternalLog(inMessage, inLevel, File, Function, Line); } static void TestInternalLog(LogMessage &inMessage, LogLevel inLevel) { InternalLog(inMessage, inLevel); } static void ResetLog() { m_LogSinks.clear(); m_AppName = "v8App"; m_LogLevel = LogLevel::Error; m_UseUTC = true; } }; TestUtils::TestLogSink *SetupGlobalSink(TestUtils::WantsLogLevelsVector inLevels) { TestUtils::TestLogSink *sink = TestUtils::TestLogSink::GetGlobalSink(); sink->SetWantsLogLevels(inLevels); sink->FlushMessages(); return sink; } } // namespace LogTest TEST(LogTest, LogLevelToString) { EXPECT_EQ("Fatal", LogLevelToString(LogLevel::Fatal)); EXPECT_EQ("Off", LogLevelToString(LogLevel::Off)); EXPECT_EQ("Error", LogLevelToString(LogLevel::Error)); EXPECT_EQ("General", LogLevelToString(LogLevel::General)); EXPECT_EQ("Warn", LogLevelToString(LogLevel::Warn)); EXPECT_EQ("Debug", LogLevelToString(LogLevel::Debug)); EXPECT_EQ("Trace", LogLevelToString(LogLevel::Trace)); } TEST(LogTest, GetSetLogLevel) { EXPECT_EQ(LogLevel::Error, Log::GetLogLevel()); Log::SetLogLevel(LogLevel::Off); EXPECT_EQ(LogLevel::Off, Log::GetLogLevel()); Log::SetLogLevel(LogLevel::Fatal); EXPECT_EQ(LogLevel::Off, Log::GetLogLevel()); } TEST(LogTest, GetSetAppName) { EXPECT_EQ("v8App", Log::GetAppName()); std::string testName("TestAppName"); Log::SetAppName(testName); EXPECT_EQ(testName, Log::GetAppName()); } TEST(LogTest, UseUTC) { EXPECT_TRUE(Log::IsUsingUTC()); Log::UseUTC(false); EXPECT_FALSE(Log::IsUsingUTC()); Log::UseUTC(true); EXPECT_TRUE(Log::IsUsingUTC()); } TEST(LogTest, AddRemoveLogSink) { //NOTE: the unique_ptr owns this and will delete it when it's removed TestUtils::WantsLogLevelsVector warns = {LogLevel::Warn}; TestUtils::TestLogSink *testSink = new TestUtils::TestLogSink("TestLogSink", warns); std::unique_ptr<ILogSink> sinkObj(testSink); TestUtils::WantsLogLevelsVector emptyWants; std::unique_ptr<ILogSink> sink2(new TestUtils::TestLogSink("TestLogSink", emptyWants)); //need to change the log level so we can see the warn Log::SetLogLevel(LogLevel::Warn); ASSERT_TRUE(Log::AddLogSink(sinkObj)); ASSERT_FALSE(Log::AddLogSink(sink2)); EXPECT_TRUE(testSink->WantsLogMessage(LogLevel::Warn)); //there are other keys in the message but we are only concerned with the msg for this test. LogMessage expected = { {MsgKey::Msg, "Sink with name:" + testSink->GetName() + " already exists"}, {MsgKey::LogLevel, "Warn"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::AppName, MsgKey::TimeStamp }; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //ok time to remove it. Log::RemoveLogSink(testSink->GetName()); //at this point the sinkObj isn't valid; sinkObj = nullptr; ASSERT_TRUE(LogTest::LogDouble::IsSinksEmpty()); } TEST(LogTest, GenerateISO8601Time) { std::string time = Log::GenerateISO8601Time(true); //utc version //EXPECT_THAT(Log::GenerateISO8601Time(true), ::testing::MatchesRegex("\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ")); //non utc version //EXPECT_THAT(Log::GenerateISO8601Time(false), ::testing::MatchesRegex("\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d")); } TEST(LogTest, testInternalLogExtended) { LogTest::LogDouble::ResetLog(); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::General); ::testing::internal::CaptureStderr(); LogTest::LogDouble::TestInternalLog(message, LogLevel::General, "File", "Function", 10); std::string output = ::testing::internal::GetCapturedStderr(); EXPECT_THAT(output, ::testing::HasSubstr(Log::GetAppName() + " Log {")); EXPECT_THAT(output, ::testing::HasSubstr("Message:Test")); EXPECT_THAT(output, ::testing::HasSubstr("File:File")); EXPECT_THAT(output, ::testing::HasSubstr("Function:Function")); EXPECT_THAT(output, ::testing::HasSubstr("Line:10")); EXPECT_THAT(output, ::testing::HasSubstr("}")); //test with the test sink TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::General}); LogTest::LogDouble::TestInternalLog(message, LogLevel::General, "File", "Function", 10); LogMessage expected = { {MsgKey::AppName, Log::GetAppName()}, {MsgKey::LogLevel, "General"}, {MsgKey::Msg, "Test"}, {MsgKey::File, "File"}, {MsgKey::Function, "Function"}, {MsgKey::Line, "10"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testInternalLog) { LogTest::LogDouble::ResetLog(); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::General); //first test with no sinks ::testing::internal::CaptureStderr(); LogTest::LogDouble::TestInternalLog(message, LogLevel::General); std::string output = ::testing::internal::GetCapturedStderr(); EXPECT_THAT(output, ::testing::HasSubstr(Log::GetAppName() + " Log {")); EXPECT_THAT(output, ::testing::HasSubstr("Message:Test")); EXPECT_THAT(output, ::testing::HasSubstr("}")); //test with the test sink TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::General}); LogTest::LogDouble::TestInternalLog(message, LogLevel::General); LogMessage expected = { {MsgKey::AppName, Log::GetAppName()}, {MsgKey::LogLevel, "General"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test not logged to sink cause it doesn't want level testSink->FlushMessages(); LogTest::LogDouble::TestInternalLog(message, LogLevel::Error); ASSERT_TRUE(testSink->NoMessages()); } TEST(LogTest, testError) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Error(message); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Error); Log::Error(message); LogMessage expected = { {MsgKey::LogLevel, "Error"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::General); testSink->FlushMessages(); Log::Error(message); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testGeneral) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::Error); Log::General(message); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::General(message); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::General); Log::General(message); LogMessage expected = { {MsgKey::LogLevel, "General"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::Warn); testSink->FlushMessages(); Log::General(message); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testWarn) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Warn, LogLevel::General}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::General); Log::Warn(message); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Warn(message); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Warn); Log::Warn(message); LogMessage expected = { {MsgKey::LogLevel, "Warn"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::Debug); testSink->FlushMessages(); Log::Warn(message); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testDebug) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Debug, LogLevel::Warn}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::Warn); Log::Debug(message); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Debug(message); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Debug); Log::Debug(message); LogMessage expected = { {MsgKey::LogLevel, "Debug"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::Trace); testSink->FlushMessages(); Log::Debug(message); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testTrace) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace, LogLevel::Debug}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::Debug); Log::Trace(message); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Trace(message); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Trace); Log::Trace(message); LogMessage expected = { {MsgKey::LogLevel, "Trace"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testFatal) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //test sends message even though off and sink doesn't want it. Log::SetLogLevel(LogLevel::Off); Log::Fatal(message); LogMessage expected = { {MsgKey::LogLevel, "Fatal"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testErrorExtended) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Error(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Error); Log::Error(message, "File", "Function", 10); LogMessage expected = { {MsgKey::LogLevel, "Error"}, {MsgKey::Msg, "Test"}, {MsgKey::File, "File"}, {MsgKey::Function, "Function"}, {MsgKey::Line, "10"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::General); testSink->FlushMessages(); Log::Error(message, "File", "Function", 10); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testGeneralExtended) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::Error); Log::General(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::General(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::General); Log::General(message, "File", "Function", 10); LogMessage expected = { {MsgKey::LogLevel, "General"}, {MsgKey::Msg, "Test"}, {MsgKey::File, "File"}, {MsgKey::Function, "Function"}, {MsgKey::Line, "10"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::Warn); testSink->FlushMessages(); Log::General(message, "File", "Function", 10); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testWarnExtended) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Warn, LogLevel::General}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::General); Log::Warn(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Warn(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Warn); Log::Warn(message, "File", "Function", 10); LogMessage expected = { {MsgKey::LogLevel, "Warn"}, {MsgKey::Msg, "Test"}, {MsgKey::File, "File"}, {MsgKey::Function, "Function"}, {MsgKey::Line, "10"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::Debug); testSink->FlushMessages(); Log::Warn(message, "File", "Function", 10); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testDebugExtended) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Debug, LogLevel::Warn}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::Warn); Log::Debug(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Debug(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Debug); Log::Debug(message, "File", "Function", 10); LogMessage expected = { {MsgKey::LogLevel, "Debug"}, {MsgKey::Msg, "Test"}, {MsgKey::File, "File"}, {MsgKey::Function, "Function"}, {MsgKey::Line, "10"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); //test that the message logged on higher level Log::SetLogLevel(LogLevel::Trace); testSink->FlushMessages(); Log::Debug(message, "File", "Function", 10); ASSERT_FALSE(testSink->NoMessages()); } TEST(LogTest, testTraceExtended) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace, LogLevel::Debug}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //first test the message doesn't get logged on lower level Log::SetLogLevel(LogLevel::Debug); Log::Trace(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test no message when level is set to off. Log::SetLogLevel(LogLevel::Off); Log::Trace(message, "File", "Function", 10); EXPECT_TRUE(testSink->NoMessages()); //test message gets logged on level Log::SetLogLevel(LogLevel::Trace); Log::Trace(message, "File", "Function", 10); LogMessage expected = { {MsgKey::LogLevel, "Trace"}, {MsgKey::Msg, "Test"}, {MsgKey::File, "File"}, {MsgKey::Function, "Function"}, {MsgKey::Line, "10"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testFatalExtended) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); //test message gets ent even though off and sink doesn't want it Log::SetLogLevel(LogLevel::Trace); Log::Fatal(message, "File", "Function", 10); LogMessage expected = { {MsgKey::LogLevel, "Fatal"}, {MsgKey::Msg, "Test"}, {MsgKey::File, "File"}, {MsgKey::Function, "Function"}, {MsgKey::Line, "10"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testLogMacroError) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::Trace); testSink->FlushMessages(); LOG_ERROR(message); //so the checks aren't as brittle size_t line = __LINE__ - 2; std::string sLine = std::to_string(line); const char *file = __FILE__; const char *func = __func__; ASSERT_FALSE(testSink->NoMessages()); LogMessage expected = { {MsgKey::LogLevel, "Error"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; #ifdef V8APP_DEBUG expected.emplace(MsgKey::File, file); expected.emplace(MsgKey::Function, func); expected.emplace(MsgKey::Line, sLine); #endif ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testLogMacroGeneral) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::Trace); LOG_GENERAL(message); //so the checks aren't as brittle size_t line = __LINE__ - 2; std::string sLine = std::to_string(line); const char *file = __FILE__; const char *func = __func__; LogMessage expected = { {MsgKey::LogLevel, "General"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; #ifdef V8APP_DEBUG expected.emplace(MsgKey::File, file); expected.emplace(MsgKey::Function, func); expected.emplace(MsgKey::Line, sLine); #endif ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testLogMacroWarn) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::Trace); testSink->FlushMessages(); LOG_WARN(message); //so the checks aren't as brittle size_t line = __LINE__ - 2; std::string sLine = std::to_string(line); const char *file = __FILE__; const char *func = __func__; LogMessage expected = { {MsgKey::LogLevel, "Warn"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; #ifdef V8APP_DEBUG expected.emplace(MsgKey::File, file); expected.emplace(MsgKey::Function, func); expected.emplace(MsgKey::Line, sLine); #endif ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testLogMacroDebug) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::Trace); LOG_DEBUG(message); //so the checks aren't as brittle size_t line = __LINE__ - 2; std::string sLine = std::to_string(line); const char *file = __FILE__; const char *func = __func__; LogMessage expected = { {MsgKey::LogLevel, "Debug"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; #ifdef V8APP_DEBUG expected.emplace(MsgKey::File, file); expected.emplace(MsgKey::Function, func); expected.emplace(MsgKey::Line, sLine); #endif ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testLogMacroTrace) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::Trace); LOG_TRACE(message); //so the checks aren't as brittle size_t line = __LINE__ - 2; std::string sLine = std::to_string(line); const char *file = __FILE__; const char *func = __func__; LogMessage expected = { {MsgKey::LogLevel, "Trace"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; #ifdef V8APP_DEBUG expected.emplace(MsgKey::File, file); expected.emplace(MsgKey::Function, func); expected.emplace(MsgKey::Line, sLine); #endif ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } TEST(LogTest, testLogMacroFatal) { LogTest::LogDouble::ResetLog(); TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace}); LogMessage message; message.emplace(MsgKey::Msg, "Test"); Log::SetLogLevel(LogLevel::Trace); LOG_FATAL(message); //so the checks aren't as brittle size_t line = __LINE__ - 2; std::string sLine = std::to_string(line); const char *file = __FILE__; const char *func = __func__; LogMessage expected = { {MsgKey::LogLevel, "Fatal"}, {MsgKey::Msg, "Test"}, }; TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName}; #ifdef V8APP_DEBUG expected.emplace(MsgKey::File, file); expected.emplace(MsgKey::Function, func); expected.emplace(MsgKey::Line, sLine); #endif ASSERT_TRUE(testSink->validateMessage(expected, ignore)); } } // namespace Log } // namespace v8App
34.923166
160
0.555852
v8App
9a97eb315751fbcc82f4df4a2637e3039cea497e
706
hpp
C++
srcs/deque/common.hpp
tristiisch/containers_test
5a4a0c098b69e79fa62348074ca0ccaeda5dde73
[ "MIT" ]
null
null
null
srcs/deque/common.hpp
tristiisch/containers_test
5a4a0c098b69e79fa62348074ca0ccaeda5dde73
[ "MIT" ]
null
null
null
srcs/deque/common.hpp
tristiisch/containers_test
5a4a0c098b69e79fa62348074ca0ccaeda5dde73
[ "MIT" ]
null
null
null
#include "../base.hpp" #if !defined(USING_STD) # include "deque.hpp" #else # include <deque> #endif /* !defined(STD) */ template <typename T> void printSize(TESTED_NAMESPACE::deque<T> const &deq, bool print_content = 1) { std::cout << "size: " << deq.size() << std::endl; std::cout << "max_size: " << deq.max_size() << std::endl; if (print_content) { typename TESTED_NAMESPACE::deque<T>::const_iterator it = deq.begin(); typename TESTED_NAMESPACE::deque<T>::const_iterator ite = deq.end(); std::cout << std::endl << "Content is:" << std::endl; for (; it != ite; ++it) std::cout << "- " << *it << std::endl; } std::cout << "###############################################" << std::endl; }
30.695652
77
0.575071
tristiisch
9a9ae4d19d7c9dacabe4dacbf24219d9ea5e3e0b
907
cpp
C++
Plugins/StoryGraphPlugin/Source/StoryGraphPluginEditor/Commands_StoryGraph.cpp
Xian-Yun-Jun/StoryGraph
36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b
[ "MIT" ]
126
2016-12-24T13:58:18.000Z
2022-03-10T03:20:47.000Z
Plugins/StoryGraphPlugin/Source/StoryGraphPluginEditor/Commands_StoryGraph.cpp
Xian-Yun-Jun/StoryGraph
36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b
[ "MIT" ]
5
2017-01-05T08:23:30.000Z
2018-01-30T19:38:33.000Z
Plugins/StoryGraphPlugin/Source/StoryGraphPluginEditor/Commands_StoryGraph.cpp
Xian-Yun-Jun/StoryGraph
36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b
[ "MIT" ]
45
2016-12-25T02:21:45.000Z
2022-02-14T16:06:58.000Z
// Copyright 2016 Dmitriy Pavlov #include "Commands_StoryGraph.h" void FCommands_StoryGraph::RegisterCommands() { #define LOCTEXT_NAMESPACE "Commands_StoryGraphCommands" UI_COMMAND(CheckObjects, "Check Objects", "Check Objects", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(SaveAsset, "Save Asset", "Save Asset", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(ExportInXML, "Export in XML", "Export in XML file", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(ImportFromXML, "Import from XML", "Import from XML file", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(FindInContentBrowser, "Find in CB", "Find in Content Browser...", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(UnlinkAllObjects, "Unlink objects", "Unlink all StoryGraph Objects", EUserInterfaceActionType::Button, FInputChord()); #undef LOCTEXT_NAMESPACE }
47.736842
130
0.790518
Xian-Yun-Jun
9a9bf1f263300b076fa07a5f58592f044b637a84
687
cpp
C++
src/Games/TicTacToe/ActGens/DefaultActGen.cpp
ClubieDong/BoardGameAI
588506278f606fa6bef2864875bf8f78557ef03b
[ "MIT" ]
2
2021-05-26T07:17:24.000Z
2021-05-26T07:21:16.000Z
src/Games/TicTacToe/ActGens/DefaultActGen.cpp
ClubieDong/ChessAI
588506278f606fa6bef2864875bf8f78557ef03b
[ "MIT" ]
null
null
null
src/Games/TicTacToe/ActGens/DefaultActGen.cpp
ClubieDong/ChessAI
588506278f606fa6bef2864875bf8f78557ef03b
[ "MIT" ]
null
null
null
#include "DefaultActGen.hpp" #include <cassert> namespace tictactoe { bool DefaultActGen::NextAction(const ActGenDataBase *, ActionBase &_act) const { // Assert and convert polymorphic types assert(_act.GetGameType() == GameType::TicTacToe); auto &act = dynamic_cast<Action &>(_act); auto &state = *dynamic_cast<const State *>(_State); do { ++act._Col; if (act._Col >= 3) { ++act._Row; act._Col = 0; } if (act._Row >= 3) return false; } while (state._Board[act._Row][act._Col] != 2); return true; } }
25.444444
82
0.512373
ClubieDong
9a9f4a5d68efc52dedec28e95460c67e41801baa
1,990
cpp
C++
tree_traversal.cpp
ivan18m/cpp-practice
1e9ae7d55a77f72a297e1ceb69fadf1cc4e7dfc6
[ "BSD-3-Clause" ]
null
null
null
tree_traversal.cpp
ivan18m/cpp-practice
1e9ae7d55a77f72a297e1ceb69fadf1cc4e7dfc6
[ "BSD-3-Clause" ]
null
null
null
tree_traversal.cpp
ivan18m/cpp-practice
1e9ae7d55a77f72a297e1ceb69fadf1cc4e7dfc6
[ "BSD-3-Clause" ]
null
null
null
/** * @file tree_traversal.cpp * @author Ivan Mercep * @brief * This program contains_ * Binary Tree traversal methods: preorder, inorder, postorder. * Functions to print and swap the binary tree. * @version 0.1 * @date 2021-09-06 * * @copyright Copyright (c) 2021 * */ #include <iostream> struct Node { int data; Node *left; Node *right; }; // <root> <left> <right> void preorder(Node *pRoot) { if (pRoot == nullptr) return; std::cout << pRoot->data << " "; preorder(pRoot->left); preorder(pRoot->right); } // <left> <root> <right> void inorder(Node *pRoot) { if (pRoot == nullptr) return; inorder(pRoot->left); std::cout << pRoot->data << " "; inorder(pRoot->right); } // <left> <right> <root> void postorder(Node *pRoot) { if (pRoot == nullptr) return; postorder(pRoot->left); postorder(pRoot->right); std::cout << pRoot->data << " "; } Node *getNewNode(int data) { Node *newNode = new Node(); newNode->data = data; newNode->left = newNode->right = nullptr; return newNode; } Node *insert(Node *pRoot, int data) { if (pRoot == nullptr) pRoot = getNewNode(data); else if (data <= pRoot->data) pRoot->left = insert(pRoot->left, data); else pRoot->right = insert(pRoot->right, data); return pRoot; } Node *swap(Node *pRoot) { if (pRoot == nullptr) return pRoot; Node *temp = pRoot->left; pRoot->left = pRoot->right; pRoot->right = temp; swap(pRoot->left); swap(pRoot->right); return pRoot; } int main() { Node *root = nullptr; root = insert(root, 15); root = insert(root, 20); root = insert(root, 25); root = insert(root, 18); root = insert(root, 1); /* 15 /\ 1 20 /\ 18 25 */ inorder(root); std::cout << "\n"; swap(root); inorder(root); std::cout << "\n"; delete root; return 0; }
17.155172
63
0.556281
ivan18m
9aa555ee9e29a90c226a3125471700e640942b3e
5,415
hpp
C++
include/RootMotion/FinalIK/FullBodyBipedIK.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/FullBodyBipedIK.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/FullBodyBipedIK.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: RootMotion.FinalIK.IK #include "RootMotion/FinalIK/IK.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: RootMotion namespace RootMotion { // Forward declaring type: BipedReferences class BipedReferences; } // Forward declaring namespace: RootMotion::FinalIK namespace RootMotion::FinalIK { // Forward declaring type: IKSolverFullBodyBiped class IKSolverFullBodyBiped; // Forward declaring type: IKSolver class IKSolver; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Size: 0x48 #pragma pack(push, 1) // Autogenerated type: RootMotion.FinalIK.FullBodyBipedIK // [HelpURLAttribute] Offset: E0618C // [AddComponentMenu] Offset: E0618C class FullBodyBipedIK : public RootMotion::FinalIK::IK { public: // Writing base type padding for base size: 0x33 to desired offset: 0x38 char ___base_padding[0x5] = {}; // public RootMotion.BipedReferences references // Size: 0x8 // Offset: 0x38 RootMotion::BipedReferences* references; // Field size check static_assert(sizeof(RootMotion::BipedReferences*) == 0x8); // public RootMotion.FinalIK.IKSolverFullBodyBiped solver // Size: 0x8 // Offset: 0x40 RootMotion::FinalIK::IKSolverFullBodyBiped* solver; // Field size check static_assert(sizeof(RootMotion::FinalIK::IKSolverFullBodyBiped*) == 0x8); // Creating value type constructor for type: FullBodyBipedIK FullBodyBipedIK(RootMotion::BipedReferences* references_ = {}, RootMotion::FinalIK::IKSolverFullBodyBiped* solver_ = {}) noexcept : references{references_}, solver{solver_} {} // private System.Void OpenSetupTutorial() // Offset: 0x1C3CD54 void OpenSetupTutorial(); // private System.Void OpenInspectorTutorial() // Offset: 0x1C3CDA0 void OpenInspectorTutorial(); // private System.Void SupportGroup() // Offset: 0x1C3CDEC void SupportGroup(); // private System.Void ASThread() // Offset: 0x1C3CE38 void ASThread(); // public System.Void SetReferences(RootMotion.BipedReferences references, UnityEngine.Transform rootNode) // Offset: 0x1C3CE84 void SetReferences(RootMotion::BipedReferences* references, UnityEngine::Transform* rootNode); // public System.Boolean ReferencesError(ref System.String errorMessage) // Offset: 0x1C3CEB0 bool ReferencesError(::Il2CppString*& errorMessage); // public System.Boolean ReferencesWarning(ref System.String warningMessage) // Offset: 0x1C3D06C bool ReferencesWarning(::Il2CppString*& warningMessage); // private System.Void Reinitiate() // Offset: 0x1C3D3C0 void Reinitiate(); // private System.Void AutoDetectReferences() // Offset: 0x1C3D3E0 void AutoDetectReferences(); // protected override System.Void OpenUserManual() // Offset: 0x1C3CCBC // Implemented from: RootMotion.FinalIK.IK // Base method: System.Void IK::OpenUserManual() void OpenUserManual(); // protected override System.Void OpenScriptReference() // Offset: 0x1C3CD08 // Implemented from: RootMotion.FinalIK.IK // Base method: System.Void IK::OpenScriptReference() void OpenScriptReference(); // public override RootMotion.FinalIK.IKSolver GetIKSolver() // Offset: 0x1C3CEA8 // Implemented from: RootMotion.FinalIK.IK // Base method: RootMotion.FinalIK.IKSolver IK::GetIKSolver() RootMotion::FinalIK::IKSolver* GetIKSolver(); // public System.Void .ctor() // Offset: 0x1C3D4BC // Implemented from: RootMotion.FinalIK.IK // Base method: System.Void IK::.ctor() // Base method: System.Void SolverManager::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static FullBodyBipedIK* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::FullBodyBipedIK::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<FullBodyBipedIK*, creationType>())); } }; // RootMotion.FinalIK.FullBodyBipedIK #pragma pack(pop) static check_size<sizeof(FullBodyBipedIK), 64 + sizeof(RootMotion::FinalIK::IKSolverFullBodyBiped*)> __RootMotion_FinalIK_FullBodyBipedIKSizeCheck; static_assert(sizeof(FullBodyBipedIK) == 0x48); } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::FullBodyBipedIK*, "RootMotion.FinalIK", "FullBodyBipedIK");
44.752066
180
0.708218
darknight1050
9aaa45337a7ce537f2c6b688feefc10d63137e47
7,836
cxx
C++
HLT/TPCLib/HWCFemulator/AliHLTTPCHWCFEmulator.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
HLT/TPCLib/HWCFemulator/AliHLTTPCHWCFEmulator.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
HLT/TPCLib/HWCFemulator/AliHLTTPCHWCFEmulator.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
// $Id$ //**************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Sergey Gorbunov, Torsten Alt * //* Developers: Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de> * //* Torsten Alt <talt@cern.ch> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //**************************************************************************** // @file AliHLTTPCHWCFEmulator.cxx // @author Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de> // @author Torsten Alt <talt@cern.ch> // @brief FPGA ClusterFinder Emulator for TPC // @note #include "AliHLTTPCHWCFDataTypes.h" #include "AliHLTTPCHWCFEmulator.h" #include "AliHLTTPCClusterMCData.h" #include "AliHLTTPCHWCFData.h" #include <iostream> #if __GNUC__ >= 3 using namespace std; #endif AliHLTTPCHWCFEmulator::AliHLTTPCHWCFEmulator() : fDebug(0), fkMapping(0), fChannelExtractor(), fPeakFinderUnit(), fChannelProcessor(), fChannelMerger(), fDivisionUnit() { //constructor } AliHLTTPCHWCFEmulator::~AliHLTTPCHWCFEmulator() { //destructor } AliHLTTPCHWCFEmulator::AliHLTTPCHWCFEmulator(const AliHLTTPCHWCFEmulator&) : fDebug(0), fkMapping(0), fChannelExtractor(), fPeakFinderUnit(), fChannelProcessor(), fChannelMerger(), fDivisionUnit() { // dummy } AliHLTTPCHWCFEmulator& AliHLTTPCHWCFEmulator::operator=(const AliHLTTPCHWCFEmulator&) { // dummy return *this; } void AliHLTTPCHWCFEmulator::Init( const AliHLTUInt32_t *mapping, AliHLTUInt32_t config1, AliHLTUInt32_t config2 ) { // Initialisation fkMapping = mapping; fPeakFinderUnit.SetChargeFluctuation( (config2>>4) & 0xF ); fChannelProcessor.SetSingleSeqLimit( (config1) & 0xFF ); fChannelProcessor.SetDeconvolutionTime( (config1>>24) & 0x1 ); fChannelProcessor.SetUseTimeBinWindow( (config2>>8) & 0x1 ); fChannelMerger.SetByPassMerger( (config1>>27) & 0x1 ); fChannelMerger.SetDeconvolution( (config1>>25) & 0x1 ); fChannelMerger.SetMatchDistance( (config2) & 0xF ); fChannelMerger.SetMatchTimeFollow( (config2>>9) & 0x1 ); fDivisionUnit.SetClusterLowerLimit( (config1>>8) & 0xFFFF ); fDivisionUnit.SetSinglePadSuppression( (config1>>26) & 0x1 ); fPeakFinderUnit.SetDebugLevel(fDebug); fChannelProcessor.SetDebugLevel(fDebug); fChannelMerger.SetDebugLevel(fDebug); fDivisionUnit.SetDebugLevel(fDebug); } int AliHLTTPCHWCFEmulator::FindClusters( const AliHLTUInt32_t *rawEvent, AliHLTUInt32_t rawEventSize32, AliHLTUInt32_t *output, AliHLTUInt32_t &outputSize32, const AliHLTTPCClusterMCLabel *mcLabels, AliHLTUInt32_t nMCLabels, AliHLTTPCClusterMCData *outputMC ) { // Loops over all rows finding the clusters AliHLTUInt32_t maxOutputSize32 = outputSize32; outputSize32 = 0; if( outputMC ) outputMC->fCount = 0; AliHLTUInt32_t maxNMCLabels = nMCLabels; if( !rawEvent ) return -1; // Initialise int ret = 0; fChannelExtractor.Init( fkMapping, mcLabels, 3*rawEventSize32 ); fPeakFinderUnit.Init(); fChannelProcessor.Init(); fChannelMerger.Init(); fDivisionUnit.Init(); // Read the data, word by word for( AliHLTUInt32_t iWord=0; iWord<=rawEventSize32; iWord++ ){ const AliHLTTPCHWCFBunch *bunch1=0; const AliHLTTPCHWCFBunch *bunch2=0; const AliHLTTPCHWCFClusterFragment *fragment=0; const AliHLTTPCHWCFClusterFragment *candidate=0; const AliHLTTPCHWCFCluster *cluster = 0; if( iWord<rawEventSize32 ) fChannelExtractor.InputStream(ReadBigEndian(rawEvent[iWord])); else fChannelExtractor.InputEndOfData(); while( (bunch1 = fChannelExtractor.OutputStream()) ){ fPeakFinderUnit.InputStream(bunch1); while( (bunch2 = fPeakFinderUnit.OutputStream() )){ fChannelProcessor.InputStream(bunch2); while( (fragment = fChannelProcessor.OutputStream() )){ fChannelMerger.InputStream( fragment ); while( (candidate = fChannelMerger.OutputStream()) ){ fDivisionUnit.InputStream(candidate); while( (cluster = fDivisionUnit.OutputStream()) ){ if( cluster->fFlag==1 ){ if( outputSize32+AliHLTTPCHWCFData::fgkAliHLTTPCHWClusterSize > maxOutputSize32 ){ // No space in the output buffer ret = -2; break; } AliHLTUInt32_t *co = &output[outputSize32]; int i=0; co[i++] = WriteBigEndian(cluster->fRowQ); co[i++] = WriteBigEndian(cluster->fQ); co[i++] = cluster->fP; co[i++] = cluster->fT; co[i++] = cluster->fP2; co[i++] = cluster->fT2; outputSize32+=AliHLTTPCHWCFData::fgkAliHLTTPCHWClusterSize; if( mcLabels && outputMC && outputMC->fCount < maxNMCLabels){ outputMC->fLabels[outputMC->fCount++] = cluster->fMC; } } else if( cluster->fFlag==2 ){ if( outputSize32+1 > maxOutputSize32 ){ // No space in the output buffer ret = -2; break; } output[outputSize32++] = cluster->fRowQ; } } } } } } } return ret; } AliHLTUInt32_t AliHLTTPCHWCFEmulator::ReadBigEndian ( AliHLTUInt32_t word ) { // read the word written in big endian format (lowest byte first) const AliHLTUInt8_t *bytes = reinterpret_cast<const AliHLTUInt8_t *>( &word ); AliHLTUInt32_t i[4] = {bytes[0],bytes[1],bytes[2],bytes[3]}; return (i[3]<<24) | (i[2]<<16) | (i[1]<<8) | i[0]; } AliHLTUInt32_t AliHLTTPCHWCFEmulator::WriteBigEndian ( AliHLTUInt32_t word ) { // write the word in big endian format (least byte first) AliHLTUInt32_t ret = 0; AliHLTUInt8_t *bytes = reinterpret_cast<AliHLTUInt8_t *>( &ret ); bytes[0] = (word ) & 0xFF; bytes[1] = (word >> 8) & 0xFF; bytes[2] = (word >> 16) & 0xFF; bytes[3] = (word >> 24) & 0xFF; return ret; } void AliHLTTPCHWCFEmulator::CreateConfiguration ( bool doDeconvTime, bool doDeconvPad, bool doFlowControl, bool doSinglePadSuppression, bool bypassMerger, AliHLTUInt32_t clusterLowerLimit, AliHLTUInt32_t singleSeqLimit, AliHLTUInt32_t mergerDistance, bool useTimeBinWindow, AliHLTUInt32_t chargeFluctuation, bool useTimeFollow, AliHLTUInt32_t &configWord1, AliHLTUInt32_t &configWord2 ) { // static method to create configuration word configWord1 = 0; configWord2 = 0; configWord1 |= ( (AliHLTUInt32_t)doFlowControl & 0x1 ) << 29; configWord1 |= ( (AliHLTUInt32_t)bypassMerger & 0x1 ) << 27; configWord1 |= ( (AliHLTUInt32_t)doSinglePadSuppression & 0x1 ) << 26; configWord1 |= ( (AliHLTUInt32_t)doDeconvPad & 0x1 ) << 25; configWord1 |= ( (AliHLTUInt32_t)doDeconvTime & 0x1 ) << 24; configWord1 |= ( (AliHLTUInt32_t)clusterLowerLimit & 0xFFFF )<<8; configWord1 |= ( (AliHLTUInt32_t)singleSeqLimit & 0xFF ); configWord2 |= ( (AliHLTUInt32_t)mergerDistance & 0xF ); configWord2 |= ( (AliHLTUInt32_t)chargeFluctuation & 0xF )<<4; configWord2 |= ( (AliHLTUInt32_t)useTimeBinWindow & 0x1 )<<8; configWord2 |= ( (AliHLTUInt32_t)useTimeFollow & 0x1 )<<9; }
33.20339
117
0.662711
AllaMaevskaya
9ab275d54314d22f77d0f51a27d325d4d8fa4bd0
1,145
cpp
C++
ToneArmEngine/OpenGLTransparencyPass.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
ToneArmEngine/OpenGLTransparencyPass.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
ToneArmEngine/OpenGLTransparencyPass.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
/* ======================== Copyright (c) 2014 Vinyl Games Studio OpenGLTransparencyPass Created by: Karl Merten Created on: 04/08/2014 ======================== */ #include "OpenGLTransparencyPass.h" #include "Renderable.h" #include <GL\glew.h> namespace vgs { OpenGLTransparencyPass* OpenGLTransparencyPass::CreateWithPriority( unsigned int priority ) { OpenGLTransparencyPass* pass = new OpenGLTransparencyPass(); if ( pass && pass->InitializePass( priority ) ) { return pass; } delete pass; return NULL; } bool OpenGLTransparencyPass::InitializePass( unsigned int priority ) { RenderPass::InitializePass( NULL ); m_passType = PassType::TRANSPARENCY; m_priority = priority; return true; } void OpenGLTransparencyPass::BeginPass( void ) { glEnable( GL_BLEND ); glEnable( GL_DEPTH_TEST ); glAlphaFunc( GL_GREATER, 0.05f ); glEnable( GL_ALPHA_TEST ); } void OpenGLTransparencyPass::FinishPass( void ) { glDisable( GL_BLEND ); glDisable( GL_ALPHA_TEST ); glDisable( GL_DEPTH_TEST ); } void OpenGLTransparencyPass::ProcessRenderable( Renderable* obj ) { obj->PreRender(); obj->Render(); obj->PostRender(); } }
20.087719
93
0.710917
Mertank
9ab2bfe0ca0c8426bbb87ec3b8e09cf5ca11a1e1
2,232
cpp
C++
cpp/08/ex01/span.cpp
maxdesalle/libft
8845656e1f5cc1fec052cf97fc8f5839b2b590a8
[ "Unlicense" ]
3
2021-01-06T13:50:12.000Z
2022-02-28T09:16:15.000Z
cpp/08/ex01/span.cpp
maxdesalle/libft
8845656e1f5cc1fec052cf97fc8f5839b2b590a8
[ "Unlicense" ]
null
null
null
cpp/08/ex01/span.cpp
maxdesalle/libft
8845656e1f5cc1fec052cf97fc8f5839b2b590a8
[ "Unlicense" ]
1
2020-11-23T12:58:18.000Z
2020-11-23T12:58:18.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* span.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: maxdesalle <mdesalle@student.s19.be> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/05 11:21:04 by maxdesall #+# #+# */ /* Updated: 2021/11/05 14:19:52 by maxdesall ### ########.fr */ /* */ /* ************************************************************************** */ #include "span.hpp" Span::Span(unsigned int n): _n(n) { } Span::~Span(void) { } Span::Span(Span const &ref): _n(ref.getN()) { } Span &Span::operator=(Span const &ref) { _n = ref.getN(); return (*this); } void Span::setN(unsigned int n) { _n = n; } void Span::setVec(std::vector<int> vec) { _vec = vec; } unsigned int Span::getN(void) const { return (_n); } std::vector<int> Span::getVec(void) const { return (_vec); } void Span::addNumber(int nbr) { std::vector<int> vec = getVec(); if (vec.size() > getN()) throw ("Storage is full"); else { vec.push_back(nbr); setVec(vec); } } int Span::longestSpan(void) { std::vector<int> vec = getVec(); std::vector<int>::iterator min = std::min_element(vec.begin(), vec.end()); std::vector<int>::iterator max = std::max_element(vec.begin(), vec.end()); if (vec.size() == 0 || vec.size() == 1) throw ("Not enough numbers"); return (*max - *min); } int Span::shortestSpan(void) { std::vector<int> vec = getVec(); std::vector<int>::iterator max = std::max_element(vec.begin(), vec.end()); int span = *max; if (vec.size() == 0 || vec.size() == 1) throw ("Not enough numbers"); for (size_t i = 1; i < vec.size(); i += 1) span = (std::abs(vec[i] - vec[i - 1]) < span) ? std::abs(vec[i] - vec[i - 1]): span; return (span); }
24.26087
86
0.396953
maxdesalle
9ab314bae0d3a200154af32ea00979a680320027
2,140
cpp
C++
src/emitter/area.cpp
abroun/psdr-cuda
bbccc01f8bb91f387d495fbfd0a8ba0093f298de
[ "BSD-3-Clause" ]
80
2020-12-07T04:29:34.000Z
2022-03-31T08:05:37.000Z
src/emitter/area.cpp
abroun/psdr-cuda
bbccc01f8bb91f387d495fbfd0a8ba0093f298de
[ "BSD-3-Clause" ]
18
2021-07-26T06:08:42.000Z
2022-03-16T20:32:53.000Z
src/emitter/area.cpp
abroun/psdr-cuda
bbccc01f8bb91f387d495fbfd0a8ba0093f298de
[ "BSD-3-Clause" ]
8
2021-06-02T06:52:05.000Z
2022-02-11T21:03:42.000Z
#include <misc/Exception.h> #include <psdr/core/frame.h> #include <psdr/core/intersection.h> #include <psdr/shape/mesh.h> #include <psdr/emitter/area.h> namespace psdr { void AreaLight::configure() { PSDR_ASSERT((m_mesh != nullptr) && m_mesh->m_ready); PSDR_ASSERT(slices(m_radiance) == 1U); m_sampling_weight = m_mesh->m_total_area* rgb2luminance<false>(detach(m_radiance))[0]; m_ready = true; } SpectrumC AreaLight::eval(const IntersectionC &its, MaskC active) const { PSDR_ASSERT(m_ready); return select(active && FrameC::cos_theta(its.wi) > 0.f, detach(m_radiance), 0.f); } SpectrumD AreaLight::eval(const IntersectionD &its, MaskD active) const { PSDR_ASSERT(m_ready); return select(active && FrameD::cos_theta(its.wi) > 0.f, m_radiance, 0.f); } PositionSampleC AreaLight::sample_position(const Vector3fC &ref_p, const Vector2fC &sample2, MaskC active) const { return __sample_position<false>(sample2, active); } PositionSampleD AreaLight::sample_position(const Vector3fD &ref_p, const Vector2fD &sample2, MaskD active) const { return __sample_position<true >(sample2, active); } template <bool ad> PositionSample<ad> AreaLight::__sample_position(const Vector2f<ad> &sample2, Mask<ad> active) const { PSDR_ASSERT(m_ready); return m_mesh->sample_position(sample2, active); } FloatC AreaLight::sample_position_pdf(const Vector3fC &ref_p, const IntersectionC &its, MaskC active) const { return __sample_position_pdf<false>(ref_p, its, active); } FloatD AreaLight::sample_position_pdf(const Vector3fD &ref_p, const IntersectionD &its, MaskD active) const { return __sample_position_pdf<true>(ref_p, its, active); } template <bool ad> Float<ad> AreaLight::__sample_position_pdf(const Vector3f<ad> &ref_p, const Intersection<ad> &its, Mask<ad> active) const { return m_sampling_weight*its.shape->sample_position_pdf(its, active); } std::string AreaLight::to_string() const { std::ostringstream oss; oss << "AreaLight[radiance = " << m_radiance << ", sampling_weight = " << m_sampling_weight << "]"; return oss.str(); } } // namespace psdr
29.722222
123
0.729907
abroun
9ab6050d91788b2c220a11836a9567221406df6f
5,520
cpp
C++
src/avalanche/math_ops/MatMul.cpp
kpot/avalanche
4bfa6f66a5610d3619414e374d77eae2edcb8b20
[ "MIT" ]
6
2019-02-02T22:35:03.000Z
2022-02-28T20:15:48.000Z
src/avalanche/math_ops/MatMul.cpp
kpot/avalanche
4bfa6f66a5610d3619414e374d77eae2edcb8b20
[ "MIT" ]
null
null
null
src/avalanche/math_ops/MatMul.cpp
kpot/avalanche
4bfa6f66a5610d3619414e374d77eae2edcb8b20
[ "MIT" ]
1
2020-08-04T21:32:35.000Z
2020-08-04T21:32:35.000Z
#include "clblast.h" #include "avalanche/base_ops_nodes.h" #include "avalanche/opencl_utils.h" #include "avalanche/math_ops/messages.h" #include "avalanche/macroses.h" #include "avalanche/casting.h" #include "avalanche/math_ops/MatMul.h" namespace avalanche { MatMul::MatMul(const NodeRef &left, const NodeRef &right, bool transpose_left, bool transpose_right) :transpose_left{transpose_left}, transpose_right{transpose_right}, _result_shape({ transpose_left ? left->shape().dim(1) : left->shape().dim(0), transpose_right ? right->shape().dim(0) : right->shape().dim(1)}), _result_dtype{left->dtype()} { if (left->dtype() != right->dtype()) { throw std::invalid_argument( "You cannot multiply matrices of different types"); } if (left->dtype() != ArrayType::float16 && left->dtype() != ArrayType::float32 && left->dtype() != ArrayType::float64) { throw std::invalid_argument( "MatMul supports only data types with floating point"); } if (left->shape().rank() != 2) { throw std::invalid_argument( "Left operand must be a matrix (tensor rank 2)"); } if (right->shape().rank() != 2) { throw std::invalid_argument( "Right operand must be a matrix (tensor rank 2)"); } if ((transpose_left ? left->shape().dim(0) : left->shape().dim(1)) != (transpose_right ? right->shape().dim(1) : right->shape().dim(0))) { throw std::invalid_argument( "Number of columns in the first matrix must be the same " "as the number of rows in the second. With respect " "to transpositions, if needed."); } } template <typename T> inline clblast::StatusCode array_gemm( const MultiArrayRef &a, bool transpose_a, const MultiArrayRef &b, bool transpose_b, const MultiArrayRef &result, cl_command_queue *queue, cl_event *result_event) { auto inputs_are_ready = make_event_list( {a->buffer_unsafe()->completion_event(), b->buffer_unsafe()->completion_event()}); if (!inputs_are_ready.empty()) { cl::Event::waitForEvents(inputs_are_ready); } return clblast::Gemm<T>( clblast::Layout::kRowMajor, transpose_a ? clblast::Transpose::kYes : clblast::Transpose::kNo, transpose_b ? clblast::Transpose::kYes : clblast::Transpose::kNo, static_cast<const size_t>(a->shape().dim(transpose_a ? 1 : 0)), static_cast<const size_t>(b->shape().dim(transpose_b ? 0 : 1)), static_cast<const size_t>(a->shape().dim(transpose_a ? 0 : 1)), to_array_type<T>(1.0f), a->cl_buffer_unsafe()(), 0, static_cast<const size_t>(a->shape().dim(-1)), b->cl_buffer_unsafe()(), 0, static_cast<const size_t>(b->shape().dim(-1)), to_array_type<T>(0.0f), result->buffer_unsafe()->cl_buffer_unsafe()(), 0, static_cast<const size_t>(result->shape().dim(-1)), queue, result_event ); } ARRAY_DTYPE_SWITCH_FLOAT_FUNCTION(gemm_switch, array_gemm, clblast::StatusCode,) MultiArrayRef MatMul::forward(const MultiArrayRef &v1, const MultiArrayRef &v2) const { if ((transpose_left ? v1->shape().dim(0) : v1->shape().dim(1)) != (transpose_right ? v2->shape().dim(1) : v2->shape().dim(0))) { throw std::invalid_argument( "Number of columns in the first matrix must be the same " "as the number of rows in the second. With respect " "to transpositions, if needed."); } Shape result_shape( {transpose_left ? v1->shape().dim(1) : v1->shape().dim(0), transpose_right ? v2->shape().dim(0) : v2->shape().dim(1)}); auto pool = v1->buffer_unsafe()->pool(); auto queue = pool->cl_queue(); auto result = pool->make_array(result_shape, _result_dtype); result->set_label(__func__, __LINE__); result->add_dependencies({v1, v2}); cl_command_queue ll_queue = queue.get(); cl_event result_event = nullptr; auto status = gemm_switch( _result_dtype, v1, transpose_left, v2, transpose_right, result, &ll_queue, &result_event); if (status != clblast::StatusCode::kSuccess) { throw std::runtime_error( std::string("OpenCL error reported failure: ") + get_opencl_error_string(static_cast<int>(status))); } result->set_completion_event(result_event); return result; } const NodeRef MatMul::apply_chain_rule(const NodeRef &wrt_input, const NodeRef &d_target_wrt_this, const NodeRefList &all_inputs) const { if (all_inputs[0] == wrt_input) { if (transpose_left) { return F<MatMul>(all_inputs[1], d_target_wrt_this, transpose_right, true); } else { return F<MatMul>(d_target_wrt_this, all_inputs[1], false, !transpose_right); } } else if (all_inputs[1] == wrt_input) { if (transpose_right) { return F<MatMul>(d_target_wrt_this, all_inputs[0], true, transpose_left); } else { return F<MatMul>(all_inputs[0], d_target_wrt_this, !transpose_left, false); } } else { throw std::logic_error(messages::CANT_DIFF_UNEXISTING_INPUT_MESSAGE); } } } // namespace
39.148936
88
0.605072
kpot
9abc64573b83e2dd51fd9bbc4cd10c7dd3a0b0b4
78
cpp
C++
sem11-mmap-instrumentation/ub.cpp
karmashka/caos_2019-2020
ecfeb944a6a8d8392ac05e833d0d77cafdd3e88d
[ "MIT" ]
32
2019-10-04T20:02:32.000Z
2020-07-21T17:18:06.000Z
sem11-mmap-instrumentation/ub.cpp
karmashka/caos_2019-2020
ecfeb944a6a8d8392ac05e833d0d77cafdd3e88d
[ "MIT" ]
2
2020-04-05T12:52:13.000Z
2020-05-04T23:42:02.000Z
sem11-mmap-instrumentation/ub.cpp
karmashka/caos_2019-2020
ecfeb944a6a8d8392ac05e833d0d77cafdd3e88d
[ "MIT" ]
10
2020-09-03T17:25:42.000Z
2022-02-18T23:36:51.000Z
// %%cpp ub.cpp int main(int argc, char** argv) { return -argc << 31; }
11.142857
33
0.538462
karmashka
9abe9a4e62c41a2cf187b1940fe6d37969a3bf51
4,709
cpp
C++
cpp/pipesquare/pipesquare.cpp
jakvrh1/paralelni-milkshake
42b8151482b0e831ab1f2f6058cd389193372022
[ "MIT" ]
null
null
null
cpp/pipesquare/pipesquare.cpp
jakvrh1/paralelni-milkshake
42b8151482b0e831ab1f2f6058cd389193372022
[ "MIT" ]
null
null
null
cpp/pipesquare/pipesquare.cpp
jakvrh1/paralelni-milkshake
42b8151482b0e831ab1f2f6058cd389193372022
[ "MIT" ]
null
null
null
/** * Uporaba cevovoda s štirimi stopnjami; * posamezno stopnjo lahko opravlja več niti */ #include <iostream> #include <random> #include <pthread.h> #include <unistd.h> #include "../input.hpp" #include "../rle.hpp" #include "../huffman.hpp" #include "../output.hpp" #include "../stream.hpp" #define REPS 1000 #define READ_THREADS 2 #define RLE_THREADS 1 #define HUFFMAN_THREADS 1 #define WRITE_THREADS 1 using namespace std; struct huffman_data { Huffman *hf; Vec<string> *encoded; }; // ker vec niti pise, moramo uporabiti mutex, // da povecujemo stevec [writes], dokler // ne dosezemo stevila REPS pthread_mutex_t mutex_write; int writes = 0; // Funkcija za niti, ki berejo. void* read(void* arg) { PipelineStage<int, string, struct image>* stage = (PipelineStage<int, string, struct image>*) arg; while (true) { auto p = stage->consume(); auto key = p.first; auto filename = p.second; try { auto image_data = Input::read_image(filename.c_str()); stage->produce(key, image_data); } catch(const std::exception& e) { std::cerr << "Read image " << filename << ": " << e.what() << '\n'; } } return nullptr; } // Funkcija za niti, ki prebrane podatke kodirajo z RLE. void* rle(void* arg) { PipelineStage<int, struct image, Vec<int_bool>*>* stage = (PipelineStage<int, struct image, Vec<int_bool>*>*) arg; while (true) { auto p = stage->consume(); auto key = p.first; auto image_data = p.second; auto rle_data = RLE::encode(image_data); stage->produce(key, rle_data); } } // Funkcija za niti, ki RLE podatke kodirajo s huffmanom. void* huffman(void* arg) { PipelineStage<int, Vec<int_bool>*, huffman_data> *stage = (PipelineStage<int, Vec<int_bool>*, huffman_data>*) arg; while (true) { auto p = stage->consume(); auto key = p.first; auto rle_data = p.second; Huffman *hf = Huffman::initialize(rle_data); auto encoded = hf->encode(); huffman_data data; data.hf = hf; data.encoded = encoded; stage->produce(key, data); } } // Funkcija za niti, ki pisejo void* write(void* arg) { PipelineStage<int, huffman_data, void>* stage = (PipelineStage<int, huffman_data, void>*) arg; while (true) { pthread_mutex_lock(&mutex_write); if (writes < REPS) { writes++; } else { pthread_mutex_unlock(&mutex_write); break; } pthread_mutex_unlock(&mutex_write); auto p = stage->consume(); auto key = p.first; auto data = p.second; auto header = data.hf->header(); auto filename = "../../out_encoded/out" + std::to_string(key) + ".txt"; try { Output::write_encoded(filename, header, data.encoded); } catch(const std::exception& e) { std::cerr << "Write encoded " << key << ": " << e.what() << '\n'; } data.hf->finalize(); delete data.encoded; } // S tem se bo program zaključil (glavna nit čaka na join) return nullptr; } /* * Glavna nit */ int main(int argc, char const *argv[]) { mutex_write = PTHREAD_MUTEX_INITIALIZER; FifoStream<int, string> input_stream(0); FifoStream<int, struct image> image_stream(0); FifoStream<int, Vec<int_bool>*> encoded_stream(0); FifoStream<int, huffman_data> output_stream(0); // Prva stopnja cevovoda, image reading PipelineStage<int, string, struct image> read_stage(&input_stream, &image_stream); pthread_t read_threads[READ_THREADS]; for (int i = 0; i < READ_THREADS; i++) pthread_create(&read_threads[i], NULL, read, &read_stage); // Druga stopnja cevovoda, run length encoding PipelineStage<int, struct image, Vec<int_bool>*> rle_stage(&image_stream, &encoded_stream); pthread_t rle_threads[RLE_THREADS]; for (int i = 0; i < RLE_THREADS; i++) pthread_create(&rle_threads[i], NULL, rle, &rle_stage); // Tretja stopnja cevovoda, huffman encoding PipelineStage<int, Vec<int_bool>*, huffman_data> huffman_stage(&encoded_stream, &output_stream); pthread_t huffman_threads[HUFFMAN_THREADS]; for (int i = 0; i < HUFFMAN_THREADS; i++) pthread_create(&huffman_threads[i], NULL, huffman, &huffman_stage); // Cetrta stopnja cevovoda, writing PipelineStage<int, huffman_data, void> write_stage(&output_stream); pthread_t write_threads[WRITE_THREADS]; for (int i = 0; i < WRITE_THREADS; i++) pthread_create(&write_threads[i], NULL, write, &write_stage); // V cevovod posljemo delo for (int i = 1; i <= REPS; i++) { int file_id = (i % 10) + 1; input_stream.produce(i, "../../assets/" + std::to_string(file_id) + ".png"); } // Pocakamo, da se pisanje zakljuci for (int i = 0; i < WRITE_THREADS; i++) pthread_join(write_threads[i], NULL); return 0; }
27.219653
116
0.661712
jakvrh1
9ac1b7250246294f2497523086d456027f7f9314
19,860
cpp
C++
Samples/Win7Samples/netds/wirelessdiagnostics/WlExtHC.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/netds/wirelessdiagnostics/WlExtHC.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/netds/wirelessdiagnostics/WlExtHC.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (C) 2006 Microsoft Corporation. All Rights Reserved. // // Module: // WlExtHC.cpp // // Abstract: // This sample shows how to create a sample Extensible Helper Class for Wireless Diagnostics // This sample is post-Windows 2006 only. // // Usage: // WlExtHC.exe [/RegServer] // /RegServer Register the HC // // Author: // Mohammad Shabbir Alam // #include "precomp.h" #pragma hdrstop GUID gWirelessHelperExtensionRepairId = { /* cb2a064e-b691-4a63-9e7e-7d2970bbe025 */ 0xcb2a064e, 0xb691, 0x4a63, {0x9e, 0x7e, 0x7d, 0x29, 0x70, 0xbb, 0xe0, 0x25}}; __inline HRESULT StringCchCopyWithAlloc ( __deref_out_opt PWSTR* Dest, size_t cchMaxLen, __in PCWSTR Src ) { size_t cchSize = 0; if (NULL == Dest || NULL == Src || cchMaxLen > USHRT_MAX) { return E_INVALIDARG; } HRESULT hr = StringCchLength (Src, cchMaxLen - 1, &cchSize); if (FAILED(hr)) { return hr; } size_t cbSize = (cchSize + 1)*sizeof(WCHAR); *Dest = (PWSTR) CoTaskMemAlloc(cbSize); if (NULL == *Dest) { return E_OUTOFMEMORY; } SecureZeroMemory(*Dest, cbSize); return StringCchCopy((STRSAFE_LPWSTR)*Dest, cchSize + 1, Src); } HRESULT CWirelessHelperExtension::GetAttributeInfo( __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) HelperAttributeInfo **pprgAttributeInfos ) { HRESULT hr = S_OK; LogEntry (this); do { if (pcelt==NULL || pprgAttributeInfos==NULL) { hr = E_INVALIDARG; break; } HelperAttributeInfo *info = (HelperAttributeInfo *)CoTaskMemAlloc(3*sizeof(HelperAttributeInfo)); if (info==NULL) { hr = E_OUTOFMEMORY; break; } SecureZeroMemory(info,3*sizeof(HelperAttributeInfo)); StringCchCopyWithAlloc(&info[0].pwszName, MAX_PATH, L"IfType"); info[0].type=AT_UINT32; StringCchCopyWithAlloc(&info[1].pwszName, MAX_PATH, L"LowHealthAttributeType"); info[1].type=AT_UINT32; StringCchCopyWithAlloc(&info[2].pwszName, MAX_PATH, L"ReturnRepair"); info[2].type=AT_BOOLEAN; *pcelt=3; *pprgAttributeInfos=info; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::Initialize( ULONG celt, __RPC__in_ecount_full(celt) HELPER_ATTRIBUTE rgAttributes[ ] ) { WDIAG_IHV_WLAN_ID WDiagID = {0}; HRESULT hr = S_OK; LogEntry (this); do { if (celt == 0) { break; } if (rgAttributes == NULL) { hr = E_INVALIDARG; break; } for (UINT i = 0; i < celt; i++) { switch (rgAttributes[i].type) { case (AT_GUID): { LogInfo ("\t[%d] GUID Attribute <%ws>, value=<%!guid!>\n", i+1, rgAttributes[i].pwszName, &rgAttributes[i].Guid); break; } case (AT_UINT32): { LogInfo ("\t[%d] UINT Attribute <%ws>, value=<%d>\n", i+1, rgAttributes[i].pwszName, rgAttributes[i].DWord); break; } case (AT_BOOLEAN): { LogInfo ("\t[%d] BOOLEAN Attribute <%ws>, value=<%d>\n", i+1, rgAttributes[i].pwszName, rgAttributes[i].Boolean); break; } case (AT_STRING): { LogInfo ("\t[%d] STRING Attribute <%ws>, value=<%ws>\n", i+1, rgAttributes[i].pwszName, rgAttributes[i].PWStr); break; } case (AT_OCTET_STRING): { LogInfo ("\t[%d] AT_OCTET_STRING Attribute <%ws>, Length=<%d>\n", i+1, rgAttributes[i].pwszName, rgAttributes[i].OctetString.dwLength); if (rgAttributes[i].OctetString.dwLength < sizeof(WDIAG_IHV_WLAN_ID)) { LogInfo ("\t\tLength=<%d> < sizeof(WDIAG_IHV_WLAN_ID)=<%d>\n", rgAttributes[i].OctetString.dwLength, sizeof(WDIAG_IHV_WLAN_ID)); break; } RtlCopyMemory (&WDiagID, rgAttributes[i].OctetString.lpValue, sizeof (WDIAG_IHV_WLAN_ID)); LogInfo ("\t\tProfileName=<%ws>\n", WDiagID.strProfileName); LogInfo ("\t\tSsidLength=<%d>\n", WDiagID.Ssid.uSSIDLength); LogInfo ("\t\tBssType=<%d>\n", WDiagID.BssType); LogInfo ("\t\tReasonCode=<%d>\n", WDiagID.dwReasonCode); LogInfo ("\t\tFlags=<0x%x>\n", WDiagID.dwFlags); break; } default: { LogInfo ("\t[%d] Attribute <%ws>, Unknown type=<%d>\n", i+1, rgAttributes[i].pwszName, rgAttributes[i].type); break; } } } if (S_OK != hr) { break; } InterlockedCompareExchange(&m_initialized, 1, 0); } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetDiagnosticsInfo( __RPC__deref_out_opt DiagnosticsInfo **ppInfo ) { HRESULT hr = S_OK; LogEntry (this); do { if (NULL == ppInfo) { break; } *ppInfo = (DiagnosticsInfo *)CoTaskMemAlloc(sizeof(DiagnosticsInfo)); if (*ppInfo == NULL) { hr = E_OUTOFMEMORY; break; } (*ppInfo)->cost = 0; (*ppInfo)->flags = DF_TRACELESS; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetKeyAttributes( __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) HELPER_ATTRIBUTE **pprgAttributes ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pcelt); UNREFERENCED_PARAMETER (pprgAttributes); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::LowHealth( __RPC__in_opt LPCWSTR pwszInstanceDescription, __RPC__deref_out_opt_string LPWSTR *ppwszDescription, __RPC__out long *pDeferredTime, __RPC__out DIAGNOSIS_STATUS *pStatus ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pwszInstanceDescription); LogEntry (this); do { if (m_initialized <= 0) { hr = E_UNEXPECTED; break; } if (pDeferredTime == NULL || pStatus == NULL || ppwszDescription == NULL) { hr = E_INVALIDARG; break; } // // this class will always confirm. this way we know the class // was instantiated and was called successfully // *pStatus = DS_CONFIRMED; m_ReturnRepair = TRUE; hr = StringCchCopyWithAlloc(ppwszDescription, 256, L"Helper Extension LowHealth call succeeded."); } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::HighUtilization( __RPC__in_opt LPCWSTR pwszInstanceDescription, __RPC__deref_out_opt_string LPWSTR *ppwszDescription, __RPC__out long *pDeferredTime, __RPC__out DIAGNOSIS_STATUS *pStatus ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pwszInstanceDescription); UNREFERENCED_PARAMETER (ppwszDescription); UNREFERENCED_PARAMETER (pDeferredTime); UNREFERENCED_PARAMETER (pStatus); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetLowerHypotheses( __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses ) { HYPOTHESIS *hypothses = NULL; HELPER_ATTRIBUTE *attributes = NULL; size_t size = sizeof(HYPOTHESIS); HRESULT hr = S_OK; LogEntry (this); do { if (m_initialized <= 0) { hr = E_UNEXPECTED; break; } if (pcelt == NULL) { hr = E_INVALIDARG; break; } //if no attribute type specified we don't perform a lower hypotheses if(m_LowHealthAttributeType==0) { *pcelt = 0; *pprgHypotheses=NULL; hr = S_OK; break; } // check to see if additional storage is needed for attributes. hypothses = (HYPOTHESIS*)CoTaskMemAlloc(size); if (hypothses == NULL) { hr = E_OUTOFMEMORY; break; } SecureZeroMemory(hypothses, size); hr = StringCchCopyWithAlloc(&(hypothses->pwszClassName), MAX_PATH, L"LowHealthHypotheses"); if (FAILED (hr)) { break; } hr = StringCchCopyWithAlloc(&(hypothses->pwszDescription), MAX_PATH, L"TestHypotheses"); if (FAILED (hr)) { break; } hypothses->celt = 1; attributes = hypothses->rgAttributes = (PHELPER_ATTRIBUTE)CoTaskMemAlloc(sizeof HELPER_ATTRIBUTE); if (attributes == NULL) { hr = E_OUTOFMEMORY; break; } switch(m_LowHealthAttributeType) { case AT_BOOLEAN: attributes->type = AT_BOOLEAN; break; case AT_INT8: attributes->type = AT_INT8; break; case AT_UINT8: attributes->type = AT_UINT8; break; case AT_INT16: attributes->type = AT_INT16; break; case AT_UINT16: attributes->type = AT_UINT16; break; case AT_INT32: attributes->type = AT_INT32; break; case AT_UINT32: attributes->type = AT_UINT32; break; case AT_INT64: attributes->type = AT_INT64; break; case AT_UINT64: attributes->type = AT_UINT64; break; case AT_STRING: attributes->type = AT_STRING; StringCchCopyWithAlloc(&(attributes->PWStr), MAX_PATH, L"String Attribute Value"); break; case AT_GUID: attributes->type = AT_GUID; break; case AT_LIFE_TIME: attributes->type = AT_LIFE_TIME; break; case AT_SOCKADDR: attributes->type = AT_SOCKADDR; break; case AT_OCTET_STRING: attributes->type = AT_OCTET_STRING; attributes->OctetString.dwLength = 32; attributes->OctetString.lpValue = (BYTE *)CoTaskMemAlloc(32*sizeof(BYTE)); if(attributes->OctetString.lpValue==NULL) { hr = E_OUTOFMEMORY; break; } SecureZeroMemory(attributes->OctetString.lpValue,32*sizeof(BYTE)); break; } if (FAILED (hr)) { break; } if (hypothses->celt!=0) { hr = StringCchCopyWithAlloc(&(attributes->pwszName), MAX_PATH, L"TestAttribute"); if (FAILED (hr)) { break; } } *pcelt = 1; if (pprgHypotheses) { *pprgHypotheses = hypothses; } } while (FALSE); if ((FAILED (hr)) && (hypothses)) { CoTaskMemFree(hypothses->pwszClassName); attributes = hypothses->rgAttributes; if (attributes) { for (UINT i = 0; i < hypothses->celt; i++, ++attributes) { CoTaskMemFree(attributes->pwszName); switch(attributes->type) { case AT_STRING: if(attributes->PWStr!=NULL) CoTaskMemFree(attributes->PWStr); case AT_OCTET_STRING: if(attributes->OctetString.lpValue!=NULL) CoTaskMemFree(attributes->OctetString.lpValue); } } CoTaskMemFree(attributes); } CoTaskMemFree(hypothses); } LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetDownStreamHypotheses( __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pcelt); UNREFERENCED_PARAMETER (pprgHypotheses); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetHigherHypotheses( __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pcelt); UNREFERENCED_PARAMETER (pprgHypotheses); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetUpStreamHypotheses( __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pcelt); UNREFERENCED_PARAMETER (pprgHypotheses); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::Repair( __RPC__in RepairInfo *pInfo, __RPC__out long *pDeferredTime, __RPC__out REPAIR_STATUS *pStatus ) { HRESULT hr = S_OK; LogEntry (this); do { if (m_initialized <= 0) { hr = E_UNEXPECTED; break; } if (pInfo == NULL || pDeferredTime == NULL || pStatus == NULL) { hr = E_INVALIDARG; break; } if (!IsEqualGUID(pInfo->guid, gWirelessHelperExtensionRepairId)) { hr = E_NOTIMPL; break; } *pDeferredTime = 0; *pStatus = RS_REPAIRED; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::Validate( PROBLEM_TYPE problem, __RPC__out long *pDeferredTime, __RPC__out REPAIR_STATUS *pStatus ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (problem); UNREFERENCED_PARAMETER (pDeferredTime); UNREFERENCED_PARAMETER (pStatus); LogEntry (this); do { if (m_initialized <= 0) { hr = E_UNEXPECTED; break; } hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetRepairInfo( PROBLEM_TYPE problem, __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) RepairInfo **ppInfo ) { RepairInfo *info = NULL; HRESULT hr = S_OK; UNREFERENCED_PARAMETER (problem); LogEntry (this); do { if (m_initialized <= 0) { hr = E_UNEXPECTED; break; } if (pcelt == NULL) { hr = E_INVALIDARG; break; } if (ppInfo == NULL) { hr = S_OK; break; } if(!m_ReturnRepair) { *pcelt=0; *ppInfo=NULL; hr = S_OK; break; } info = (RepairInfo *)CoTaskMemAlloc(sizeof(RepairInfo)); if (info == NULL) { hr = E_OUTOFMEMORY; break; } SecureZeroMemory(info, sizeof(RepairInfo)); info->guid = gWirelessHelperExtensionRepairId; hr = StringCchCopyWithAlloc(&(info->pwszClassName), MAX_PATH, L"SampleWirelessHelperExtension"); if (FAILED (hr)) { break; } hr = StringCchCopyWithAlloc(&(info->pwszDescription), MAX_PATH, L"Sample repair from SampleWirelessHelperExtension"); if (FAILED (hr)) { break; } info->cost = 5; info->sidType = WinBuiltinNetworkConfigurationOperatorsSid; info->flags = RF_INFORMATION_ONLY; info->scope = RS_SYSTEM; info->risk = RR_NORISK; info->UiInfo.type = UIT_NONE; *pcelt = 1; *ppInfo = info; } while (FALSE); if ((FAILED (hr)) && (info)) { CoTaskMemFree(info->pwszClassName); CoTaskMemFree(info->pwszDescription); CoTaskMemFree(info); } LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetLifeTime( __RPC__out LIFE_TIME *pLifeTime ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pLifeTime); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::SetLifeTime( LIFE_TIME lifeTime ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (lifeTime); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetCacheTime( __RPC__out FILETIME *pCacheTime ) { HRESULT hr = S_OK; LogEntry (this); do { SecureZeroMemory (pCacheTime, sizeof(FILETIME)); } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::GetAttributes( __RPC__out ULONG *pcelt, __RPC__deref_out_ecount_full_opt(*pcelt) HELPER_ATTRIBUTE **pprgAttributes ) { HRESULT hr = S_OK; UNREFERENCED_PARAMETER (pcelt); UNREFERENCED_PARAMETER (pprgAttributes); LogEntry (this); do { hr = E_NOTIMPL; } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::Cancel( ) { HRESULT hr = S_OK; LogEntry (this); do { } while (FALSE); LogExit (hr); return (hr); } HRESULT CWirelessHelperExtension::Cleanup( ) { HRESULT hr = S_OK; LogEntry (this); do { } while (FALSE); LogExit (hr); return (hr); }
23.146853
126
0.512739
windows-development
9acd71e8de724a3ce78857d7a32b50b495be5614
858
cpp
C++
outbound_place/src/mosaic.cpp
ManuelBeschi/manipulation
0caddd6dc78dc6d00a39b2e674093d1eafdc7221
[ "BSD-3-Clause" ]
null
null
null
outbound_place/src/mosaic.cpp
ManuelBeschi/manipulation
0caddd6dc78dc6d00a39b2e674093d1eafdc7221
[ "BSD-3-Clause" ]
null
null
null
outbound_place/src/mosaic.cpp
ManuelBeschi/manipulation
0caddd6dc78dc6d00a39b2e674093d1eafdc7221
[ "BSD-3-Clause" ]
1
2021-03-12T09:50:37.000Z
2021-03-12T09:50:37.000Z
#include <ros/ros.h> #include <outbound_place/outbound_mosaic.h> #include <moveit_msgs/GetPlanningScene.h> int main(int argc, char **argv) { ros::init(argc, argv, "outbound_mosaic"); ros::NodeHandle nh; ros::NodeHandle pnh("~"); ros::ServiceClient ps_client=nh.serviceClient<moveit_msgs::GetPlanningScene>("/get_planning_scene"); ps_client.waitForExistence(); moveit_msgs::GetPlanningScene ps_srv; ros::AsyncSpinner spinner(8); spinner.start(); pickplace::OutboundMosaic pallet(nh,pnh) ; if (!pallet.init()) { ROS_ERROR_NAMED(nh.getNamespace(),"unable to load parameter"); return -1; } while (ros::ok()) { if (!ps_client.call(ps_srv)) ROS_ERROR("call to get_planning_scene srv not ok"); else pallet.updatePlanningScene(ps_srv.response.scene); ros::Duration(0.1).sleep(); } return 0; }
22.578947
102
0.693473
ManuelBeschi
9acff9eb651719e76456180855e61aded949fd78
33,501
cpp
C++
av/media/libstagefright/codecs/avc/enc/src/header.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
10
2020-04-17T04:02:36.000Z
2021-11-23T11:38:42.000Z
av/media/libstagefright/codecs/avc/enc/src/header.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
3
2020-02-19T16:53:25.000Z
2021-04-29T07:28:40.000Z
av/media/libstagefright/codecs/avc/enc/src/header.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
5
2019-12-25T04:05:02.000Z
2022-01-14T16:57:55.000Z
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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 "avcenc_lib.h" #include "avcenc_api.h" /** see subclause 7.4.2.1 */ /* no need for checking the valid range , already done in SetEncodeParam(), if we have to send another SPS, the ranges should be verified first before users call PVAVCEncodeSPS() */ AVCEnc_Status EncodeSPS(AVCEncObject *encvid, AVCEncBitstream *stream) { AVCCommonObj *video = encvid->common; AVCSeqParamSet *seqParam = video->currSeqParams; AVCVUIParams *vui = &(seqParam->vui_parameters); int i; AVCEnc_Status status = AVCENC_SUCCESS; //DEBUG_LOG(userData,AVC_LOGTYPE_INFO,"EncodeSPS",-1,-1); status = BitstreamWriteBits(stream, 8, seqParam->profile_idc); status = BitstreamWrite1Bit(stream, seqParam->constrained_set0_flag); status = BitstreamWrite1Bit(stream, seqParam->constrained_set1_flag); status = BitstreamWrite1Bit(stream, seqParam->constrained_set2_flag); status = BitstreamWrite1Bit(stream, seqParam->constrained_set3_flag); status = BitstreamWriteBits(stream, 4, 0); /* forbidden zero bits */ if (status != AVCENC_SUCCESS) /* we can check after each write also */ { return status; } status = BitstreamWriteBits(stream, 8, seqParam->level_idc); status = ue_v(stream, seqParam->seq_parameter_set_id); status = ue_v(stream, seqParam->log2_max_frame_num_minus4); status = ue_v(stream, seqParam->pic_order_cnt_type); if (status != AVCENC_SUCCESS) { return status; } if (seqParam->pic_order_cnt_type == 0) { status = ue_v(stream, seqParam->log2_max_pic_order_cnt_lsb_minus4); } else if (seqParam->pic_order_cnt_type == 1) { status = BitstreamWrite1Bit(stream, seqParam->delta_pic_order_always_zero_flag); status = se_v(stream, seqParam->offset_for_non_ref_pic); /* upto 32 bits */ status = se_v(stream, seqParam->offset_for_top_to_bottom_field); /* upto 32 bits */ status = ue_v(stream, seqParam->num_ref_frames_in_pic_order_cnt_cycle); for (i = 0; i < (int)(seqParam->num_ref_frames_in_pic_order_cnt_cycle); i++) { status = se_v(stream, seqParam->offset_for_ref_frame[i]); /* upto 32 bits */ } } if (status != AVCENC_SUCCESS) { return status; } status = ue_v(stream, seqParam->num_ref_frames); status = BitstreamWrite1Bit(stream, seqParam->gaps_in_frame_num_value_allowed_flag); status = ue_v(stream, seqParam->pic_width_in_mbs_minus1); status = ue_v(stream, seqParam->pic_height_in_map_units_minus1); status = BitstreamWrite1Bit(stream, seqParam->frame_mbs_only_flag); if (status != AVCENC_SUCCESS) { return status; } /* if frame_mbs_only_flag is 0, then write, mb_adaptive_frame_field_frame here */ status = BitstreamWrite1Bit(stream, seqParam->direct_8x8_inference_flag); status = BitstreamWrite1Bit(stream, seqParam->frame_cropping_flag); if (seqParam->frame_cropping_flag) { status = ue_v(stream, seqParam->frame_crop_left_offset); status = ue_v(stream, seqParam->frame_crop_right_offset); status = ue_v(stream, seqParam->frame_crop_top_offset); status = ue_v(stream, seqParam->frame_crop_bottom_offset); } if (status != AVCENC_SUCCESS) { return status; } status = BitstreamWrite1Bit(stream, seqParam->vui_parameters_present_flag); if (seqParam->vui_parameters_present_flag) { /* not supported */ //return AVCENC_SPS_FAIL; EncodeVUI(stream, vui); } return status; } void EncodeVUI(AVCEncBitstream* stream, AVCVUIParams* vui) { int temp; temp = vui->aspect_ratio_info_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { BitstreamWriteBits(stream, 8, vui->aspect_ratio_idc); if (vui->aspect_ratio_idc == 255) { BitstreamWriteBits(stream, 16, vui->sar_width); BitstreamWriteBits(stream, 16, vui->sar_height); } } temp = vui->overscan_info_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { BitstreamWrite1Bit(stream, vui->overscan_appropriate_flag); } temp = vui->video_signal_type_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { BitstreamWriteBits(stream, 3, vui->video_format); BitstreamWrite1Bit(stream, vui->video_full_range_flag); temp = vui->colour_description_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { BitstreamWriteBits(stream, 8, vui->colour_primaries); BitstreamWriteBits(stream, 8, vui->transfer_characteristics); BitstreamWriteBits(stream, 8, vui->matrix_coefficients); } } temp = vui->chroma_location_info_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { ue_v(stream, vui->chroma_sample_loc_type_top_field); ue_v(stream, vui->chroma_sample_loc_type_bottom_field); } temp = vui->timing_info_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { BitstreamWriteBits(stream, 32, vui->num_units_in_tick); BitstreamWriteBits(stream, 32, vui->time_scale); BitstreamWrite1Bit(stream, vui->fixed_frame_rate_flag); } temp = vui->nal_hrd_parameters_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { EncodeHRD(stream, &(vui->nal_hrd_parameters)); } temp = vui->vcl_hrd_parameters_present_flag; BitstreamWrite1Bit(stream, temp); if (temp) { EncodeHRD(stream, &(vui->vcl_hrd_parameters)); } if (vui->nal_hrd_parameters_present_flag || vui->vcl_hrd_parameters_present_flag) { BitstreamWrite1Bit(stream, vui->low_delay_hrd_flag); } BitstreamWrite1Bit(stream, vui->pic_struct_present_flag); temp = vui->bitstream_restriction_flag; BitstreamWrite1Bit(stream, temp); if (temp) { BitstreamWrite1Bit(stream, vui->motion_vectors_over_pic_boundaries_flag); ue_v(stream, vui->max_bytes_per_pic_denom); ue_v(stream, vui->max_bits_per_mb_denom); ue_v(stream, vui->log2_max_mv_length_horizontal); ue_v(stream, vui->log2_max_mv_length_vertical); ue_v(stream, vui->max_dec_frame_reordering); ue_v(stream, vui->max_dec_frame_buffering); } return ; } void EncodeHRD(AVCEncBitstream* stream, AVCHRDParams* hrd) { int i; ue_v(stream, hrd->cpb_cnt_minus1); BitstreamWriteBits(stream, 4, hrd->bit_rate_scale); BitstreamWriteBits(stream, 4, hrd->cpb_size_scale); for (i = 0; i <= (int)hrd->cpb_cnt_minus1; i++) { ue_v(stream, hrd->bit_rate_value_minus1[i]); ue_v(stream, hrd->cpb_size_value_minus1[i]); ue_v(stream, hrd->cbr_flag[i]); } BitstreamWriteBits(stream, 5, hrd->initial_cpb_removal_delay_length_minus1); BitstreamWriteBits(stream, 5, hrd->cpb_removal_delay_length_minus1); BitstreamWriteBits(stream, 5, hrd->dpb_output_delay_length_minus1); BitstreamWriteBits(stream, 5, hrd->time_offset_length); return ; } /** see subclause 7.4.2.2 */ /* no need for checking the valid range , already done in SetEncodeParam(). If we have to send another SPS, the ranges should be verified first before users call PVAVCEncodeSPS()*/ AVCEnc_Status EncodePPS(AVCEncObject *encvid, AVCEncBitstream *stream) { AVCCommonObj *video = encvid->common; AVCEnc_Status status = AVCENC_SUCCESS; AVCPicParamSet *picParam = video->currPicParams; int i, iGroup, numBits; uint temp; status = ue_v(stream, picParam->pic_parameter_set_id); status = ue_v(stream, picParam->seq_parameter_set_id); status = BitstreamWrite1Bit(stream, picParam->entropy_coding_mode_flag); status = BitstreamWrite1Bit(stream, picParam->pic_order_present_flag); if (status != AVCENC_SUCCESS) { return status; } status = ue_v(stream, picParam->num_slice_groups_minus1); if (picParam->num_slice_groups_minus1 > 0) { status = ue_v(stream, picParam->slice_group_map_type); if (picParam->slice_group_map_type == 0) { for (iGroup = 0; iGroup <= (int)picParam->num_slice_groups_minus1; iGroup++) { status = ue_v(stream, picParam->run_length_minus1[iGroup]); } } else if (picParam->slice_group_map_type == 2) { for (iGroup = 0; iGroup < (int)picParam->num_slice_groups_minus1; iGroup++) { status = ue_v(stream, picParam->top_left[iGroup]); status = ue_v(stream, picParam->bottom_right[iGroup]); } } else if (picParam->slice_group_map_type == 3 || picParam->slice_group_map_type == 4 || picParam->slice_group_map_type == 5) { status = BitstreamWrite1Bit(stream, picParam->slice_group_change_direction_flag); status = ue_v(stream, picParam->slice_group_change_rate_minus1); } else /*if(picParam->slice_group_map_type == 6)*/ { status = ue_v(stream, picParam->pic_size_in_map_units_minus1); numBits = 0;/* ceil(log2(num_slice_groups_minus1+1)) bits */ i = picParam->num_slice_groups_minus1; while (i > 0) { numBits++; i >>= 1; } for (i = 0; i <= (int)picParam->pic_size_in_map_units_minus1; i++) { status = BitstreamWriteBits(stream, numBits, picParam->slice_group_id[i]); } } } if (status != AVCENC_SUCCESS) { return status; } status = ue_v(stream, picParam->num_ref_idx_l0_active_minus1); status = ue_v(stream, picParam->num_ref_idx_l1_active_minus1); status = BitstreamWrite1Bit(stream, picParam->weighted_pred_flag); status = BitstreamWriteBits(stream, 2, picParam->weighted_bipred_idc); if (status != AVCENC_SUCCESS) { return status; } status = se_v(stream, picParam->pic_init_qp_minus26); status = se_v(stream, picParam->pic_init_qs_minus26); status = se_v(stream, picParam->chroma_qp_index_offset); temp = picParam->deblocking_filter_control_present_flag << 2; temp |= (picParam->constrained_intra_pred_flag << 1); temp |= picParam->redundant_pic_cnt_present_flag; status = BitstreamWriteBits(stream, 3, temp); return status; } /** see subclause 7.4.3 */ AVCEnc_Status EncodeSliceHeader(AVCEncObject *encvid, AVCEncBitstream *stream) { AVCCommonObj *video = encvid->common; AVCSliceHeader *sliceHdr = video->sliceHdr; AVCPicParamSet *currPPS = video->currPicParams; AVCSeqParamSet *currSPS = video->currSeqParams; AVCEnc_Status status = AVCENC_SUCCESS; int slice_type, temp, i; int num_bits; num_bits = (stream->write_pos << 3) - stream->bit_left; status = ue_v(stream, sliceHdr->first_mb_in_slice); slice_type = video->slice_type; if (video->mbNum == 0) /* first mb in frame */ { status = ue_v(stream, sliceHdr->slice_type); } else { status = ue_v(stream, slice_type); } status = ue_v(stream, sliceHdr->pic_parameter_set_id); status = BitstreamWriteBits(stream, currSPS->log2_max_frame_num_minus4 + 4, sliceHdr->frame_num); if (status != AVCENC_SUCCESS) { return status; } /* if frame_mbs_only_flag is 0, encode field_pic_flag, bottom_field_flag here */ if (video->nal_unit_type == AVC_NALTYPE_IDR) { status = ue_v(stream, sliceHdr->idr_pic_id); } if (currSPS->pic_order_cnt_type == 0) { status = BitstreamWriteBits(stream, currSPS->log2_max_pic_order_cnt_lsb_minus4 + 4, sliceHdr->pic_order_cnt_lsb); if (currPPS->pic_order_present_flag && !sliceHdr->field_pic_flag) { status = se_v(stream, sliceHdr->delta_pic_order_cnt_bottom); /* 32 bits */ } } if (currSPS->pic_order_cnt_type == 1 && !currSPS->delta_pic_order_always_zero_flag) { status = se_v(stream, sliceHdr->delta_pic_order_cnt[0]); /* 32 bits */ if (currPPS->pic_order_present_flag && !sliceHdr->field_pic_flag) { status = se_v(stream, sliceHdr->delta_pic_order_cnt[1]); /* 32 bits */ } } if (currPPS->redundant_pic_cnt_present_flag) { status = ue_v(stream, sliceHdr->redundant_pic_cnt); } if (slice_type == AVC_B_SLICE) { status = BitstreamWrite1Bit(stream, sliceHdr->direct_spatial_mv_pred_flag); } if (status != AVCENC_SUCCESS) { return status; } if (slice_type == AVC_P_SLICE || slice_type == AVC_SP_SLICE || slice_type == AVC_B_SLICE) { status = BitstreamWrite1Bit(stream, sliceHdr->num_ref_idx_active_override_flag); if (sliceHdr->num_ref_idx_active_override_flag) { /* we shouldn't enter this part at all */ status = ue_v(stream, sliceHdr->num_ref_idx_l0_active_minus1); if (slice_type == AVC_B_SLICE) { status = ue_v(stream, sliceHdr->num_ref_idx_l1_active_minus1); } } } if (status != AVCENC_SUCCESS) { return status; } /* ref_pic_list_reordering() */ status = ref_pic_list_reordering(video, stream, sliceHdr, slice_type); if (status != AVCENC_SUCCESS) { return status; } if ((currPPS->weighted_pred_flag && (slice_type == AVC_P_SLICE || slice_type == AVC_SP_SLICE)) || (currPPS->weighted_bipred_idc == 1 && slice_type == AVC_B_SLICE)) { // pred_weight_table(); // not supported !! return AVCENC_PRED_WEIGHT_TAB_FAIL; } if (video->nal_ref_idc != 0) { status = dec_ref_pic_marking(video, stream, sliceHdr); if (status != AVCENC_SUCCESS) { return status; } } if (currPPS->entropy_coding_mode_flag && slice_type != AVC_I_SLICE && slice_type != AVC_SI_SLICE) { return AVCENC_CABAC_FAIL; /* ue_v(stream,&(sliceHdr->cabac_init_idc)); if(sliceHdr->cabac_init_idc > 2){ // not supported !!!! }*/ } status = se_v(stream, sliceHdr->slice_qp_delta); if (status != AVCENC_SUCCESS) { return status; } if (slice_type == AVC_SP_SLICE || slice_type == AVC_SI_SLICE) { if (slice_type == AVC_SP_SLICE) { status = BitstreamWrite1Bit(stream, sliceHdr->sp_for_switch_flag); /* if sp_for_switch_flag is 0, P macroblocks in SP slice is decoded using SP decoding process for non-switching pictures in 8.6.1 */ /* else, P macroblocks in SP slice is decoded using SP and SI decoding process for switching picture in 8.6.2 */ } status = se_v(stream, sliceHdr->slice_qs_delta); if (status != AVCENC_SUCCESS) { return status; } } if (currPPS->deblocking_filter_control_present_flag) { status = ue_v(stream, sliceHdr->disable_deblocking_filter_idc); if (sliceHdr->disable_deblocking_filter_idc != 1) { status = se_v(stream, sliceHdr->slice_alpha_c0_offset_div2); status = se_v(stream, sliceHdr->slice_beta_offset_div_2); } if (status != AVCENC_SUCCESS) { return status; } } if (currPPS->num_slice_groups_minus1 > 0 && currPPS->slice_group_map_type >= 3 && currPPS->slice_group_map_type <= 5) { /* Ceil(Log2(PicSizeInMapUnits/(float)SliceGroupChangeRate + 1)) */ temp = video->PicSizeInMapUnits / video->SliceGroupChangeRate; if (video->PicSizeInMapUnits % video->SliceGroupChangeRate) { temp++; } i = 0; while (temp > 1) { temp >>= 1; i++; } BitstreamWriteBits(stream, i, sliceHdr->slice_group_change_cycle); } encvid->rateCtrl->NumberofHeaderBits += (stream->write_pos << 3) - stream->bit_left - num_bits; return AVCENC_SUCCESS; } /** see subclause 7.4.3.1 */ AVCEnc_Status ref_pic_list_reordering(AVCCommonObj *video, AVCEncBitstream *stream, AVCSliceHeader *sliceHdr, int slice_type) { (void)(video); int i; AVCEnc_Status status = AVCENC_SUCCESS; if (slice_type != AVC_I_SLICE && slice_type != AVC_SI_SLICE) { status = BitstreamWrite1Bit(stream, sliceHdr->ref_pic_list_reordering_flag_l0); if (sliceHdr->ref_pic_list_reordering_flag_l0) { i = 0; do { status = ue_v(stream, sliceHdr->reordering_of_pic_nums_idc_l0[i]); if (sliceHdr->reordering_of_pic_nums_idc_l0[i] == 0 || sliceHdr->reordering_of_pic_nums_idc_l0[i] == 1) { status = ue_v(stream, sliceHdr->abs_diff_pic_num_minus1_l0[i]); /* this check should be in InitSlice(), if we ever use it */ /*if(sliceHdr->reordering_of_pic_nums_idc_l0[i] == 0 && sliceHdr->abs_diff_pic_num_minus1_l0[i] > video->MaxPicNum/2 -1) { return AVCENC_REF_PIC_REORDER_FAIL; // out of range } if(sliceHdr->reordering_of_pic_nums_idc_l0[i] == 1 && sliceHdr->abs_diff_pic_num_minus1_l0[i] > video->MaxPicNum/2 -2) { return AVCENC_REF_PIC_REORDER_FAIL; // out of range }*/ } else if (sliceHdr->reordering_of_pic_nums_idc_l0[i] == 2) { status = ue_v(stream, sliceHdr->long_term_pic_num_l0[i]); } i++; } while (sliceHdr->reordering_of_pic_nums_idc_l0[i] != 3 && i <= (int)sliceHdr->num_ref_idx_l0_active_minus1 + 1) ; } } if (slice_type == AVC_B_SLICE) { status = BitstreamWrite1Bit(stream, sliceHdr->ref_pic_list_reordering_flag_l1); if (sliceHdr->ref_pic_list_reordering_flag_l1) { i = 0; do { status = ue_v(stream, sliceHdr->reordering_of_pic_nums_idc_l1[i]); if (sliceHdr->reordering_of_pic_nums_idc_l1[i] == 0 || sliceHdr->reordering_of_pic_nums_idc_l1[i] == 1) { status = ue_v(stream, sliceHdr->abs_diff_pic_num_minus1_l1[i]); /* This check should be in InitSlice() if we ever use it if(sliceHdr->reordering_of_pic_nums_idc_l1[i] == 0 && sliceHdr->abs_diff_pic_num_minus1_l1[i] > video->MaxPicNum/2 -1) { return AVCENC_REF_PIC_REORDER_FAIL; // out of range } if(sliceHdr->reordering_of_pic_nums_idc_l1[i] == 1 && sliceHdr->abs_diff_pic_num_minus1_l1[i] > video->MaxPicNum/2 -2) { return AVCENC_REF_PIC_REORDER_FAIL; // out of range }*/ } else if (sliceHdr->reordering_of_pic_nums_idc_l1[i] == 2) { status = ue_v(stream, sliceHdr->long_term_pic_num_l1[i]); } i++; } while (sliceHdr->reordering_of_pic_nums_idc_l1[i] != 3 && i <= (int)sliceHdr->num_ref_idx_l1_active_minus1 + 1) ; } } return status; } /** see subclause 7.4.3.3 */ AVCEnc_Status dec_ref_pic_marking(AVCCommonObj *video, AVCEncBitstream *stream, AVCSliceHeader *sliceHdr) { int i; AVCEnc_Status status = AVCENC_SUCCESS; if (video->nal_unit_type == AVC_NALTYPE_IDR) { status = BitstreamWrite1Bit(stream, sliceHdr->no_output_of_prior_pics_flag); status = BitstreamWrite1Bit(stream, sliceHdr->long_term_reference_flag); if (sliceHdr->long_term_reference_flag == 0) /* used for short-term */ { video->MaxLongTermFrameIdx = -1; /* no long-term frame indx */ } else /* used for long-term */ { video->MaxLongTermFrameIdx = 0; video->LongTermFrameIdx = 0; } } else { status = BitstreamWrite1Bit(stream, sliceHdr->adaptive_ref_pic_marking_mode_flag); /* default to zero */ if (sliceHdr->adaptive_ref_pic_marking_mode_flag) { i = 0; do { status = ue_v(stream, sliceHdr->memory_management_control_operation[i]); if (sliceHdr->memory_management_control_operation[i] == 1 || sliceHdr->memory_management_control_operation[i] == 3) { status = ue_v(stream, sliceHdr->difference_of_pic_nums_minus1[i]); } if (sliceHdr->memory_management_control_operation[i] == 2) { status = ue_v(stream, sliceHdr->long_term_pic_num[i]); } if (sliceHdr->memory_management_control_operation[i] == 3 || sliceHdr->memory_management_control_operation[i] == 6) { status = ue_v(stream, sliceHdr->long_term_frame_idx[i]); } if (sliceHdr->memory_management_control_operation[i] == 4) { status = ue_v(stream, sliceHdr->max_long_term_frame_idx_plus1[i]); } i++; } while (sliceHdr->memory_management_control_operation[i] != 0 && i < MAX_DEC_REF_PIC_MARKING); if (i >= MAX_DEC_REF_PIC_MARKING && sliceHdr->memory_management_control_operation[i] != 0) { return AVCENC_DEC_REF_PIC_MARK_FAIL; /* we're screwed!!, not enough memory */ } } } return status; } /* see subclause 8.2.1 Decoding process for picture order count. See also PostPOC() for initialization of some variables. */ AVCEnc_Status InitPOC(AVCEncObject *encvid) { AVCCommonObj *video = encvid->common; AVCSeqParamSet *currSPS = video->currSeqParams; AVCSliceHeader *sliceHdr = video->sliceHdr; AVCFrameIO *currInput = encvid->currInput; int i; switch (currSPS->pic_order_cnt_type) { case 0: /* POC MODE 0 , subclause 8.2.1.1 */ /* encoding part */ if (video->nal_unit_type == AVC_NALTYPE_IDR) { encvid->dispOrdPOCRef = currInput->disp_order; } while (currInput->disp_order < encvid->dispOrdPOCRef) { encvid->dispOrdPOCRef -= video->MaxPicOrderCntLsb; } sliceHdr->pic_order_cnt_lsb = currInput->disp_order - encvid->dispOrdPOCRef; while (sliceHdr->pic_order_cnt_lsb >= video->MaxPicOrderCntLsb) { sliceHdr->pic_order_cnt_lsb -= video->MaxPicOrderCntLsb; } /* decoding part */ /* Calculate the MSBs of current picture */ if (video->nal_unit_type == AVC_NALTYPE_IDR) { video->prevPicOrderCntMsb = 0; video->prevPicOrderCntLsb = 0; } if (sliceHdr->pic_order_cnt_lsb < video->prevPicOrderCntLsb && (video->prevPicOrderCntLsb - sliceHdr->pic_order_cnt_lsb) >= (video->MaxPicOrderCntLsb / 2)) video->PicOrderCntMsb = video->prevPicOrderCntMsb + video->MaxPicOrderCntLsb; else if (sliceHdr->pic_order_cnt_lsb > video->prevPicOrderCntLsb && (sliceHdr->pic_order_cnt_lsb - video->prevPicOrderCntLsb) > (video->MaxPicOrderCntLsb / 2)) video->PicOrderCntMsb = video->prevPicOrderCntMsb - video->MaxPicOrderCntLsb; else video->PicOrderCntMsb = video->prevPicOrderCntMsb; /* JVT-I010 page 81 is different from JM7.3 */ if (!sliceHdr->field_pic_flag || !sliceHdr->bottom_field_flag) { video->PicOrderCnt = video->TopFieldOrderCnt = video->PicOrderCntMsb + sliceHdr->pic_order_cnt_lsb; } if (!sliceHdr->field_pic_flag) { video->BottomFieldOrderCnt = video->TopFieldOrderCnt + sliceHdr->delta_pic_order_cnt_bottom; } else if (sliceHdr->bottom_field_flag) { video->PicOrderCnt = video->BottomFieldOrderCnt = video->PicOrderCntMsb + sliceHdr->pic_order_cnt_lsb; } if (!sliceHdr->field_pic_flag) { video->PicOrderCnt = AVC_MIN(video->TopFieldOrderCnt, video->BottomFieldOrderCnt); } if (video->currPicParams->pic_order_present_flag && !sliceHdr->field_pic_flag) { sliceHdr->delta_pic_order_cnt_bottom = 0; /* defaulted to zero */ } break; case 1: /* POC MODE 1, subclause 8.2.1.2 */ /* calculate FrameNumOffset */ if (video->nal_unit_type == AVC_NALTYPE_IDR) { encvid->dispOrdPOCRef = currInput->disp_order; /* reset the reference point */ video->prevFrameNumOffset = 0; video->FrameNumOffset = 0; } else if (video->prevFrameNum > sliceHdr->frame_num) { video->FrameNumOffset = video->prevFrameNumOffset + video->MaxFrameNum; } else { video->FrameNumOffset = video->prevFrameNumOffset; } /* calculate absFrameNum */ if (currSPS->num_ref_frames_in_pic_order_cnt_cycle) { video->absFrameNum = video->FrameNumOffset + sliceHdr->frame_num; } else { video->absFrameNum = 0; } if (video->absFrameNum > 0 && video->nal_ref_idc == 0) { video->absFrameNum--; } /* derive picOrderCntCycleCnt and frameNumInPicOrderCntCycle */ if (video->absFrameNum > 0) { video->picOrderCntCycleCnt = (video->absFrameNum - 1) / currSPS->num_ref_frames_in_pic_order_cnt_cycle; video->frameNumInPicOrderCntCycle = (video->absFrameNum - 1) % currSPS->num_ref_frames_in_pic_order_cnt_cycle; } /* derive expectedDeltaPerPicOrderCntCycle, this value can be computed up front. */ video->expectedDeltaPerPicOrderCntCycle = 0; for (i = 0; i < (int)currSPS->num_ref_frames_in_pic_order_cnt_cycle; i++) { video->expectedDeltaPerPicOrderCntCycle += currSPS->offset_for_ref_frame[i]; } /* derive expectedPicOrderCnt */ if (video->absFrameNum) { video->expectedPicOrderCnt = video->picOrderCntCycleCnt * video->expectedDeltaPerPicOrderCntCycle; for (i = 0; i <= video->frameNumInPicOrderCntCycle; i++) { video->expectedPicOrderCnt += currSPS->offset_for_ref_frame[i]; } } else { video->expectedPicOrderCnt = 0; } if (video->nal_ref_idc == 0) { video->expectedPicOrderCnt += currSPS->offset_for_non_ref_pic; } /* derive TopFieldOrderCnt and BottomFieldOrderCnt */ /* encoding part */ if (!currSPS->delta_pic_order_always_zero_flag) { sliceHdr->delta_pic_order_cnt[0] = currInput->disp_order - encvid->dispOrdPOCRef - video->expectedPicOrderCnt; if (video->currPicParams->pic_order_present_flag && !sliceHdr->field_pic_flag) { sliceHdr->delta_pic_order_cnt[1] = sliceHdr->delta_pic_order_cnt[0]; /* should be calculated from currInput->bottom_field->disp_order */ } else { sliceHdr->delta_pic_order_cnt[1] = 0; } } else { sliceHdr->delta_pic_order_cnt[0] = sliceHdr->delta_pic_order_cnt[1] = 0; } if (sliceHdr->field_pic_flag == 0) { video->TopFieldOrderCnt = video->expectedPicOrderCnt + sliceHdr->delta_pic_order_cnt[0]; video->BottomFieldOrderCnt = video->TopFieldOrderCnt + currSPS->offset_for_top_to_bottom_field + sliceHdr->delta_pic_order_cnt[1]; video->PicOrderCnt = AVC_MIN(video->TopFieldOrderCnt, video->BottomFieldOrderCnt); } else if (sliceHdr->bottom_field_flag == 0) { video->TopFieldOrderCnt = video->expectedPicOrderCnt + sliceHdr->delta_pic_order_cnt[0]; video->PicOrderCnt = video->TopFieldOrderCnt; } else { video->BottomFieldOrderCnt = video->expectedPicOrderCnt + currSPS->offset_for_top_to_bottom_field + sliceHdr->delta_pic_order_cnt[0]; video->PicOrderCnt = video->BottomFieldOrderCnt; } break; case 2: /* POC MODE 2, subclause 8.2.1.3 */ /* decoding order must be the same as display order */ /* we don't check for that. The decoder will just output in decoding order. */ /* Check for 2 consecutive non-reference frame */ if (video->nal_ref_idc == 0) { if (encvid->dispOrdPOCRef == 1) { return AVCENC_CONSECUTIVE_NONREF; } encvid->dispOrdPOCRef = 1; /* act as a flag for non ref */ } else { encvid->dispOrdPOCRef = 0; } if (video->nal_unit_type == AVC_NALTYPE_IDR) { video->FrameNumOffset = 0; } else if (video->prevFrameNum > sliceHdr->frame_num) { video->FrameNumOffset = video->prevFrameNumOffset + video->MaxFrameNum; } else { video->FrameNumOffset = video->prevFrameNumOffset; } /* derive tempPicOrderCnt, we just use PicOrderCnt */ if (video->nal_unit_type == AVC_NALTYPE_IDR) { video->PicOrderCnt = 0; } else if (video->nal_ref_idc == 0) { video->PicOrderCnt = 2 * (video->FrameNumOffset + sliceHdr->frame_num) - 1; } else { video->PicOrderCnt = 2 * (video->FrameNumOffset + sliceHdr->frame_num); } /* derive TopFieldOrderCnt and BottomFieldOrderCnt */ if (sliceHdr->field_pic_flag == 0) { video->TopFieldOrderCnt = video->BottomFieldOrderCnt = video->PicOrderCnt; } else if (sliceHdr->bottom_field_flag) { video->BottomFieldOrderCnt = video->PicOrderCnt; } else { video->TopFieldOrderCnt = video->PicOrderCnt; } break; default: return AVCENC_POC_FAIL; } return AVCENC_SUCCESS; } /** see subclause 8.2.1 */ AVCEnc_Status PostPOC(AVCCommonObj *video) { AVCSliceHeader *sliceHdr = video->sliceHdr; AVCSeqParamSet *currSPS = video->currSeqParams; video->prevFrameNum = sliceHdr->frame_num; switch (currSPS->pic_order_cnt_type) { case 0: /* subclause 8.2.1.1 */ if (video->mem_mgr_ctrl_eq_5) { video->prevPicOrderCntMsb = 0; video->prevPicOrderCntLsb = video->TopFieldOrderCnt; } else { video->prevPicOrderCntMsb = video->PicOrderCntMsb; video->prevPicOrderCntLsb = sliceHdr->pic_order_cnt_lsb; } break; case 1: /* subclause 8.2.1.2 and 8.2.1.3 */ case 2: if (video->mem_mgr_ctrl_eq_5) { video->prevFrameNumOffset = 0; } else { video->prevFrameNumOffset = video->FrameNumOffset; } break; } return AVCENC_SUCCESS; }
36.493464
156
0.591624
Keneral
9ad1d5d732e096c5ce1dfba081bf6fde98c5a130
3,713
cpp
C++
src/navigation/camera.cpp
h4k1m0u/first-person-shooter
b1e60d77edb3144daf252f65c28a340aa63e6945
[ "MIT" ]
null
null
null
src/navigation/camera.cpp
h4k1m0u/first-person-shooter
b1e60d77edb3144daf252f65c28a340aa63e6945
[ "MIT" ]
null
null
null
src/navigation/camera.cpp
h4k1m0u/first-person-shooter
b1e60d77edb3144daf252f65c28a340aa63e6945
[ "MIT" ]
null
null
null
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/constants.hpp> #include <algorithm> #include <iostream> #include "navigation/camera.hpp" // not declared as private members as constants cause class's implicit copy-constructor to be deleted (prevents re-assignment) // movement constants const float SPEED = 0.1f; const float SENSITIVITY = 0.25e-2; Camera::Camera(const glm::vec3& pos, const glm::vec3& dir, const glm::vec3& up): position(pos), direction(dir), m_up(up), m_forward_dir(dir), pitch(0.0f), yaw(0.0f), fov(45.0f) { } /** * View matrix orients a scene in such a way to simulate camera's movement (inversion of camera's transformation matrix) * i.e. translation/rotation of scene in opposite directions to camera * Important: pitch/yaw angles rotate scene's object not camera */ glm::mat4 Camera::get_view() { // only camera direction is rotated by mouse in `rotate()` glm::mat4 view = glm::lookAt(position, position + direction, m_up); return view; } void Camera::zoom(Zoom z) { if (z == Zoom::IN) { fov -= 5.0f; } else if (z == Zoom::OUT) { fov += 5.0f; } } /** * Check if future camera position is too close from its distance to closest wall tile * Used to prevent camera from going through walls * @param position_future Next position of camera */ bool Camera::is_close_to_boundaries(const glm::vec3& position_future) { std::vector<float> distances; std::transform(boundaries.begin(), boundaries.end(), std::back_inserter(distances), [position_future](const glm::vec3& position_wall) { return glm::length(position_future - position_wall); }); float min_distance = *std::min_element(distances.begin(), distances.end()); return min_distance < 1.2f; } void Camera::move(Direction d) { // move forward/backward & sideways glm::vec3 right_dir = glm::normalize(glm::cross(m_forward_dir, m_up)); glm::vec3 position_future; if (d == Direction::FORWARD) { position_future = position + SPEED*m_forward_dir; } else if (d == Direction::BACKWARD) { position_future = position - SPEED*m_forward_dir; } else if (d == Direction::RIGHT) { position_future = position + SPEED*right_dir; } else if (d == Direction::LEFT) { position_future = position - SPEED*right_dir; } // only move camera if not too close to walls std::vector<Direction> dirs = { Direction::FORWARD, Direction::BACKWARD, Direction::RIGHT, Direction::LEFT}; if (std::find(dirs.begin(), dirs.end(), d) != dirs.end() && !is_close_to_boundaries(position_future)) position = position_future; } void Camera::rotate(float x_offset, float y_offset) { // increment angles accord. to 2D mouse movement float PI = glm::pi<float>(); float yaw_offset = SENSITIVITY * x_offset; float pitch_offset = SENSITIVITY * y_offset; yaw += yaw_offset; pitch += pitch_offset; // yaw in [-2pi, 2pi] & clamp pitch angle to prevent weird rotation of camera when pitch ~ pi/2 yaw = std::fmod(yaw, 2 * PI); pitch = std::clamp(pitch, glm::radians(-60.0f), glm::radians(60.0f)); if (pitch == glm::radians(-60.0f) || pitch == glm::radians(60.0f)) { return; } // fps camera navigation by rotating its direction vector around x/y-axis glm::vec3 right_dir = glm::normalize(glm::cross(m_forward_dir, m_up)); glm::mat4 rotation_yaw_mat = glm::rotate(glm::mat4(1.0f), yaw_offset, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 rotation_pitch_mat = glm::rotate(glm::mat4(1.0f), pitch_offset, right_dir); direction = glm::vec3(rotation_pitch_mat * rotation_yaw_mat * glm::vec4(direction, 1.0f)); // forward dir. of movement unaffected by vertical angle (sticks camera to ground) m_forward_dir = {direction.x, 0.0f, direction.z}; }
35.361905
126
0.699973
h4k1m0u
9ad2e36a016ddc139c298b984b4c0c4d6e1d7c53
10,937
hpp
C++
external/boost_1_60_0/qsboost/preprocessor/slot/detail/slot3.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/preprocessor/slot/detail/slot3.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/preprocessor/slot/detail/slot3.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * 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 for most recent version. */ # # include <qsboost/preprocessor/slot/detail/shared.hpp> # # undef QSBOOST_PP_SLOT_3 # # undef QSBOOST_PP_SLOT_3_DIGIT_1 # undef QSBOOST_PP_SLOT_3_DIGIT_2 # undef QSBOOST_PP_SLOT_3_DIGIT_3 # undef QSBOOST_PP_SLOT_3_DIGIT_4 # undef QSBOOST_PP_SLOT_3_DIGIT_5 # undef QSBOOST_PP_SLOT_3_DIGIT_6 # undef QSBOOST_PP_SLOT_3_DIGIT_7 # undef QSBOOST_PP_SLOT_3_DIGIT_8 # undef QSBOOST_PP_SLOT_3_DIGIT_9 # undef QSBOOST_PP_SLOT_3_DIGIT_10 # # if QSBOOST_PP_SLOT_TEMP_10 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_10 0 # elif QSBOOST_PP_SLOT_TEMP_10 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_10 1 # elif QSBOOST_PP_SLOT_TEMP_10 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_10 2 # elif QSBOOST_PP_SLOT_TEMP_10 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_10 3 # elif QSBOOST_PP_SLOT_TEMP_10 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_10 4 # elif QSBOOST_PP_SLOT_TEMP_10 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_10 5 # elif QSBOOST_PP_SLOT_TEMP_10 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_10 6 # elif QSBOOST_PP_SLOT_TEMP_10 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_10 7 # elif QSBOOST_PP_SLOT_TEMP_10 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_10 8 # elif QSBOOST_PP_SLOT_TEMP_10 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_10 9 # endif # # if QSBOOST_PP_SLOT_TEMP_9 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_9 0 # elif QSBOOST_PP_SLOT_TEMP_9 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_9 1 # elif QSBOOST_PP_SLOT_TEMP_9 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_9 2 # elif QSBOOST_PP_SLOT_TEMP_9 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_9 3 # elif QSBOOST_PP_SLOT_TEMP_9 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_9 4 # elif QSBOOST_PP_SLOT_TEMP_9 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_9 5 # elif QSBOOST_PP_SLOT_TEMP_9 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_9 6 # elif QSBOOST_PP_SLOT_TEMP_9 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_9 7 # elif QSBOOST_PP_SLOT_TEMP_9 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_9 8 # elif QSBOOST_PP_SLOT_TEMP_9 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_9 9 # endif # # if QSBOOST_PP_SLOT_TEMP_8 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_8 0 # elif QSBOOST_PP_SLOT_TEMP_8 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_8 1 # elif QSBOOST_PP_SLOT_TEMP_8 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_8 2 # elif QSBOOST_PP_SLOT_TEMP_8 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_8 3 # elif QSBOOST_PP_SLOT_TEMP_8 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_8 4 # elif QSBOOST_PP_SLOT_TEMP_8 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_8 5 # elif QSBOOST_PP_SLOT_TEMP_8 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_8 6 # elif QSBOOST_PP_SLOT_TEMP_8 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_8 7 # elif QSBOOST_PP_SLOT_TEMP_8 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_8 8 # elif QSBOOST_PP_SLOT_TEMP_8 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_8 9 # endif # # if QSBOOST_PP_SLOT_TEMP_7 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_7 0 # elif QSBOOST_PP_SLOT_TEMP_7 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_7 1 # elif QSBOOST_PP_SLOT_TEMP_7 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_7 2 # elif QSBOOST_PP_SLOT_TEMP_7 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_7 3 # elif QSBOOST_PP_SLOT_TEMP_7 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_7 4 # elif QSBOOST_PP_SLOT_TEMP_7 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_7 5 # elif QSBOOST_PP_SLOT_TEMP_7 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_7 6 # elif QSBOOST_PP_SLOT_TEMP_7 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_7 7 # elif QSBOOST_PP_SLOT_TEMP_7 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_7 8 # elif QSBOOST_PP_SLOT_TEMP_7 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_7 9 # endif # # if QSBOOST_PP_SLOT_TEMP_6 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_6 0 # elif QSBOOST_PP_SLOT_TEMP_6 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_6 1 # elif QSBOOST_PP_SLOT_TEMP_6 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_6 2 # elif QSBOOST_PP_SLOT_TEMP_6 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_6 3 # elif QSBOOST_PP_SLOT_TEMP_6 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_6 4 # elif QSBOOST_PP_SLOT_TEMP_6 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_6 5 # elif QSBOOST_PP_SLOT_TEMP_6 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_6 6 # elif QSBOOST_PP_SLOT_TEMP_6 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_6 7 # elif QSBOOST_PP_SLOT_TEMP_6 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_6 8 # elif QSBOOST_PP_SLOT_TEMP_6 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_6 9 # endif # # if QSBOOST_PP_SLOT_TEMP_5 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_5 0 # elif QSBOOST_PP_SLOT_TEMP_5 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_5 1 # elif QSBOOST_PP_SLOT_TEMP_5 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_5 2 # elif QSBOOST_PP_SLOT_TEMP_5 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_5 3 # elif QSBOOST_PP_SLOT_TEMP_5 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_5 4 # elif QSBOOST_PP_SLOT_TEMP_5 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_5 5 # elif QSBOOST_PP_SLOT_TEMP_5 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_5 6 # elif QSBOOST_PP_SLOT_TEMP_5 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_5 7 # elif QSBOOST_PP_SLOT_TEMP_5 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_5 8 # elif QSBOOST_PP_SLOT_TEMP_5 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_5 9 # endif # # if QSBOOST_PP_SLOT_TEMP_4 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_4 0 # elif QSBOOST_PP_SLOT_TEMP_4 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_4 1 # elif QSBOOST_PP_SLOT_TEMP_4 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_4 2 # elif QSBOOST_PP_SLOT_TEMP_4 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_4 3 # elif QSBOOST_PP_SLOT_TEMP_4 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_4 4 # elif QSBOOST_PP_SLOT_TEMP_4 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_4 5 # elif QSBOOST_PP_SLOT_TEMP_4 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_4 6 # elif QSBOOST_PP_SLOT_TEMP_4 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_4 7 # elif QSBOOST_PP_SLOT_TEMP_4 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_4 8 # elif QSBOOST_PP_SLOT_TEMP_4 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_4 9 # endif # # if QSBOOST_PP_SLOT_TEMP_3 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_3 0 # elif QSBOOST_PP_SLOT_TEMP_3 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_3 1 # elif QSBOOST_PP_SLOT_TEMP_3 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_3 2 # elif QSBOOST_PP_SLOT_TEMP_3 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_3 3 # elif QSBOOST_PP_SLOT_TEMP_3 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_3 4 # elif QSBOOST_PP_SLOT_TEMP_3 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_3 5 # elif QSBOOST_PP_SLOT_TEMP_3 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_3 6 # elif QSBOOST_PP_SLOT_TEMP_3 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_3 7 # elif QSBOOST_PP_SLOT_TEMP_3 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_3 8 # elif QSBOOST_PP_SLOT_TEMP_3 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_3 9 # endif # # if QSBOOST_PP_SLOT_TEMP_2 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_2 0 # elif QSBOOST_PP_SLOT_TEMP_2 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_2 1 # elif QSBOOST_PP_SLOT_TEMP_2 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_2 2 # elif QSBOOST_PP_SLOT_TEMP_2 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_2 3 # elif QSBOOST_PP_SLOT_TEMP_2 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_2 4 # elif QSBOOST_PP_SLOT_TEMP_2 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_2 5 # elif QSBOOST_PP_SLOT_TEMP_2 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_2 6 # elif QSBOOST_PP_SLOT_TEMP_2 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_2 7 # elif QSBOOST_PP_SLOT_TEMP_2 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_2 8 # elif QSBOOST_PP_SLOT_TEMP_2 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_2 9 # endif # # if QSBOOST_PP_SLOT_TEMP_1 == 0 # define QSBOOST_PP_SLOT_3_DIGIT_1 0 # elif QSBOOST_PP_SLOT_TEMP_1 == 1 # define QSBOOST_PP_SLOT_3_DIGIT_1 1 # elif QSBOOST_PP_SLOT_TEMP_1 == 2 # define QSBOOST_PP_SLOT_3_DIGIT_1 2 # elif QSBOOST_PP_SLOT_TEMP_1 == 3 # define QSBOOST_PP_SLOT_3_DIGIT_1 3 # elif QSBOOST_PP_SLOT_TEMP_1 == 4 # define QSBOOST_PP_SLOT_3_DIGIT_1 4 # elif QSBOOST_PP_SLOT_TEMP_1 == 5 # define QSBOOST_PP_SLOT_3_DIGIT_1 5 # elif QSBOOST_PP_SLOT_TEMP_1 == 6 # define QSBOOST_PP_SLOT_3_DIGIT_1 6 # elif QSBOOST_PP_SLOT_TEMP_1 == 7 # define QSBOOST_PP_SLOT_3_DIGIT_1 7 # elif QSBOOST_PP_SLOT_TEMP_1 == 8 # define QSBOOST_PP_SLOT_3_DIGIT_1 8 # elif QSBOOST_PP_SLOT_TEMP_1 == 9 # define QSBOOST_PP_SLOT_3_DIGIT_1 9 # endif # # if QSBOOST_PP_SLOT_3_DIGIT_10 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_10(QSBOOST_PP_SLOT_3_DIGIT_10, QSBOOST_PP_SLOT_3_DIGIT_9, QSBOOST_PP_SLOT_3_DIGIT_8, QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_9 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_9(QSBOOST_PP_SLOT_3_DIGIT_9, QSBOOST_PP_SLOT_3_DIGIT_8, QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_8 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_8(QSBOOST_PP_SLOT_3_DIGIT_8, QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_7 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_7(QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_6 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_6(QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_5 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_5(QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_4 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_4(QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_3 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_3(QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # elif QSBOOST_PP_SLOT_3_DIGIT_2 # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_2(QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1) # else # define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_3_DIGIT_1 # endif
40.809701
324
0.782481
wouterboomsma
9ad3840865e3e2067328758f90a58750f42428df
45,140
cpp
C++
wbs/src/Basic/UtilMath.cpp
RNCan/WeatherBasedSimulationFramework
19df207d11b1dddf414d78e52bece77f31d45df8
[ "MIT" ]
6
2017-05-26T21:19:41.000Z
2021-09-03T14:17:29.000Z
wbs/src/Basic/UtilMath.cpp
RNCan/WeatherBasedSimulationFramework
19df207d11b1dddf414d78e52bece77f31d45df8
[ "MIT" ]
5
2016-02-18T12:39:58.000Z
2016-03-13T12:57:45.000Z
wbs/src/Basic/UtilMath.cpp
RNCan/WeatherBasedSimulationFramework
19df207d11b1dddf414d78e52bece77f31d45df8
[ "MIT" ]
1
2019-06-16T02:49:20.000Z
2019-06-16T02:49:20.000Z
//****************************************************************************** // project: Weather-based simulation framework (WBSF) // Programmer: Rémi Saint-Amant // // It under the terms of the GNU General Public License as published by // the Free Software Foundation // It is provided "as is" without express or implied warranty. //****************************************************************************** // 01-01-2016 Rémi Saint-Amant Creation //****************************************************************************** #include "stdafx.h" #include <time.h> #include <float.h> #include <limits> #include "Basic/UtilMath.h" #include "Basic/psychrometrics_SI.h" using namespace std; namespace WBSF { double InvLogistic(double y, double k1, double k2) { // Eq. [3] in Regniere, J. 1984. Canadian Entomologist 116: 1367-1376 // inverted y = f(x) double x = 1.0 - log((pow(y, -k2) - 1) / (pow(0.5, -k2) - 1)) / k1; return x; } double InvWeibull(double y, double alpha, double beta, double gamma) { //inverted y = 1 - e( - ((x-gamma)/beta)^alpha) //Note that Gray et al's (2001) equ. [9] is in error, as alpha is exponent of negative sign as well... //Gray et al (1991) had their equ. right. double x = gamma + beta * pow((-log(1 - y)), (1 / alpha)); //Inverted Weibull function return x; } double Weibull(double t, double tb, double tm, double b1, double b2, double b3, double b4) { double w; double tau; double x, y; x = (t - tb); y = (tm - tb); _ASSERTE(y != 0); _ASSERTE(b4 != 0); _ASSERTE(/*(x!=0)&&*/(y != 0)); tau = x / y; if ((tau >= .01) && (tau <= .99)) { w = (double)(b1*(1 / (1 + exp(b2 - tau * b3)) - exp((tau - 1) / b4))); } else w = 0; return w; } double Linearize(double x2, double x1, double y1, double x3, double y3) { _ASSERTE(x1 != x3); // x1 = x3 => not a function double m, b, y2 = 0; m = (y3 - y1) / (x3 - x1); b = y1 - m * x1; y2 = m * x2 + b; return y2; } double zScore(void) { //Polar method for producing two normal deviates via polar method by D. Knuth, // volume 3, p. 117 double u1, u2, v1, v2, s, x, a; do { u1 = Randu(); u2 = Randu(); v1 = 2 * u1 - 1; v2 = 2 * u2 - 1; s = (double)(pow(v1, 2) + pow(v2, 2)); } while (s >= 1); _ASSERTE(s > 0); a = (double)sqrt(-2 * log(s) / s); x = v1 * a; return x; } double Polynom(double x, int degree, const double *coeffs) { double sum = 0.0; while (degree >= 0) { sum += (double)(coeffs[degree] * pow(x, degree)); degree--; } return sum; } double Schoolfield(const double p[NB_SCHOOLFIELD_PARAMETERS], double T) { const double R = 1.987; double Tk = T + 273.15; double a1 = p[SF_PRHO25] * Tk / 298.15; double a2 = exp(p[SF_PHA] / R * (1 / 298.15 - 1 / Tk)); double b1 = exp(p[SF_PHL] / R * (1 / p[SF_PTL] - 1 / Tk)); double b2 = exp(p[SF_PHH] / R * (1 / p[SF_PTH] - 1 / Tk)); double r = (a1*a2) / (1 + b1 + b2); ASSERT(r >= 0); return r; } // Visit http://www.johndcook.com/stand_alone_code.html for the source of this code and more like it. // We require x > 0 double Gamma(double x) { ASSERT(x > 0); // Split the function domain into three intervals: // (0, 0.001), [0.001, 12), and (12, infinity) /////////////////////////////////////////////////////////////////////////// // First interval: (0, 0.001) // // For small x, 1/Gamma(x) has power series x + gamma x^2 - ... // So in this range, 1/Gamma(x) = x + gamma x^2 with error on the order of x^3. // The relative error over this interval is less than 6e-7. const double gamma = 0.577215664901532860606512090; // Euler's gamma constant if (x < 0.001) return 1.0 / (x*(1.0 + gamma * x)); /////////////////////////////////////////////////////////////////////////// // Second interval: [0.001, 12) if (x < 12.0) { // The algorithm directly approximates gamma over (1,2) and uses // reduction identities to reduce other arguments to this interval. double y = x; int n = 0; bool arg_was_less_than_one = (y < 1.0); // Add or subtract integers as necessary to bring y into (1,2) // Will correct for this below if (arg_was_less_than_one) { y += 1.0; } else { n = static_cast<int> (floor(y)) - 1; // will use n later y -= n; } // numerator coefficients for approximation over the interval (1,2) static const double p[] = { -1.71618513886549492533811E+0, 2.47656508055759199108314E+1, -3.79804256470945635097577E+2, 6.29331155312818442661052E+2, 8.66966202790413211295064E+2, -3.14512729688483675254357E+4, -3.61444134186911729807069E+4, 6.64561438202405440627855E+4 }; // denominator coefficients for approximation over the interval (1,2) static const double q[] = { -3.08402300119738975254353E+1, 3.15350626979604161529144E+2, -1.01515636749021914166146E+3, -3.10777167157231109440444E+3, 2.25381184209801510330112E+4, 4.75584627752788110767815E+3, -1.34659959864969306392456E+5, -1.15132259675553483497211E+5 }; double num = 0.0; double den = 1.0; int i; double z = y - 1; for (i = 0; i < 8; i++) { num = (num + p[i])*z; den = den * z + q[i]; } double result = num / den + 1.0; // Apply correction if argument was not initially in (1,2) if (arg_was_less_than_one) { // Use identity gamma(z) = gamma(z+1)/z // The variable "result" now holds gamma of the original y + 1 // Thus we use y-1 to get back the orginal y. result /= (y - 1.0); } else { // Use the identity gamma(z+n) = z*(z+1)* ... *(z+n-1)*gamma(z) for (i = 0; i < n; i++) result *= y++; } return result; } /////////////////////////////////////////////////////////////////////////// // Third interval: [12, infinity) if (x > 171.624) { // Correct answer too large to display. Force +infinity. //double temp = DBL_MAX; return std::numeric_limits<double>::infinity(); } return exp(LogGamma(x)); } // x must be positive double LogGamma(double x) { ASSERT(x > 0); if (x < 12.0) { return log(fabs(Gamma(x))); } // Abramowitz and Stegun 6.1.41 // Asymptotic series should be good to at least 11 or 12 figures // For error analysis, see Whittiker and Watson // A Course in Modern Analysis (1927), page 252 static const double c[8] = { 1.0 / 12.0, -1.0 / 360.0, 1.0 / 1260.0, -1.0 / 1680.0, 1.0 / 1188.0, -691.0 / 360360.0, 1.0 / 156.0, -3617.0 / 122400.0 }; double z = 1.0 / (x*x); double sum = c[7]; for (int i = 6; i >= 0; i--) { sum *= z; sum += c[i]; } double series = sum / x; static const double halfLogTwoPi = 0.91893853320467274178032973640562; double logGamma = (x - 0.5)*log(x) - x + halfLogTwoPi + series; return logGamma; } double StringToCoord(const std::string& coordStr) { double coord = 0; double a = 0, b = 0, c = 0; int nbVal = sscanf(coordStr.c_str(), "%lf %lf %lf", &a, &b, &c); if (nbVal == 1) { //decimal degree coord = a; } else if (nbVal >= 2 && nbVal <= 3) { //degree minute if (a >= -360 && a <= 360 && b >= 0 && b <= 60 && c >= 0 && c <= 60) coord = GetDecimalDegree((long)a, (long)b, c); } return coord; } std::string CoordToString(double coord, int prec) { double mult = pow(10.0, prec); std::string deg = ToString(GetDegrees(coord, mult)); std::string min = ToString(GetMinutes(coord, mult)); std::string sec = ToString(GetSeconds(coord, mult), prec); if (sec == "0" || sec == "-0") sec.clear(); if (sec.empty() && (min == "0" || min == "-0")) min.clear(); std::string str = deg + " " + min + " " + sec; Trim(str); return str; } //************************************************************************************************************************** //Humidity function //latent heat of vaporisation (J/kg) //Tair: dry bulb air temperature [°C] //L: J kg-1 at T = 273.15 K double GetL(double Tair) { double T = Tair + 273.15; double a = (2.501E6 - 2.257E6) / (273.15 - 373.15); double b = 2.501E6 - a * 273.15; double L = a * T + b; return L; //J kg-1 } void GetWindUV(double windSpeed, double windDir, double& U, double &V, bool from) { ASSERT(windSpeed >= 0 && windSpeed < 150); ASSERT(windDir >= 0 && windDir <= 360); double d = Deg2Rad(90 - windDir); double x = cos(d)*windSpeed; double y = sin(d)*windSpeed; ASSERT(fabs(sqrt(Square(x) + Square(y)) - windSpeed) < 0.0001); U = from ? -x : x; V = from ? -y : y; if (fabs(U) < 0.1) U = 0; if (fabs(V) < 0.1) V = 0; } double GetWindDirection(double u, double v, bool from) { double d = (180 / PI)*(atan2(u, v)); ASSERT(d >= -180 && d <= 180); if (from) d = int(d + 360 + 180) % 360; else d = int(d + 360) % 360; return d; } // //Excel = 0.6108 * exp(17.27*T / (T + 237.3)) //hourly vapor pressure //T : temperature [°C] //e°: saturation vapor pressure function [kPa] double eᵒ(double T) { return 0.6108 * exp(17.27*T / (T + 237.3));//Same as CASCE_ETsz } //daily vapor pressure double eᵒ(double Tmin, double Tmax) { return (eᵒ(Tmax) + eᵒ(Tmin)) / 2; } //Relative humidity [%] to dew point [°C] //Excel formula: =Min( T, (1/(1/(T+273.15) - (461*ln(max(0.0,Min(100,RH))/100))/2.5E6))-273.15) //Tair: temperature of dry bulb [°C] //Hr: relative humidity [%] double Hr2Td(double Tair, double Hr) { _ASSERTE(Tair > -999); _ASSERTE(Hr >= 0 && Hr <= 101); Hr = max(1.0, Hr);//limit to avoid division by zero double L = GetL(Tair); //(J/kg) //static const double L = 2.453E6; static const double Rv = 461; //constant for moist air (J/kg) double T = Tair + 273.15; double Td = 1 / (1 / T - (Rv*log(Hr / 100)) / L); _ASSERTE(Td - 273.15 > -99 && Td - 273.15 < 99); return min(Tair, Td - 273.15); } //Dew point teprature [°C] to relative humidity [%] //Excel formula: =max(0.0, Min(100, exp( 2.5E6/461*(1/(T+273.15) - 1/Min(T+273.15, Td+273.15)))*100)) //Tair: Temperature of dry bulb [°C] //Tdew: Dew point temperature [°C] double Td2Hr(double Tair, double Tdew) { double L = GetL(Tair); //J/kg static const double Rv = 461; //J/kg double T = Tair + 273.15; double Td = min(T, Tdew + 273.15); double Hr = exp(L / Rv * (1 / T - 1 / Td)); _ASSERTE(Hr >= 0 && Hr <= 1); return Hr * 100; } static const double Ra = 287.058; // Specific gas constant for dry air J/(kg·K) static const double Rw = 461.495; // Specific gas constant for water vapor J/(kg·K) static const double Ma = 0.028964;//Molar mass of dry air, kg/mol static const double Mw = 0.018016;//Molar mass of water vapor, kg/mol static const double R = 8.314; //Universal gas constant J/(K·mol) static const double M = Mw / Ma; // 0.6220135 //Td : dew point temperature [°C] //Pv : vapor pressure [kPa] double Td2Pv(double Td) { //return Pv(Td) * 1000; //from : http://www.conservationphysics.org/atmcalc/atmoclc2.pdf return 0.61078 * exp(17.2694*Td / (Td + 238.3)); } //Pv : vapor pressure [kPa] //Td : dew point temperature [°C] double Pv2Td(double Pv) { //from : http://www.conservationphysics.org/atmcalc/atmoclc2.pdf return (241.88 * log(Pv / 0.61078)) / (17.558 - log(Pv / 0.61078)); } //mixing ratio ( kg[H2O]/kg[dry air] ) to specific humidity ( g(H²O)/kg(air) ) //MR: g[H2O]/kg[dry air] //Hs: g(H²O)/kg(air) double MR2Hs(double MR) { return 1000 * (MR / (1000 * (1 + MR / 1000)));//Mixing ratio to Specific humidity [ g(H²O)/kg(air) ] } //specific humidity ( g(H²O)/kg(air) ) to mixing ratio ( g[H2O]/kg[dry air] ) //Hs: specific humidity g(H²O)/kg(air) //MR: mixing ratio g[H2O]/kg[dry air] double Hs2MR(double Hs) { return 1000 * (Hs / (1000 * (1 - Hs / 1000))); //specific humidity g(H²O)/kg(air) to mixing ratio g[H2O]/kg[dry air] } //Relative humidity [%] to specific humidity [ g(H²O)/kg(air) ] //From wikipedia : http://en.wikipedia.org/wiki/Humidity //validation was made with RH WMO without correction of the site : http://www.humidity-calculator.com/index.php //and also http://www.cactus2000.de/uk/unit/masshum.shtml //Tair: Dry bulb temperature [°C] //Hr: Relative humidity WMO (over water) [%] //altitude: altitude [m] double Hr2Hs(double Tair, double Hr) { _ASSERTE(Hr >= 0 && Hr <= 100); double Pv = Hr2Pv(Tair, Hr); return Pv2Hs(Pv); //double Psat = GetPsat(Tair);//Vapor pressure of water [Pa] //double Pv = Psat*Hr/100; //Vapor pressure [Pa] //double MR = M*Pv/(P-Pv);//Mixing ratio [ kg[H2O]/kg[dry air] ] //double Hs = MR/(1+MR);//Mixing ratio to Specific humidity [ kg(H²O)/kg(air) ] //return Hs*1000; //convert to [ g(H²O)/kg(air) ] } //hourly specific humidity [ g(H²O)/kg(air) ] to relative humidity [%] //Tair: air temperature °C //Hs: specific humidity g(H²O)/kg(air) double Hs2Hr(double Tair, double Hs) { _ASSERTE(Hs > 0); double Pv = Hs2Pv(Hs); return Pv2Hr(Tair, Pv); } //daily specific humidity [ g(H²O)/kg(air) ] to relative humidity [%] //Tmin: Daily minimum air temperature °C //Tmax: Daily maximum air temperature °C //Hs: Specific humidity g(H²O)/kg(air) double Hs2Hr(double Tmin, double Tmax, double Hs) { _ASSERTE(Hs > 0); double Pv = Hs2Pv(Hs); return Pv2Hr(Tmin, Tmax, Pv); } //Daily relative humidity [%] to specific humidity [ g(H²O)/kg(air) ] //Tmin: Daily minimum air temperature °C //Tmax: Daily maximum air temperature °C //Hr: Relative humidity (over water) [%] double Hr2Hs(double Tmin, double Tmax, double Hr) { _ASSERTE(Hr >= 0 && Hr <= 100); double Pv = Hr2Pv(Tmin, Tmax, Hr); return Pv2Hs(Pv); } //Pv : vapor pressure [Pa] double Pv2Hr(double Tair, double Pv) { double Psat = eᵒ(Tair) * 1000;//kPa --> Pa double Hr = 100 * Pv / Psat; return max(0.0, min(100.0, Hr)); } //Tair: air temperature [°C] //Hr: relativce humidity [%] //Pv : vapor pressure [Pa] double Hr2Pv(double Tair, double Hr) { ASSERT(Hr >= 0 && Hr <= 100); double Psat = eᵒ(Tair) * 1000;//kPa --> Pa double Pv = Psat * Hr / 100.0; return Pv; } double Pv2Hr(double Tmin, double Tmax, double Pv) { double Psat = eᵒ(Tmin, Tmax) * 1000;//kPa --> Pa double Hr = 100 * Pv / Psat; return max(0.0, min(100.0, Hr)); } //Tmin: Daily minimum air temperature [°C] //Tmax: Daily maximum air temperature [°C] //Hr: Relative humidity [%] double Hr2Pv(double Tmin, double Tmax, double Hr) { ASSERT(Hr >= 0 && Hr <= 100); double Psat = eᵒ(Tmin, Tmax) * 1000;//kPa --> Pa double Pv = Hr * Psat / 100; return Pv; } //Pv2Hs: vapor pressure [Pa] to Specific Humidity (g(H²O)/kg(air)) //Pv: partial pressure of water vapor in moist air [Pa] double Pv2Hs(double Pv) { double P = 101325;//[Pa] double Hs = (M*Pv) / (P - Pv * (1 - M)); ASSERT(Hs >= 0); return Hs * 1000;//Convert to g(H²O)/kg(air) } //Pv2Hs: vapor pressure ([Pa]) to Specific Humidity ( g(H²O)/kg(air) ) //Pv: partial pressure of water vapor in moist air [Pa] //Excel formala: = (101325 * (Hs/1000)) / (0.6220135 + (Hs /1000 )* (1 - 0.6220135)) double Hs2Pv(double Hs) { double P = 101325;//Pa Hs /= 1000;//Convert to kg(H²O)/kg(air) double Pv = (P*Hs) / (M + Hs * (1 - M)); return Pv; } //Tair: dry bulb air temperature [°C] //Hs: specific humidity ( g(H²O)/kg(air) ) //Out: Dew point temperature [°C] double Hs2Td(double Tair, double Hs) { double Hr = Hs2Hr(Tair, Hs); return Hr2Td(Tair, Hr); } //Tair: dry bulb air temperature [°C] //Tdew: dewpoint temperature [°C] double Td2Hs(double Tair, double Tdew) { double Hr = Td2Hr(Tair, Tdew); return Hr2Hs(Tair, Hr); } //Wet-Bulb Temperature from Relative Humidity and Air Temperature //Roland Stull //University of British Columbia, Vancouver, British Columbia, Canada //T: dry air temperature [°C] //Hr: relativce humidity [%] //Twb: wet bulb temperature [°C] double Hr2Twb(double T, double RH) { ASSERT(RH >= 0 && RH <= 100); double Twb = T * atan(0.151977*sqrt(RH + 18.313659)) + atan(T + RH) - atan(RH - 1.676331) + 0.00391838*pow(RH, 3.0 / 2)*atan(0.023101*RH) - 4.686035; return Twb; } //Relative humidity from temperature and wet bulb temperature //Tair: dry bulb temperature of air [°C] //Twet : wet bulb temperature [°C] double Twb2Hr(double Tair, double Twet) { static const double Cp = 1.005; //specific heat of dry air at constant pressure(J/g) ~1.005 J/g static const double Cpv = 4.186; //specific heat of water vapor at constant pressure(J/g) ~4.186 J/g static const double P = 1013; //atmospheric pressure at surface ~1013 mb at sea-level //Latent heat of vaporization(J/g) ~2500 J/g double Lv = GetL(Tair) / 1000; //saturation vapor pressure at the wet bulb temperature(hPa) double Eswb = 6.11*pow(10.0, 7.5*Twet / (237.7 + Twet)); //If you know the air temperature and the wet bulb temperature, you first want to calculate the actual mixing ratio of the air(W) using the following formula. //W=actual mixing ratio of air //(12) W=[(Tair-Twb)(Cp)-Lv(Eswb/P)]/[-(Tc-Twb)(Cpv)-Lv] double W = ((Tair - Twet)*Cp - Lv * (Eswb / P)) / (-(Tair - Twet)*Cpv - Lv); //Once you have the actual vapor pressure, you can use the following formula to calculate the saturation mixing ratio for the air. //(13) Ws=Es/P double Es = 6.11*pow(10.0, 7.5*Tair / (237.7 + Tair)); double Ws = Es / P; //Once you have the actual mixing ratio and the saturation mixing ratio, you can use the following formula to calculate relative humidity. //(14) Relative Humidity(RH) in percent=(W/Ws)*100 double RH = (W / Ws) * 100; //Note: The latent heat of vaporization(Lv) varies slightly with temperature. The value given above is an approximate value for the standard atmosphere at 0 degrees Celsius. //Note: Due to the large numbers of approximations using these formulas, your final answer may vary by as much as 10 percent. return RH; } //alt : altitude [m] //P : normal atmoshpheric pressure [Pa] double GetPressure(double alt) { // daily atmospheric pressure (Pa) as a function of elevation (m) // From the discussion on atmospheric statics in: // Iribane, J.V., and W.L. Godson, 1981. Atmospheric Thermodynamics, 2nd // Edition. D. Reidel Publishing Company, Dordrecht, The Netherlands. (p. 168) static const double MA = 28.9644e-3; // (kg mol-1) molecular weight of air static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant static const double LR_STD = 0.0065; // (-K m-1) standard temperature lapse rate static const double G_STD = 9.80665; // (m s-2) standard gravitational accel. static const double P_STD = 101325.0; // (Pa) standard pressure at 0.0 m elevation static const double T_STD = 288.15; // (K) standard temp at 0.0 m elevation double t1 = 1.0 - (LR_STD * alt) / T_STD; double t2 = G_STD / (LR_STD * (R / MA)); double P = P_STD * pow(t1, t2); return P; } //P : normal atmoshpheric pressure [Pa] //alt : altitude [m] double GetAltitude(double P) { // daily atmospheric pressure (Pa) as a function of elevation (m) // From the discussion on atmospheric statics in: // Iribane, J.V., and W.L. Godson, 1981. Atmospheric Thermodynamics, 2nd // Edition. D. Reidel Publishing Company, Dordrecht, The Netherlands. (p. 168) static const double MA = 28.9644e-3; // (kg mol-1) molecular weight of air static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant static const double LR_STD = 0.0065; // (-K m-1) standard temperature lapse rate static const double G_STD = 9.80665; // (m s-2) standard gravitational accel. static const double P_STD = 101325.0; // (Pa) standard pressure at 0.0 m elevation static const double T_STD = 288.15; // (K) standard temp at 0.0 m elevation double t2 = G_STD / (LR_STD * (R / MA)); double t1 = pow(P / P_STD, 1 / t2); double alt = (1.0 - t1)*T_STD / LR_STD; return alt; } double GetPolarInterpol(double T0, double T1, double T2, double h) { double Tair = 0; if (h < 12) { Tair = T0 + h * (T1 - T0) / 11.0; } else { Tair = T1 + (h - 12)*(T2 - T1) / 11.0; } return Round(Tair, 1); } double GetPolarSummer(double Tmin[3], double Tmax[3], double h) { return WBSF::GetDoubleSine(Tmin, Tmax, h, 05, 16); } double GetPolarWinter(double Tmin[3], double Tmax[3], double h) { double Tair[3] = { (Tmin[0] + Tmax[0]) / 2, (Tmin[1] + Tmax[1]) / 2, (Tmin[2] + Tmax[2]) / 2 }; double T[3] = { (Tair[0] < Tair[1]) ? Tmin[1] : Tmax[1], (Tair[0] < Tair[1]) ? Tmax[1] : Tmin[1], (Tair[1] < Tair[2]) ? Tmin[2] : Tmax[2], }; return GetPolarInterpol(T[0], T[1], T[2], h); } // original from Parton (1981), corrected by Brandsma (2006) //from : Application of nearest-neighbor resampling for homogenizing temperature records on a daily to sub - daily level //Brandsma (2006) double GetSineExponential(double Tmin[3], double Tmax[3], double t, double Tsr, double Tss, size_t method) { ASSERT(method < NB_SINE_EXP); double Tair = 0; double D = Tss - Tsr; if (D > 22) { //because of the correction, SineExponential can be use when day is 24 hour //we used Ebrs instead Tair = WBSF::GetSinePower(Tmin, Tmax, t, Tsr, Tss); } else { //Tsr = ceil(Tsr); //Tss = floor(Tss); //Tsr = floor(Tsr); //Tss = ceil(Tss); //Tsr = Round(Tsr); //Tss = Round(Tss); //D = Tss - Tsr; static const double ALPHA[NB_SINE_EXP] = { 2.59, 1.86 }; static const double BETA[NB_SINE_EXP] = { 1.55, 0.00 }; static const double GAMMA[NB_SINE_EXP] = { 2.20, 2.20 }; double alpha = ALPHA[method]; double beta = BETA[method]; double gamma = GAMMA[method]; //double Tn = Tsr;// +beta; if (t < Tsr) { //compute temperature at nightime before midnight //double fs = D / (D + 2 * a); double fs = (Tss - Tsr - beta) / (D + 2 * (alpha - beta)); assert(sin(PI*fs) >= 0); double Tsun = float(Tmin[0] + (Tmax[0] - Tmin[0])*sin(PI*fs)); double f = min(0.0, -gamma * (t + 24 - Tss) / (24 - D + beta)); double fo = min(0.0, -gamma * (Tsr + 24 - Tss) / (24 - D + beta)); //double f = min(0.0, -b*(t + 24 - Tss) / (24 - D)); //double f° = min(0.0, -b*(Tsr + 24 - Tss) / (24 - D)); double rho = (Tmin[1] - Tsun * exp(fo)) / (1 - exp(fo)); Tair = rho + (Tsun - rho)*exp(f); ASSERT(Tair >= rho || Tair >= Tsun); ASSERT(f <= 0); ASSERT(f <= 0); } else if (t <= Tss) { //compute daylight (equation 3a) double f = max(0.0, (t - Tsr - beta) / (D + 2 * (alpha - beta))); //double f = (t - Tsr) / (D + 2 * a); assert(sin(PI*f) >= 0); Tair = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*f); ASSERT(Tair >= Tmin[1]); } else //compute nightime (equation 1) { double fs = (Tss - Tsr - beta) / (D + 2 * (alpha - beta)); //double fs = D / (D + 2 * a); assert(sin(PI*fs) >= 0); double Tsun = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*fs); double f = min(0.0, -gamma * (t - Tss) / (24 - D + beta)); double fo = min(0.0, -gamma * (Tsr + 24 - Tss) / (24 - D + beta)); //double f = min(0.0, -b*(t - Tss) / (24 - D)); //double f° = min(0.0, -b*(Tsr + 24 - Tss) / (24 - D)); ASSERT(f <= 0 && fo <= 0); double rho = (Tmin[2] - Tsun * exp(fo)) / (1 - exp(fo)); Tair = rho + (Tsun - rho)*exp(f); ASSERT(Tair >= rho || Tair >= Tsun); } } return Round(Tair, 1); } double GetErbs(double Tmin[3], double Tmax[3], double t) { size_t i = t < 14 ? 1 : 2; size_t ii = t < 05 ? 0 : 1; double Tmin² = Tmin[i]; double Tmax² = Tmax[ii]; double mean = (Tmin² + Tmax²) / 2; double range = Tmax² - Tmin²; double a = 2 * PI*t / 24; double c = 0.4632*cos(a - 3.805) + 0.0984*cos(2 * a - 0.36) + 0.0168*cos(3 * a - 0.822) + 0.0138*cos(4 * a - 3.513); double Tair = mean + range * c; return Round(Tair, 1); } double GetSinePower(double Tmin[3], double Tmax[3], double t, double Tsr, double Tss) { double Tair = 0; double D = Tss - Tsr; //Tsr = Round(Tsr); //Tss = Round(Tss); //Tsr = ceil(Tsr); //Tss = floor(Tss); //D = Tss - Tsr; static const double a = 1.86;//savage2015 static const double b = 1.0 / 2.0; //compute nightime (modified equation 1) if (t < Tsr || t > Tss) { size_t i = t < Tsr ? 0 : 1; size_t ii = t < Tsr ? 1 : 2; double fs = D / (D + 2 * a); assert(sin(PI*fs) >= 0); double Tsun = float(Tmin[i] + (Tmax[i] - Tmin[i])*sin(PI*fs)); if (t < Tsr) t += 24; double f = max(0.0, (t - Tss) / (24 - D)); Tair = Tsun + (Tmin[ii] - Tsun)*pow(f, b); ASSERT(Tair >= Tmin[ii] || Tair >= Tsun); } else { double f = (t - Tsr) / (D + 2 * a); assert(sin(PI*f) >= 0); Tair = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*f); ASSERT(Tair >= Tmin[1]); } //else //compute nightime (equation 1) //{ // double fs = D / (D + 2 * a); // assert(sin(PI*fs) >= 0); // double Tsun = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*fs); // double f = max(0.0, (t - Tss) / (24 - D)); // Tair = Tsun + (Tmin[2] - Tsun)*pow(f, 1.0 / 2); // ASSERT(Tair >= Tmin[2] || Tair >= Tsun); //} //} return Round(Tair, 1); } //compute AllenWave temperature for one hour double GetDoubleSine(double Tmin[3], double Tmax[3], double h, double hourTmin, double hourTmax) { _ASSERTE(hourTmin < hourTmax); //force to arrive on extrem if (fabs(h - hourTmin) <= 0.5) h = hourTmin; if (fabs(h - hourTmax) <= 0.5) h = hourTmax; size_t i = h < hourTmin ? 0 : 1; size_t ii = h <= hourTmax ? 1 : 2; double Tmax² = Tmax[i]; double Tmin² = Tmin[ii]; double mean = (Tmin² + Tmax²) / 2; double range = Tmax² - Tmin²; //double theta = ((int)h - time_factor)*r_hour; double theta = 0; if (h >= hourTmin && h <= hourTmax) { //from Tmin to Tmax //size_t hh = (24 + h - hourTmin) % 24; double hh = h - hourTmin; double nbh = hourTmax - hourTmin; theta = PI * (-0.5 + hh / nbh); } else { //From Tmax to Tmin //size_t hh = (24 + h - hourTmax) % 24; if (h < hourTmax) h += 24; double hh = h - hourTmax; double nbh = 24 - (hourTmax - hourTmin); theta = PI * (0.5 - hh / nbh); } //round at .1 return Round(mean + range / 2 * sin(theta), 1); } //mean_sea_level to atmospheric pressure (at elevation) //po : mean sea level [kPa] double msl2atp(double po, double h) { //https://en.wikipedia.org/wiki/Atmospheric_pressure static const double M = 28.9644e-3; // (kg mol-1) molecular weight of air static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant static const double L = 0.0065; // (K/m) standard temperature lapse rate static const double g = 9.80665; // (m s-2) standard gravitational accel. static const double To = 288.15; // (K) standard temp at 0.0 m elevation const double a = 1 - (L*h) / To; const double b = (g*M) / (R*L); return po * pow(a, b); //return 1013 * pow((293 - 0.0065*elev) / 293, 5.26);//pressure at elevation [hPa] or [mbar] } //p : atmospheric pressure [kPa] double atp2msl(double p, double h) {//https://en.wikipedia.org/wiki/Atmospheric_pressure static const double M = 28.9644e-3; // (kg mol-1) molecular weight of air static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant static const double L = 0.0065; // (K/m) standard temperature lapse rate static const double g = 9.80665; // (m s-2) standard gravitational accel. static const double To = 288.15; // (K) standard temp at 0.0 m elevation const double a = 1 - (L*h) / To; const double b = (g*M) / (R*L); return p / pow(a, b); } //Constants: //NL = 6.0221415·1023 mol-1 Avogadro constant NIST //R = 8.31447215 J mol-1 K-1 Universal gas constant NIST //MH2O = 18.01534 g mol-1 molar mass of water //Mdry 28.9644 g mol-1 molar mass of dry air //http://www.gorhamschaffler.com/humidity_formulas.htm //E: actual vapor pressure(kPa) //double GetTd(double E) //{ // double Td=(-430.22+237.7*log(E*10))/(-log(E*10)+19.08); // return Td; ////} //\begin{ align }P_{ s:m }(T) &= a\exp\bigg(\left(b - \frac{ T }{d}\right)\left(\frac{ T }{c + T}\right)\bigg); \\[8pt] //\gamma_m(T, R\!H) &= \ln\Bigg(\frac{ R\!H }{100}\exp //\bigg(\left(b - \frac{ T }{d}\right)\left(\frac{ T }{c + T}\right)\bigg) //\Bigg); \\ //T_{ dp } &= \frac{ c\gamma_m(T, R\!H) }{b - \gamma_m(T, R\!H)}; \end{ align } //(where \scriptstyle{ //a = 6.1121 [hKa] //b = 18.678 //c = 257.14 [°C] //d = 234.5 [°C] //There are several different constant sets in use.The ones used in NOAA's //******************************************************************* //Randomize void Randomize(unsigned rand) { //time_t t; //srand((unsigned) time(&t)); if (rand == unsigned(0)) srand((unsigned)time(NULL)); else srand((unsigned)rand); } //returns a double on the interval [0,1] /*double Randu(void) { double u,x; x = (double) rand(); u = x/RAND_MAX; _ASSERTE ((u>=0)&&(u<=1)); return u; }*/ //returns a double on the interval //[0,1] : rand()/RAND_MAX //]0,1] : (rand()+1)/(RAND_MAX+1) //[0,1[ : rand()/(RAND_MAX+1) //]0,1[ : (rand()+1)/(RAND_MAX+2) double Randu(bool bExcLower, bool bExcUpper) { double numerator = (double)rand(); double denominator = (double)RAND_MAX; if (bExcLower) { numerator++; denominator++; } if (bExcUpper) denominator++; double u = numerator / denominator; _ASSERTE(bExcLower || (u >= 0)); _ASSERTE(!bExcLower || (u > 0)); _ASSERTE(bExcUpper || (u <= 1)); _ASSERTE(!bExcUpper || (u < 1)); return u; } //special case of randu double RanduExclusif(void) { return Randu(true, true); } //returns an integer on the range [0,num] int Rand(int num) { double x = (num + 1)*Randu(false, true); return (int)x; } //returns an integer on the interval [l,u] or [l,u[ or ]l,u] or ]l,u[ int Rand(int l, int u) { if (l > u) Switch(l, u); _ASSERTE(l <= u); //get a number [0, u-l] and add l return l + Rand(u - l); } double Rand(double l, double u) { if (l > u) Switch(l, u); _ASSERTE(l <= u); //get a number [0, u-l] and add l return l + (u - l)*Randu(); } double RandNormal(const double x, const double s) { return x + (zScore()*s); } double RandLogNormal(double x, double s) { return exp(RandNormal(x - Square(s) / 2.0, s)); } /************************** * erf.cpp * author: Steve Strand * written: 29-Jan-04 ***************************/ //#include <iostream.h> //#include <iomanip.h> //#include <strstream.h> //#include <math.h> /* static const double rel_error= 1E-12; //calculate 12 significant figures //you can adjust rel_error to trade off between accuracy and speed //but don't ask for > 15 figures (assuming usual 52 bit mantissa in a double) double erf(double x) //erf(x) = 2/sqrt(pi)*integral(exp(-t^2),t,0,x) // = 2/sqrt(pi)*[x - x^3/3 + x^5/5*2! - x^7/7*3! + ...] // = 1-erfc(x) { static const double two_sqrtpi= 1.128379167095512574; // 2/sqrt(pi) if (fabs(x) > 2.2) { return 1.0 - erfc(x); //use continued fraction when fabs(x) > 2.2 } double sum= x, term= x, xsqr= x*x; int j= 1; do { term*= xsqr/j; sum-= term/(2*j+1); ++j; term*= xsqr/j; sum+= term/(2*j+1); ++j; } while (fabs(term)/sum > rel_error); return two_sqrtpi*sum; } double erfc(double x) //erfc(x) = 2/sqrt(pi)*integral(exp(-t^2),t,x,inf) // = exp(-x^2)/sqrt(pi) * [1/x+ (1/2)/x+ (2/2)/x+ (3/2)/x+ (4/2)/x+ // = 1-erf(x) //expression inside [] is a continued fraction so '+' means add to denominator only { static const double one_sqrtpi= 0.564189583547756287; // 1/sqrt(pi) if (fabs(x) < 2.2) { return 1.0 - erf(x); //use series when fabs(x) < 2.2 } //if (signbit(x)) { //continued fraction only valid for x>0 if (x>-DBL_MAX && x<-DBL_MIN) { return 2.0 - erfc(-x); } double a=1, b=x; //last two convergent numerators double c=x, d=x*x+0.5; //last two convergent denominators double q1=0,q2=b/d; //last two convergents (a/c and b/d) double n= 1.0, t; do { t= a*n+b*x; a= b; b= t; t= c*n+d*x; c= d; d= t; n+= 0.5; q1= q2; q2= b/d; } while (fabs(q1-q2)/q2 > rel_error); return one_sqrtpi*exp(-x*x)*q2; } */ static const double rel_error = 1E-12; //calculate 12 significant figures //you can adjust rel_error to trade off between accuracy and speed //but don't ask for > 15 figures (assuming usual 52 bit mantissa in a double) double erf(double x) //erf(x) = 2/sqrt(pi)*integral(exp(-t^2),t,0,x) // = 2/sqrt(pi)*[x - x^3/3 + x^5/5*2! - x^7/7*3! + ...] // = 1-erfc(x) { static const double two_sqrtpi = 1.128379167095512574; // 2/sqrt(pi) if (fabs(x) > 2.2) { return 1.0 - erfc(x); //use continued fraction when fabs(x) > 2.2 } double sum = x, term = x, xsqr = x * x; int j = 1; do { term *= xsqr / j; sum -= term / (2 * j + 1); ++j; term *= xsqr / j; sum += term / (2 * j + 1); ++j; } while (fabs(term / sum) > rel_error); // CORRECTED LINE return two_sqrtpi * sum; } double erfc(double x) //erfc(x) = 2/sqrt(pi)*integral(exp(-t^2),t,x,inf) // = exp(-x^2)/sqrt(pi) * [1/x+ (1/2)/x+ (2/2)/x+ (3/2)/x+ (4/2)/x+ ...] // = 1-erf(x) //expression inside [] is a continued fraction so '+' means add to denominator only { static const double one_sqrtpi = 0.564189583547756287; // 1/sqrt(pi) if (fabs(x) < 2.2) { return 1.0 - erf(x); //use series when fabs(x) < 2.2 } if (x > -DBL_MAX && x < -DBL_MIN) { //continued fraction only valid for x>0 return 2.0 - erfc(-x); } double a = 1, b = x; //last two convergent numerators double c = x, d = x * x + 0.5; //last two convergent denominators double q1, q2 = b / d; //last two convergents (a/c and b/d) double n = 1.0, t; do { t = a * n + b * x; a = b; b = t; t = c * n + d * x; c = d; d = t; n += 0.5; q1 = q2; q2 = b / d; } while (fabs(q1 - q2) / q2 > rel_error); return one_sqrtpi * exp(-x * x)*q2; } /*double TestExposure(double latDeg, double slopeDeg, double aspectDeg) { ASSERT( latDeg>=-90 && latDeg<=90); ASSERT( slopeDeg>=0 && slopeDeg<=90); ASSERT( aspectDeg>=0 && aspectDeg<=360); double latitude = Deg2Rad(latDeg); double slope = Deg2Rad(slopeDeg); double aspect = Deg2Rad(180-aspectDeg); double SRI = cos(latitude)*cos(slope) + sin(latitude)*sin(slope)*cos(aspect); return SRI; } */ double GetExposition(double latDeg, double slopePourcent, double aspectDeg) { double SRI = 0; if (slopePourcent != -999 && aspectDeg != -999 && slopePourcent != 0 && aspectDeg != 0) { double slopeDeg = Rad2Deg(atan(slopePourcent / 100)); ASSERT(latDeg >= -90 && latDeg <= 90); ASSERT(slopeDeg >= 0 && slopeDeg <= 90); ASSERT(aspectDeg >= 0 && aspectDeg <= 360); double latitude = Deg2Rad(latDeg); double slope = Deg2Rad(slopeDeg); double aspect = Deg2Rad(180 - aspectDeg); SRI = cos(latitude)*cos(slope) + sin(latitude)*sin(slope)*cos(aspect); } return SRI; //******************************** // _ASSERTE( slopePourcent >= 0); // _ASSERTE(aspect >= 0 && aspect <= 360); // // //Sin et cos carré // double cosLat² = Square(cos(lat*DEG2RAD)); // double sinLat² = Square(sin(lat*DEG2RAD)); // //// double fPente = DEG_PER_RAD * asin( fPentePourcent / 100 ); // //slope in degree // double slope = RAD2DEG*atan( slopePourcent/100 ); // ASSERT( slope == Rad2Deg(atan( slopePourcent/100 )) ); // ASSERT(slope>=0 && slope<=90 ); // // // int nPhi = ((aspect < 135) || (aspect >= 255))?1:-1; // // return slope*(cosLat²*nPhi + sinLat²*cos((aspect - 15)*DEG2RAD)); } void ComputeSlopeAndAspect(double latDeg, double exposition, double& slopePourcent, double& aspect) { //double fCosLat2 = cos(Deg2Rad(lat)); fCosLat2 *= fCosLat2; //double fSinLat2 = sin(Deg2Rad(lat)); fSinLat2 *= fSinLat2; double slope = 0; int nbRun = 0; if (latDeg != 0) { double latitude = Deg2Rad(latDeg); aspect = -1; //double slope = 0; double denominateur = 0; do { slope = Rand(0.0, 89.0); slope = Deg2Rad(slope); //aspect = (float)Rand(0.0, 360.0); //int nPhi = ((aspect < 135) || (aspect >= 255))?1:-1; //_ASSERT(false); // a revoir avex la nouvelle exposition //denominateur = (fCosLat2*nPhi + fSinLat2*cos(Deg2Rad(aspect - 15))); denominateur = sin(latitude)*sin(slope); if (denominateur != 0) { double tmp = (exposition - cos(latitude)*cos(slope)) / denominateur; if (tmp >= -1 && tmp <= 1) { aspect = float(180 - Rad2Deg(acos(tmp))); //slopePourcent = (float)tan( slope )*100; //double test = GetExposition(latDeg, slopePourcent, aspect); } } //else //{ //aspect can be anything //aspect = 0; //} //slope = exposition/denominateur; nbRun++; } while (nbRun < 500 && (denominateur == 0 || aspect < 0 || aspect>359)); if (nbRun == 500) { slope = 0; aspect = 0; } } else { ASSERT(exposition >= -1 && exposition <= 1); slope = acos(exposition); } //fPentePourcent = (float)sin( fPente/DEG_PER_RAD )*100; slopePourcent = (float)tan(slope) * 100; _ASSERTE(slopePourcent >= 0);//&& fPentePourcent <= 100 ); _ASSERTE(nbRun == 500 || fabs(exposition - GetExposition(latDeg, slopePourcent, aspect)) < 0.001); } double GetDistance(double lat1, double lon1, double lat2, double lon2) { double angle = 0; if (lat1 != lat2 || lon1 != lon2) { double P = (fabs(lon2 - lon1) <= 180) ? (lon2 - lon1) : (360.0 - fabs(lon2 - lon1)); double cosA = sin(lat1*DEG2RAD)*sin(lat2*DEG2RAD) + cos(lat1*DEG2RAD)*cos(lat2*DEG2RAD)*cos(P*DEG2RAD); angle = acos(std::max(-1.0, std::min(1.0, cosA))); } return angle * 6371 * 1000; } bool IsValidSlopeWindow(float window[3][3], double noData) { int nbNoData = 0; for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { if (window[y][x] <= noData) { nbNoData++; window[y][x] = window[1][1]; } } } //We don't need the center cell to compute slope and aspect //then if it's only the center cell that are missing we return true anyway return window[1][1] > noData || nbNoData == 1; } void GetSlopeAndAspect(float window[3][3], double ewres, double nsres, double scale, double& slope, double& aspect) { //slope = 0; //aspect = 0; //if( !IsValidSlopeWindow(window) ) //return; double dx = ((window[0][2] + window[1][2] + window[1][2] + window[2][2]) - (window[0][0] + window[1][0] + window[1][0] + window[2][0])) / ewres; double dy = ((window[0][0] + window[0][1] + window[0][1] + window[0][2]) - (window[2][0] + window[2][1] + window[2][1] + window[2][2])) / nsres; double key = (dx * dx + dy * dy); slope = (float)(100 * (sqrt(key) / (8 * scale))); aspect = (float)(atan2(dy, -dx) * RAD2DEG); if (dx == 0 && dy == 0) { // lat area aspect = 0; } else //transform from azimut angle to geographic angle { if (aspect > 90.0f) aspect = 450.0f - aspect; else aspect = 90.0f - aspect; } if (aspect == 360.0) aspect = 0.0f; } //************************************************************** const double CMathEvaluation::EPSILON = 0.000001; CMathEvaluation::CMathEvaluation(const char* strIn) { ASSERT(strIn != NULL); string str(strIn); size_t pos = str.find_first_not_of("!=<>"); ASSERT(pos >= 0); m_op = GetOp(str.substr(0, pos)); m_value = ToValue<double>(str.substr(pos)); } short CMathEvaluation::GetOp(const string& str) { short op = UNKNOWN; if (str == "==") op = EQUAL; else if (str == "!=") op = NOT_EQUAL; else if (str == ">=") op = GREATER_EQUAL; else if (str == "<=") op = LOWER_EQUAL; else if (str == ">") op = GREATER; else if (str == "<") op = LOWER; return op; } bool CMathEvaluation::Evaluate(double value1, short op, double value2) { bool bRep = false; switch (op) { case EQUAL: bRep = fabs(value1 - value2) < EPSILON; break; case NOT_EQUAL: bRep = !Evaluate(value1, EQUAL, value2); break; case GREATER_EQUAL: bRep = value1 >= value2; break; case LOWER_EQUAL: bRep = value1 <= value2; break; case GREATER: bRep = value1 > value2; break; case LOWER: bRep = value1 < value2; break; default: ASSERT(false); } return bRep; } //******************************************************************************************** void CBetaDistribution::SetTable(double alpha, double beta) { int i; double tmp; double sum_P = 0; //Compute Beta cumulative probability distribution m_XP[0].m_x = 0; m_XP[0].m_p = 0; for (i = 1; i <= 50; ++i) { tmp = (double)i / 50.; m_XP[i].m_x = tmp; if (i == 50) tmp = 0.995; sum_P += pow(tmp, alpha - 1) * pow((1 - tmp), beta - 1); m_XP[i].m_p = sum_P; } //Scale so P is [0,1] for (i = 0; i <= 50; ++i) { m_XP[i].m_p /= sum_P; } } double CBetaDistribution::XfromP(double p)const { _ASSERTE(p >= 0.0 && p <= 1.0); double x = 0; for (int i = 49; i >= 0; --i) { if (p > m_XP[i].m_p) { double slope = (m_XP[i + 1].m_x - m_XP[i].m_x) / (m_XP[i + 1].m_p - m_XP[i].m_p); x = m_XP[i].m_x + (p - m_XP[i].m_p)* slope; break; } } ASSERT(!_isnan(x)); ASSERT(x >= 0); return x; } double CSchoolfield::operator[](double T)const { const double R = 1.987; double Tk = T + 273.15; double a1 = m_p[PRHO25] * Tk / 298.15; double a2 = exp(m_p[PHA] / R * (1 / 298.15 - 1 / Tk)); double b1 = exp(m_p[PHL] / R * (1 / m_p[PTL] - 1 / Tk)); double b2 = exp(m_p[PHH] / R * (1 / m_p[PTH] - 1 / Tk)); double r = (a1*a2) / (1 + b1 + b2); ASSERT(r >= 0); return r; } double CUnknown::operator[](double T)const { ASSERT(T >= -40 && T < 40); double Fo = m_p[PA] + m_p[PB] * pow(fabs(T - m_p[PT0]), m_p[PX]); return max(0.0, Fo); } /*unsigned int good_seed() { unsigned int random_seed, random_seed_a, random_seed_b; std::ifstream file ("/dev/urandom", std::ios::binary); if (file.is_open()) { char * memblock; int size = sizeof(int); memblock = new char [size]; file.read (memblock, size); file.close(); random_seed_a = *reinterpret_cast<int*>(memblock); delete[] memblock; }// end if else { random_seed_a = 0; } random_seed_b = std::time(0); random_seed = random_seed_a xor random_seed_b; std::cout << "random_seed_a = " << random_seed_a << std::endl; std::cout << "random_seed_b = " << random_seed_b << std::endl; std::cout << " random_seed = " << random_seed << std::endl; return random_seed; } // end good_seed() */ void CRandomGenerator::Randomize(size_t seed) { if (seed == RANDOM_SEED) { static unsigned long ID = 1; //seed = static_cast<unsigned long>(std::time(NULL)+ID*1000); seed = static_cast<unsigned long>(__rdtsc() + ID * 1000); ID++; m_gen.seed((ULONG)seed); } else { m_gen.seed((ULONG)seed); } } }//namespace WBSF
27.407407
176
0.554741
RNCan
9ad6a8505f14e03c3def5a20acdd37af0be43ce6
2,092
cpp
C++
test/TestHelpers/ClangCompileHelper.cpp
ptensschi/CppUMockGen
d11f12297688f99863238b263f241b6e3ac66dfd
[ "BSD-3-Clause" ]
null
null
null
test/TestHelpers/ClangCompileHelper.cpp
ptensschi/CppUMockGen
d11f12297688f99863238b263f241b6e3ac66dfd
[ "BSD-3-Clause" ]
null
null
null
test/TestHelpers/ClangCompileHelper.cpp
ptensschi/CppUMockGen
d11f12297688f99863238b263f241b6e3ac66dfd
[ "BSD-3-Clause" ]
1
2019-01-10T20:36:24.000Z
2019-01-10T20:36:24.000Z
#include "ClangCompileHelper.hpp" #include "ClangHelper.hpp" #include <iostream> bool ClangCompileHelper::CheckCompilation( const std::string &testedHeader, const std::string &testedSource ) { #ifdef DISABLE_COMPILATION_CHECK return true; #else CXIndex index = clang_createIndex( 0, 0 ); const char* clangOpts[] = { "-xc++", "-I" CPPUTEST_INCLUDE_DIR }; std::string compiledCode = "#include <CppUTest/TestHarness.h>\n" "#include <CppUTestExt/MockSupport.h>\n"; #ifdef INTERPRET_C compiledCode += "extern \"C\" {"; #endif compiledCode += testedHeader + "\n"; #ifdef INTERPRET_C compiledCode += "}"; #endif compiledCode += testedSource; CXUnsavedFile unsavedFiles[] = { { "test_mock.cpp", compiledCode.c_str(), (unsigned long) compiledCode.length() } }; CXTranslationUnit tu = clang_parseTranslationUnit( index, "test_mock.cpp", clangOpts, std::extent<decltype(clangOpts)>::value, unsavedFiles, std::extent<decltype(unsavedFiles)>::value, CXTranslationUnit_None ); if( tu == nullptr ) { clang_disposeIndex( index ); throw std::runtime_error( "Error creating translation unit" ); } unsigned int numDiags = clang_getNumDiagnostics(tu); if( numDiags > 0 ) { std::cerr << std::endl; std::cerr << "---------------- Error compiling --------------" << std::endl; std::cerr << compiledCode << std::endl; std::cerr << "-----------------------------------------------" << std::endl; for( unsigned int i = 0; i < numDiags; i++ ) { CXDiagnostic diag = clang_getDiagnostic( tu, i ); std::cerr << clang_formatDiagnostic( diag, clang_defaultDiagnosticDisplayOptions() ) << std::endl; clang_disposeDiagnostic( diag ); } } clang_disposeTranslationUnit( tu ); clang_disposeIndex( index ); return ( numDiags == 0 ); #endif }
34.295082
121
0.5674
ptensschi
9ad71a08b9b66a7fd19a1b166b84d41e177fb8f0
5,249
hpp
C++
uwc_common/uwc_util/include/ZmqHandler.hpp
aditisa1/uwc
637b3888bb617b4f44c4818d4d62d5c822cd683d
[ "MIT" ]
4
2021-07-16T23:03:56.000Z
2021-10-21T19:04:12.000Z
uwc_common/uwc_util/include/ZmqHandler.hpp
aditisa1/uwc
637b3888bb617b4f44c4818d4d62d5c822cd683d
[ "MIT" ]
24
2021-07-23T15:49:18.000Z
2022-03-30T18:24:51.000Z
uwc_common/uwc_util/include/ZmqHandler.hpp
vanidesai/uwc
637b3888bb617b4f44c4818d4d62d5c822cd683d
[ "MIT" ]
7
2021-07-22T08:55:52.000Z
2022-02-07T08:56:40.000Z
/******************************************************************************** * Copyright (c) 2021 Intel Corporation. * 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. *********************************************************************************/ /*** ZmqHandler.hpp is To prepare and manage context related information for ZMQ communication*/ #ifndef INCLUDE_INC_ZMQHANDLDER_HPP_ #define INCLUDE_INC_ZMQHANDLDER_HPP_ #include <string> #include <map> #include <functional> #include <mutex> #include "cjson/cJSON.h" #include <eii/utils/thread_safe_queue.h> #include <eii/utils/config.h> #include <eii/utils/json_config.h> #include <eii/msgbus/msgbus.h> //eii configmgr #include "eii/config_manager/config_mgr.hpp" // uwc configmgr #include "ConfigManager.hpp" #include "CommonDataShare.hpp" #include "LibErrCodeManager.hpp" /** removepubctx.. keep that & as local variable*/ /** return ctx from creating */ extern std::function<bool(std::string, std::string)> regExFun; /** zmq_handler is a namespace holding context regarding information and functions for zmq communication*/ namespace zmq_handler { /** structure maintain context related information*/ struct stZmqContext { void *m_pContext;/**msg bus context*/ std::mutex m_mutex; /** mutex for msg*/ stZmqContext(void *a_pContext):m_pContext{a_pContext}, m_mutex{} {;}; stZmqContext(const stZmqContext &a_copy):m_pContext{a_copy.m_pContext}, m_mutex{} {;}; stZmqContext& operator=(const stZmqContext &a_copy)=delete; }; /** structure maintaining zmq publish context*/ struct stZmqPubContext { void *m_pContext; /**msg bus context*/ }; /** structure maintaining zmq subscribe context*/ struct stZmqSubContext { recv_ctx_t* sub_ctx; /** sub context*/ }; /** * Prepare all EII contexts for zmq communications based on topic configured in * SubTopics or PubTopics section from docker-compose.yml file * Following is the sequence of context creation * 1. Get the topic from SubTopics/PubTopics section * 2. Create msgbus config * 3. Create the msgbus context based on msgbus config * 4. Once msgbus context is successful then create pub and sub context for zmq publisher/subscriber * * @param topicType :[in] topic type to create context for, value is either "sub" or "pub" * @return true : on success, * false : on error */ bool prepareCommonContext(std::string topicType); bool prepareContext(bool a_bIsPub, void* msgbus_ctx, std::string a_sTopic, config_t *config); /** function to set topic for different operations*/ bool setTopicForOperation(std::string a_sTopic); /** function to get message bus context based on topic*/ stZmqContext& getCTX(std::string str_Topic); /** function to insert new entry in map*/ void insertCTX(std::string, stZmqContext& ); /** function to remove entry from the map once reply is sent*/ void removeCTX(std::string); /** function to get message bus context based on topic*/ stZmqSubContext& getSubCTX(std::string str_Topic); /** function to insert new entry in map*/ void insertSubCTX(std::string, stZmqSubContext ); /** function to remove entry from the map once reply is sent*/ void removeSubCTX(std::string); /** function to get message bus publish context based on topic*/ stZmqPubContext& getPubCTX(std::string str_Topic); /** function to insert new entry in map*/ bool insertPubCTX(std::string, stZmqPubContext ); /** function to remove entry from the map*/ void removePubCTX(std::string); /** function to publish json data on ZMQ*/ bool publishJson(std::string &a_sUsec, msg_envelope_t* msg, const std::string &a_sTopic, std::string a_sPubTimeField); /** * function to return all pub/sub topics * @param topicType : [in] pub or sub * @param vector : [out] vector of topics of pub/sub * @return bool : true for success. false for failure **/ bool returnAllTopics(std::string topicType, std::vector<std::string>& vecTopics); /** * function to return number of pub/sub topics * @param topicType : [in] pub or sub * @return size_t : [out] count of publishers or subscribers **/ size_t getNumPubOrSub(std::string topicType); } #endif /* INCLUDE_INC_ZMQHANDLDER_HPP_ */
36.451389
119
0.714803
aditisa1
9adbde8d8df6929094dbf124677a1d4183c57238
3,073
cpp
C++
Publications/DPC++/Ch14_common_parallel_patterns/fig_14_18-20_inclusive_scan.cpp
tiwaria1/oneAPI-samples
18310adf63c7780715f24034acfb0bf01d15521f
[ "MIT" ]
310
2020-07-09T01:00:11.000Z
2022-03-31T17:52:14.000Z
Publications/DPC++/Ch14_common_parallel_patterns/fig_14_18-20_inclusive_scan.cpp
tiwaria1/oneAPI-samples
18310adf63c7780715f24034acfb0bf01d15521f
[ "MIT" ]
438
2020-06-30T23:25:19.000Z
2022-03-31T00:37:13.000Z
Publications/DPC++/Ch14_common_parallel_patterns/fig_14_18-20_inclusive_scan.cpp
junxnone/oneAPI-samples
f414747b5676688d690655c6043b71577027fc19
[ "MIT" ]
375
2020-06-04T22:58:24.000Z
2022-03-30T11:04:18.000Z
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: MIT #include <CL/sycl.hpp> #include <algorithm> #include <cstdio> #include <cstdlib> #include <iostream> #include <numeric> #include <random> using namespace sycl; template <typename T, int dimensions> using local_accessor = accessor<T, dimensions, access::mode::read_write, access::target::local>; int main() { queue q; const size_t N = 128; const size_t L = 16; const size_t G = N / L; int32_t* input = malloc_shared<int32_t>(N, q); int32_t* output = malloc_shared<int32_t>(N, q); std::iota(input, input + N, 1); std::fill(output, output + N, 0); // Create a temporary allocation that will only be used by the device int32_t* tmp = malloc_device<int32_t>(G, q); // Phase 1: Compute local scans over input blocks q.submit([&](handler& h) { auto local = local_accessor<int32_t, 1>(L, h); h.parallel_for(nd_range<1>(N, L), [=](nd_item<1> it) { int i = it.get_global_id(0); int li = it.get_local_id(0); // Copy input to local memory local[li] = input[i]; it.barrier(); // Perform inclusive scan in local memory for (int32_t d = 0; d <= log2((float)L) - 1; ++d) { uint32_t stride = (1 << d); int32_t update = (li >= stride) ? local[li - stride] : 0; it.barrier(); local[li] += update; it.barrier(); } // Write the result for each item to the output buffer // Write the last result from this block to the temporary buffer output[i] = local[li]; if (li == it.get_local_range()[0] - 1) { tmp[it.get_group(0)] = local[li]; } }); }).wait(); // Phase 2: Compute scan over partial results q.submit([&](handler& h) { auto local = local_accessor<int32_t, 1>(G, h); h.parallel_for(nd_range<1>(G, G), [=](nd_item<1> it) { int i = it.get_global_id(0); int li = it.get_local_id(0); // Copy input to local memory local[li] = tmp[i]; it.barrier(); // Perform inclusive scan in local memory for (int32_t d = 0; d <= log2((float)G) - 1; ++d) { uint32_t stride = (1 << d); int32_t update = (li >= stride) ? local[li - stride] : 0; it.barrier(); local[li] += update; it.barrier(); } // Overwrite result from each work-item in the temporary buffer tmp[i] = local[li]; }); }).wait(); // Phase 3: Update local scans using partial results q.parallel_for(nd_range<1>(N, L), [=](nd_item<1> it) { int g = it.get_group(0); if (g > 0) { int i = it.get_global_id(0); output[i] += tmp[g - 1]; } }).wait(); // Check that all outputs match serial execution bool passed = true; int32_t gold = 0; for (int i = 0; i < N; ++i) { gold += input[i]; if (output[i] != gold) { passed = false; } } std::cout << ((passed) ? "SUCCESS" : "FAILURE") << "\n"; free(tmp, q); free(output, q); free(input, q); return (passed) ? 0 : 1; }
27.19469
77
0.5685
tiwaria1
9adc96be6da2e72d5bbd72bc81c6703360f88afa
2,076
cpp
C++
code/random/functions.cpp
adm244/mwsilver
d88ebb240095f0bd0adfe3cc983fa504d974ba83
[ "Unlicense" ]
null
null
null
code/random/functions.cpp
adm244/mwsilver
d88ebb240095f0bd0adfe3cc983fa504d974ba83
[ "Unlicense" ]
null
null
null
code/random/functions.cpp
adm244/mwsilver
d88ebb240095f0bd0adfe3cc983fa504d974ba83
[ "Unlicense" ]
null
null
null
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. */ //IMPORTANT(adm244): SCRATCH VERSION JUST TO GET IT UP WORKING #ifndef RANDOM_FUNCTIONS_CPP #define RANDOM_FUNCTIONS_CPP #include "random/randomlib.c" internal int randomGenerated = 0; internal uint8 randomCounters[MAX_BATCHES]; internal void RandomClearCounters() { randomGenerated = 0; for( int i = 0; i < MAX_BATCHES; ++i ) { randomCounters[i] = 0; } } internal int GetNextBatchIndex(int batchesCount) { if( randomGenerated >= batchesCount ) { RandomClearCounters(); } int value; for( ;; ) { value = RandomInt(0, batchesCount - 1); if( randomCounters[value] == 0 ) break; } ++randomGenerated; randomCounters[value] = 1; return value; } internal void RandomGeneratorInitialize(int batchesCount) { int ticksPassed = GetTickCount(); int ij = ticksPassed % 31328; int kj = ticksPassed % 30081; RandomInitialize(ij, kj); RandomClearCounters(); } #endif
28.054054
71
0.753854
adm244
9ae01cf510cfe3101db22d06c44216aaff943420
7,302
cc
C++
centreon-engine/tests/test_engine.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
8
2020-07-26T09:12:02.000Z
2022-03-30T17:24:29.000Z
centreon-engine/tests/test_engine.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
47
2020-06-18T12:11:37.000Z
2022-03-16T10:28:56.000Z
centreon-engine/tests/test_engine.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
5
2020-06-29T14:22:02.000Z
2022-03-17T10:34:10.000Z
/* * Copyright 2019 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ #include "test_engine.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/timeperiod.hh" #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/modules/external_commands/commands.hh" using namespace com::centreon::engine; using namespace com::centreon::engine::downtimes; configuration::contact TestEngine::new_configuration_contact( std::string const& name, bool full, const std::string& notif) const { if (full) { // Add command. { configuration::command cmd; cmd.parse("command_name", "cmd"); cmd.parse("command_line", "true"); configuration::applier::command aplyr; aplyr.add_object(cmd); } // Add timeperiod. { configuration::timeperiod tperiod; tperiod.parse("timeperiod_name", "24x7"); tperiod.parse("alias", "24x7"); tperiod.parse("monday", "00:00-24:00"); tperiod.parse("tuesday", "00:00-24:00"); tperiod.parse("wednesday", "00:00-24:00"); tperiod.parse("thursday", "00:00-24:00"); tperiod.parse("friday", "00:00-24:00"); tperiod.parse("saterday", "00:00-24:00"); tperiod.parse("sunday", "00:00-24:00"); configuration::applier::timeperiod aplyr; aplyr.add_object(tperiod); } } // Valid contact configuration // (will generate 0 warnings or 0 errors). configuration::contact ctct; ctct.parse("contact_name", name.c_str()); ctct.parse("host_notification_period", "24x7"); ctct.parse("service_notification_period", "24x7"); ctct.parse("host_notification_commands", "cmd"); ctct.parse("service_notification_commands", "cmd"); ctct.parse("host_notification_options", "d,r,f,s"); ctct.parse("service_notification_options", notif.c_str()); ctct.parse("host_notifications_enabled", "1"); ctct.parse("service_notifications_enabled", "1"); return ctct; } configuration::contactgroup TestEngine::new_configuration_contactgroup( std::string const& name, std::string const& contactname) { configuration::contactgroup cg; cg.parse("contactgroup_name", name.c_str()); cg.parse("alias", name.c_str()); cg.parse("members", contactname.c_str()); return cg; } configuration::serviceescalation TestEngine::new_configuration_serviceescalation( std::string const& hostname, std::string const& svc_desc, std::string const& contactgroup) { configuration::serviceescalation se; se.parse("first_notification", "2"); se.parse("last_notification", "11"); se.parse("notification_interval", "9"); se.parse("escalation_options", "w,u,c,r"); se.parse("host_name", hostname.c_str()); se.parse("service_description", svc_desc.c_str()); se.parse("contact_groups", contactgroup.c_str()); return se; } configuration::hostdependency TestEngine::new_configuration_hostdependency( std::string const& hostname, std::string const& dep_hostname) { configuration::hostdependency hd; hd.parse("master_host", hostname.c_str()); hd.parse("dependent_host", dep_hostname.c_str()); hd.parse("notification_failure_options", "u,d"); hd.parse("inherits_parent", "1"); hd.dependency_type(configuration::hostdependency::notification_dependency); return hd; } configuration::servicedependency TestEngine::new_configuration_servicedependency( std::string const& hostname, std::string const& service, std::string const& dep_hostname, std::string const& dep_service) { configuration::servicedependency sd; sd.parse("master_host", hostname.c_str()); sd.parse("master_description", service.c_str()); sd.parse("dependent_host", dep_hostname.c_str()); sd.parse("dependent_description", dep_service.c_str()); sd.parse("notification_failure_options", "u,w,c"); sd.dependency_type(configuration::servicedependency::notification_dependency); return sd; } configuration::host TestEngine::new_configuration_host( std::string const& hostname, std::string const& contacts, uint64_t hst_id) { configuration::host hst; hst.parse("host_name", hostname.c_str()); hst.parse("address", "127.0.0.1"); hst.parse("_HOST_ID", std::to_string(hst_id).c_str()); hst.parse("contacts", contacts.c_str()); configuration::command cmd("hcmd"); cmd.parse("command_line", "echo 0"); hst.parse("check_command", "hcmd"); configuration::applier::command cmd_aply; cmd_aply.add_object(cmd); return hst; } configuration::hostescalation TestEngine::new_configuration_hostescalation( std::string const& hostname, std::string const& contactgroup, uint32_t first_notif, uint32_t last_notif, uint32_t interval_notif) { configuration::hostescalation he; he.parse("first_notification", std::to_string(first_notif).c_str()); he.parse("last_notification", std::to_string(last_notif).c_str()); he.parse("notification_interval", std::to_string(interval_notif).c_str()); he.parse("escalation_options", "d,u,r"); he.parse("host_name", hostname.c_str()); he.parse("contact_groups", contactgroup.c_str()); return he; } configuration::service TestEngine::new_configuration_service( std::string const& hostname, std::string const& description, std::string const& contacts, uint64_t svc_id) { configuration::service svc; svc.parse("host_name", hostname.c_str()); svc.parse("description", description.c_str()); svc.parse("_HOST_ID", "12"); svc.parse("_SERVICE_ID", std::to_string(svc_id).c_str()); svc.parse("contacts", contacts.c_str()); // We fake here the expand_object on configuration::service svc.set_host_id(12); configuration::command cmd("cmd"); cmd.parse("command_line", "echo 'output| metric=12;50;75'"); svc.parse("check_command", "cmd"); configuration::applier::command cmd_aply; cmd_aply.add_object(cmd); return svc; } configuration::anomalydetection TestEngine::new_configuration_anomalydetection( std::string const& hostname, std::string const& description, std::string const& contacts, uint64_t svc_id, uint64_t dependent_svc_id, std::string const& thresholds_file) { configuration::anomalydetection ad; ad.parse("host_name", hostname.c_str()); ad.parse("description", description.c_str()); ad.parse("dependent_service_id", std::to_string(dependent_svc_id).c_str()); ad.parse("_HOST_ID", "12"); ad.parse("_SERVICE_ID", std::to_string(svc_id).c_str()); ad.parse("contacts", contacts.c_str()); ad.parse("metric_name", "metric"); ad.parse("thresholds_file", thresholds_file.c_str()); // We fake here the expand_object on configuration::service ad.set_host_id(12); return ad; }
34.937799
80
0.717338
centreon
9ae1a107777ee6b083cecdb1b1d22f709516f306
406
cpp
C++
admin/snapin/certmgr/snapmgr.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/snapin/certmgr/snapmgr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/snapin/certmgr/snapmgr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1997-2001. // // File: SnapMgr.cpp // // Contents: implementation file for Snapin Manager property page // // //---------------------------------------------------------------------------- #include "stdafx.h" #include "chooser.cpp"
23.882353
79
0.376847
npocmaka
9aea51745f3235fd439cd911bbe86c13eca10d38
12,965
cpp
C++
winmisc/shared/plugin.winmisc.cpp
ggcrunchy/solar2d-plugins
c3c9f41659ea64a1b04f992c3ca4b8549aa0dbe1
[ "MIT" ]
12
2020-05-04T08:49:04.000Z
2021-12-30T09:35:17.000Z
winmisc/shared/plugin.winmisc.cpp
ggcrunchy/solar2d-plugins
c3c9f41659ea64a1b04f992c3ca4b8549aa0dbe1
[ "MIT" ]
null
null
null
winmisc/shared/plugin.winmisc.cpp
ggcrunchy/solar2d-plugins
c3c9f41659ea64a1b04f992c3ca4b8549aa0dbe1
[ "MIT" ]
3
2021-02-19T18:39:02.000Z
2022-03-09T17:14:57.000Z
/* * 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. * * [ MIT license: http://www.opensource.org/licenses/mit-license.php ] */ #include "CoronaLua.h" #include <windows.h> #include <cstdlib> #include <vector> #define HWND_NAME "winmisc.window" static HWND GetWindow (lua_State * L, int arg = 1) { return *(HWND *)luaL_checkudata(L, arg, HWND_NAME); } template<typename T> int Box (lua_State * L, T item, const char * name) { if (item) { *static_cast<T *>(lua_newuserdata(L, sizeof(T))) = item; // ..., item luaL_newmetatable(L, HWND_NAME);// ..., item, mt lua_setmetatable(L, -2);// ..., item; item.metatable = mt } else lua_pushnil(L); // ..., nil return 1; } static bool GetBytesFromBitmap (lua_State * L, HDC hdc, HBITMAP hBitmap) { BITMAPINFO info = {}; bool ok = false; info.bmiHeader.biSize = sizeof(info.bmiHeader); if (GetDIBits(hdc, hBitmap, 0, 0, nullptr, &info, DIB_RGB_COLORS)) { // https://stackoverflow.com/a/3688682 std::vector<BYTE> bytes(info.bmiHeader.biSizeImage); LONG abs_height = abs(info.bmiHeader.biHeight); info.bmiHeader.biBitCount = 32; info.bmiHeader.biCompression = BI_RGB; info.bmiHeader.biHeight = -abs_height; ok = GetDIBits(hdc, hBitmap, 0, abs_height, bytes.data(), &info, DIB_RGB_COLORS); if (ok) { const BYTE * input = bytes.data(); LONG count = info.bmiHeader.biWidth * abs_height; std::vector<BYTE> out(count * 3); BYTE * output = out.data(); for (LONG i = 0; i < count; ++i) { output[0] = input[2]; output[1] = input[1]; output[2] = input[0]; output += 3; input += 4; } lua_pushlstring(L, reinterpret_cast<char *>(out.data()), out.size()); // image lua_pushinteger(L, info.bmiHeader.biWidth); // image, width lua_pushinteger(L, abs_height); // image, width, height } } ReleaseDC(NULL, hdc); return ok; } static BOOL CALLBACK EnumWindowsProc (HWND window, LPARAM lparam) { lua_State * L = reinterpret_cast<lua_State *>(lparam); lua_pushvalue(L, 1); // enumerator, enumerator Box(L, window, HWND_NAME); // enumerator, enumerator, window if (lua_pcall(L, 1, 1, 0) == 0) // enumerator, result? / err { lua_pushliteral(L, "done");// enumerator, result?, "done" if (!lua_equal(L, 2, 3)) { lua_pop(L, 2); // enumerator return TRUE; } } return FALSE; } CORONA_EXPORT int luaopen_plugin_winmisc (lua_State* L) { lua_newtable(L);// winmisc luaL_Reg funcs[] = { { "CopyScreenToClipboard", [](lua_State * L) { // https://stackoverflow.com/a/28248531 int x = GetSystemMetrics(SM_XVIRTUALSCREEN); int y = GetSystemMetrics(SM_YVIRTUALSCREEN); int w = GetSystemMetrics(SM_CXVIRTUALSCREEN); int h = GetSystemMetrics(SM_CYVIRTUALSCREEN); // copy screen to bitmap HDC hScreen = GetDC(nullptr); HDC hDC = CreateCompatibleDC(hScreen); HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h); HGDIOBJ old_obj = SelectObject(hDC, hBitmap); BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x, y, SRCCOPY); // save bitmap to clipboard OpenClipboard(nullptr); EmptyClipboard(); SetClipboardData(CF_BITMAP, hBitmap); CloseClipboard(); // clean up SelectObject(hDC, old_obj); DeleteDC(hDC); ReleaseDC(nullptr, hScreen); DeleteObject(hBitmap); return 0; } }, { "CopyWindowToClipboard", [](lua_State * L) { HWND window = GetWindow(L); HDC hScreen = GetDC(window); HDC hDC = CreateCompatibleDC(hScreen); RECT rect; GetWindowRect(window, &rect); LONG w = rect.right - rect.left, h = rect.bottom - rect.top; HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h); HGDIOBJ old_obj = SelectObject(hDC, hBitmap); BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, rect.left, rect.top, SRCCOPY); // save bitmap to clipboard OpenClipboard(nullptr); EmptyClipboard(); SetClipboardData(CF_BITMAP, hBitmap); CloseClipboard(); // clean up SelectObject(hDC, old_obj); DeleteDC(hDC); ReleaseDC(window, hScreen); DeleteObject(hBitmap); return 0; } }, { "EnumerateDesktops", [](lua_State * L) { lua_settop(L, 1); // enumerator luaL_argcheck(L, lua_isfunction(L, 1), 1, "Non-function desktop enumerator"); BOOL result = EnumDesktops(GetProcessWindowStation(), [](char * name, LPARAM state) { lua_State * lstate = reinterpret_cast<lua_State *>(state); lua_pushvalue(lstate, 1); // enumerator, enumerator lua_pushstring(lstate, name); // enumerator, enumerator, name if (lua_pcall(lstate, 1, 1, 0) == 0) // enumerator, result? / err { lua_pushliteral(lstate, "done");// enumerator, result?, "done" if (!lua_equal(lstate, 2, 3)) { lua_pop(lstate, 2); // enumerator return TRUE; } } return FALSE; }, LONG_PTR(L)); lua_pushboolean(L, result); // enumerator[, result[, "done"]], ok return 1; } }, { "EnumerateDesktopWindows", [](lua_State * L) { lua_settop(L, 2); // name, enumerator const char * name = luaL_checkstring(L, 1); luaL_argcheck(L, lua_isfunction(L, 2), 2, "Non-function desktop window enumerator"); HDESK desktop = OpenDesktop(name, 0, FALSE, GENERIC_READ); lua_remove(L, 1); // enumerator BOOL result = !!desktop; if (desktop) { result = EnumDesktopWindows(desktop, EnumWindowsProc, LONG_PTR(L)); CloseDesktop(desktop); } lua_pushboolean(L, result); // enumerator[, result[, "done"]], ok return 1; } }, { "EnumerateWindows", [](lua_State * L) { luaL_argcheck(L, lua_isfunction(L, 1), 1, "Non-function window enumerator"); BOOL result = EnumWindows(EnumWindowsProc, LONG_PTR(L)); lua_pushboolean(L, result); // enumerator[, result[, "done"]], ok return 1; } }, { "GetClipboardText", [](lua_State * L) { lua_settop(L, 0); // (empty) BOOL ok = FALSE; if (OpenClipboard(nullptr)) { HANDLE hMem = GetClipboardData(CF_TEXT); if (hMem) { void * data = GlobalLock(hMem); if (data) { ok = TRUE; lua_pushstring(L, (char *)data);// text GlobalUnlock(hMem); } } CloseClipboard(); } lua_pushboolean(L, ok); // [text, ]ok if (ok) lua_insert(L, -2); // ok, text return lua_gettop(L); } }, { "GetForegroundWindow", [](lua_State * L) { return Box(L, GetForegroundWindow(), HWND_NAME); } }, { "GetImageDataFromClipboard", [](lua_State * L) { bool ok = false; if (IsClipboardFormatAvailable(CF_BITMAP) && OpenClipboard(nullptr)) { HDC hdc = GetDC(nullptr); ok = GetBytesFromBitmap(L, hdc, (HBITMAP)GetClipboardData(CF_BITMAP)); CloseClipboard(); ReleaseDC(nullptr, hdc); } if (!ok) lua_pushboolean(L, 0); // false return ok ? 3 : 1; } }, { "GetImageDataFromScreen", [](lua_State * L) { int x = GetSystemMetrics(SM_XVIRTUALSCREEN); int y = GetSystemMetrics(SM_YVIRTUALSCREEN); int w = GetSystemMetrics(SM_CXVIRTUALSCREEN); int h = GetSystemMetrics(SM_CYVIRTUALSCREEN); // copy screen to bitmap HDC hScreen = GetDC(nullptr); HDC hDC = CreateCompatibleDC(hScreen); HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h); HGDIOBJ old_obj = SelectObject(hDC, hBitmap); BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x, y, SRCCOPY); bool ok = GetBytesFromBitmap(L, hDC, hBitmap); // clean up SelectObject(hDC, old_obj); DeleteDC(hDC); ReleaseDC(nullptr, hScreen); DeleteObject(hBitmap); if (!ok) lua_pushboolean(L, 0); // false return ok ? 3 : 1; } }, { "GetImageDataFromWindow", [](lua_State * L) { HWND window = GetWindow(L); HDC hScreen = GetDC(window); HDC hDC = CreateCompatibleDC(hScreen); RECT rect; GetWindowRect(window, &rect); LONG w = rect.right - rect.left, h = rect.bottom - rect.top; HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h); HGDIOBJ old_obj = SelectObject(hDC, hBitmap); BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, rect.left, rect.top, SRCCOPY); bool ok = GetBytesFromBitmap(L, hDC, hBitmap); // clean up SelectObject(hDC, old_obj); DeleteDC(hDC); ReleaseDC(window, hScreen); DeleteObject(hBitmap); if (!ok) lua_pushboolean(L, 0); // false return ok ? 3 : 1; } }, { "GetWindowText", [](lua_State * L) { HWND window = GetWindow(L); int len = GetWindowTextLength(window); std::vector<char> str(len + 1); GetWindowText(window, str.data(), len + 1); lua_pushlstring(L, str.data(), size_t(len));// window, text return 1; } }, { "IsWindowVisible", [](lua_State * L) { lua_pushboolean(L, IsWindowVisible(GetWindow(L))); // window, is_visible return 1; } }, { "SetClipboardText", [](lua_State * L) { BOOL ok = FALSE; if(OpenClipboard(nullptr)) { if(EmptyClipboard()) { HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, lua_objlen(L, 1) + 1); memcpy(GlobalLock(hMem), lua_tostring(L, 1), lua_objlen(L, 1) + 1); GlobalUnlock(hMem); ok = SetClipboardData(CF_TEXT, hMem) != nullptr; } CloseClipboard(); } lua_pushboolean(L, ok); // text, ok return 1; } }, { nullptr, nullptr } }; luaL_register(L, nullptr, funcs); return 1; }
30.650118
101
0.514925
ggcrunchy
9aeccd7619f02a5e8ac6121283591e62a7483674
4,694
cpp
C++
ardupilot/ArduCopter/esc_calibration.cpp
quadrotor-IITKgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
1
2021-07-17T11:37:16.000Z
2021-07-17T11:37:16.000Z
ardupilot/ArduCopter/esc_calibration.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
ardupilot/ArduCopter/esc_calibration.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include "Copter.h" /***************************************************************************** * esc_calibration.pde : functions to check and perform ESC calibration *****************************************************************************/ #define ESC_CALIBRATION_HIGH_THROTTLE 950 // enum for ESC CALIBRATION enum ESCCalibrationModes { ESCCAL_NONE = 0, ESCCAL_PASSTHROUGH_IF_THROTTLE_HIGH = 1, ESCCAL_PASSTHROUGH_ALWAYS = 2, ESCCAL_AUTO = 3, ESCCAL_DISABLED = 9, }; // check if we should enter esc calibration mode void Copter::esc_calibration_startup_check() { #if FRAME_CONFIG != HELI_FRAME // exit immediately if pre-arm rc checks fail pre_arm_rc_checks(); if (!ap.pre_arm_rc_check) { // clear esc flag for next time if ((g.esc_calibrate != ESCCAL_NONE) && (g.esc_calibrate != ESCCAL_DISABLED)) { g.esc_calibrate.set_and_save(ESCCAL_NONE); } return; } // check ESC parameter switch (g.esc_calibrate) { case ESCCAL_NONE: // check if throttle is high if (channel_throttle->control_in >= ESC_CALIBRATION_HIGH_THROTTLE) { // we will enter esc_calibrate mode on next reboot g.esc_calibrate.set_and_save(ESCCAL_PASSTHROUGH_IF_THROTTLE_HIGH); // send message to gcs gcs_send_text_P(MAV_SEVERITY_CRITICAL,PSTR("ESC Calibration: restart board")); // turn on esc calibration notification AP_Notify::flags.esc_calibration = true; // block until we restart while(1) { delay(5); } } break; case ESCCAL_PASSTHROUGH_IF_THROTTLE_HIGH: // check if throttle is high if (channel_throttle->control_in >= ESC_CALIBRATION_HIGH_THROTTLE) { // pass through pilot throttle to escs esc_calibration_passthrough(); } break; case ESCCAL_PASSTHROUGH_ALWAYS: // pass through pilot throttle to escs esc_calibration_passthrough(); break; case ESCCAL_AUTO: // perform automatic ESC calibration esc_calibration_auto(); break; case ESCCAL_DISABLED: default: // do nothing break; } // clear esc flag for next time if (g.esc_calibrate != ESCCAL_DISABLED) { g.esc_calibrate.set_and_save(ESCCAL_NONE); } #endif // FRAME_CONFIG != HELI_FRAME } // esc_calibration_passthrough - pass through pilot throttle to escs void Copter::esc_calibration_passthrough() { #if FRAME_CONFIG != HELI_FRAME // clear esc flag for next time g.esc_calibrate.set_and_save(ESCCAL_NONE); // reduce update rate to motors to 50Hz motors.set_update_rate(50); // send message to GCS gcs_send_text_P(MAV_SEVERITY_CRITICAL,PSTR("ESC Calibration: passing pilot throttle to ESCs")); while(1) { // arm motors motors.armed(true); motors.enable(); // flash LEDS AP_Notify::flags.esc_calibration = true; // read pilot input read_radio(); delay(10); // pass through to motors motors.throttle_pass_through(channel_throttle->radio_in); } #endif // FRAME_CONFIG != HELI_FRAME } // esc_calibration_auto - calibrate the ESCs automatically using a timer and no pilot input void Copter::esc_calibration_auto() { #if FRAME_CONFIG != HELI_FRAME bool printed_msg = false; // reduce update rate to motors to 50Hz motors.set_update_rate(50); // send message to GCS gcs_send_text_P(MAV_SEVERITY_CRITICAL,PSTR("ESC Calibration: auto calibration")); // arm and enable motors motors.armed(true); motors.enable(); // flash LEDS AP_Notify::flags.esc_calibration = true; // raise throttle to maximum delay(10); motors.throttle_pass_through(channel_throttle->radio_max); // wait for safety switch to be pressed while (hal.util->safety_switch_state() == AP_HAL::Util::SAFETY_DISARMED) { if (!printed_msg) { gcs_send_text_P(MAV_SEVERITY_CRITICAL,PSTR("ESC Calibration: push safety switch")); printed_msg = true; } delay(10); } // delay for 5 seconds delay(5000); // reduce throttle to minimum motors.throttle_pass_through(channel_throttle->radio_min); // clear esc parameter g.esc_calibrate.set_and_save(ESCCAL_NONE); // block until we restart while(1) { delay(5); } #endif // FRAME_CONFIG != HELI_FRAME }
30.679739
99
0.618662
quadrotor-IITKgp
9af0e6da4690501ad32249fcdf44fc6f93b6266d
861
hpp
C++
src/main/linux_verifier.hpp
NickCao/ebpf-verifier
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
[ "Apache-2.0", "MIT" ]
null
null
null
src/main/linux_verifier.hpp
NickCao/ebpf-verifier
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
[ "Apache-2.0", "MIT" ]
null
null
null
src/main/linux_verifier.hpp
NickCao/ebpf-verifier
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
[ "Apache-2.0", "MIT" ]
null
null
null
// Copyright (c) Prevail Verifier contributors. // SPDX-License-Identifier: MIT #pragma once #include "platform.hpp" #if __linux__ #include "etl/tuple.h" #include "etl/vector.h" #include "asm_syntax.hpp" #include "spec_type_descriptors.hpp" #include "linux/gpl/spec_type_descriptors.hpp" #include "ebpf_vm_isa.hpp" int create_map_linux(uint32_t map_type, uint32_t key_size, uint32_t value_size, uint32_t max_entries, ebpf_verifier_options_t options); etl::tuple<bool, double> bpf_verify_program(const EbpfProgramType& type, const etl::vector<ebpf_inst, SIZE_VEC>& raw_prog, ebpf_verifier_options_t* options); #else #define create_map_linux (nullptr) inline etl::tuple<bool, double> bpf_verify_program(EbpfProgramType type, const etl::vector<ebpf_inst, SIZE_VEC>& raw_prog, ebpf_verifier_options_t* options) { exit(64); return {{}, {}}; } #endif
29.689655
158
0.779326
NickCao
9af2ffea551526586de0251519d1ae9fac9ae037
587
cpp
C++
String/MaximumOccurence.cpp
sanp9/DSA-Questions
f265075b83f66ec696576be3eaa5517ee387d5cf
[ "MIT" ]
null
null
null
String/MaximumOccurence.cpp
sanp9/DSA-Questions
f265075b83f66ec696576be3eaa5517ee387d5cf
[ "MIT" ]
null
null
null
String/MaximumOccurence.cpp
sanp9/DSA-Questions
f265075b83f66ec696576be3eaa5517ee387d5cf
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; void maxOccur(string str) { int freq[26] = {0}; char ans = 'a'; int maxF = 0; for (int i = 0; i < str.length(); i++) { freq[str[i] - 'a']++; } // for maintaining the count of occurrences of characters for (int i = 0; i < 26; i++) { if (freq[i] > maxF) { maxF = freq[i]; ans = i + 'a'; } } cout << ans << endl; cout << maxF << endl; } int main() { string str; getline(cin, str); maxOccur(str); return 0; }
15.447368
63
0.46678
sanp9
9af63fd957bf2a9c951afd6267b2a04f4f4752b2
8,407
cpp
C++
binding-cpp/runtime/src/test/common/EtchHashTableTest.cpp
apache/etch
5a875755019a7f342a07c8c368a50e3efb6ae68c
[ "ECL-2.0", "Apache-2.0" ]
9
2015-02-14T15:09:54.000Z
2021-11-10T15:09:45.000Z
binding-cpp/runtime/src/test/common/EtchHashTableTest.cpp
apache/etch
5a875755019a7f342a07c8c368a50e3efb6ae68c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
binding-cpp/runtime/src/test/common/EtchHashTableTest.cpp
apache/etch
5a875755019a7f342a07c8c368a50e3efb6ae68c
[ "ECL-2.0", "Apache-2.0" ]
14
2015-04-20T10:35:00.000Z
2021-11-10T15:09:35.000Z
/* $Id$ * * 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 <gtest/gtest.h> #include "common/EtchHashTable.h" #include "common/EtchComparatorNative.h" #include "common/EtchHashNative.h" #include "common/EtchInt32.h" #include "common/EtchString.h" TEST(EtchHashTableTest, Constructor_Default){ EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); delete h1; EtchHashTable<char*, capu::int32_t, EtchComparatorNative, EtchHashNative >* h2 = new EtchHashTable<char*, capu::int32_t, EtchComparatorNative, EtchHashNative > (); delete h2; } TEST(EtchHashTableTest, put){ EtchString key("key1"); EtchInt32 value(5); status_t status = ETCH_OK; capu::uint64_t count = 5; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); // add new key status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); // check count count = h1->count(); EXPECT_TRUE(count == 1); EtchHashTable<char*, capu::int32_t, EtchComparatorNative, EtchHashNative >* h2 = new EtchHashTable<char*, capu::int32_t, EtchComparatorNative, EtchHashNative> (); // add new key char* key1 = const_cast<char*>("key1"); capu::int32_t value1 = 5; status = h2->put(key1, value1); EXPECT_TRUE(status == ETCH_OK); // check count count = h2->count(); EXPECT_TRUE(count == 1); delete h1; delete h2; } TEST(EtchHashTableTest, count){ EtchString key("key"); EtchInt32 value(5); capu::uint64_t count = 5; status_t status = ETCH_OK; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); //check count count = h1->count(); EXPECT_TRUE(count == 0); //add new keys status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); // check count count = h1->count(); EXPECT_TRUE(count == 1); delete h1; } TEST(EtchHashTableTest, get){ EtchString key("key"); EtchString key2("key2"); EtchInt32 value(5); status_t status = ETCH_OK; EtchInt32 return_value(-1); capu::uint64_t count = 5; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); // add new key status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); // check count count = h1->count(); EXPECT_TRUE(count == 1); // get the added element status = h1->get(key, &return_value); EXPECT_TRUE(status == ETCH_OK); //check its value EXPECT_TRUE(return_value.get() == value.get()); //get a element to null variable status = h1->get(key, NULL); EXPECT_TRUE(status == ETCH_EINVAL); //get an element of non existing key status = h1->get(key2, &return_value); EXPECT_TRUE(status == ETCH_ENOT_EXIST); EtchHashTable<char*, capu::int32_t, EtchComparatorNative, EtchHashNative >* h2 = new EtchHashTable<char*, capu::int32_t, EtchComparatorNative, EtchHashNative > (); // add new key char* key1 = const_cast<char*>("key1"); capu::int32_t value1 = 5; capu::int32_t return_value1; status = h2->put(key1, value1); EXPECT_TRUE(status == ETCH_OK); // get the added element status = h2->get(key1, &return_value1); EXPECT_TRUE(status == ETCH_OK); //check its value EXPECT_TRUE(return_value1 == value1); delete h1; delete h2; } TEST(EtchHashTableTest, clear){ EtchString key("key"); EtchString key2("key2"); EtchInt32 value(5); status_t status = ETCH_OK; capu::uint64_t count = 5; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); // add new keys status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); //add new keys status = h1->put(key2, value); EXPECT_TRUE(status == ETCH_OK); // check count count = h1->count(); EXPECT_TRUE(count == 2); //remove all status = h1->clear(); EXPECT_TRUE(status == ETCH_OK); //check count count = h1->count(); EXPECT_TRUE(count == 0); delete h1; } TEST(EtchHashTableTest, remove){ EtchString key("key"); EtchString key2("key2"); EtchInt32 value(5); status_t status = ETCH_OK; EtchInt32 return_value(-1); capu::uint64_t count = 5; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); // add new keys status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); //delete a non existing key status = h1->remove(key2, &return_value); EXPECT_TRUE(status == ETCH_ERANGE); //add new value status = h1->put(key2, value); EXPECT_TRUE(status == ETCH_OK); // check count count = h1->count(); EXPECT_TRUE(count == 2); //delete existing key status = h1->remove(key, &return_value); EXPECT_TRUE(status == ETCH_OK); EXPECT_TRUE(value.get() == return_value.get()); //check count count = h1->count(); EXPECT_TRUE(count == 1); delete h1; } TEST(EtchHashTableTest, put_get_existing){ EtchString key("key"); EtchString key2("key2"); EtchInt32 value(5); status_t status = ETCH_OK; EtchInt32 return_value(-1); capu::uint64_t count = 5; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); // add new keys status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); //add new value status = h1->put(key2, value); EXPECT_TRUE(status == ETCH_OK); value.set(3); //add new value over existing one status = h1->put(key, value, &return_value); EXPECT_TRUE(status == ETCH_OK); //check the retrieved old value EXPECT_TRUE(5 == return_value.get()); //check the new value status = h1->get(key, &return_value); EXPECT_TRUE(3 == return_value.get()); // check count count = h1->count(); EXPECT_TRUE(count == 2); delete h1; } TEST(EtchHashTableIterator, hasNext){ EtchString key("key"); EtchString key2("key2"); EtchInt32 value(5); status_t status = ETCH_OK; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); //create iterator EtchHashTable<EtchString, EtchInt32>::Iterator it = h1->begin(); //check hasNext EXPECT_TRUE(it.hasNext() == false); // add new keys status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); //add new value status = h1->put(key2, value); EXPECT_TRUE(status == ETCH_OK); it = h1->begin(); EXPECT_TRUE(it.hasNext() == true); delete h1; } TEST(EtchHashTableConstIterator, hasNext){ EtchString key("key"); EtchString key2("key2"); EtchInt32 value(5); status_t status = ETCH_OK; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); //create iterator EtchHashTable<EtchString, EtchInt32>::Iterator it = h1->begin(); //check hasNext EXPECT_TRUE(it.hasNext() == false); // add new keys status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); //add new value status = h1->put(key2, value); EXPECT_TRUE(status == ETCH_OK); it = h1->begin(); EXPECT_TRUE(it.hasNext() == true); delete h1; } TEST(EtchHashTableIterator, next){ EtchString key("key"); EtchString key2("key2"); EtchInt32 value(5); status_t status = ETCH_OK; EtchHashTable<EtchString, EtchInt32>* h1 = new EtchHashTable<EtchString, EtchInt32 > (); //create iterator EtchHashTable<EtchString, EtchInt32>::Iterator it = h1->begin(); //check hasNext EXPECT_TRUE(it.hasNext() == false); EtchHashTable<EtchString, EtchInt32>::HashTableEntry entry; EXPECT_TRUE(it.next(&entry) == ETCH_ERANGE); // add new keys status = h1->put(key, value); EXPECT_TRUE(status == ETCH_OK); //add new value status = h1->put(key2, value); EXPECT_TRUE(status == ETCH_OK); it = h1->begin(); EXPECT_EQ(ETCH_OK, it.next(&entry)); EXPECT_EQ(ETCH_OK, it.next(&entry)); EXPECT_EQ(ETCH_ERANGE, it.next(&entry)); delete h1; }
26.190031
165
0.689782
apache
9af73ce4c787f073abdfd54bc2461d8070e92fe4
5,009
cpp
C++
Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter17Exercise13Def.cpp
Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
9
2018-10-24T15:16:47.000Z
2021-12-14T13:53:50.000Z
Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter17Exercise13Def.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
null
null
null
Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter17Exercise13Def.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
7
2018-10-29T15:30:37.000Z
2021-01-18T15:15:09.000Z
/* TITLE Linked list Chapter17Exercise13.cpp "Bjarne Stroustrup "C++ Programming: Principles and Practice."" COMMENT Objcective: Modify Link to include struct God, containing members of type string: name, mythology, vehicle, weapon. Write: print_all(), add_ordered() functions. Input: - Output: - Author: Chris B. Kirov Date: 07.12.2015 */ // modifying member functions /* Member function: insert() It inserts the new link in before this object. */ Link* Link::insert (Link* n) { if (n == 0) { return this; } if (this == 0) { return n; } n->succ = this; n->prev = prev; if (prev) { prev->succ = n; } prev = n; return n; } //------------------------------------------------------------------------ /* Member function: add() It adds new link after this object. */ Link* Link::add (Link* n) { if (n == 0 ) { return this; } if (this == 0) { return n; } n->prev = this; if (succ) { succ->prev = n; } n->succ = succ; succ = n; return n; } //------------------------------------------------------------------------ /* Member function: add_ordered() It inserts new link taking into consideration the God's name of the current last Link such that the name of the last and the new are in lexicographically (increasing) order. */ Link* Link::add_ordered (Link* n) { if (n == 0) { return this; } // new list: first node if (this == 0) { n->succ = 0; n->prev = 0; return n; } if (n->god < god) { Link* p = insert(n); // first element has changed return p; } Link* p = this; while (!(n->god < p->god)) // >= not defined for God { if (p->succ==0) // last element reached { p->add(n); // attach to end of list return this; // first element has not changed } p = p->succ; } p->insert(n); return this; } //------------------------------------------------------------------------ /* Member function: erase() It erases the current object and connects its successor to its predecessor; returns successor. */ Link* Link::erase (void) { if (this == 0) { return 0; } if (prev) { prev->succ = succ; } if (succ) { succ->prev = prev; } return succ; } //------------------------------------------------------------------------ /* Member function: find() It returns the first successor link containing string name. Read and write permissions. */ Link* Link::find (const std::string& n) { Link* p = this; while (p) { if (p->god.name == n) { return p; } p = p->succ; } return 0; } //------------------------------------------------------------------------ // non - modifying member functions /* Member function: find() It returns the first successor link containing string value. Read permission only. */ const Link* Link::find(const std::string &n) const { const Link* p = this; while (p) { if (p->god.name == n) { return p; } p = p->succ; } return 0; } //------------------------------------------------------------------------ /* Member function: advance() It returns the link found after n links, where n could be either positive or negative. */ Link* Link::advance (int n) { if (this == 0) { return 0; } Link* p = this; if (n < 0) { while (n++) { if (prev == 0) { return 0; } p = prev; } } if (n > 0) { while (n--) { if (succ == 0) { return 0; } p = succ; } } return p; } //------------------------------------------------------------------------ // non - member functions /* Function: print_all_back_to_front(); It prints all nodes of the doubly linked list starting from the last and advancing to first node. */ void print_all_back_to_front(Link* n) { std::cout <<"{"; while (n) { std::cout << n->god; if (n = n->next()) { std::cout <<'\n'; } } std::cout <<"}"; } //------------------------------------------------------------------------ /* Function: print_all_front_to_back(); It prints all nodes of the doubly linked list starting from the last and advancing to first node. */ void print_all_front_to_back(Link* n) { std::cout <<"{"; while (n) { std::cout << n->god; if (n = n->previous()) { std::cout <<'\n'; } } std::cout <<"}"; } //------------------------------------------------------------------------ /* Function: order_list (); It uses src link ptr to create a lexicograhically ordered list: dest link ptr, in terms of God's name. */ void order_list (Link* src, Link*& dest) { // traverse src from back to front while (src) { // use src's God element to create a new Link as an element of an ordered List dest = dest->add_ordered(new Link(God(src->god.name, src->god.mythology, src->god.vehicle, src->god.weapon))); src = src->next(); } }
15.555901
80
0.489918
Ziezi
9af9f58090a73a97ed73dde269039e1b91b34a4f
253
cpp
C++
src/rick/RickState.cpp
ZZBGames/games
8da707b0beb38aa4308dde1ce70ebe38fd82003a
[ "MIT" ]
null
null
null
src/rick/RickState.cpp
ZZBGames/games
8da707b0beb38aa4308dde1ce70ebe38fd82003a
[ "MIT" ]
null
null
null
src/rick/RickState.cpp
ZZBGames/games
8da707b0beb38aa4308dde1ce70ebe38fd82003a
[ "MIT" ]
null
null
null
// // Created by mathbagu on 19/03/16. // #include <zzbgames/rick/RickState.hpp> namespace zzbgames { namespace rick { RickState::RickState(RickStateStack& stateStack, RickContext& context) : State(stateStack), m_context(context) { } } }
12.047619
70
0.699605
ZZBGames
9afaa845542f25886c2843e813a355e93dc14bad
2,637
hpp
C++
libsynthpp/src/LSP/MIDI/Messages/BasicMessage.hpp
my04337/libsynthpp
99584d0e568e6c92a5c298d4fdcde277fe7511f1
[ "MIT" ]
1
2018-01-31T14:02:32.000Z
2018-01-31T14:02:32.000Z
libsynthpp/src/LSP/MIDI/Messages/BasicMessage.hpp
my04337/libsynthpp
99584d0e568e6c92a5c298d4fdcde277fe7511f1
[ "MIT" ]
1
2018-02-21T02:33:47.000Z
2018-02-21T02:36:23.000Z
libsynthpp/src/LSP/MIDI/Messages/BasicMessage.hpp
my04337/libsynthpp
99584d0e568e6c92a5c298d4fdcde277fe7511f1
[ "MIT" ]
1
2018-02-20T05:30:52.000Z
2018-02-20T05:30:52.000Z
#pragma once #include <LSP/Base/Base.hpp> #include <LSP/MIDI/Message.hpp> namespace LSP::MIDI::Messages { /// ノートオン class NoteOn : public ChannelVoiceMessage { public: NoteOn(uint8_t ch, uint8_t noteNo, uint8_t vel) : mChannel(ch), mNoteNo(noteNo), mVelocity(vel) {} uint8_t channel()const noexcept override final { return mChannel; } uint8_t noteNo()const noexcept { return mNoteNo; } uint8_t velocity()const noexcept { return mVelocity; } private: uint8_t mChannel; uint8_t mNoteNo; uint8_t mVelocity; }; /// ノートオフ class NoteOff : public ChannelVoiceMessage { public: NoteOff(uint8_t ch, uint8_t noteNo, uint8_t vel) : mChannel(ch), mNoteNo(noteNo), mVelocity(vel) {} uint8_t channel()const noexcept override final { return mChannel; } uint8_t noteNo()const noexcept { return mNoteNo; } private: uint8_t mChannel; uint8_t mNoteNo; uint8_t mVelocity; }; /// ポリフォニックキープレッシャー (アフタータッチ) class PolyphonicKeyPressure : public ChannelVoiceMessage { public: PolyphonicKeyPressure(uint8_t ch, uint8_t noteNo, uint8_t value) : mChannel(ch), mNoteNo(noteNo), mValue(value) {} uint8_t channel()const noexcept override final { return mChannel; } private: uint8_t mChannel; uint8_t mNoteNo; uint8_t mValue; }; /// コントロールチェンジ & チャネルモードメッセージ class ControlChange : public ChannelVoiceMessage { public: ControlChange(uint8_t ch, uint8_t ctrlNo, uint8_t value) : mChannel(ch), mCtrlNo(ctrlNo), mValue(value) {} uint8_t channel()const noexcept override final { return mChannel; } uint8_t ctrlNo()const noexcept { return mCtrlNo; } uint8_t value()const noexcept { return mValue; } private: uint8_t mChannel; uint8_t mCtrlNo; uint8_t mValue; }; /// プログラムチェンジ class ProgramChange : public ChannelVoiceMessage { public: ProgramChange(uint8_t ch, uint8_t progNo) : mChannel(ch), mProgNo(progNo) {} uint8_t channel()const noexcept override final { return mChannel; } uint8_t progId()const noexcept { return mProgNo; } private: uint8_t mChannel; uint8_t mProgNo; }; /// チャネルプレッシャー (アフタータッチ) class ChannelPressure : public ChannelVoiceMessage { public: ChannelPressure(uint8_t ch, uint8_t value) : mChannel(ch), mValue(value) {} uint8_t channel()const noexcept override final { return mChannel; } private: uint8_t mChannel; uint8_t mValue; }; /// ピッチベンド class PitchBend : public ChannelVoiceMessage { public: PitchBend(uint8_t ch, int16_t pitch) : mChannel(ch), mPitch(pitch) {} uint8_t channel()const noexcept override final { return mChannel; } int16_t pitch()const noexcept { return mPitch; } private: uint8_t mChannel; int16_t mPitch; // -8192 <= x < +8191 }; }
19.977273
69
0.740235
my04337
9afc1a96924b965c5593c598045877e39440a6ed
511
cpp
C++
2021/day24/tests/TestClass.cpp
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
3
2021-07-01T14:31:06.000Z
2022-03-29T20:41:21.000Z
2021/day24/tests/TestClass.cpp
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
null
null
null
2021/day24/tests/TestClass.cpp
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
null
null
null
#include "TestClass.h" #include "../test.h" namespace aoc2021_day24 { TEST_F(Tests2021Day24, part_1_test) { ASSERT_EQ(part_1("../2021/day24/input_test.in"), 0); } TEST_F(Tests2021Day24, part_1_real_test) { ASSERT_EQ(part_1("../2021/day24/input.in"), 0); } TEST_F(Tests2021Day24, part_2_test) { ASSERT_EQ(part_2("../2021/day24/input_test.in"), 0); } TEST_F(Tests2021Day24, part_2_real_test) { ASSERT_EQ(part_2("../2021/day24/input.in"), 0); } }
25.55
60
0.632094
alexandru-andronache
9aff74edeb68c2441c3d1ca7b99dd3393f623d08
2,466
hpp
C++
libbio/include/bio/gpu/gpu_TransactionTypes.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
libbio/include/bio/gpu/gpu_TransactionTypes.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
libbio/include/bio/gpu/gpu_TransactionTypes.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
#pragma once #include <bio/gpu/gpu_Types.hpp> namespace bio::gpu { enum class ConnectionApi : i32 { EGL = 1, Cpu = 2, Media = 3, Camera = 4, }; enum class DisconnectMode : u32 { Api = 0, AllLocal = 1, }; struct QueueBufferOutput { u32 width; u32 height; u32 transform_hint; u32 pending_buffer_count; }; struct Plane { u32 width; u32 height; ColorFormat color_format; Layout layout; u32 pitch; u32 map_handle_unused; u32 offset; Kind kind; u32 block_height_log2; DisplayScanFormat display_scan_format; u32 second_field_offset; u64 flags; u64 size; u32 unk[6]; }; static_assert(sizeof(Plane) == 0x58); struct GraphicBufferHeader { u32 magic; u32 width; u32 height; u32 stride; PixelFormat pixel_format; GraphicsAllocatorUsage usage; u32 pid; u32 refcount; u32 fd_count; u32 buffer_size; static constexpr u32 Magic = 0x47424652; // GBFR (Graphic Buffer) }; // TODO: is the packed attribute really needed here? struct __attribute__((packed)) GraphicBuffer { GraphicBufferHeader header; u32 null; u32 map_id; u32 zero; u32 buffer_magic; u32 pid; u32 type; GraphicsAllocatorUsage usage; PixelFormat pixel_format; PixelFormat external_pixel_format; u32 stride; u32 full_size; u32 plane_count; u32 zero_2; Plane planes[3]; u64 unused; static constexpr u32 Magic = 0xDAFFCAFF; }; static_assert(sizeof(GraphicBuffer) == 0x16C); struct Fence { u32 id; u32 value; }; struct MultiFence { u32 fence_count; Fence fences[4]; }; struct Rect { i32 left; i32 top; i32 right; i32 bottom; }; enum class Transform : u32 { FlipH = 1, FlipV = 2, Rotate90 = 4, Rotate180 = 3, Rotate270 = 7, }; struct QueueBufferInput { i64 timestamp; i32 is_auto_timestamp; Rect crop; i32 scaling_mode; Transform transform; u32 sticky_transform; u32 unk; u32 swap_interval; MultiFence fence; }; }
20.213115
73
0.544201
biosphere-switch
b104357842a56d514edbcdeada4e43077f9c4043
433
cpp
C++
logsource.cpp
rdffg/bcaa_importer
f92e0b39673b5c557540154d4567c53a15adadcd
[ "Apache-2.0" ]
null
null
null
logsource.cpp
rdffg/bcaa_importer
f92e0b39673b5c557540154d4567c53a15adadcd
[ "Apache-2.0" ]
2
2019-05-07T22:49:31.000Z
2021-08-20T20:03:53.000Z
logsource.cpp
rdffg/bcaa_importer
f92e0b39673b5c557540154d4567c53a15adadcd
[ "Apache-2.0" ]
null
null
null
#include "logsource.h" #include <QCoreApplication> LogSource::LogSource(QObject *parent) : QObject(parent) , m_logtext("") { } void LogSource::addLogText(QString text) { m_logtext += "\n" + text; QCoreApplication::processEvents(); emit dataChanged(); } void LogSource::clearLogText() { m_logtext = ""; emit dataChanged(); } QString LogSource::logtext() { return m_logtext; }
16.653846
56
0.628176
rdffg
b1059e99204a486f1fe034c1385e955a5ee6b3ae
4,015
cpp
C++
src/main.cpp
qiujiangkun/GraphicsPractice
de2703c1c2cb924f62a40c46fe5f80fa6a81f072
[ "MIT" ]
null
null
null
src/main.cpp
qiujiangkun/GraphicsPractice
de2703c1c2cb924f62a40c46fe5f80fa6a81f072
[ "MIT" ]
null
null
null
src/main.cpp
qiujiangkun/GraphicsPractice
de2703c1c2cb924f62a40c46fe5f80fa6a81f072
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <fstream> #include "engine/separate_application.h" #include "engine/MyECS.h" #include "engine/utils.h" #include "movement.h" #include "engine/window_glfw.h" #include "engine/scene.h" #include "engine/renderer2d.h" using namespace Escape; using namespace Escape::Render; class Logic : public SystemManager { class PostInit : public ECSSystem { Logic *logic; public: PostInit(Logic *logic) : logic(logic) {} void initialize() override { ECSSystem::initialize(); logic->player = world->create(); logic->player->assign<Position>(Position(0, 0)); logic->player->assign<Name>("agent"); } }; public: Entity *player; TimeServer *timeserver; void initialize() override { SystemManager::initialize(); timeserver = findSystem<Application>()->timeserver; } Logic() { addSubSystem(new PostInit(this)); } void fire(Entity *ent, float angle) { // weapon_system->fire(ent, angle); } void move(Entity *ent, const glm::vec2 &vel) { // movement_system->move(ent, vel); } }; class Display : public WindowGLFW { Scene scene; Renderer2D renderer; Logic *logic; World *world; public: Display() : WindowGLFW("Escape", 800, 600) { windowResized(800, 600); } void initialize() override { WindowGLFW::initialize(); logic = findSystem<Logic>(); world = logic->getWorld(); } void windowResized(int width, int height) override { WindowGLFW::windowResized(width, height); scene.mat = glm::ortho<float>(-width / 2, width / 2, -height / 2, height / 2); } virtual void processInput() override { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (logic->player == nullptr) return; if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { double x, y; glfwGetCursorPos(window, &x, &y); x -= width / 2; y = height / 2 - y; // std::cerr << "Cursor: " << x << " " << y << std::endl; auto pos = logic->player->get<Position>(); assert(pos.isValid()); float angle = atan2(y - pos->y, x - pos->x); logic->fire(logic->player, angle); } glm::vec2 vel(0, 0); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) vel.y += 1; if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) vel.y += -1; if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) vel.x += -1; if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) vel.x += 1; float spd = glm::length(*(glm::vec2 *)&vel); if (spd > 0) { if (spd > 1) { vel /= spd; } vel *= 64.0f; } logic->move(logic->player, vel); } void render() override { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderer.applyScene(scene); world->each<Name>([&, this](Entity *ent, ComponentHandle<Name> name) { if (name.get() == "agent") { renderAgent(ent); } if (name.get() == "bullet") { renderBullet(ent); } }); } void renderAgent(Entity *ent) { auto pos = ent->get<Position>(); renderer.drawRect(Rectangle(pos->x, pos->y, 32, 32, 1, 1, 1)); } void renderBullet(Entity *ent) { auto &&pos = ent->get<Position>(); assert(pos.isValid()); renderer.drawRect(Rectangle(pos->x, pos->y, 2, 2, 1, 0, 0)); } }; int main() { Escape::SeparateApplication app(new Display(), new Logic()); app.loop(); return 0; }
26.589404
86
0.534496
qiujiangkun
b1087963cac05ba26a4d3919f61c568c7f0af261
421
cc
C++
chrome/browser/ui/views/color_chooser_aura.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
chrome/browser/ui/views/color_chooser_aura.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
chrome/browser/ui/views/color_chooser_aura.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.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 "content/public/browser/color_chooser.h" #include "base/logging.h" // static content::ColorChooser* content::ColorChooser::Create( int identifier, content::WebContents* tab, SkColor initial_color) { NOTIMPLEMENTED(); return NULL; }
28.066667
73
0.745843
Scopetta197
623f6880c191cb8b07b9393f313a4d08c17c5afa
1,876
hpp
C++
RL-master/Engine/UE3/PropertyFlags.hpp
jeremwhitten/RL
15ff898afe82b6a07e076b8a3609c81a0942e6ca
[ "MIT" ]
230
2018-01-26T07:20:25.000Z
2022-03-26T14:57:00.000Z
Engine/UE3/PropertyFlags.hpp
ChairGraveyard/UnrealEngineSDKGenerator
0589f640fa61c05316c1708e6c3b9ab3e13eb6aa
[ "MIT" ]
1
2020-10-18T16:30:26.000Z
2020-10-18T16:30:26.000Z
Engine/UE3/PropertyFlags.hpp
ChairGraveyard/UnrealEngineSDKGenerator
0589f640fa61c05316c1708e6c3b9ab3e13eb6aa
[ "MIT" ]
164
2018-01-15T09:11:46.000Z
2022-03-08T11:57:12.000Z
#pragma once #include <type_traits> #include <string> enum class UEPropertyFlags : uint64_t { Edit = 0x0000000000000001, Const = 0x0000000000000002, Input = 0x0000000000000004, ExportObject = 0x0000000000000008, OptionalParm = 0x0000000000000010, Net = 0x0000000000000020, EditFixedSize = 0x0000000000000040, Parm = 0x0000000000000080, OutParm = 0x0000000000000100, SkipParm = 0x0000000000000200, ReturnParm = 0x0000000000000400, CoerceParm = 0x0000000000000800, Native = 0x0000000000001000, Transient = 0x0000000000002000, Config = 0x0000000000004000, Localized = 0x0000000000008000, EditConst = 0x0000000000020000, GlobalConfig = 0x0000000000040000, Component = 0x0000000000080000, AlwaysInit = 0x0000000000100000, DuplicateTransient = 0x0000000000200000, NeedCtorLink = 0x0000000000400000, NoExport = 0x0000000000800000, NoImport = 0x0000000001000000, NoClear = 0x0000000002000000, EditInline = 0x0000000004000000, EditInlineUse = 0x0000000010000000, Deprecated = 0x0000000020000000, DataBinding = 0x0000000040000000, SerializeText = 0x0000000080000000, RepNotify = 0x0000000100000000, Interp = 0x0000000200000000, NonTransactional = 0x0000000400000000, EditorOnly = 0x0000000800000000, NotForConsole = 0x0000001000000000, RepRetry = 0x0000002000000000, PrivateWrite = 0x0000004000000000, ProtectedWrite = 0x0000008000000000, ArchetypeProperty = 0x0000010000000000, EditHide = 0x0000020000000000, EditTextBox = 0x0000040000000000, CrossLevelPassive = 0x0000100000000000, CrossLevelActive = 0x0000200000000000 }; inline bool operator&(UEPropertyFlags lhs, UEPropertyFlags rhs) { return (static_cast<std::underlying_type_t<UEPropertyFlags>>(lhs) & static_cast<std::underlying_type_t<UEPropertyFlags>>(rhs)) == static_cast<std::underlying_type_t<UEPropertyFlags>>(rhs); } std::string StringifyFlags(const UEPropertyFlags flags);
32.344828
189
0.816631
jeremwhitten
62489fe7a0d3546aec6300f80ec138a763f427b7
2,775
cpp
C++
performerservice.cpp
audurara/verklegt1
ca07845b9fc7129cb4c7ea4c3f1bad46899a4bcf
[ "MIT" ]
1
2016-11-28T12:24:02.000Z
2016-11-28T12:24:02.000Z
performerservice.cpp
audurara/verklegt1
ca07845b9fc7129cb4c7ea4c3f1bad46899a4bcf
[ "MIT" ]
null
null
null
performerservice.cpp
audurara/verklegt1
ca07845b9fc7129cb4c7ea4c3f1bad46899a4bcf
[ "MIT" ]
null
null
null
#include "performerservice.h" #include "dataaccess.h" #include <algorithm> #include <iostream> using namespace std; struct PerformerComparison { //Struct sem ber saman nöfn bool operator() (Performer i,Performer j) { return (i.getName()<j.getName()); } }; struct CompareYear{ //Fæðingarár borin saman bool operator() (Performer i, Performer j) { int value = atoi(i.getbYear().c_str()); int value2 = atoi(j.getbYear().c_str()); return (value < value2); } }; struct CompareGender{ //Kyn borin saman bool operator() (Performer i, Performer j) { return (i.getGender() > j.getGender()); } }; struct CompareNationality{ //Þjóðerni borin saman bool operator() (Performer i, Performer j) { return (i.getNation() <j.getNation()); } }; PerformerService::PerformerService() //Tómur smiður { } vector<Performer> PerformerService::getPerformers() //Nær í gögn úr skrá og skilar þeim í vector { vector<Performer> getPerformers = _data.readData(); return getPerformers; } vector <Performer> PerformerService:: search(string name) //Leitar að ákveðnu nafni í listanum { vector<Performer> pf = getPerformers(); vector<Performer> newVector; for(size_t i = 0; i < pf.size(); i++) { if(pf[i].getName() == name) { newVector.push_back(pf[i]); } } return newVector; } vector<Performer> PerformerService::sortByName() { //Ber saman nöfn og raðar þeim í stafrófsröð vector<Performer> pf = getPerformers(); PerformerComparison cmp; sort(pf.begin(), pf.end(), cmp); return pf; } vector <Performer> PerformerService::sortBybYear() //Ber saman ár og raðar þeim frá því lægsta til þess hæsta { vector <Performer> pf = getPerformers(); CompareYear cmp; sort(pf.begin(), pf.end(), cmp); return pf; } vector <Performer> PerformerService::sortByGender() //Ber saman kyn { vector <Performer> pf = getPerformers(); CompareGender cmp; sort(pf.begin(), pf.end(), cmp); return pf; } vector <Performer> PerformerService::sortByNationality() //Ber saman þjóðerni og raðar þeim eftir stafrófsröð { vector <Performer> pf = getPerformers(); CompareNationality cmp; sort(pf.begin(), pf.end(), cmp); return pf; } string PerformerService::addPerformer(string name, string gender, string birth, string death, string nation) //Bætir nýjum tölvunarfræðingi inn í skrána { string all = "," + name + "," + gender + "," + birth + "," + death + "," + nation; _data.writeData(all); return all; } string PerformerService::removeElement(string name) //Skilar til baka streng eftir að hafa eytt einu tilviki { _data.removeData(name); return name; }
25.458716
153
0.654054
audurara