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
109
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
48.5k
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
58614c941a10a050a810e7f34c18c37e5de685ad
2,459
cpp
C++
src/Networking/ParseBaseStation.cpp
jonahbardos/PY2020
af4f61b86ae5013e58faf4842bf20863b3de3957
[ "Apache-2.0" ]
null
null
null
src/Networking/ParseBaseStation.cpp
jonahbardos/PY2020
af4f61b86ae5013e58faf4842bf20863b3de3957
[ "Apache-2.0" ]
null
null
null
src/Networking/ParseBaseStation.cpp
jonahbardos/PY2020
af4f61b86ae5013e58faf4842bf20863b3de3957
[ "Apache-2.0" ]
null
null
null
#include "Network.h" #include "log.h" #include "IK.h" #include "motor_interface.h" #include "ParseBaseStation.h" #include <cmath> #include <tgmath.h> #include "../simulator/world_interface.h" #include "../Globals.h" #include <iostream> using nlohmann::json; bool ParseDrivePacket(json &message); bool ParseEmergencyStop(json &message); bool sendError(std::string const &msg) { json error_message = {}; error_message["status"] = "error"; error_message["msg"] = msg; sendBaseStationPacket(error_message.dump()); log(LOG_ERROR, error_message.dump()); return false; } bool ParseBaseStationPacket(char const* buffer) { log(LOG_INFO, "Message from base station: " + (std::string) buffer); json parsed_message; try { parsed_message = json::parse(buffer); } catch (json::parse_error) { return sendError("Parse error"); } std::string type; try { type = parsed_message["type"]; } catch (json::type_error) { return sendError("Could not find message type"); } log(LOG_DEBUG, "Message type: " + type); bool success = false; if (type == "estop") { success = ParseEmergencyStop(parsed_message); } else if (Globals::E_STOP) { return sendError("Emergency stop is activated"); } if (type == "ik") { success = ParseIKPacket(parsed_message); } else if (type == "drive") { success = ParseDrivePacket(parsed_message); } else if (type == "motor") { success = ParseMotorPacket(parsed_message); } if (success) { json response = {{"status", "ok"}}; sendBaseStationPacket(response.dump()); } return success; } bool ParseEmergencyStop(json &message) { // TODO actually send e-stop packet (packet id 0x30 broadcast) bool success = setCmdVel(0,0); Globals::E_STOP = true; bool release; try { release = message["release"]; } catch (json::type_error) { return sendError("Malformatted estop packet"); } if (release) { Globals::E_STOP = false; return success; } else { return success; } } bool ParseDrivePacket(json &message) { double fb, lr; try { fb = message["forward_backward"]; lr = message["left_right"]; } catch (json::type_error) { return sendError("Malformatted drive packet"); } if (fb > 1.0 || fb < -1.0 || lr > 1.0 || lr < -1.0) { return sendError("Drive targets not within bounds +/- 1.0"); } // TODO do we need to scale or invert these? return setCmdVel(lr, fb); }
21.017094
70
0.649858
jonahbardos
5864ca14de111e2a98dc80bcb8e458ae2ecfa65b
1,405
cc
C++
src/base/message_loop/timer_slack.cc
lazymartin/naiveproxy
696e8714278e85e67e56a2eaea11f26c53116f0c
[ "BSD-3-Clause" ]
2,219
2018-03-26T02:57:34.000Z
2022-03-31T00:27:59.000Z
src/base/message_loop/timer_slack.cc
uszhen/naiveproxy
0aa27e8bd37428f2124a891be1e5e793928cd726
[ "BSD-3-Clause" ]
250
2018-02-02T23:16:57.000Z
2022-03-21T06:09:53.000Z
src/base/message_loop/timer_slack.cc
uszhen/naiveproxy
0aa27e8bd37428f2124a891be1e5e793928cd726
[ "BSD-3-Clause" ]
473
2019-03-24T16:34:23.000Z
2022-03-31T02:01:05.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop/timer_slack.h" #include <atomic> #include "base/check_op.h" #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" namespace base { namespace features { constexpr base::Feature kLudicrousTimerSlack{"LudicrousTimerSlack", base::FEATURE_DISABLED_BY_DEFAULT}; namespace { constexpr base::FeatureParam<base::TimeDelta> kSlackValueMs{ &kLudicrousTimerSlack, "slack_ms", // 1.5 seconds default slack for this ludicrous experiment. base::TimeDelta::FromMilliseconds(1500)}; } // namespace } // namespace features namespace { std::atomic<size_t> g_ludicrous_timer_suspend_count{0}; } // namespace bool IsLudicrousTimerSlackEnabled() { return base::FeatureList::IsEnabled(base::features::kLudicrousTimerSlack); } base::TimeDelta GetLudicrousTimerSlack() { return features::kSlackValueMs.Get(); } void SuspendLudicrousTimerSlack() { ++g_ludicrous_timer_suspend_count; } void ResumeLudicrousTimerSlack() { size_t old_count = g_ludicrous_timer_suspend_count.fetch_sub(1); DCHECK_LT(0u, old_count); } bool IsLudicrousTimerSlackSuspended() { return g_ludicrous_timer_suspend_count.load() > 0u; } } // namespace base
25.089286
80
0.745907
lazymartin
58678121a455e51d562ddd820e632fc544f9d61c
38,417
cpp
C++
sven_internal/config.cpp
revoiid/sven_internal
99c0e8148fd8cd44100d5c7730ebb1fc71b7f368
[ "MIT" ]
null
null
null
sven_internal/config.cpp
revoiid/sven_internal
99c0e8148fd8cd44100d5c7730ebb1fc71b7f368
[ "MIT" ]
null
null
null
sven_internal/config.cpp
revoiid/sven_internal
99c0e8148fd8cd44100d5c7730ebb1fc71b7f368
[ "MIT" ]
null
null
null
// Config #include "config.h" #include "../ini-parser/ini_parser.h" #include "../features/skybox.h" #include "../utils/styles.h" #include "../interfaces.h" #include <stdio.h> #include <stdlib.h> #include <type_traits> //----------------------------------------------------------------------------- // Make import/export easier //----------------------------------------------------------------------------- template <class T> constexpr const char *ini_get_format_specifier(T var) { if (std::is_same_v<T, int> || std::is_same_v<T, bool>) return "%s = %d\n"; if (std::is_same_v<T, float>) return "%s = %.3f\n"; if (std::is_same_v<T, DWORD>) return "%s = %X\n"; } template <class T> constexpr ini_field_type_t ini_get_fieldtype(T var) { if (std::is_same_v<T, bool>) return INI_FIELD_BOOL; else if (std::is_same_v<T, int>) return INI_FIELD_INTEGER; else if (std::is_same_v<T, float>) return INI_FIELD_FLOAT; else if (std::is_same_v<T, DWORD>) return INI_FIELD_UINT32; } template <class T> constexpr void ini_get_datatype(T &var, ini_datatype &datatype) { #pragma warning(push) #pragma warning(disable: 4244) if (std::is_same_v<T, bool>) var = datatype.m_bool; else if (std::is_same_v<T, int>) var = datatype.m_int; else if (std::is_same_v<T, float>) var = datatype.m_float; else if (std::is_same_v<T, DWORD>) var = datatype.m_uint32; #pragma warning(pop) } #define INI_EXPORT_BEGIN() FILE *file = fopen("sven_internal/sven_internal.ini", "w"); if (file) { #define INI_EXPORT_END() fclose(file); } #define INI_EXPORT_BEGIN_SECTION(section) fprintf(file, "[" section "]\n") #define INI_EXPORT_END_SECTION() fprintf(file, "\n") #define INI_EXPORT_VARIABLE(name, var) fprintf(file, ini_get_format_specifier(var), name, var) #define INI_IMPORT_BEGIN() const char *pszSection = NULL; ini_datatype datatype; ini_data *data = (ini_data *)calloc(sizeof(ini_data), 1) #define INI_IMPORT_END() ini_free_data(data, 1); return true #define INI_IMPORT_BEGIN_SECTION(section) pszSection = section #define INI_IMPORT_END_SECTION() #define INI_IMPORT_VARIABLE_SET_RADIX(_radix) datatype.radix = _radix #define INI_IMPORT_VARIABLE(name, var) \ if (ini_read_data(data, pszSection, name, &datatype, ini_get_fieldtype(var))) \ ini_get_datatype(var, datatype) #define INI_IMPORT_PARSE_DATA() \ if (!ini_parse_data("sven_internal/sven_internal.ini", data)) \ { \ if (ini_get_last_error() == INI_MISSING_FILE) \ g_pEngineFuncs->Con_Printf("Failed to parse the config file: Missing file sven_internal/sven_internal.ini to parse\n"); \ else \ g_pEngineFuncs->Con_Printf("Failed to parse the config file: Syntax error: %s in line %d\n", ini_get_last_error_msg(), ini_get_last_line()); \ \ ini_free_data(data, 1); \ return false; \ } //----------------------------------------------------------------------------- // Vars //----------------------------------------------------------------------------- CConfig g_Config; //----------------------------------------------------------------------------- // Implementations //----------------------------------------------------------------------------- bool CConfig::Load() { INI_IMPORT_BEGIN(); INI_IMPORT_PARSE_DATA(); INI_IMPORT_BEGIN_SECTION("SETTINGS"); INI_IMPORT_VARIABLE_SET_RADIX(16); INI_IMPORT_VARIABLE("ToggleButton", dwToggleButton); INI_IMPORT_VARIABLE("AutoResize", ImGuiAutoResize); INI_IMPORT_VARIABLE("Theme", theme); INI_IMPORT_VARIABLE("Opacity", opacity); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("ESP"); INI_IMPORT_VARIABLE("Enable", cvars.esp); INI_IMPORT_VARIABLE("Distance", cvars.esp_distance); INI_IMPORT_VARIABLE("Box", cvars.esp_box); INI_IMPORT_VARIABLE("Outline", cvars.esp_box_outline); INI_IMPORT_VARIABLE("Fill", cvars.esp_box_fill); INI_IMPORT_VARIABLE("ShowIndex", cvars.esp_box_index); INI_IMPORT_VARIABLE("ShowDistance", cvars.esp_box_distance); INI_IMPORT_VARIABLE("ShowPlayerHealth", cvars.esp_box_player_health); INI_IMPORT_VARIABLE("ShowPlayerArmor", cvars.esp_box_player_armor); INI_IMPORT_VARIABLE("ShowEntityName", cvars.esp_box_entity_name); INI_IMPORT_VARIABLE("ShowPlayerName", cvars.esp_box_player_name); INI_IMPORT_VARIABLE("ShowItems", cvars.esp_show_items); INI_IMPORT_VARIABLE("IgnoreUnknownEnts", cvars.esp_ignore_unknown_ents); INI_IMPORT_VARIABLE("Targets", cvars.esp_targets); INI_IMPORT_VARIABLE("ShowSkeleton", cvars.esp_skeleton); INI_IMPORT_VARIABLE("ShowBonesName", cvars.esp_bones_name); INI_IMPORT_VARIABLE("ShowSkeletonType", cvars.esp_skeleton_type); INI_IMPORT_VARIABLE("FriendColor_R", cvars.esp_friend_color[0]); INI_IMPORT_VARIABLE("FriendColor_G", cvars.esp_friend_color[1]); INI_IMPORT_VARIABLE("FriendColor_B", cvars.esp_friend_color[2]); INI_IMPORT_VARIABLE("EnemyColor_R", cvars.esp_enemy_color[0]); INI_IMPORT_VARIABLE("EnemyColor_G", cvars.esp_enemy_color[1]); INI_IMPORT_VARIABLE("EnemyColor_B", cvars.esp_enemy_color[2]); INI_IMPORT_VARIABLE("NeutralColor_R", cvars.esp_neutral_color[0]); INI_IMPORT_VARIABLE("NeutralColor_G", cvars.esp_neutral_color[1]); INI_IMPORT_VARIABLE("NeutralColor_B", cvars.esp_neutral_color[2]); INI_IMPORT_VARIABLE("ItemColor_R", cvars.esp_item_color[0]); INI_IMPORT_VARIABLE("ItemColor_G", cvars.esp_item_color[1]); INI_IMPORT_VARIABLE("ItemColor_B", cvars.esp_item_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("WALLHACK"); INI_IMPORT_VARIABLE("Wallhack", cvars.wallhack); INI_IMPORT_VARIABLE("Negative", cvars.wallhack_negative); INI_IMPORT_VARIABLE("WhiteWalls", cvars.wallhack_white_walls); INI_IMPORT_VARIABLE("Wireframe", cvars.wallhack_wireframe); INI_IMPORT_VARIABLE("WireframeModels", cvars.wallhack_wireframe_models); INI_IMPORT_VARIABLE("Wireframe_Width", cvars.wh_wireframe_width); INI_IMPORT_VARIABLE("Wireframe_R", cvars.wh_wireframe_color[0]); INI_IMPORT_VARIABLE("Wireframe_G", cvars.wh_wireframe_color[2]); INI_IMPORT_VARIABLE("Wireframe_B", cvars.wh_wireframe_color[1]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CROSSHAIR"); INI_IMPORT_VARIABLE("Enable", cvars.draw_crosshair); INI_IMPORT_VARIABLE("EnableDot", cvars.draw_crosshair_dot); INI_IMPORT_VARIABLE("EnableOutline", cvars.draw_crosshair_outline); INI_IMPORT_VARIABLE("Size", cvars.crosshair_size); INI_IMPORT_VARIABLE("Gap", cvars.crosshair_gap); INI_IMPORT_VARIABLE("Thickness", cvars.crosshair_thickness); INI_IMPORT_VARIABLE("OutlineThickness", cvars.crosshair_outline_thickness); INI_IMPORT_VARIABLE("OutlineColor_R", cvars.crosshair_outline_color[0]); INI_IMPORT_VARIABLE("OutlineColor_G", cvars.crosshair_outline_color[1]); INI_IMPORT_VARIABLE("OutlineColor_B", cvars.crosshair_outline_color[2]); INI_IMPORT_VARIABLE("OutlineColor_A", cvars.crosshair_outline_color[3]); INI_IMPORT_VARIABLE("Color_R", cvars.crosshair_color[0]); INI_IMPORT_VARIABLE("Color_G", cvars.crosshair_color[1]); INI_IMPORT_VARIABLE("Color_B", cvars.crosshair_color[2]); INI_IMPORT_VARIABLE("Color_A", cvars.crosshair_color[3]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("VISUAL"); INI_IMPORT_VARIABLE("NoShake", cvars.no_shake); INI_IMPORT_VARIABLE("NoFade", cvars.no_fade); INI_IMPORT_VARIABLE("DrawEntities", cvars.draw_entities); INI_IMPORT_VARIABLE("ShowSpeed", cvars.show_speed); INI_IMPORT_VARIABLE("StoreVerticalSpeed", cvars.show_vertical_speed); INI_IMPORT_VARIABLE("SpeedWidthFraction", cvars.speed_width_fraction); INI_IMPORT_VARIABLE("SpeedHeightFraction", cvars.speed_height_fraction); INI_IMPORT_VARIABLE("Speed_R", cvars.speed_color[0]); INI_IMPORT_VARIABLE("Speed_G", cvars.speed_color[1]); INI_IMPORT_VARIABLE("Speed_B", cvars.speed_color[2]); INI_IMPORT_VARIABLE("Speed_A", cvars.speed_color[3]); INI_IMPORT_VARIABLE("LightmapOverride", cvars.lightmap_override); INI_IMPORT_VARIABLE("LightmapOverrideBrightness", cvars.lightmap_brightness); INI_IMPORT_VARIABLE("LightmapOverride_R", cvars.lightmap_color[0]); INI_IMPORT_VARIABLE("LightmapOverride_G", cvars.lightmap_color[1]); INI_IMPORT_VARIABLE("LightmapOverride_B", cvars.lightmap_color[2]); INI_IMPORT_VARIABLE("ShowPlayersPushDirection", cvars.show_players_push_direction); INI_IMPORT_VARIABLE("PushDirectionLength", cvars.push_direction_length); INI_IMPORT_VARIABLE("PushDirectionWidth", cvars.push_direction_width); INI_IMPORT_VARIABLE("PushDirectionColor_R", cvars.push_direction_color[0]); INI_IMPORT_VARIABLE("PushDirectionColor_G", cvars.push_direction_color[1]); INI_IMPORT_VARIABLE("PushDirectionColor_B", cvars.push_direction_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CHAMS"); INI_IMPORT_VARIABLE("Enable", cvars.chams); INI_IMPORT_VARIABLE("ChamsPlayers", cvars.chams_players); INI_IMPORT_VARIABLE("ChamsEntities", cvars.chams_entities); INI_IMPORT_VARIABLE("ChamsItems", cvars.chams_items); INI_IMPORT_VARIABLE("ChamsPlayersWall", cvars.chams_players_wall); INI_IMPORT_VARIABLE("ChamsEntitiesWall", cvars.chams_entities_wall); INI_IMPORT_VARIABLE("ChamsItemsWall", cvars.chams_items_wall); INI_IMPORT_VARIABLE("ChamsPlayersColor_R", cvars.chams_players_color[0]); INI_IMPORT_VARIABLE("ChamsPlayersColor_G", cvars.chams_players_color[1]); INI_IMPORT_VARIABLE("ChamsPlayersColor_B", cvars.chams_players_color[2]); INI_IMPORT_VARIABLE("ChamsEntitiesColor_R", cvars.chams_entities_color[0]); INI_IMPORT_VARIABLE("ChamsEntitiesColor_G", cvars.chams_entities_color[1]); INI_IMPORT_VARIABLE("ChamsEntitiesColor_B", cvars.chams_entities_color[2]); INI_IMPORT_VARIABLE("ChamsItemsColor_R", cvars.chams_items_color[0]); INI_IMPORT_VARIABLE("ChamsItemsColor_G", cvars.chams_items_color[1]); INI_IMPORT_VARIABLE("ChamsItemsColor_B", cvars.chams_items_color[2]); INI_IMPORT_VARIABLE("ChamsPlayersWallColor_R", cvars.chams_players_wall_color[0]); INI_IMPORT_VARIABLE("ChamsPlayersWallColor_G", cvars.chams_players_wall_color[1]); INI_IMPORT_VARIABLE("ChamsPlayersWallColor_B", cvars.chams_players_wall_color[2]); INI_IMPORT_VARIABLE("ChamsEntitiesWallColor_R", cvars.chams_entities_wall_color[0]); INI_IMPORT_VARIABLE("ChamsEntitiesWallColor_G", cvars.chams_entities_wall_color[1]); INI_IMPORT_VARIABLE("ChamsEntitiesWallColor_B", cvars.chams_entities_wall_color[2]); INI_IMPORT_VARIABLE("ChamsItemsWallColor_R", cvars.chams_items_wall_color[0]); INI_IMPORT_VARIABLE("ChamsItemsWallColor_G", cvars.chams_items_wall_color[1]); INI_IMPORT_VARIABLE("ChamsItemsWallColor_B", cvars.chams_items_wall_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("GLOW"); INI_IMPORT_VARIABLE("Enable", cvars.glow); INI_IMPORT_VARIABLE("Optimize", cvars.glow_optimize); INI_IMPORT_VARIABLE("GlowPlayers", cvars.glow_players); INI_IMPORT_VARIABLE("GlowEntities", cvars.glow_entities); INI_IMPORT_VARIABLE("GlowItems", cvars.glow_items); INI_IMPORT_VARIABLE("GlowPlayersWidth", cvars.glow_players_width); INI_IMPORT_VARIABLE("GlowEntitiesWidth", cvars.glow_entities_width); INI_IMPORT_VARIABLE("GlowItemsWidth", cvars.glow_items_width); INI_IMPORT_VARIABLE("GlowPlayersWall", cvars.glow_players_wall); INI_IMPORT_VARIABLE("GlowEntitiesWall", cvars.glow_entities_wall); INI_IMPORT_VARIABLE("GlowItemsWall", cvars.glow_items_wall); INI_IMPORT_VARIABLE("GlowPlayersColor_R", cvars.glow_players_color[0]); INI_IMPORT_VARIABLE("GlowPlayersColor_G", cvars.glow_players_color[1]); INI_IMPORT_VARIABLE("GlowPlayersColor_B", cvars.glow_players_color[2]); INI_IMPORT_VARIABLE("GlowEntitiesColor_R", cvars.glow_entities_color[0]); INI_IMPORT_VARIABLE("GlowEntitiesColor_G", cvars.glow_entities_color[1]); INI_IMPORT_VARIABLE("GlowEntitiesColor_B", cvars.glow_entities_color[2]); INI_IMPORT_VARIABLE("GlowItemsColor_R", cvars.glow_items_color[0]); INI_IMPORT_VARIABLE("GlowItemsColor_G", cvars.glow_items_color[1]); INI_IMPORT_VARIABLE("GlowItemsColor_B", cvars.glow_items_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("DYNAMICGLOW"); INI_IMPORT_VARIABLE("GlowAttach", cvars.dyn_glow_attach); INI_IMPORT_VARIABLE("GlowSelf", cvars.dyn_glow_self); INI_IMPORT_VARIABLE("GlowSelfRadius", cvars.dyn_glow_self_radius); INI_IMPORT_VARIABLE("GlowSelfDecay", cvars.dyn_glow_self_decay); INI_IMPORT_VARIABLE("GlowSelfColor_R", cvars.dyn_glow_self_color[0]); INI_IMPORT_VARIABLE("GlowSelfColor_G", cvars.dyn_glow_self_color[1]); INI_IMPORT_VARIABLE("GlowSelfColor_B", cvars.dyn_glow_self_color[2]); INI_IMPORT_VARIABLE("GlowPlayers", cvars.dyn_glow_players); INI_IMPORT_VARIABLE("GlowPlayersRadius", cvars.dyn_glow_players_radius); INI_IMPORT_VARIABLE("GlowPlayersDecay", cvars.dyn_glow_players_decay); INI_IMPORT_VARIABLE("GlowPlayersColor_R", cvars.dyn_glow_players_color[0]); INI_IMPORT_VARIABLE("GlowPlayersColor_G", cvars.dyn_glow_players_color[1]); INI_IMPORT_VARIABLE("GlowPlayersColor_B", cvars.dyn_glow_players_color[2]); INI_IMPORT_VARIABLE("GlowEntities", cvars.dyn_glow_entities); INI_IMPORT_VARIABLE("GlowEntitiesRadius", cvars.dyn_glow_entities_radius); INI_IMPORT_VARIABLE("GlowEntitiesDecay", cvars.dyn_glow_entities_decay); INI_IMPORT_VARIABLE("GlowEntitiesColor_R", cvars.dyn_glow_entities_color[0]); INI_IMPORT_VARIABLE("GlowEntitiesColor_G", cvars.dyn_glow_entities_color[1]); INI_IMPORT_VARIABLE("GlowEntitiesColor_B", cvars.dyn_glow_entities_color[2]); INI_IMPORT_VARIABLE("GlowItems", cvars.dyn_glow_items); INI_IMPORT_VARIABLE("GlowItemsRadius", cvars.dyn_glow_items_radius); INI_IMPORT_VARIABLE("GlowItemsDecay", cvars.dyn_glow_items_decay); INI_IMPORT_VARIABLE("GlowItemsColor_R", cvars.dyn_glow_items_color[0]); INI_IMPORT_VARIABLE("GlowItemsColor_G", cvars.dyn_glow_items_color[1]); INI_IMPORT_VARIABLE("GlowItemsColor_B", cvars.dyn_glow_items_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("STRAFE"); INI_IMPORT_VARIABLE("Enable", cvars.strafe); INI_IMPORT_VARIABLE("IgnoreGround", cvars.strafe_ignore_ground); INI_IMPORT_VARIABLE("Direction", cvars.strafe_dir); INI_IMPORT_VARIABLE("Type", cvars.strafe_type); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("FAKELAG"); INI_IMPORT_VARIABLE("Enable", cvars.fakelag); INI_IMPORT_VARIABLE("AdaptiveInterp", cvars.fakelag_adaptive_ex_interp); INI_IMPORT_VARIABLE("Type", cvars.fakelag_type); INI_IMPORT_VARIABLE("Move", cvars.fakelag_move); INI_IMPORT_VARIABLE("Limit", cvars.fakelag_limit); INI_IMPORT_VARIABLE("Variance", cvars.fakelag_variance); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("ANTIAFK"); INI_IMPORT_VARIABLE("Type", cvars.antiafk); INI_IMPORT_VARIABLE("RotateCamera", cvars.antiafk_rotate_camera); INI_IMPORT_VARIABLE("StayWithinRange", cvars.antiafk_stay_within_range); INI_IMPORT_VARIABLE("ResetStayPos", cvars.antiafk_reset_stay_pos); INI_IMPORT_VARIABLE("RotationAngle", cvars.antiafk_rotation_angle); INI_IMPORT_VARIABLE("StayRadius", cvars.antiafk_stay_radius); INI_IMPORT_VARIABLE("StayRadiusOffsetAngle", cvars.antiafk_stay_radius_offset_angle); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("MISC"); INI_IMPORT_VARIABLE("AutoJump", cvars.autojump); INI_IMPORT_VARIABLE("JumpBug", cvars.jumpbug); INI_IMPORT_VARIABLE("DoubleDuck", cvars.doubleduck); INI_IMPORT_VARIABLE("FastRun", cvars.fastrun); INI_IMPORT_VARIABLE("QuakeGuns", cvars.quake_guns); INI_IMPORT_VARIABLE("TertiaryAttackGlitch", cvars.tertiary_attack_glitch); INI_IMPORT_VARIABLE("SaveSoundcache", cvars.save_soundcache); INI_IMPORT_VARIABLE("RotateDeadBody", cvars.rotate_dead_body); INI_IMPORT_VARIABLE("RemoveFOVCap", cvars.remove_fov_cap); INI_IMPORT_VARIABLE("NoWeaponAnim", cvars.no_weapon_anim); INI_IMPORT_VARIABLE("ColorPulsator", cvars.color_pulsator); INI_IMPORT_VARIABLE("ColorPulsatorTop", cvars.color_pulsator_top); INI_IMPORT_VARIABLE("ColorPulsatorBottom", cvars.color_pulsator_bottom); INI_IMPORT_VARIABLE("ColorPulsatorDelay", cvars.color_pulsator_delay); INI_IMPORT_VARIABLE("LockPitch", cvars.lock_pitch); INI_IMPORT_VARIABLE("LockYaw", cvars.lock_yaw); INI_IMPORT_VARIABLE("LockPitchAngle", cvars.lock_pitch_angle); INI_IMPORT_VARIABLE("LockYawAngle", cvars.lock_yaw_angle); INI_IMPORT_VARIABLE("SpinYaw", cvars.spin_yaw_angle); INI_IMPORT_VARIABLE("SpinPitch", cvars.spin_pitch_angle); INI_IMPORT_VARIABLE("SpinYawAngle", cvars.spin_yaw_rotation_angle); INI_IMPORT_VARIABLE("SpinPitchAngle", cvars.spin_pitch_rotation_angle); INI_IMPORT_VARIABLE("ApplicationSpeed", cvars.application_speed); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("KEYSPAM"); INI_IMPORT_VARIABLE("HoldMode", cvars.keyspam_hold_mode); INI_IMPORT_VARIABLE("Spam_E", cvars.keyspam_e); INI_IMPORT_VARIABLE("Spam_W", cvars.keyspam_w); INI_IMPORT_VARIABLE("Spam_S", cvars.keyspam_s); INI_IMPORT_VARIABLE("Spam_Q", cvars.keyspam_q); INI_IMPORT_VARIABLE("Spam_CTRL", cvars.keyspam_ctrl); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("FOG"); INI_IMPORT_VARIABLE("Enable", cvars.fog); INI_IMPORT_VARIABLE("FogSkybox", cvars.fog_skybox); INI_IMPORT_VARIABLE("RemoveInWater", cvars.remove_water_fog); INI_IMPORT_VARIABLE("Start", cvars.fog_start); INI_IMPORT_VARIABLE("End", cvars.fog_end); INI_IMPORT_VARIABLE("Density", cvars.fog_density); INI_IMPORT_VARIABLE("Fog_R", cvars.fog_color[0]); INI_IMPORT_VARIABLE("Fog_G", cvars.fog_color[1]); INI_IMPORT_VARIABLE("Fog_B", cvars.fog_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("SKYBOX"); INI_IMPORT_VARIABLE("Type", cvars.skybox); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CHATCOLORS"); INI_IMPORT_VARIABLE("Enable", cvars.enable_chat_colors); INI_IMPORT_VARIABLE("PlayerName_R", cvars.player_name_color[0]); INI_IMPORT_VARIABLE("PlayerName_G", cvars.player_name_color[1]); INI_IMPORT_VARIABLE("PlayerName_B", cvars.player_name_color[2]); INI_IMPORT_VARIABLE("RainbowUpdateDelay", cvars.chat_rainbow_update_delay); INI_IMPORT_VARIABLE("RainbowHueDelta", cvars.chat_rainbow_hue_delta); INI_IMPORT_VARIABLE("RainbowSaturation", cvars.chat_rainbow_saturation); INI_IMPORT_VARIABLE("RainbowLightness", cvars.chat_rainbow_lightness); INI_IMPORT_VARIABLE("ColorOne_R", cvars.chat_color_one[0]); INI_IMPORT_VARIABLE("ColorOne_G", cvars.chat_color_one[1]); INI_IMPORT_VARIABLE("ColorOne_B", cvars.chat_color_one[2]); INI_IMPORT_VARIABLE("ColorTwo_R", cvars.chat_color_two[0]); INI_IMPORT_VARIABLE("ColorTwo_G", cvars.chat_color_two[1]); INI_IMPORT_VARIABLE("ColorTwo_B", cvars.chat_color_two[2]); INI_IMPORT_VARIABLE("ColorThree_R", cvars.chat_color_three[0]); INI_IMPORT_VARIABLE("ColorThree_G", cvars.chat_color_three[1]); INI_IMPORT_VARIABLE("ColorThree_B", cvars.chat_color_three[2]); INI_IMPORT_VARIABLE("ColorFour_R", cvars.chat_color_four[0]); INI_IMPORT_VARIABLE("ColorFour_G", cvars.chat_color_four[1]); INI_IMPORT_VARIABLE("ColorFour_B", cvars.chat_color_four[2]); INI_IMPORT_VARIABLE("ColorFive_R", cvars.chat_color_five[0]); INI_IMPORT_VARIABLE("ColorFive_G", cvars.chat_color_five[1]); INI_IMPORT_VARIABLE("ColorFive_B", cvars.chat_color_five[2]); INI_IMPORT_VARIABLE("ColorSix_R", cvars.chat_color_six[0]); INI_IMPORT_VARIABLE("ColorSix_G", cvars.chat_color_six[1]); INI_IMPORT_VARIABLE("ColorSix_B", cvars.chat_color_six[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CAMHACK"); INI_IMPORT_VARIABLE("SpeedFactor", cvars.camhack_speed_factor); INI_IMPORT_VARIABLE("ShowModel", cvars.camhack_show_model); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("FPROAMING"); INI_IMPORT_VARIABLE("Enable", cvars.fp_roaming); INI_IMPORT_VARIABLE("Crosshair", cvars.fp_roaming_draw_crosshair); INI_IMPORT_VARIABLE("Lerp", cvars.fp_roaming_lerp); INI_IMPORT_VARIABLE("LerpValue", cvars.fp_roaming_lerp_value); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("VOTEPOPUP"); INI_IMPORT_VARIABLE("Enable", cvars.vote_popup); INI_IMPORT_VARIABLE("WidthSize", cvars.vote_popup_width_size); INI_IMPORT_VARIABLE("HeightSize", cvars.vote_popup_height_size); INI_IMPORT_VARIABLE("WidthBorderPixels", cvars.vote_popup_w_border_pix); INI_IMPORT_VARIABLE("HeightBorderPixels", cvars.vote_popup_h_border_pix); INI_IMPORT_VARIABLE("WidthFraction", cvars.vote_popup_width_frac); INI_IMPORT_VARIABLE("HeightFraction", cvars.vote_popup_height_frac); INI_IMPORT_END_SECTION(); //INI_IMPORT_BEGIN_SECTION("AUTOVOTE"); // INI_IMPORT_VARIABLE("Mode", cvars.autovote_mode); // INI_IMPORT_VARIABLE("UseOnCustomVotes", cvars.autovote_custom); // INI_IMPORT_VARIABLE("IgnoreVoteFilter", cvars.autovote_ignore_filter); //INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("AMS"); INI_IMPORT_VARIABLE("MuteEverything", cvars.ams_mute_everything); INI_IMPORT_END_SECTION(); // Callbacks g_Skybox.OnConfigLoad(); INI_IMPORT_END(); } void CConfig::Save() { INI_EXPORT_BEGIN() INI_EXPORT_BEGIN_SECTION("SETTINGS"); INI_EXPORT_VARIABLE("ToggleButton", dwToggleButton); INI_EXPORT_VARIABLE("AutoResize", ImGuiAutoResize); INI_EXPORT_VARIABLE("Theme", theme); INI_EXPORT_VARIABLE("Opacity", opacity); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("ESP"); INI_EXPORT_VARIABLE("Enable", cvars.esp); INI_EXPORT_VARIABLE("Distance", cvars.esp_distance); INI_EXPORT_VARIABLE("Box", cvars.esp_box); INI_EXPORT_VARIABLE("Outline", cvars.esp_box_outline); INI_EXPORT_VARIABLE("Fill", cvars.esp_box_fill); INI_EXPORT_VARIABLE("ShowIndex", cvars.esp_box_index); INI_EXPORT_VARIABLE("ShowDistance", cvars.esp_box_distance); INI_EXPORT_VARIABLE("ShowPlayerHealth", cvars.esp_box_player_health); INI_EXPORT_VARIABLE("ShowPlayerArmor", cvars.esp_box_player_armor); INI_EXPORT_VARIABLE("ShowEntityName", cvars.esp_box_entity_name); INI_EXPORT_VARIABLE("ShowPlayerName", cvars.esp_box_player_name); INI_EXPORT_VARIABLE("ShowItems", cvars.esp_show_items); INI_EXPORT_VARIABLE("IgnoreUnknownEnts", cvars.esp_ignore_unknown_ents); INI_EXPORT_VARIABLE("Targets", cvars.esp_targets); INI_EXPORT_VARIABLE("ShowSkeleton", cvars.esp_skeleton); INI_EXPORT_VARIABLE("ShowBonesName", cvars.esp_bones_name); INI_EXPORT_VARIABLE("ShowSkeletonType", cvars.esp_skeleton_type); INI_EXPORT_VARIABLE("FriendColor_R", cvars.esp_friend_color[0]); INI_EXPORT_VARIABLE("FriendColor_G", cvars.esp_friend_color[1]); INI_EXPORT_VARIABLE("FriendColor_B", cvars.esp_friend_color[2]); INI_EXPORT_VARIABLE("EnemyColor_R", cvars.esp_enemy_color[0]); INI_EXPORT_VARIABLE("EnemyColor_G", cvars.esp_enemy_color[1]); INI_EXPORT_VARIABLE("EnemyColor_B", cvars.esp_enemy_color[2]); INI_EXPORT_VARIABLE("NeutralColor_R", cvars.esp_neutral_color[0]); INI_EXPORT_VARIABLE("NeutralColor_G", cvars.esp_neutral_color[1]); INI_EXPORT_VARIABLE("NeutralColor_B", cvars.esp_neutral_color[2]); INI_EXPORT_VARIABLE("ItemColor_R", cvars.esp_item_color[0]); INI_EXPORT_VARIABLE("ItemColor_G", cvars.esp_item_color[1]); INI_EXPORT_VARIABLE("ItemColor_B", cvars.esp_item_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("WALLHACK"); INI_EXPORT_VARIABLE("Wallhack", cvars.wallhack); INI_EXPORT_VARIABLE("Negative", cvars.wallhack_negative); INI_EXPORT_VARIABLE("WhiteWalls", cvars.wallhack_white_walls); INI_EXPORT_VARIABLE("Wireframe", cvars.wallhack_wireframe); INI_EXPORT_VARIABLE("WireframeModels", cvars.wallhack_wireframe_models); INI_EXPORT_VARIABLE("Wireframe_Width", cvars.wh_wireframe_width); INI_EXPORT_VARIABLE("Wireframe_R", cvars.wh_wireframe_color[0]); INI_EXPORT_VARIABLE("Wireframe_G", cvars.wh_wireframe_color[2]); INI_EXPORT_VARIABLE("Wireframe_B", cvars.wh_wireframe_color[1]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CROSSHAIR"); INI_EXPORT_VARIABLE("Enable", cvars.draw_crosshair); INI_EXPORT_VARIABLE("EnableDot", cvars.draw_crosshair_dot); INI_EXPORT_VARIABLE("EnableOutline", cvars.draw_crosshair_outline); INI_EXPORT_VARIABLE("Size", cvars.crosshair_size); INI_EXPORT_VARIABLE("Gap", cvars.crosshair_gap); INI_EXPORT_VARIABLE("Thickness", cvars.crosshair_thickness); INI_EXPORT_VARIABLE("OutlineThickness", cvars.crosshair_outline_thickness); INI_EXPORT_VARIABLE("OutlineColor_R", cvars.crosshair_outline_color[0]); INI_EXPORT_VARIABLE("OutlineColor_G", cvars.crosshair_outline_color[1]); INI_EXPORT_VARIABLE("OutlineColor_B", cvars.crosshair_outline_color[2]); INI_EXPORT_VARIABLE("OutlineColor_A", cvars.crosshair_outline_color[3]); INI_EXPORT_VARIABLE("Color_R", cvars.crosshair_color[0]); INI_EXPORT_VARIABLE("Color_G", cvars.crosshair_color[1]); INI_EXPORT_VARIABLE("Color_B", cvars.crosshair_color[2]); INI_EXPORT_VARIABLE("Color_A", cvars.crosshair_color[3]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("VISUAL"); INI_EXPORT_VARIABLE("NoShake", cvars.no_shake); INI_EXPORT_VARIABLE("NoFade", cvars.no_fade); INI_EXPORT_VARIABLE("DrawEntities", cvars.draw_entities); INI_EXPORT_VARIABLE("ShowSpeed", cvars.show_speed); INI_EXPORT_VARIABLE("StoreVerticalSpeed", cvars.show_vertical_speed); INI_EXPORT_VARIABLE("SpeedWidthFraction", cvars.speed_width_fraction); INI_EXPORT_VARIABLE("SpeedHeightFraction", cvars.speed_height_fraction); INI_EXPORT_VARIABLE("Speed_R", cvars.speed_color[0]); INI_EXPORT_VARIABLE("Speed_G", cvars.speed_color[1]); INI_EXPORT_VARIABLE("Speed_B", cvars.speed_color[2]); INI_EXPORT_VARIABLE("Speed_A", cvars.speed_color[3]); INI_EXPORT_VARIABLE("LightmapOverride", cvars.lightmap_override); INI_EXPORT_VARIABLE("LightmapOverrideBrightness", cvars.lightmap_brightness); INI_EXPORT_VARIABLE("LightmapOverride_R", cvars.lightmap_color[0]); INI_EXPORT_VARIABLE("LightmapOverride_G", cvars.lightmap_color[1]); INI_EXPORT_VARIABLE("LightmapOverride_B", cvars.lightmap_color[2]); INI_EXPORT_VARIABLE("ShowPlayersPushDirection", cvars.show_players_push_direction); INI_EXPORT_VARIABLE("PushDirectionLength", cvars.push_direction_length); INI_EXPORT_VARIABLE("PushDirectionWidth", cvars.push_direction_width); INI_EXPORT_VARIABLE("PushDirectionColor_R", cvars.push_direction_color[0]); INI_EXPORT_VARIABLE("PushDirectionColor_G", cvars.push_direction_color[1]); INI_EXPORT_VARIABLE("PushDirectionColor_B", cvars.push_direction_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CHAMS"); INI_EXPORT_VARIABLE("Enable", cvars.chams); INI_EXPORT_VARIABLE("ChamsPlayers", cvars.chams_players); INI_EXPORT_VARIABLE("ChamsEntities", cvars.chams_entities); INI_EXPORT_VARIABLE("ChamsItems", cvars.chams_items); INI_EXPORT_VARIABLE("ChamsPlayersWall", cvars.chams_players_wall); INI_EXPORT_VARIABLE("ChamsEntitiesWall", cvars.chams_entities_wall); INI_EXPORT_VARIABLE("ChamsItemsWall", cvars.chams_items_wall); INI_EXPORT_VARIABLE("ChamsPlayersColor_R", cvars.chams_players_color[0]); INI_EXPORT_VARIABLE("ChamsPlayersColor_G", cvars.chams_players_color[1]); INI_EXPORT_VARIABLE("ChamsPlayersColor_B", cvars.chams_players_color[2]); INI_EXPORT_VARIABLE("ChamsEntitiesColor_R", cvars.chams_entities_color[0]); INI_EXPORT_VARIABLE("ChamsEntitiesColor_G", cvars.chams_entities_color[1]); INI_EXPORT_VARIABLE("ChamsEntitiesColor_B", cvars.chams_entities_color[2]); INI_EXPORT_VARIABLE("ChamsItemsColor_R", cvars.chams_items_color[0]); INI_EXPORT_VARIABLE("ChamsItemsColor_G", cvars.chams_items_color[1]); INI_EXPORT_VARIABLE("ChamsItemsColor_B", cvars.chams_items_color[2]); INI_EXPORT_VARIABLE("ChamsPlayersWallColor_R", cvars.chams_players_wall_color[0]); INI_EXPORT_VARIABLE("ChamsPlayersWallColor_G", cvars.chams_players_wall_color[1]); INI_EXPORT_VARIABLE("ChamsPlayersWallColor_B", cvars.chams_players_wall_color[2]); INI_EXPORT_VARIABLE("ChamsEntitiesWallColor_R", cvars.chams_entities_wall_color[0]); INI_EXPORT_VARIABLE("ChamsEntitiesWallColor_G", cvars.chams_entities_wall_color[1]); INI_EXPORT_VARIABLE("ChamsEntitiesWallColor_B", cvars.chams_entities_wall_color[2]); INI_EXPORT_VARIABLE("ChamsItemsWallColor_R", cvars.chams_items_wall_color[0]); INI_EXPORT_VARIABLE("ChamsItemsWallColor_G", cvars.chams_items_wall_color[1]); INI_EXPORT_VARIABLE("ChamsItemsWallColor_B", cvars.chams_items_wall_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("GLOW"); INI_EXPORT_VARIABLE("Enable", cvars.glow); INI_EXPORT_VARIABLE("Optimize", cvars.glow_optimize); INI_EXPORT_VARIABLE("GlowPlayers", cvars.glow_players); INI_EXPORT_VARIABLE("GlowEntities", cvars.glow_entities); INI_EXPORT_VARIABLE("GlowItems", cvars.glow_items); INI_EXPORT_VARIABLE("GlowPlayersWidth", cvars.glow_players_width); INI_EXPORT_VARIABLE("GlowEntitiesWidth", cvars.glow_entities_width); INI_EXPORT_VARIABLE("GlowItemsWidth", cvars.glow_items_width); INI_EXPORT_VARIABLE("GlowPlayersWall", cvars.glow_players_wall); INI_EXPORT_VARIABLE("GlowEntitiesWall", cvars.glow_entities_wall); INI_EXPORT_VARIABLE("GlowItemsWall", cvars.glow_items_wall); INI_EXPORT_VARIABLE("GlowPlayersColor_R", cvars.glow_players_color[0]); INI_EXPORT_VARIABLE("GlowPlayersColor_G", cvars.glow_players_color[1]); INI_EXPORT_VARIABLE("GlowPlayersColor_B", cvars.glow_players_color[2]); INI_EXPORT_VARIABLE("GlowEntitiesColor_R", cvars.glow_entities_color[0]); INI_EXPORT_VARIABLE("GlowEntitiesColor_G", cvars.glow_entities_color[1]); INI_EXPORT_VARIABLE("GlowEntitiesColor_B", cvars.glow_entities_color[2]); INI_EXPORT_VARIABLE("GlowItemsColor_R", cvars.glow_items_color[0]); INI_EXPORT_VARIABLE("GlowItemsColor_G", cvars.glow_items_color[1]); INI_EXPORT_VARIABLE("GlowItemsColor_B", cvars.glow_items_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("DYNAMICGLOW"); INI_EXPORT_VARIABLE("GlowAttach", cvars.dyn_glow_attach); INI_EXPORT_VARIABLE("GlowSelf", cvars.dyn_glow_self); INI_EXPORT_VARIABLE("GlowSelfRadius", cvars.dyn_glow_self_radius); INI_EXPORT_VARIABLE("GlowSelfDecay", cvars.dyn_glow_self_decay); INI_EXPORT_VARIABLE("GlowSelfColor_R", cvars.dyn_glow_self_color[0]); INI_EXPORT_VARIABLE("GlowSelfColor_G", cvars.dyn_glow_self_color[1]); INI_EXPORT_VARIABLE("GlowSelfColor_B", cvars.dyn_glow_self_color[2]); INI_EXPORT_VARIABLE("GlowPlayers", cvars.dyn_glow_players); INI_EXPORT_VARIABLE("GlowPlayersRadius", cvars.dyn_glow_players_radius); INI_EXPORT_VARIABLE("GlowPlayersDecay", cvars.dyn_glow_players_decay); INI_EXPORT_VARIABLE("GlowPlayersColor_R", cvars.dyn_glow_players_color[0]); INI_EXPORT_VARIABLE("GlowPlayersColor_G", cvars.dyn_glow_players_color[1]); INI_EXPORT_VARIABLE("GlowPlayersColor_B", cvars.dyn_glow_players_color[2]); INI_EXPORT_VARIABLE("GlowEntities", cvars.dyn_glow_entities); INI_EXPORT_VARIABLE("GlowEntitiesRadius", cvars.dyn_glow_entities_radius); INI_EXPORT_VARIABLE("GlowEntitiesDecay", cvars.dyn_glow_entities_decay); INI_EXPORT_VARIABLE("GlowEntitiesColor_R", cvars.dyn_glow_entities_color[0]); INI_EXPORT_VARIABLE("GlowEntitiesColor_G", cvars.dyn_glow_entities_color[1]); INI_EXPORT_VARIABLE("GlowEntitiesColor_B", cvars.dyn_glow_entities_color[2]); INI_EXPORT_VARIABLE("GlowItems", cvars.dyn_glow_items); INI_EXPORT_VARIABLE("GlowItemsRadius", cvars.dyn_glow_items_radius); INI_EXPORT_VARIABLE("GlowItemsDecay", cvars.dyn_glow_items_decay); INI_EXPORT_VARIABLE("GlowItemsColor_R", cvars.dyn_glow_items_color[0]); INI_EXPORT_VARIABLE("GlowItemsColor_G", cvars.dyn_glow_items_color[1]); INI_EXPORT_VARIABLE("GlowItemsColor_B", cvars.dyn_glow_items_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("STRAFE"); INI_EXPORT_VARIABLE("Enable", cvars.strafe); INI_EXPORT_VARIABLE("IgnoreGround", cvars.strafe_ignore_ground); INI_EXPORT_VARIABLE("Direction", cvars.strafe_dir); INI_EXPORT_VARIABLE("Type", cvars.strafe_type); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("FAKELAG"); INI_EXPORT_VARIABLE("Enable", cvars.fakelag); INI_EXPORT_VARIABLE("AdaptiveInterp", cvars.fakelag_adaptive_ex_interp); INI_EXPORT_VARIABLE("Type", cvars.fakelag_type); INI_EXPORT_VARIABLE("Move", cvars.fakelag_move); INI_EXPORT_VARIABLE("Limit", cvars.fakelag_limit); INI_EXPORT_VARIABLE("Variance", cvars.fakelag_variance); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("ANTIAFK"); INI_EXPORT_VARIABLE("Type", cvars.antiafk); INI_EXPORT_VARIABLE("RotateCamera", cvars.antiafk_rotate_camera); INI_EXPORT_VARIABLE("StayWithinRange", cvars.antiafk_stay_within_range); INI_EXPORT_VARIABLE("ResetStayPos", cvars.antiafk_reset_stay_pos); INI_EXPORT_VARIABLE("RotationAngle", cvars.antiafk_rotation_angle); INI_EXPORT_VARIABLE("StayRadius", cvars.antiafk_stay_radius); INI_EXPORT_VARIABLE("StayRadiusOffsetAngle", cvars.antiafk_stay_radius_offset_angle); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("MISC"); INI_EXPORT_VARIABLE("AutoJump", cvars.autojump); INI_EXPORT_VARIABLE("JumpBug", cvars.jumpbug); INI_EXPORT_VARIABLE("DoubleDuck", cvars.doubleduck); INI_EXPORT_VARIABLE("FastRun", cvars.fastrun); INI_EXPORT_VARIABLE("QuakeGuns", cvars.quake_guns); INI_EXPORT_VARIABLE("TertiaryAttackGlitch", cvars.tertiary_attack_glitch); INI_EXPORT_VARIABLE("SaveSoundcache", cvars.save_soundcache); INI_EXPORT_VARIABLE("RotateDeadBody", cvars.rotate_dead_body); INI_EXPORT_VARIABLE("RemoveFOVCap", cvars.remove_fov_cap); INI_EXPORT_VARIABLE("NoWeaponAnim", cvars.no_weapon_anim); INI_EXPORT_VARIABLE("ColorPulsator", cvars.color_pulsator); INI_EXPORT_VARIABLE("ColorPulsatorTop", cvars.color_pulsator_top); INI_EXPORT_VARIABLE("ColorPulsatorBottom", cvars.color_pulsator_bottom); INI_EXPORT_VARIABLE("ColorPulsatorDelay", cvars.color_pulsator_delay); INI_EXPORT_VARIABLE("LockPitch", cvars.lock_pitch); INI_EXPORT_VARIABLE("LockYaw", cvars.lock_yaw); INI_EXPORT_VARIABLE("LockPitchAngle", cvars.lock_pitch_angle); INI_EXPORT_VARIABLE("LockYawAngle", cvars.lock_yaw_angle); INI_EXPORT_VARIABLE("SpinYaw", cvars.spin_yaw_angle); INI_EXPORT_VARIABLE("SpinPitch", cvars.spin_pitch_angle); INI_EXPORT_VARIABLE("SpinYawAngle", cvars.spin_yaw_rotation_angle); INI_EXPORT_VARIABLE("SpinPitchAngle", cvars.spin_pitch_rotation_angle); INI_EXPORT_VARIABLE("ApplicationSpeed", cvars.application_speed); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("KEYSPAM"); INI_EXPORT_VARIABLE("HoldMode", cvars.keyspam_hold_mode); INI_EXPORT_VARIABLE("Spam_E", cvars.keyspam_e); INI_EXPORT_VARIABLE("Spam_W", cvars.keyspam_w); INI_EXPORT_VARIABLE("Spam_S", cvars.keyspam_s); INI_EXPORT_VARIABLE("Spam_Q", cvars.keyspam_q); INI_EXPORT_VARIABLE("Spam_CTRL", cvars.keyspam_ctrl); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("FOG"); INI_EXPORT_VARIABLE("Enable", cvars.fog); INI_EXPORT_VARIABLE("FogSkybox", cvars.fog_skybox); INI_EXPORT_VARIABLE("RemoveInWater", cvars.remove_water_fog); INI_EXPORT_VARIABLE("Start", cvars.fog_start); INI_EXPORT_VARIABLE("End", cvars.fog_end); INI_EXPORT_VARIABLE("Density", cvars.fog_density); INI_EXPORT_VARIABLE("Fog_R", cvars.fog_color[0]); INI_EXPORT_VARIABLE("Fog_G", cvars.fog_color[1]); INI_EXPORT_VARIABLE("Fog_B", cvars.fog_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("SKYBOX"); INI_EXPORT_VARIABLE("Type", cvars.skybox); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CHATCOLORS"); INI_EXPORT_VARIABLE("Enable", cvars.enable_chat_colors); INI_EXPORT_VARIABLE("PlayerName_R", cvars.player_name_color[0]); INI_EXPORT_VARIABLE("PlayerName_G", cvars.player_name_color[1]); INI_EXPORT_VARIABLE("PlayerName_B", cvars.player_name_color[2]); INI_EXPORT_VARIABLE("RainbowUpdateDelay", cvars.chat_rainbow_update_delay); INI_EXPORT_VARIABLE("RainbowHueDelta", cvars.chat_rainbow_hue_delta); INI_EXPORT_VARIABLE("RainbowSaturation", cvars.chat_rainbow_saturation); INI_EXPORT_VARIABLE("RainbowLightness", cvars.chat_rainbow_lightness); INI_EXPORT_VARIABLE("ColorOne_R", cvars.chat_color_one[0]); INI_EXPORT_VARIABLE("ColorOne_G", cvars.chat_color_one[1]); INI_EXPORT_VARIABLE("ColorOne_B", cvars.chat_color_one[2]); INI_EXPORT_VARIABLE("ColorTwo_R", cvars.chat_color_two[0]); INI_EXPORT_VARIABLE("ColorTwo_G", cvars.chat_color_two[1]); INI_EXPORT_VARIABLE("ColorTwo_B", cvars.chat_color_two[2]); INI_EXPORT_VARIABLE("ColorThree_R", cvars.chat_color_three[0]); INI_EXPORT_VARIABLE("ColorThree_G", cvars.chat_color_three[1]); INI_EXPORT_VARIABLE("ColorThree_B", cvars.chat_color_three[2]); INI_EXPORT_VARIABLE("ColorFour_R", cvars.chat_color_four[0]); INI_EXPORT_VARIABLE("ColorFour_G", cvars.chat_color_four[1]); INI_EXPORT_VARIABLE("ColorFour_B", cvars.chat_color_four[2]); INI_EXPORT_VARIABLE("ColorFive_R", cvars.chat_color_five[0]); INI_EXPORT_VARIABLE("ColorFive_G", cvars.chat_color_five[1]); INI_EXPORT_VARIABLE("ColorFive_B", cvars.chat_color_five[2]); INI_EXPORT_VARIABLE("ColorSix_R", cvars.chat_color_six[0]); INI_EXPORT_VARIABLE("ColorSix_G", cvars.chat_color_six[1]); INI_EXPORT_VARIABLE("ColorSix_B", cvars.chat_color_six[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CAMHACK"); INI_EXPORT_VARIABLE("SpeedFactor", cvars.camhack_speed_factor); INI_EXPORT_VARIABLE("ShowModel", cvars.camhack_show_model); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("FPROAMING"); INI_EXPORT_VARIABLE("Enable", cvars.fp_roaming); INI_EXPORT_VARIABLE("Crosshair", cvars.fp_roaming_draw_crosshair); INI_EXPORT_VARIABLE("Lerp", cvars.fp_roaming_lerp); INI_EXPORT_VARIABLE("LerpValue", cvars.fp_roaming_lerp_value); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("VOTEPOPUP"); INI_EXPORT_VARIABLE("Enable", cvars.vote_popup); INI_EXPORT_VARIABLE("WidthSize", cvars.vote_popup_width_size); INI_EXPORT_VARIABLE("HeightSize", cvars.vote_popup_height_size); INI_EXPORT_VARIABLE("WidthBorderPixels", cvars.vote_popup_w_border_pix); INI_EXPORT_VARIABLE("HeightBorderPixels", cvars.vote_popup_h_border_pix); INI_EXPORT_VARIABLE("WidthFraction", cvars.vote_popup_width_frac); INI_EXPORT_VARIABLE("HeightFraction", cvars.vote_popup_height_frac); INI_EXPORT_END_SECTION(); //INI_EXPORT_BEGIN_SECTION("AUTOVOTE"); // INI_EXPORT_VARIABLE("Mode", cvars.autovote_mode); // INI_EXPORT_VARIABLE("UseOnCustomVotes", cvars.autovote_custom); // INI_EXPORT_VARIABLE("IgnoreVoteFilter", cvars.autovote_ignore_filter); //INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("AMS"); INI_EXPORT_VARIABLE("MuteEverything", cvars.ams_mute_everything); INI_EXPORT_END_SECTION(); INI_EXPORT_END() }
51.635753
145
0.799516
revoiid
58692dbc09fcbcd91582427f34e2931ae3322c63
24,901
cpp
C++
Gem/Code/Source/RHI/MatrixAlignmentTestExampleComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
15
2021-07-07T02:16:06.000Z
2022-03-22T07:39:06.000Z
Gem/Code/Source/RHI/MatrixAlignmentTestExampleComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
66
2021-07-07T00:01:05.000Z
2022-03-28T06:37:41.000Z
Gem/Code/Source/RHI/MatrixAlignmentTestExampleComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
13
2021-07-06T18:21:33.000Z
2022-01-04T18:29:18.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <RHI/MatrixAlignmentTestExampleComponent.h> #include <Utils/Utils.h> #include <SampleComponentManager.h> #include <Atom/RHI/CommandList.h> #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h> #include <Atom/RHI.Reflect/RenderAttachmentLayoutBuilder.h> #include <Atom/RPI.Public/Shader/Shader.h> #include <Atom/RPI.Reflect/Shader/ShaderAsset.h> #include <AzCore/Serialization/SerializeContext.h> namespace AtomSampleViewer { void MatrixAlignmentTestExampleComponent::Reflect(AZ::ReflectContext* context) { if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<MatrixAlignmentTestExampleComponent, AZ::Component>() ->Version(0) ; } } void MatrixAlignmentTestExampleComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { bool numFloatsChanged = false; if (m_imguiSidebar.Begin()) { ImGui::Spacing(); ImGui::Text("Number Of Rows"); ScriptableImGui::RadioButton("1##R1", &m_numRows, 1); ImGui::SameLine(); ScriptableImGui::RadioButton("2##R2", &m_numRows, 2); ImGui::SameLine(); ScriptableImGui::RadioButton("3##R3", &m_numRows, 3); ImGui::SameLine(); ScriptableImGui::RadioButton("4##R4", &m_numRows, 4); ImGui::Spacing(); ImGui::Text("Number Of Columns"); ScriptableImGui::RadioButton("1##C1", &m_numColumns, 1); ImGui::SameLine(); ScriptableImGui::RadioButton("2##C2", &m_numColumns, 2); ImGui::SameLine(); ScriptableImGui::RadioButton("3##C3", &m_numColumns, 3); ImGui::SameLine(); ScriptableImGui::RadioButton("4##C4", &m_numColumns, 4); ImGui::Spacing(); ImGui::Text("Checked Location Value:"); ScriptableImGui::SliderFloat("##CheckedLocationValue", &m_matrixLocationValue, 0.f, 1.f, "%.1f", ImGuiSliderFlags_AlwaysClamp); ImGui::Text("Unchecked Location Value: "); ImGui::Text("%.1f", 1.0f - m_matrixLocationValue); DrawMatrixValuesTable(); ImGui::Spacing(); ImGui::Text("Data After Matrix:"); numFloatsChanged |= ScriptableImGui::RadioButton("float", &m_numFloatsAfterMatrix, 1); ImGui::SameLine(); numFloatsChanged |= ScriptableImGui::RadioButton("float2", &m_numFloatsAfterMatrix, 2); ImGui::Text("float value:"); ScriptableImGui::SliderFloat("##FloatAfterMatrix", &m_floatAfterMatrix, 0.f, 1.f, "%.1f", ImGuiSliderFlags_AlwaysClamp); m_imguiSidebar.End(); } if (numFloatsChanged) { m_needPipelineReload = true; } } void MatrixAlignmentTestExampleComponent::DrawMatrixValuesTable() { const auto flags = ImGuiTableFlags_Borders; if (ImGui::BeginTable("Matrix Data", m_numColumns + 1, flags)) { // Table header setup ImGui::TableSetupColumn("R\\C"); for (int col = 0; col < m_numColumns; ++col) { AZStd::string colName = AZStd::string::format("C%d", col); ImGui::TableSetupColumn(colName.c_str()); } ImGui::TableHeadersRow(); for (int row = 0; row < m_numRows; ++row) { for (int col = 0; col < m_numColumns + 1; ++col) { ImGui::TableNextColumn(); if (col == 0) { ImGui::Text("R%d", row); } else { AZStd::string cellId = AZStd::string::format("##R%dC%d", row, col-1); ScriptableImGui::Checkbox(cellId.c_str(), &m_checkedMatrixValues[row][col-1]); } } } ImGui::EndTable(); } } void MatrixAlignmentTestExampleComponent::FrameBeginInternal([[maybe_unused]] AZ::RHI::FrameGraphBuilder& frameGraphBuilder) { if (m_needPipelineReload) { ReleaseRhiData(); InitializeRenderPipeline(); } } bool MatrixAlignmentTestExampleComponent::SetSrgMatrixData(int numRows, int numColumns, const AZ::RHI::ShaderInputConstantIndex& dataAfterMatrixConstantId, const AZ::RHI::ShaderInputConstantIndex& matrixConstantId) { if ((m_numRows != numRows) || (m_numColumns != numColumns)) { return false; } if (!dataAfterMatrixConstantId.IsValid() || !matrixConstantId.IsValid()) { return false; } // Always set the float first, this way if there are alignment issues We'll notice the unexpected // colors bool success = false; if (m_numFloatsAfterMatrix == 1) { success = m_shaderResourceGroup->SetConstant(dataAfterMatrixConstantId, m_floatAfterMatrix); } else { AZ::Vector2 float2(m_floatAfterMatrix, m_floatAfterMatrix); success = m_shaderResourceGroup->SetConstant(dataAfterMatrixConstantId, float2); } AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_fAfter%d%d", numRows, numColumns); constexpr size_t SizeOfFloat4 = sizeof(float) * 4; constexpr size_t SizeOfFloat = sizeof(float); uint32_t numBytes = (SizeOfFloat4 * numRows) - ((4 - numColumns) * SizeOfFloat); success = m_shaderResourceGroup->SetConstantRaw(matrixConstantId, m_rawMatrix, numBytes); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_matrix%d%d", numRows, numColumns); return true; } void MatrixAlignmentTestExampleComponent::OnFramePrepare(AZ::RHI::FrameGraphBuilder& frameGraphBuilder) { using namespace AZ; { AZ::Vector4 screenResolution(GetViewportWidth(), GetViewportHeight(), 0, 0); [[maybe_unused]] bool success = m_shaderResourceGroup->SetConstant(m_resolutionConstantIndex, screenResolution); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_resolution"); success = m_shaderResourceGroup->SetConstant(m_numRowsConstantIndex, m_numRows); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_numRows"); success = m_shaderResourceGroup->SetConstant(m_numColumnsConstantIndex, m_numColumns); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_numColumns"); for (int row = 0; row < m_numRows; ++row) { for (int col = 0; col < m_numColumns; ++col) { m_rawMatrix[row][col] = m_checkedMatrixValues[row][col] ? m_matrixLocationValue : 1.0f - m_matrixLocationValue; } } if ( SetSrgMatrixData(1, 1, m_fAfter11ConstantIndex, m_matrix11ConstantIndex)) {} else if ( SetSrgMatrixData(1, 2, m_fAfter12ConstantIndex, m_matrix12ConstantIndex)) {} else if ( SetSrgMatrixData(1, 3, m_fAfter13ConstantIndex, m_matrix13ConstantIndex)) {} else if ( SetSrgMatrixData(1, 4, m_fAfter14ConstantIndex, m_matrix14ConstantIndex)) {} //else if (SetSrgMatrixData(2, 1, m_fAfter21ConstantIndex, m_matrix21ConstantIndex)) {} //Not supported by AZSLc else if ( SetSrgMatrixData(2, 2, m_fAfter22ConstantIndex, m_matrix22ConstantIndex)) {} else if ( SetSrgMatrixData(2, 3, m_fAfter23ConstantIndex, m_matrix23ConstantIndex)) {} else if ( SetSrgMatrixData(2, 4, m_fAfter24ConstantIndex, m_matrix24ConstantIndex)) {} //else if (SetSrgMatrixData(3, 1, m_fAfter31ConstantIndex, m_matrix31ConstantIndex)) {} //Not supported by AZSLc else if ( SetSrgMatrixData(3, 2, m_fAfter32ConstantIndex, m_matrix32ConstantIndex)) {} else if ( SetSrgMatrixData(3, 3, m_fAfter33ConstantIndex, m_matrix33ConstantIndex)) {} else if ( SetSrgMatrixData(3, 4, m_fAfter34ConstantIndex, m_matrix34ConstantIndex)) {} //else if (SetSrgMatrixData(4, 1, m_fAfter41ConstantIndex, m_matrix41ConstantIndex)) {} //Not supported by AZSLc else if ( SetSrgMatrixData(4, 2, m_fAfter42ConstantIndex, m_matrix42ConstantIndex)) {} else if ( SetSrgMatrixData(4, 3, m_fAfter43ConstantIndex, m_matrix43ConstantIndex)) {} else if ( SetSrgMatrixData(4, 4, m_fAfter44ConstantIndex, m_matrix44ConstantIndex)) {} m_shaderResourceGroup->Compile(); } BasicRHIComponent::OnFramePrepare(frameGraphBuilder); } MatrixAlignmentTestExampleComponent::MatrixAlignmentTestExampleComponent() { m_supportRHISamplePipeline = true; } void MatrixAlignmentTestExampleComponent::InitializeRenderPipeline() { using namespace AZ; RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice(); AZ::RHI::PipelineStateDescriptorForDraw pipelineStateDescriptor; { m_inputAssemblyBufferPool = RHI::Factory::Get().CreateBufferPool(); RHI::BufferPoolDescriptor bufferPoolDesc; bufferPoolDesc.m_bindFlags = RHI::BufferBindFlags::InputAssembly; bufferPoolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device; m_inputAssemblyBufferPool->Init(*device, bufferPoolDesc); BufferData bufferData; SetFullScreenRect(bufferData.m_positions.data(), nullptr, bufferData.m_indices.data()); // All blue. SetVertexColor(bufferData.m_colors.data(), 0, 0.0, 0.0, 1.0, 1.0); SetVertexColor(bufferData.m_colors.data(), 1, 0.0, 0.0, 1.0, 1.0); SetVertexColor(bufferData.m_colors.data(), 2, 0.0, 0.0, 1.0, 1.0); SetVertexColor(bufferData.m_colors.data(), 3, 0.0, 0.0, 1.0, 1.0); m_inputAssemblyBuffer = RHI::Factory::Get().CreateBuffer(); RHI::BufferInitRequest request; request.m_buffer = m_inputAssemblyBuffer.get(); request.m_descriptor = RHI::BufferDescriptor{ RHI::BufferBindFlags::InputAssembly, sizeof(bufferData) }; request.m_initialData = &bufferData; m_inputAssemblyBufferPool->InitBuffer(request); m_streamBufferViews[0] = { *m_inputAssemblyBuffer, offsetof(BufferData, m_positions), sizeof(BufferData::m_positions), sizeof(VertexPosition) }; m_streamBufferViews[1] = { *m_inputAssemblyBuffer, offsetof(BufferData, m_colors), sizeof(BufferData::m_colors), sizeof(VertexColor) }; RHI::InputStreamLayoutBuilder layoutBuilder; layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT); layoutBuilder.AddBuffer()->Channel("COLOR", RHI::Format::R32G32B32A32_FLOAT); pipelineStateDescriptor.m_inputStreamLayout = layoutBuilder.End(); RHI::ValidateStreamBufferViews(pipelineStateDescriptor.m_inputStreamLayout, m_streamBufferViews); } { const char* triangeShaderFilePath = "Shaders/RHI/MatrixAlignmentTest.azshader"; const char* sampleName = "MatrixAlignmentTest"; const AZ::Name supervariantName = (m_numFloatsAfterMatrix == 1) ? AZ::Name{""} : AZ::Name{"float2"}; auto shader = LoadShader(triangeShaderFilePath, sampleName, &supervariantName); if (shader == nullptr) return; auto shaderVariant = shader->GetRootVariant(); shaderVariant.ConfigurePipelineState(pipelineStateDescriptor); RHI::RenderAttachmentLayoutBuilder attachmentsBuilder; attachmentsBuilder.AddSubpass() ->RenderTargetAttachment(m_outputFormat); [[maybe_unused]] AZ::RHI::ResultCode result = attachmentsBuilder.End(pipelineStateDescriptor.m_renderAttachmentConfiguration.m_renderAttachmentLayout); AZ_Assert(result == AZ::RHI::ResultCode::Success, "Failed to create render attachment layout"); m_pipelineState = shader->AcquirePipelineState(pipelineStateDescriptor); if (!m_pipelineState) { AZ_Error(sampleName, false, "Failed to acquire default pipeline state for shader '%s'", triangeShaderFilePath); return; } m_shaderResourceGroup = CreateShaderResourceGroup(shader, "AlignmentValidatorSrg", sampleName); const Name resolutionConstantId{ "m_resolution" }; FindShaderInputIndex(&m_resolutionConstantIndex, m_shaderResourceGroup, resolutionConstantId, sampleName); const Name rowSelectionConstantId{ "m_numRows" }; FindShaderInputIndex(&m_numRowsConstantIndex, m_shaderResourceGroup, rowSelectionConstantId, sampleName); const Name colSelectionConstantId{ "m_numColumns" }; FindShaderInputIndex(&m_numColumnsConstantIndex, m_shaderResourceGroup, colSelectionConstantId, sampleName); { const Name MatrixName{ "m_matrix11" }; FindShaderInputIndex(&m_matrix11ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter11" }; FindShaderInputIndex(&m_fAfter11ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix12" }; FindShaderInputIndex(&m_matrix12ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter12" }; FindShaderInputIndex(&m_fAfter12ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix13" }; FindShaderInputIndex(&m_matrix13ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter13" }; FindShaderInputIndex(&m_fAfter13ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix14" }; FindShaderInputIndex(&m_matrix14ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter14" }; FindShaderInputIndex(&m_fAfter14ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } // Not supported by AZSLc //{ // const Name MatrixName{ "m_matrix21" }; // FindShaderInputIndex(&m_matrix21ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); // const Name floatAfterMatrixName{ "m_fAfter21" }; // FindShaderInputIndex(&m_fAfter21ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); //} { const Name MatrixName{ "m_matrix22" }; FindShaderInputIndex(&m_matrix22ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter22" }; FindShaderInputIndex(&m_fAfter22ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix23" }; FindShaderInputIndex(&m_matrix23ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter23" }; FindShaderInputIndex(&m_fAfter23ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix24" }; FindShaderInputIndex(&m_matrix24ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter24" }; FindShaderInputIndex(&m_fAfter24ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } // Not supported by AZSLc //{ // const Name MatrixName{ "m_matrix31" }; // FindShaderInputIndex(&m_matrix31ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); // const Name floatAfterMatrixName{ "m_fAfter31" }; // FindShaderInputIndex(&m_fAfter31ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); //} { const Name MatrixName{ "m_matrix32" }; FindShaderInputIndex(&m_matrix32ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter32" }; FindShaderInputIndex(&m_fAfter32ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix33" }; FindShaderInputIndex(&m_matrix33ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter33" }; FindShaderInputIndex(&m_fAfter33ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix34" }; FindShaderInputIndex(&m_matrix34ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter34" }; FindShaderInputIndex(&m_fAfter34ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } // Not supported by AZSLc //{ // const Name MatrixName{ "m_matrix41" }; // FindShaderInputIndex(&m_matrix41ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); // const Name floatAfterMatrixName{ "m_fAfter41" }; // FindShaderInputIndex(&m_fAfter41ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); //} { const Name MatrixName{ "m_matrix42" }; FindShaderInputIndex(&m_matrix42ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter42" }; FindShaderInputIndex(&m_fAfter42ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix43" }; FindShaderInputIndex(&m_matrix43ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter43" }; FindShaderInputIndex(&m_fAfter43ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix44" }; FindShaderInputIndex(&m_matrix44ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter44" }; FindShaderInputIndex(&m_fAfter44ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } } // Creates a scope for rendering the triangle. { struct ScopeData { }; const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData) { // Binds the swap chain as a color attachment. Clears it to white. { RHI::ImageScopeAttachmentDescriptor descriptor; descriptor.m_attachmentId = m_outputAttachmentId; descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load; frameGraph.UseColorAttachment(descriptor); } // We will submit a single draw item. frameGraph.SetEstimatedItemCount(1); }; RHI::EmptyCompileFunction<ScopeData> compileFunction; const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData) { RHI::CommandList* commandList = context.GetCommandList(); // Set persistent viewport and scissor state. commandList->SetViewports(&m_viewport, 1); commandList->SetScissors(&m_scissor, 1); const RHI::IndexBufferView indexBufferView = { *m_inputAssemblyBuffer, offsetof(BufferData, m_indices), sizeof(BufferData::m_indices), RHI::IndexFormat::Uint16 }; RHI::DrawIndexed drawIndexed; drawIndexed.m_indexCount = 6; drawIndexed.m_instanceCount = 2; const RHI::ShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroup->GetRHIShaderResourceGroup() }; RHI::DrawItem drawItem; drawItem.m_arguments = drawIndexed; drawItem.m_pipelineState = m_pipelineState.get(); drawItem.m_indexBufferView = &indexBufferView; drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups)); drawItem.m_shaderResourceGroups = shaderResourceGroups; drawItem.m_streamBufferViewCount = static_cast<uint8_t>(m_streamBufferViews.size()); drawItem.m_streamBufferViews = m_streamBufferViews.data(); // Submit the triangle draw item. commandList->Submit(drawItem); }; m_scopeProducers.emplace_back( aznew RHI::ScopeProducerFunction< ScopeData, decltype(prepareFunction), decltype(compileFunction), decltype(executeFunction)>( RHI::ScopeId{"Triangle"}, ScopeData{}, prepareFunction, compileFunction, executeFunction)); } m_needPipelineReload = false; } void MatrixAlignmentTestExampleComponent::Activate() { using namespace AZ; m_numRows = 4; m_numColumns = 4; m_matrixLocationValue = 1.0f; m_checkedMatrixValues[0][0] = true; m_checkedMatrixValues[0][1] = false; m_checkedMatrixValues[0][2] = true; m_checkedMatrixValues[0][3] = false; m_checkedMatrixValues[1][0] = false; m_checkedMatrixValues[1][1] = true; m_checkedMatrixValues[1][2] = false; m_checkedMatrixValues[1][3] = true; m_checkedMatrixValues[2][0] = true; m_checkedMatrixValues[2][1] = false; m_checkedMatrixValues[2][2] = true; m_checkedMatrixValues[2][3] = false; m_checkedMatrixValues[3][0] = false; m_checkedMatrixValues[3][1] = true; m_checkedMatrixValues[3][2] = false; m_checkedMatrixValues[3][3] = true; m_numFloatsAfterMatrix = 1; m_floatAfterMatrix = 0.5; m_needPipelineReload = true; InitializeRenderPipeline(); m_imguiSidebar.Activate(); AZ::RHI::RHISystemNotificationBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); } void MatrixAlignmentTestExampleComponent::ReleaseRhiData() { m_inputAssemblyBuffer = nullptr; m_inputAssemblyBufferPool = nullptr; m_pipelineState = nullptr; m_shaderResourceGroup = nullptr; m_scopeProducers.clear(); } void MatrixAlignmentTestExampleComponent::Deactivate() { m_inputAssemblyBuffer = nullptr; m_inputAssemblyBufferPool = nullptr; m_pipelineState = nullptr; m_shaderResourceGroup = nullptr; AZ::TickBus::Handler::BusDisconnect(); AZ::RHI::RHISystemNotificationBus::Handler::BusDisconnect(); m_imguiSidebar.Deactivate(); m_windowContext = nullptr; m_scopeProducers.clear(); } } // namespace AtomSampleViewer
45.192377
163
0.627967
Bindless-Chicken
586bee0bdc08ad7200215c2abdf39c0f4803774a
9,735
cpp
C++
src/core/SLSManager.cpp
rstular/srt-live-server
968d29b7bd4d81b0b6cbe702ebf6bbc164b6a22c
[ "MIT" ]
4
2021-12-17T07:58:48.000Z
2022-02-04T17:35:37.000Z
src/core/SLSManager.cpp
rstular/srt-live-server
968d29b7bd4d81b0b6cbe702ebf6bbc164b6a22c
[ "MIT" ]
null
null
null
src/core/SLSManager.cpp
rstular/srt-live-server
968d29b7bd4d81b0b6cbe702ebf6bbc164b6a22c
[ "MIT" ]
1
2021-12-15T21:56:57.000Z
2021-12-15T21:56:57.000Z
/** * The MIT License (MIT) * * Copyright (c) 2019-2020 Edward.Wu * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <errno.h> #include <string.h> #include "spdlog/spdlog.h" #include <nlohmann/json.hpp> using json = nlohmann::json; #include "common.hpp" #include "SLSManager.hpp" #include "SLSLog.hpp" #include "SLSListener.hpp" #include "SLSPublisher.hpp" /** * srt conf */ SLS_CONF_DYNAMIC_IMPLEMENT(srt) /** * CSLSManager class implementation */ #define DEFAULT_GROUP 1 CSLSManager::CSLSManager() { m_worker_threads = DEFAULT_GROUP; m_server_count = 1; m_list_role = NULL; m_single_group = NULL; m_map_data = NULL; m_map_publisher = NULL; m_map_puller = NULL; m_map_pusher = NULL; } CSLSManager::~CSLSManager() { } int CSLSManager::start() { int ret = 0; int i = 0; // Read loaded config file sls_conf_srt_t *conf_srt = (sls_conf_srt_t *)sls_conf_get_root_conf(); if (!conf_srt) { spdlog::error("[{}] CSLSManager::start, no srt info, please check the conf file.", fmt::ptr(this)); return SLS_ERROR; } //set log level if (strlen(conf_srt->log_level) > 0) { sls_set_log_level(conf_srt->log_level); } //set log file if (strlen(conf_srt->log_file) > 0) { sls_set_log_file(conf_srt->log_file); } sls_conf_server_t *conf_server = (sls_conf_server_t *)conf_srt->child; if (!conf_server) { spdlog::error("[{}] CSLSManager::start, no server info, please check the conf file.", fmt::ptr(this)); return SLS_ERROR; } m_server_count = sls_conf_get_conf_count((sls_conf_base_t *)conf_server); sls_conf_server_t *conf = conf_server; m_map_data = new CSLSMapData[m_server_count]; m_map_publisher = new CSLSMapPublisher[m_server_count]; m_map_puller = new CSLSMapRelay[m_server_count]; m_map_pusher = new CSLSMapRelay[m_server_count]; //role list m_list_role = new CSLSRoleList; spdlog::info("[{}] CSLSManager::start, new m_list_role={}.", fmt::ptr(this), fmt::ptr(m_list_role)); //create listeners according config, delete by groups for (i = 0; i < m_server_count; i++) { CSLSListener *p = new CSLSListener(); //deleted by groups p->set_role_list(m_list_role); p->set_conf((sls_conf_base_t *)conf); p->set_record_hls_path_prefix(conf_srt->record_hls_path_prefix); p->set_map_data("", &m_map_data[i]); p->set_map_publisher(&m_map_publisher[i]); p->set_map_puller(&m_map_puller[i]); p->set_map_pusher(&m_map_pusher[i]); if (p->init() != SLS_OK) { spdlog::error("[{}] CSLSManager::start, p->init failed.", fmt::ptr(this)); return SLS_ERROR; } if (p->start() != SLS_OK) { spdlog::error("[{}] CSLSManager::start, p->start failed.", fmt::ptr(this)); return SLS_ERROR; } m_servers.push_back(p); conf = (sls_conf_server_t *)conf->sibling; } spdlog::info("[{}] CSLSManager::start, init listeners, count={:d}.", fmt::ptr(this), m_server_count); //create groups m_worker_threads = conf_srt->worker_threads; if (m_worker_threads == 0) { CSLSGroup *p = new CSLSGroup(); p->set_worker_number(0); p->set_role_list(m_list_role); p->set_worker_connections(conf_srt->worker_connections); p->set_stat_post_interval(conf_srt->stat_post_interval); if (SLS_OK != p->init_epoll()) { spdlog::error("[{}] CSLSManager::start, p->init_epoll failed.", fmt::ptr(this)); return SLS_ERROR; } m_workers.push_back(p); m_single_group = p; } else { for (i = 0; i < m_worker_threads; i++) { CSLSGroup *p = new CSLSGroup(); p->set_worker_number(i); p->set_role_list(m_list_role); p->set_worker_connections(conf_srt->worker_connections); p->set_stat_post_interval(conf_srt->stat_post_interval); if (SLS_OK != p->init_epoll()) { spdlog::error("[{}] CSLSManager::start, p->init_epoll failed.", fmt::ptr(this)); return SLS_ERROR; } p->start(); m_workers.push_back(p); } } spdlog::info("[{}] CSLSManager::start, init worker, count={:d}.", fmt::ptr(this), m_worker_threads); return ret; } int CSLSManager::single_thread_handler() { if (m_single_group) { return m_single_group->handler(); } return SLS_OK; } bool CSLSManager::is_single_thread() { if (m_single_group) return true; return false; } int CSLSManager::stop() { int ret = 0; int i = 0; // spdlog::info("[{}] CSLSManager::stop.", fmt::ptr(this)); //stop all listeners for (CSLSListener *server : m_servers) { if (server) { server->uninit(); } } m_servers.clear(); vector<CSLSGroup *>::iterator it_worker; for (it_worker = m_workers.begin(); it_worker != m_workers.end(); it_worker++) { CSLSGroup *p = *it_worker; if (p) { p->stop(); p->uninit_epoll(); delete p; p = NULL; } } m_workers.clear(); if (m_map_data) { delete[] m_map_data; m_map_data = NULL; } if (m_map_publisher) { delete[] m_map_publisher; m_map_publisher = NULL; } if (m_map_puller) { delete[] m_map_puller; m_map_puller = NULL; } if (m_map_pusher) { delete[] m_map_pusher; m_map_pusher = NULL; } //release rolelist if (m_list_role) { spdlog::info("[{}] CSLSManager::stop, release rolelist, size={:d}.", fmt::ptr(this), m_list_role->size()); m_list_role->erase(); delete m_list_role; m_list_role = NULL; } return ret; } int CSLSManager::reload() { spdlog::info("[{}] CSLSManager::reload begin.", fmt::ptr(this)); // stop all listeners for (CSLSListener *server : m_servers) { if (server) { server->uninit(); } } m_servers.clear(); // set all groups reload flag for (CSLSGroup *worker : m_workers) { if (worker) { worker->reload(); } } return 0; } int CSLSManager::check_invalid() { vector<CSLSGroup *>::iterator it; vector<CSLSGroup *>::iterator it_erase; vector<CSLSGroup *>::iterator it_end = m_workers.end(); for (it = m_workers.begin(); it != it_end;) { CSLSGroup *worker = *it; it_erase = it; it++; if (NULL == worker) { m_workers.erase(it_erase); continue; } if (worker->is_exit()) { spdlog::info("[{}] CSLSManager::check_invalid, delete worker={}.", fmt::ptr(this), fmt::ptr(worker)); worker->stop(); worker->uninit_epoll(); delete worker; m_workers.erase(it_erase); } } if (m_workers.size() == 0) return SLS_OK; return SLS_ERROR; } std::string CSLSManager::get_stat_info() { json info_obj; info_obj["stats"] = json::array(); for (CSLSGroup *worker : m_workers) { if (worker) { vector<stat_info_t> worker_info; worker->get_stat_info(worker_info); for (stat_info_t &role_info : worker_info) { info_obj["stats"].push_back(json{ {"port", role_info.port}, {"role", role_info.role}, {"pub_domain_app", role_info.pub_domain_app}, {"stream_name", role_info.stream_name}, {"url", role_info.url}, {"remote_ip", role_info.remote_ip}, {"remote_port", role_info.remote_port}, {"start_time", role_info.start_time}, {"kbitrate", role_info.kbitrate}}); } } } return info_obj.dump(); } int CSLSManager::stat_client_callback(void *p, HTTP_CALLBACK_TYPE type, void *v, void *context) { CSLSManager *manager = (CSLSManager *)context; if (HCT_REQUEST_CONTENT == type) { std::string *p_response = (std::string *)v; p_response->assign(manager->get_stat_info()); } else if (HCT_RESPONSE_END == type) { //response info maybe include info that server send client, such as reload cmd... } else { } return SLS_OK; }
27.116992
114
0.58942
rstular
586e6fa9f3536074c0781d20546a308cc5f1b608
31,226
cpp
C++
partial_digestion/src/uDGP.cpp
shuai-huang/turnpike-beltway
20b68a48b68c2daad02346b1c076c0dce99c4431
[ "Apache-2.0" ]
null
null
null
partial_digestion/src/uDGP.cpp
shuai-huang/turnpike-beltway
20b68a48b68c2daad02346b1c076c0dce99c4431
[ "Apache-2.0" ]
null
null
null
partial_digestion/src/uDGP.cpp
shuai-huang/turnpike-beltway
20b68a48b68c2daad02346b1c076c0dce99c4431
[ "Apache-2.0" ]
1
2020-01-06T17:17:17.000Z
2020-01-06T17:17:17.000Z
#include<chrono> #include "uDGP.h" uDGP::uDGP() { M=0; } void uDGP::SetOutputFile(char* output_file) { output_ite_file = output_file; } void uDGP::SetInitFile(char* init_file) { smp_pos_init_file = init_file; } double uDGP::NormalCdf(double x_val, double mu, double sigma) { return 0.5*(1+erf((x_val-mu)/(sigma*sqrt(2)))); } //bool uDGP::mypair_des_com ( const mypair& l, const mypair& r) { return l.second > r.second; } void uDGP::SetData(DataReader* data_reader) { raw_distribution = data_reader->getDistributionData(); max_distance = 0; for (int i=0; i<num_raw_uq_distance; i++) { double raw_val = raw_distribution[i][0]; if (raw_val>max_distance) { max_distance = raw_val; } } domain_sz = max_distance + 2*tau; M = round(max_distance/min_space_unit) + 1 + 2*round(tau/min_space_unit); // convert raw data to uq_distance and uq_distribution, convolution with the noise distribution // this is used to determine the possible locations for (int i=0; i<num_raw_uq_distance; i++) { double raw_val = raw_distribution[i][0]; if (raw_val==0) { // only keep track of distances between two different points continue; } int raw_distance_idx = round(raw_val/min_space_unit); vector<int> distance_val_approx_seq; distance_val_approx_seq.push_back(raw_distance_idx); for (int j=1; j<=M; j++) { if (j*min_space_unit>tau) { break; } if (((raw_distance_idx-j)*min_space_unit)>=0) { distance_val_approx_seq.push_back(raw_distance_idx-j); } if (((raw_distance_idx+j)*min_space_unit)<=domain_sz) { distance_val_approx_seq.push_back(raw_distance_idx+j); } } for (int j=0; j<distance_val_approx_seq.size(); j++) { int distance_val_approx = distance_val_approx_seq[j]; if (all_distance_diff.find(distance_val_approx)==all_distance_diff.end()) { // contains all the distances to be considered all_distance_diff[distance_val_approx] = 0; } } } } double uDGP::ComputeEstDbt( VectorXd* smp_vec, int distance_val) { double est_dbt_val = 0; //est_dbt_val += ( (*smp_vec).segment(0, M-distance_val).array() * (*smp_vec).segment(distance_val, M-distance_val).array() ).sum(); int j_idx, k_idx; for (int i=0; i<valid_idx_vec.size(); i++) { j_idx = valid_idx_vec[i]; k_idx = j_idx + distance_val; if (k_idx<=M-1) { est_dbt_val += (*smp_vec)(j_idx) * (*smp_vec)(k_idx); } } return est_dbt_val; } void uDGP::ComputeEstProj(VectorXd* smp_vec, VectorXd* smp_vec_proj, double mut_factor, int distance_val) { //(*smp_vec_proj).segment(0, M-distance_val) += mut_factor * (*smp_vec).segment(distance_val, M-distance_val); //(*smp_vec_proj).segment(distance_val, M-distance_val) += mut_factor * (*smp_vec).segment(0, M-distance_val); int j_idx, k_idx, l_idx; for (int i=0; i<valid_idx_vec.size(); i++) { j_idx = valid_idx_vec[i]; k_idx = j_idx + distance_val; l_idx = j_idx - distance_val; if (k_idx<=M-1) { (*smp_vec_proj)(j_idx) += mut_factor * (*smp_vec)(k_idx); } if (l_idx>=0) { (*smp_vec_proj)(j_idx) += mut_factor * (*smp_vec)(l_idx); } } } void uDGP::SetMeasureMatrix() { // set measurement matrix and the all_distribution // set the two anchor points indices corresponding to the two outmost points anchor_one = round(tau/min_space_unit); // the index starts from 0, there are round(tau/min_space_unit) segments to the left anchor_two = anchor_one + round(max_distance/min_space_unit); int dist_val_tmp_1, dist_val_tmp_2; // Put the anchor point positions // Find valid idx positions valid_idx_pos = VectorXd::Zero(M); for (int i=0; i<(anchor_one+round(tau/min_space_unit)+1); i++) { anchor_one_seq[i]=0; valid_idx_pos[i]=1; valid_idx_vec.push_back(i); } for (int i=anchor_two-round(tau/min_space_unit); i<(anchor_two+round(tau/min_space_unit)+1); i++) { anchor_two_seq[i]=0; valid_idx_pos[i]=1; valid_idx_vec.push_back(i); } for (int i=anchor_one+1; i<anchor_two; i++) { // distance to first anchor point dist_val_tmp_1 = abs(i-anchor_one); // distance to second anchor point dist_val_tmp_2 = abs(i-anchor_two); if ( ( all_distance_diff.find(dist_val_tmp_1)!=all_distance_diff.end() ) && ( all_distance_diff.find(dist_val_tmp_2)!=all_distance_diff.end() ) ) { if ( (anchor_one_seq.find(i)==anchor_one_seq.end()) && (anchor_two_seq.find(i)==anchor_two_seq.end()) ) { valid_idx_pos[i]=1; valid_idx_vec.push_back(i); valid_idx_vec_exclude.push_back(i); } } } num_pos = valid_idx_vec.size(); cout<<"Number of valid index: "<<valid_idx_vec.size()<<endl; cout<<"Number of anchor one: "<<anchor_one_seq.size()<<endl; cout<<"Number of anchor two: "<<anchor_two_seq.size()<<endl; // Find all possible distances in the domain all_distribution[0]=0; all_distance.push_back(0); int distance_val_tmp; for (int i=0; i<num_pos; i++) { for (int j=i+1; j<num_pos; j++) { distance_val_tmp = abs(valid_idx_vec[i]-valid_idx_vec[j]); // In the noiseless case, only consider the distances that appear in the measurements if (all_distance_diff.find(distance_val_tmp)==all_distance_diff.end()) { continue; } if ( all_distribution.find(distance_val_tmp)==all_distribution.end() ) { all_distribution[distance_val_tmp]=0; all_distance.push_back(distance_val_tmp); } } } cout<<"Valid distance size: "<<all_distance.size()<<endl; cout<<"Distribution size: "<<all_distribution.size()<<endl; // approximate the oracle distance distribution for (int i=0; i<num_raw_uq_distance; i++) { double raw_val = raw_distribution[i][0]; map<int, double> prob_cov; double prob_cov_sum = 0; int raw_distance_idx = round(raw_val/min_space_unit); vector<int> distance_val_approx_seq; if (all_distribution.find(raw_distance_idx)!=all_distribution.end()) { distance_val_approx_seq.push_back(raw_distance_idx); if (raw_distance_idx==0) { prob_cov[raw_distance_idx] = 2*(NormalCdf( (raw_distance_idx+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx)*min_space_unit, raw_val, sigma) ); } else { prob_cov[raw_distance_idx] = NormalCdf( (raw_distance_idx+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx-0.5)*min_space_unit, raw_val, sigma); } prob_cov_sum += prob_cov[raw_distance_idx]; } for (int j=1; j<M; j++) { if (j*min_space_unit>tau) { break; } if (all_distribution.find(raw_distance_idx-j)!=all_distribution.end()) { distance_val_approx_seq.push_back(raw_distance_idx-j); prob_cov[raw_distance_idx-j] = NormalCdf( (raw_distance_idx-j+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx-j-0.5)*min_space_unit, raw_val, sigma ); prob_cov_sum += prob_cov[raw_distance_idx-j]; } if (all_distribution.find(raw_distance_idx+j)!=all_distribution.end()) { distance_val_approx_seq.push_back(raw_distance_idx+j); prob_cov[raw_distance_idx+j] = NormalCdf( (raw_distance_idx+j+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx+j-0.5)*min_space_unit, raw_val, sigma ); prob_cov_sum += prob_cov[raw_distance_idx+j]; } } prob_cov_sum = 1; for (int j=0; j<distance_val_approx_seq.size(); j++) { int distance_val_approx = distance_val_approx_seq[j]; prob_cov[distance_val_approx] = prob_cov[distance_val_approx]/prob_cov_sum; double distribution_val_tmp = prob_cov[distance_val_approx]*raw_distribution[i][1]; all_distribution[distance_val_approx] += distribution_val_tmp; } } cout<<"No. of raw uq sq distance: "<<raw_distribution.size()<<endl; cout<<"Distribution size: "<<all_distribution.size()<<"\t"<<all_distance.size()<<endl; // sort the all_distance sort(all_distance.begin(), all_distance.end()); // count the number of blocks for each unique distance, this is for the multi-threading program for (int i=0; i<all_distance.size(); i++) { all_block_count.push_back({all_distance[i], 1}); } // sort the all_distance according to the block_count sort(all_block_count.begin(), all_block_count.end(), []( const mypair& l, const mypair& r) { return l.second > r.second; }); num_thread_assign = num_thread > all_distance.size() ? all_distance.size() : num_thread; vector<int> all_partition_sz(num_thread_assign,0); for (int i=0; i<all_block_count.size(); i++) { int idx_min=distance( all_partition_sz.begin(), min_element(all_partition_sz.begin(), all_partition_sz.end()) ); all_partition[idx_min].push_back(all_block_count[i].first); all_partition_sz[idx_min] += all_block_count[i].second; } // initialize the estimated sq distributin here *** for (int i=0; i<all_distance.size(); i++) { est_distribution[all_distance[i]] = 0; } cout<<"Multithreading assignment stats: "; for (int i=0; i<all_partition_sz.size(); i++) { cout<<all_partition_sz[i]<<"\t"; } cout<<endl; cout<<"Setting measurement matrices finished."<<endl; } void uDGP::Initialization() { smp_pos_init = VectorXd::Zero(M); if (init_type==1) { // initialization with leading eigenvector // Compute the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { int distance_val_tmp = ite->first; anchor_one_seq[ite->first] = NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2) ); } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { int distance_val_tmp = ite->first; anchor_two_seq[ite->first] = NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } // use the probability vector as the initializer int row_idx, col_idx; for (int i=0; i<all_distance.size(); i++) { VectorXd smp_pos_init_tmp = VectorXd::Zero(M); smp_pos_init_tmp.segment(0, M-all_distance[i]).array() += valid_idx_pos.segment(0, M-all_distance[i]).array() * valid_idx_pos.segment(all_distance[i], M-all_distance[i]).array(); D_mat_norm[all_distance[i]] = sqrt(smp_pos_init_tmp.sum()); smp_pos_init_tmp *= all_distribution[all_distance[i]] / smp_pos_init_tmp.sum(); smp_pos_init += smp_pos_init_tmp; } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = anchor_two_seq[ite->first]; } // Sum up the points other than the two anchor points and then normalize double smp_pos_init_exclude_sum = smp_pos_init.segment((anchor_one+round(tau/min_space_unit)+1), M-(4*round(tau/min_space_unit)+2)).sum(); smp_pos_init.segment((anchor_one+round(tau/min_space_unit)+1), M-(4*round(tau/min_space_unit)+2)) = smp_pos_init.segment((anchor_one+round(tau/min_space_unit)+1), M-(4*round(tau/min_space_unit)+2)) / smp_pos_init_exclude_sum * (num_smp-2); VectorXd smp_pos_init_reverse = smp_pos_init.reverse(); smp_pos_init = 0.5 * (smp_pos_init + smp_pos_init_reverse); obj_val = ComputeObjFun(smp_pos_init); cout<<"Obj_val: "<<obj_val<<endl; // use power method to compute the singular vector for (int ite=0; ite<max_sg_ite; ite++) { VectorXd smp_pos_init_pre = smp_pos_init; VectorXd smp_pos_init_tmp = VectorXd::Zero(M); for (int i=0; i<all_distance.size(); i++) { smp_pos_init_tmp.segment(0, M-all_distance[i]) += all_distribution[all_distance[i]] / pow(D_mat_norm[all_distance[i]], 2) * smp_pos_init_pre.segment(all_distance[i], M-all_distance[i]); smp_pos_init_tmp.segment(all_distance[i], M-all_distance[i]) += all_distribution[all_distance[i]] / pow(D_mat_norm[all_distance[i]], 2) * smp_pos_init_pre.segment(0, M-all_distance[i]); } smp_pos_init = VectorXd::Zero(M); for (int i=0; i<valid_idx_vec.size(); i++) { smp_pos_init(valid_idx_vec[i]) = smp_pos_init_tmp(valid_idx_vec[i]); } double smp_pos_init_norm = smp_pos_init.norm(); smp_pos_init = smp_pos_init/smp_pos_init_norm; double sg_cvg_val = (smp_pos_init-smp_pos_init_pre).norm(); cout<<ite<<" "<<sg_cvg_val<<endl; if (sg_cvg_val<sg_tol) { cout<<"Eig_iteration: "<<ite<<endl; break; } } smp_pos_init = smp_pos_init * sqrt(num_smp*1.0); // break even unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count(); default_random_engine generator(seed); normal_distribution<double> distribution(0, perturb_std); for (int i=0; i<M; i++) { smp_pos_init(i) = smp_pos_init(i) * (1+distribution(generator)); } // map the initialization onto the convex set // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // Project on to the l1-ball with box constraints VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_init(valid_idx_vec_exclude[i]); } smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_init(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } obj_val = ComputeObjFun(smp_pos_init); cout<<"Obj val: "<<obj_val<<endl; } else if (init_type==2) { // initialize with random vector unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count(); default_random_engine generator(seed); normal_distribution<double> distribution(0, perturb_std); for (int i=0; i<M; i++) { smp_pos_init(i) = abs(distribution(generator)); } // Compute the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( ( distance_val_tmp >= (M-round(3*sigma/min_space_unit)) ) && ( distance_val_tmp <= M-1 ) ) { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2) ); } else { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2) ); } } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( (distance_val_tmp >= 0) && (distance_val_tmp<=round(3*sigma/min_space_unit)) ) { anchor_two_seq[ite->first] += NormalCdf( (M+distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (M+distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } else { anchor_two_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end();ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end();ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // map the initialization onto the convex set // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // Project on to the l1-ball with box constraints VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_init(valid_idx_vec_exclude[i]); } smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_init(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } //obj_val = ComputeObjFun(smp_pos_init); obj_val = 0; cout<<"Obj val: "<<obj_val<<endl; } else if (init_type==3) { // initialize with uniform vector smp_pos_init = VectorXd::Ones(M); // Compute the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( ( distance_val_tmp >= (M-round(3*sigma/min_space_unit)) ) && ( distance_val_tmp <= M-1 ) ) { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2) ); } else { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2) ); } } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( (distance_val_tmp >= 0) && (distance_val_tmp<=round(3*sigma/min_space_unit)) ) { anchor_two_seq[ite->first] += NormalCdf( (M+distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (M+distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } else { anchor_two_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end();ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end();ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // break even unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count(); default_random_engine generator(seed); normal_distribution<double> distribution(0, perturb_std); for (int i=0; i<M; i++) { smp_pos_init(i) = smp_pos_init(i) * (1+distribution(generator)); } // map the initialization onto the convex set // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // Project on to the l1-ball with box constraints VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_init(valid_idx_vec_exclude[i]); } smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_init(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } obj_val = ComputeObjFun(smp_pos_init); cout<<"Obj val: "<<obj_val<<endl; } else { cout<<"Unknown initialization type."<<endl; abort(); } cout<<"Initialization finished."<<endl; } VectorXd uDGP::ProjectOntoCvxSet(VectorXd smp_vec, int num_smp_proj) { // make sure all the entries of v are above the convex set // Note that the vector index starts from 0 double offset = -smp_vec.array().minCoeff() + num_smp_proj; smp_vec = smp_vec.array() + offset; VectorXd smp_sort_vec = smp_vec; sort(smp_sort_vec.data(), smp_sort_vec.data()+smp_sort_vec.size(), greater<double>()); int smp_vec_len=smp_sort_vec.size(); double theta = 0; int check_status = 0; for (int r=1; r<=num_smp_proj; r++) { VectorXd smp_sort_vec_new = smp_sort_vec.segment(r-1, smp_vec_len-r+1); VectorXd smp_sort_vec_new_cumsum = smp_sort_vec_new; for (int j=1; j<smp_sort_vec_new_cumsum.size(); j++) { smp_sort_vec_new_cumsum(j) += smp_sort_vec_new_cumsum(j-1); } VectorXd smp_sort_vec_new_thr = smp_sort_vec_new_cumsum; for (int j=0; j<smp_sort_vec_new_thr.size(); j++) { smp_sort_vec_new_thr(j) = smp_sort_vec_new(j) - (smp_sort_vec_new_thr(j)-(num_smp_proj-r+1))/(j+1); } int rho_new = -1; for (int j=smp_sort_vec_new_thr.size()-1; j>=0; j--) { if (smp_sort_vec_new_thr(j)>0) { rho_new = j+1; // Note that the vector index starts from 0, we need to add 1 here break; } } if (rho_new==-1) {break;} // check that rho = rho_new+r-1 is larger than num_smp_proj if (rho_new+r-1<=num_smp_proj) {continue;} // Compute the threshold double theta_new = (smp_sort_vec_new_cumsum(rho_new-1)-(num_smp_proj-r+1))/rho_new; int break_marker = 0; double w_r = smp_sort_vec(r-1)-theta_new; if ( (w_r>0) && (w_r<1) ) { if (r==1) { break_marker = 1; check_status = 1; } else { double w_rm1 = smp_sort_vec(r-2)-theta_new ; if (w_rm1>=1) { break_marker=1; check_status=1; } } } else { continue; } theta = theta_new; if (break_marker==1) { break; } } VectorXd smp_vec_proj = smp_vec; if (check_status==1) { smp_vec_proj = smp_vec.array() - theta; for (int i=0; i<smp_vec_len; i++) { if (smp_vec_proj(i)<0) { smp_vec_proj(i)=0; } if (smp_vec_proj(i)>1) { smp_vec_proj(i)=1; } } } else { // set the top N entries to 1 and the rest to 0 double thd_tmp = smp_sort_vec(num_smp_proj-1); for (int i=0; i<smp_vec_len; i++) { if (smp_vec_proj(i)>=thd_tmp) { smp_vec_proj(i)=1; } else { smp_vec_proj(i)=0; } } } return smp_vec_proj; } void uDGP::GradientDescent() { smp_pos = smp_pos_init; step = step_ori; obj_val = ComputeObjFun(smp_pos); VectorXd smp_pos_pre; double obj_val_pre; int ite; int num_cov = 0; for (ite=1; ite<max_ite; ite++) { //for (int i=0; i<all_distance.size(); i++) { // if (all_distribution[all_distance[i]]>0) { // cout<<all_distance[i]<<" "<<all_distribution[all_distance[i]]<<" "<<est_distribution[all_distance[i]]<<" "; // } //} //cout<<endl; smp_pos_pre = smp_pos; obj_val_pre = obj_val; VectorXd smp_pos_der = ComputeGradient(smp_pos_pre); smp_pos_der = smp_pos_der.array() - smp_pos_der.sum()/M; VectorXd smp_pos_tmp = VectorXd::Zero(M); while (step>step_thd) { smp_pos_tmp = smp_pos_pre-smp_pos_der*step; VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_tmp(valid_idx_vec_exclude[i]); } smp_pos_tmp = VectorXd::Zero(M); smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_tmp(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_tmp[ite->first] = anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_tmp[ite->first] = anchor_two_seq[ite->first]; } obj_val = ComputeObjFun(smp_pos_tmp); if ((obj_val<obj_val_pre)||(obj_val==0)) { step = step/bkt_rate; break; } else { step = step*bkt_rate; } } if (step<=step_thd) { cout<<"Step size too small!" << "\t"<<step<<"\t"<<smp_pos_tmp.sum()<<"\t"<<num_smp<<endl; break; } smp_pos = smp_pos_tmp; VectorXd smp_pos_diff = smp_pos - smp_pos_pre; double cvg_val = smp_pos_diff.norm() / smp_pos.norm(); if (cvg_val<cvg_thd) { num_cov += 1; } if (num_cov>=10) { cout<<"Convergence reached!"<<endl; break; } // Save the results at each iteration // choose between the trunc and app mode when saving the results //ofstream write_result(output_ite_file, ios_base::trunc); //ofstream write_result(output_ite_file, ios_base::app); //write_result<<obj_val<<" "; //for (int i=0; i<smp_pos.size(); i++) { // write_result<<smp_pos(i)<<" "; //} //write_result<<"\n"; //write_result.close(); cout<<"Ite: "<<ite<<"\t"<<step<<"\t"<<obj_val<<"\t"<<cvg_val<<"\t"<<smp_pos.sum()<<endl; } if (ite>=max_ite) { cout<<"Max iteration reached!"<<endl; } } VectorXd uDGP::ComputeGradient(VectorXd smp_pos_vect) {return VectorXd::Zero(1);} void uDGP::ComputeGradientMuti( vector<int> all_distance_block, VectorXd* smp_vec_muti, VectorXd* smp_der_seq_pt, int val_idx ) {} double uDGP::ComputeObjFun(VectorXd smp_pos_vect) { return 0.0;} void uDGP::ComputeObjFunMuti(vector<int> all_distance_block, VectorXd* smp_vec_muti, vector<double>* obj_seq_pt, int val_idx ) {} VectorXd uDGP::GetSamplePos() {return smp_pos;} double uDGP::GetObjFun() {return obj_val;} uDGP::~uDGP() {}
41.801874
247
0.600749
shuai-huang
5871ec92b26b8a28353bb7b4803321901bae76f4
32,269
hpp
C++
Sources/SolarTears/Rendering/Vulkan/VulkanFunctions.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
4
2021-06-30T16:00:20.000Z
2021-10-13T06:17:56.000Z
Sources/SolarTears/Rendering/Vulkan/VulkanFunctions.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
Sources/SolarTears/Rendering/Vulkan/VulkanFunctions.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <vulkan/vulkan.h> #ifdef VK_NO_PROTOTYPES #define DECLARE_VULKAN_FUNCTION(funcName) extern PFN_##funcName funcName; extern "C" { DECLARE_VULKAN_FUNCTION(vkCreateInstance) DECLARE_VULKAN_FUNCTION(vkDestroyInstance) DECLARE_VULKAN_FUNCTION(vkEnumeratePhysicalDevices) DECLARE_VULKAN_FUNCTION(vkGetDeviceProcAddr) DECLARE_VULKAN_FUNCTION(vkGetInstanceProcAddr) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceQueueFamilyProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceMemoryProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFeatures) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFormatProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceImageFormatProperties) DECLARE_VULKAN_FUNCTION(vkCreateDevice) DECLARE_VULKAN_FUNCTION(vkDestroyDevice) DECLARE_VULKAN_FUNCTION(vkEnumerateInstanceVersion) DECLARE_VULKAN_FUNCTION(vkEnumerateInstanceLayerProperties) DECLARE_VULKAN_FUNCTION(vkEnumerateInstanceExtensionProperties) DECLARE_VULKAN_FUNCTION(vkEnumerateDeviceLayerProperties) DECLARE_VULKAN_FUNCTION(vkEnumerateDeviceExtensionProperties) DECLARE_VULKAN_FUNCTION(vkGetDeviceQueue) DECLARE_VULKAN_FUNCTION(vkQueueSubmit) DECLARE_VULKAN_FUNCTION(vkQueueWaitIdle) DECLARE_VULKAN_FUNCTION(vkDeviceWaitIdle) DECLARE_VULKAN_FUNCTION(vkAllocateMemory) DECLARE_VULKAN_FUNCTION(vkFreeMemory) DECLARE_VULKAN_FUNCTION(vkMapMemory) DECLARE_VULKAN_FUNCTION(vkUnmapMemory) DECLARE_VULKAN_FUNCTION(vkFlushMappedMemoryRanges) DECLARE_VULKAN_FUNCTION(vkInvalidateMappedMemoryRanges) DECLARE_VULKAN_FUNCTION(vkGetDeviceMemoryCommitment) DECLARE_VULKAN_FUNCTION(vkGetBufferMemoryRequirements) DECLARE_VULKAN_FUNCTION(vkBindBufferMemory) DECLARE_VULKAN_FUNCTION(vkGetImageMemoryRequirements) DECLARE_VULKAN_FUNCTION(vkBindImageMemory) DECLARE_VULKAN_FUNCTION(vkGetImageSparseMemoryRequirements) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSparseImageFormatProperties) DECLARE_VULKAN_FUNCTION(vkQueueBindSparse) DECLARE_VULKAN_FUNCTION(vkCreateFence) DECLARE_VULKAN_FUNCTION(vkDestroyFence) DECLARE_VULKAN_FUNCTION(vkResetFences) DECLARE_VULKAN_FUNCTION(vkGetFenceStatus) DECLARE_VULKAN_FUNCTION(vkWaitForFences) DECLARE_VULKAN_FUNCTION(vkCreateSemaphore) DECLARE_VULKAN_FUNCTION(vkDestroySemaphore) DECLARE_VULKAN_FUNCTION(vkCreateEvent) DECLARE_VULKAN_FUNCTION(vkDestroyEvent) DECLARE_VULKAN_FUNCTION(vkGetEventStatus) DECLARE_VULKAN_FUNCTION(vkSetEvent) DECLARE_VULKAN_FUNCTION(vkResetEvent) DECLARE_VULKAN_FUNCTION(vkCreateQueryPool) DECLARE_VULKAN_FUNCTION(vkDestroyQueryPool) DECLARE_VULKAN_FUNCTION(vkGetQueryPoolResults) DECLARE_VULKAN_FUNCTION(vkResetQueryPool) DECLARE_VULKAN_FUNCTION(vkCreateBuffer) DECLARE_VULKAN_FUNCTION(vkDestroyBuffer) DECLARE_VULKAN_FUNCTION(vkCreateBufferView) DECLARE_VULKAN_FUNCTION(vkDestroyBufferView) DECLARE_VULKAN_FUNCTION(vkCreateImage) DECLARE_VULKAN_FUNCTION(vkDestroyImage) DECLARE_VULKAN_FUNCTION(vkGetImageSubresourceLayout) DECLARE_VULKAN_FUNCTION(vkCreateImageView) DECLARE_VULKAN_FUNCTION(vkDestroyImageView) DECLARE_VULKAN_FUNCTION(vkCreateShaderModule) DECLARE_VULKAN_FUNCTION(vkDestroyShaderModule) DECLARE_VULKAN_FUNCTION(vkCreatePipelineCache) DECLARE_VULKAN_FUNCTION(vkDestroyPipelineCache) DECLARE_VULKAN_FUNCTION(vkGetPipelineCacheData) DECLARE_VULKAN_FUNCTION(vkMergePipelineCaches) DECLARE_VULKAN_FUNCTION(vkCreateGraphicsPipelines) DECLARE_VULKAN_FUNCTION(vkCreateComputePipelines) DECLARE_VULKAN_FUNCTION(vkDestroyPipeline) DECLARE_VULKAN_FUNCTION(vkCreatePipelineLayout) DECLARE_VULKAN_FUNCTION(vkDestroyPipelineLayout) DECLARE_VULKAN_FUNCTION(vkCreateSampler) DECLARE_VULKAN_FUNCTION(vkDestroySampler) DECLARE_VULKAN_FUNCTION(vkCreateDescriptorSetLayout) DECLARE_VULKAN_FUNCTION(vkDestroyDescriptorSetLayout) DECLARE_VULKAN_FUNCTION(vkCreateDescriptorPool) DECLARE_VULKAN_FUNCTION(vkDestroyDescriptorPool) DECLARE_VULKAN_FUNCTION(vkResetDescriptorPool) DECLARE_VULKAN_FUNCTION(vkAllocateDescriptorSets) DECLARE_VULKAN_FUNCTION(vkFreeDescriptorSets) DECLARE_VULKAN_FUNCTION(vkUpdateDescriptorSets) DECLARE_VULKAN_FUNCTION(vkCreateFramebuffer) DECLARE_VULKAN_FUNCTION(vkDestroyFramebuffer) DECLARE_VULKAN_FUNCTION(vkCreateRenderPass) DECLARE_VULKAN_FUNCTION(vkDestroyRenderPass) DECLARE_VULKAN_FUNCTION(vkGetRenderAreaGranularity) DECLARE_VULKAN_FUNCTION(vkCreateCommandPool) DECLARE_VULKAN_FUNCTION(vkDestroyCommandPool) DECLARE_VULKAN_FUNCTION(vkResetCommandPool) DECLARE_VULKAN_FUNCTION(vkAllocateCommandBuffers) DECLARE_VULKAN_FUNCTION(vkFreeCommandBuffers) DECLARE_VULKAN_FUNCTION(vkBeginCommandBuffer) DECLARE_VULKAN_FUNCTION(vkEndCommandBuffer) DECLARE_VULKAN_FUNCTION(vkResetCommandBuffer) DECLARE_VULKAN_FUNCTION(vkCmdBindPipeline) DECLARE_VULKAN_FUNCTION(vkCmdSetViewport) DECLARE_VULKAN_FUNCTION(vkCmdSetScissor) DECLARE_VULKAN_FUNCTION(vkCmdSetLineWidth) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBias) DECLARE_VULKAN_FUNCTION(vkCmdSetBlendConstants) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBounds) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilCompareMask) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilWriteMask) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilReference) DECLARE_VULKAN_FUNCTION(vkCmdBindDescriptorSets) DECLARE_VULKAN_FUNCTION(vkCmdBindIndexBuffer) DECLARE_VULKAN_FUNCTION(vkCmdBindVertexBuffers) DECLARE_VULKAN_FUNCTION(vkCmdDraw) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndexed) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndirect) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndexedIndirect) DECLARE_VULKAN_FUNCTION(vkCmdDispatch) DECLARE_VULKAN_FUNCTION(vkCmdDispatchIndirect) DECLARE_VULKAN_FUNCTION(vkCmdCopyBuffer) DECLARE_VULKAN_FUNCTION(vkCmdCopyImage) DECLARE_VULKAN_FUNCTION(vkCmdBlitImage) DECLARE_VULKAN_FUNCTION(vkCmdCopyBufferToImage) DECLARE_VULKAN_FUNCTION(vkCmdCopyImageToBuffer) DECLARE_VULKAN_FUNCTION(vkCmdUpdateBuffer) DECLARE_VULKAN_FUNCTION(vkCmdFillBuffer) DECLARE_VULKAN_FUNCTION(vkCmdClearColorImage) DECLARE_VULKAN_FUNCTION(vkCmdClearDepthStencilImage) DECLARE_VULKAN_FUNCTION(vkCmdClearAttachments) DECLARE_VULKAN_FUNCTION(vkCmdResolveImage) DECLARE_VULKAN_FUNCTION(vkCmdSetEvent) DECLARE_VULKAN_FUNCTION(vkCmdResetEvent) DECLARE_VULKAN_FUNCTION(vkCmdWaitEvents) DECLARE_VULKAN_FUNCTION(vkCmdPipelineBarrier) DECLARE_VULKAN_FUNCTION(vkCmdBeginQuery) DECLARE_VULKAN_FUNCTION(vkCmdEndQuery) DECLARE_VULKAN_FUNCTION(vkCmdResetQueryPool) DECLARE_VULKAN_FUNCTION(vkCmdWriteTimestamp) DECLARE_VULKAN_FUNCTION(vkCmdCopyQueryPoolResults) DECLARE_VULKAN_FUNCTION(vkCmdPushConstants) DECLARE_VULKAN_FUNCTION(vkCmdBeginRenderPass) DECLARE_VULKAN_FUNCTION(vkCmdNextSubpass) DECLARE_VULKAN_FUNCTION(vkCmdEndRenderPass) DECLARE_VULKAN_FUNCTION(vkCmdExecuteCommands) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFeatures2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFormatProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceImageFormatProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceQueueFamilyProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceMemoryProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSparseImageFormatProperties2) DECLARE_VULKAN_FUNCTION(vkTrimCommandPool) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalBufferProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalSemaphoreProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalFenceProperties) DECLARE_VULKAN_FUNCTION(vkEnumeratePhysicalDeviceGroups) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupPeerMemoryFeatures) DECLARE_VULKAN_FUNCTION(vkBindBufferMemory2) DECLARE_VULKAN_FUNCTION(vkBindImageMemory2) DECLARE_VULKAN_FUNCTION(vkCmdSetDeviceMask) DECLARE_VULKAN_FUNCTION(vkCmdDispatchBase) DECLARE_VULKAN_FUNCTION(vkCreateDescriptorUpdateTemplate) DECLARE_VULKAN_FUNCTION(vkDestroyDescriptorUpdateTemplate) DECLARE_VULKAN_FUNCTION(vkUpdateDescriptorSetWithTemplate) DECLARE_VULKAN_FUNCTION(vkGetBufferMemoryRequirements2) DECLARE_VULKAN_FUNCTION(vkGetImageMemoryRequirements2) DECLARE_VULKAN_FUNCTION(vkGetImageSparseMemoryRequirements2) DECLARE_VULKAN_FUNCTION(vkCreateSamplerYcbcrConversion) DECLARE_VULKAN_FUNCTION(vkDestroySamplerYcbcrConversion) DECLARE_VULKAN_FUNCTION(vkGetDeviceQueue2) DECLARE_VULKAN_FUNCTION(vkGetDescriptorSetLayoutSupport) DECLARE_VULKAN_FUNCTION(vkCreateRenderPass2) DECLARE_VULKAN_FUNCTION(vkCmdBeginRenderPass2) DECLARE_VULKAN_FUNCTION(vkCmdNextSubpass2) DECLARE_VULKAN_FUNCTION(vkCmdEndRenderPass2) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreCounterValue) DECLARE_VULKAN_FUNCTION(vkWaitSemaphores) DECLARE_VULKAN_FUNCTION(vkSignalSemaphore) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndirectCount) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndexedIndirectCount) DECLARE_VULKAN_FUNCTION(vkGetBufferOpaqueCaptureAddress) DECLARE_VULKAN_FUNCTION(vkGetBufferDeviceAddress) DECLARE_VULKAN_FUNCTION(vkGetDeviceMemoryOpaqueCaptureAddress) #if defined(VK_AMD_BUFFER_MARKER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdWriteBufferMarkerAMD) #endif #if defined(VK_AMD_DISPLAY_NATIVE_HDR_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetLocalDimmingAMD) #endif #if defined(VK_AMD_SHADER_INFO_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetShaderInfoAMD) #endif #if defined(VK_EXT_ACQUIRE_DRM_DISPLAY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkAcquireDrmDisplayEXT) DECLARE_VULKAN_FUNCTION(vkGetDrmDisplayEXT) #endif #if defined(VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceCalibrateableTimeDomainsEXT) DECLARE_VULKAN_FUNCTION(vkGetCalibratedTimestampsEXT) #endif #if defined(VK_EXT_COLOR_WRITE_ENABLE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetColorWriteEnableEXT) #endif #if defined(VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBeginConditionalRenderingEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndConditionalRenderingEXT) #endif #if defined(VK_EXT_DEBUG_MARKER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDebugMarkerSetObjectNameEXT) DECLARE_VULKAN_FUNCTION(vkDebugMarkerSetObjectTagEXT) DECLARE_VULKAN_FUNCTION(vkCmdDebugMarkerBeginEXT) DECLARE_VULKAN_FUNCTION(vkCmdDebugMarkerEndEXT) DECLARE_VULKAN_FUNCTION(vkCmdDebugMarkerInsertEXT) #endif #if defined(VK_EXT_DEBUG_REPORT_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateDebugReportCallbackEXT) DECLARE_VULKAN_FUNCTION(vkDestroyDebugReportCallbackEXT) DECLARE_VULKAN_FUNCTION(vkDebugReportMessageEXT) #endif #if defined(VK_EXT_DEBUG_UTILS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetDebugUtilsObjectNameEXT) DECLARE_VULKAN_FUNCTION(vkSetDebugUtilsObjectTagEXT) DECLARE_VULKAN_FUNCTION(vkQueueBeginDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkQueueEndDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkQueueInsertDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCmdBeginDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCmdInsertDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCreateDebugUtilsMessengerEXT) DECLARE_VULKAN_FUNCTION(vkDestroyDebugUtilsMessengerEXT) DECLARE_VULKAN_FUNCTION(vkSubmitDebugUtilsMessageEXT) #endif #if defined(VK_EXT_DIRECT_MODE_DISPLAY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkReleaseDisplayEXT) #endif #if defined(VK_EXT_DISCARD_RECTANGLES_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetDiscardRectangleEXT) #endif #if defined(VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDisplayPowerControlEXT) DECLARE_VULKAN_FUNCTION(vkRegisterDeviceEventEXT) DECLARE_VULKAN_FUNCTION(vkRegisterDisplayEventEXT) DECLARE_VULKAN_FUNCTION(vkGetSwapchainCounterEXT) #endif #if defined(VK_EXT_DISPLAY_SURFACE_COUNTER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilities2EXT) #endif #if defined(VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetPatchControlPointsEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetRasterizerDiscardEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBiasEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetLogicOpEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetPrimitiveRestartEnableEXT) #endif #if defined(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetCullModeEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetFrontFaceEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetPrimitiveTopologyEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetViewportWithCountEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetScissorWithCountEXT) DECLARE_VULKAN_FUNCTION(vkCmdBindVertexBuffers2EXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthTestEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthWriteEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthCompareOpEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBoundsTestEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilTestEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilOpEXT) #endif #if defined(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetMemoryHostPointerPropertiesEXT) #endif #if defined(VK_EXT_HDR_METADATA_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetHdrMetadataEXT) #endif #if defined(VK_EXT_HEADLESS_SURFACE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateHeadlessSurfaceEXT) #endif #if defined(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetImageDrmFormatModifierPropertiesEXT) #endif #if defined(VK_EXT_LINE_RASTERIZATION_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetLineStippleEXT) #endif #if defined(VK_EXT_MULTI_DRAW_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdDrawMultiEXT) DECLARE_VULKAN_FUNCTION(vkCmdDrawMultiIndexedEXT) #endif #if defined(VK_EXT_PAGEABLE_DEVICE_LOCAL_MEMORY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetDeviceMemoryPriorityEXT) #endif #if defined(VK_EXT_PRIVATE_DATA_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreatePrivateDataSlotEXT) DECLARE_VULKAN_FUNCTION(vkDestroyPrivateDataSlotEXT) DECLARE_VULKAN_FUNCTION(vkSetPrivateDataEXT) DECLARE_VULKAN_FUNCTION(vkGetPrivateDataEXT) #endif #if defined(VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetSampleLocationsEXT) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceMultisamplePropertiesEXT) #endif #if defined(VK_EXT_TOOLING_INFO_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceToolPropertiesEXT) #endif #if defined(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBindTransformFeedbackBuffersEXT) DECLARE_VULKAN_FUNCTION(vkCmdBeginTransformFeedbackEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndTransformFeedbackEXT) DECLARE_VULKAN_FUNCTION(vkCmdBeginQueryIndexedEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndQueryIndexedEXT) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndirectByteCountEXT) #endif #if defined(VK_EXT_VALIDATION_CACHE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateValidationCacheEXT) DECLARE_VULKAN_FUNCTION(vkDestroyValidationCacheEXT) DECLARE_VULKAN_FUNCTION(vkGetValidationCacheDataEXT) DECLARE_VULKAN_FUNCTION(vkMergeValidationCachesEXT) #endif #if defined(VK_EXT_VERTEX_INPUT_DYNAMIC_STATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetVertexInputEXT) #endif #if defined(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetRefreshCycleDurationGOOGLE) DECLARE_VULKAN_FUNCTION(vkGetPastPresentationTimingGOOGLE) #endif #if defined(VK_HUAWEI_INVOCATION_MASK_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBindInvocationMaskHUAWEI) #endif #if defined(VK_HUAWEI_SUBPASS_SHADING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI) DECLARE_VULKAN_FUNCTION(vkCmdSubpassShadingHUAWEI) #endif #if defined(VK_INTEL_PERFORMANCE_QUERY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkInitializePerformanceApiINTEL) DECLARE_VULKAN_FUNCTION(vkUninitializePerformanceApiINTEL) DECLARE_VULKAN_FUNCTION(vkCmdSetPerformanceMarkerINTEL) DECLARE_VULKAN_FUNCTION(vkCmdSetPerformanceStreamMarkerINTEL) DECLARE_VULKAN_FUNCTION(vkCmdSetPerformanceOverrideINTEL) DECLARE_VULKAN_FUNCTION(vkAcquirePerformanceConfigurationINTEL) DECLARE_VULKAN_FUNCTION(vkReleasePerformanceConfigurationINTEL) DECLARE_VULKAN_FUNCTION(vkQueueSetPerformanceConfigurationINTEL) DECLARE_VULKAN_FUNCTION(vkGetPerformanceParameterINTEL) #endif #if defined(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDestroyAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCopyAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyAccelerationStructureToMemoryKHR) DECLARE_VULKAN_FUNCTION(vkCopyAccelerationStructureToMemoryKHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyMemoryToAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCopyMemoryToAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdWriteAccelerationStructuresPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkWriteAccelerationStructuresPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceAccelerationStructureCompatibilityKHR) DECLARE_VULKAN_FUNCTION(vkCreateAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdBuildAccelerationStructuresKHR) DECLARE_VULKAN_FUNCTION(vkCmdBuildAccelerationStructuresIndirectKHR) DECLARE_VULKAN_FUNCTION(vkBuildAccelerationStructuresKHR) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureDeviceAddressKHR) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureBuildSizesKHR) #endif #if defined(VK_KHR_COPY_COMMANDS_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdCopyBuffer2KHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyImage2KHR) DECLARE_VULKAN_FUNCTION(vkCmdBlitImage2KHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyBufferToImage2KHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyImageToBuffer2KHR) DECLARE_VULKAN_FUNCTION(vkCmdResolveImage2KHR) #endif #if defined(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateDeferredOperationKHR) DECLARE_VULKAN_FUNCTION(vkDestroyDeferredOperationKHR) DECLARE_VULKAN_FUNCTION(vkGetDeferredOperationMaxConcurrencyKHR) DECLARE_VULKAN_FUNCTION(vkGetDeferredOperationResultKHR) DECLARE_VULKAN_FUNCTION(vkDeferredOperationJoinKHR) #endif #if defined(VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdPushDescriptorSetWithTemplateKHR) #endif #if defined(VK_KHR_DEVICE_GROUP_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupPresentCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupSurfacePresentModesKHR) DECLARE_VULKAN_FUNCTION(vkAcquireNextImage2KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDevicePresentRectanglesKHR) #endif #if defined(VK_KHR_DISPLAY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayPlanePropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayPlaneSupportedDisplaysKHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayModePropertiesKHR) DECLARE_VULKAN_FUNCTION(vkCreateDisplayModeKHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayPlaneCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkCreateDisplayPlaneSurfaceKHR) #endif #if defined(VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateSharedSwapchainsKHR) #endif #if defined(VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetFenceFdKHR) DECLARE_VULKAN_FUNCTION(vkImportFenceFdKHR) #endif #if defined(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetMemoryFdKHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryFdPropertiesKHR) #endif #if defined(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreFdKHR) DECLARE_VULKAN_FUNCTION(vkImportSemaphoreFdKHR) #endif #if defined(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetFragmentShadingRateKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFragmentShadingRatesKHR) #endif #if defined(VK_KHR_GET_DISPLAY_PROPERTIES_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayProperties2KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayPlaneProperties2KHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayModeProperties2KHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayPlaneCapabilities2KHR) #endif #if defined(VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilities2KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceFormats2KHR) #endif #if defined(VK_KHR_MAINTENANCE_4_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetDeviceBufferMemoryRequirementsKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceImageMemoryRequirementsKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceImageSparseMemoryRequirementsKHR) #endif #if defined(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR) DECLARE_VULKAN_FUNCTION(vkAcquireProfilingLockKHR) DECLARE_VULKAN_FUNCTION(vkReleaseProfilingLockKHR) #endif #if defined(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPipelineExecutablePropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPipelineExecutableStatisticsKHR) DECLARE_VULKAN_FUNCTION(vkGetPipelineExecutableInternalRepresentationsKHR) #endif #if defined(VK_KHR_PRESENT_WAIT_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkWaitForPresentKHR) #endif #if defined(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdPushDescriptorSetKHR) #endif #if defined(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdTraceRaysKHR) DECLARE_VULKAN_FUNCTION(vkGetRayTracingShaderGroupHandlesKHR) DECLARE_VULKAN_FUNCTION(vkGetRayTracingCaptureReplayShaderGroupHandlesKHR) DECLARE_VULKAN_FUNCTION(vkCreateRayTracingPipelinesKHR) DECLARE_VULKAN_FUNCTION(vkCmdTraceRaysIndirectKHR) DECLARE_VULKAN_FUNCTION(vkGetRayTracingShaderGroupStackSizeKHR) DECLARE_VULKAN_FUNCTION(vkCmdSetRayTracingPipelineStackSizeKHR) #endif #if defined(VK_KHR_SHARED_PRESENTABLE_IMAGE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetSwapchainStatusKHR) #endif #if defined(VK_KHR_SURFACE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDestroySurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceSupportKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceFormatsKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfacePresentModesKHR) #endif #if defined(VK_KHR_SWAPCHAIN_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateSwapchainKHR) DECLARE_VULKAN_FUNCTION(vkDestroySwapchainKHR) DECLARE_VULKAN_FUNCTION(vkGetSwapchainImagesKHR) DECLARE_VULKAN_FUNCTION(vkAcquireNextImageKHR) DECLARE_VULKAN_FUNCTION(vkQueuePresentKHR) #endif #if defined(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetEvent2KHR) DECLARE_VULKAN_FUNCTION(vkCmdResetEvent2KHR) DECLARE_VULKAN_FUNCTION(vkCmdWaitEvents2KHR) DECLARE_VULKAN_FUNCTION(vkCmdPipelineBarrier2KHR) DECLARE_VULKAN_FUNCTION(vkQueueSubmit2KHR) DECLARE_VULKAN_FUNCTION(vkCmdWriteTimestamp2KHR) DECLARE_VULKAN_FUNCTION(vkCmdWriteBufferMarker2AMD) DECLARE_VULKAN_FUNCTION(vkGetQueueCheckpointData2NV) #endif #if defined(VK_NVX_BINARY_IMPORT_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateCuModuleNVX) DECLARE_VULKAN_FUNCTION(vkCreateCuFunctionNVX) DECLARE_VULKAN_FUNCTION(vkDestroyCuModuleNVX) DECLARE_VULKAN_FUNCTION(vkDestroyCuFunctionNVX) DECLARE_VULKAN_FUNCTION(vkCmdCuLaunchKernelNVX) #endif #if defined(VK_NVX_IMAGE_VIEW_HANDLE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetImageViewHandleNVX) DECLARE_VULKAN_FUNCTION(vkGetImageViewAddressNVX) #endif #if defined(VK_NV_CLIP_SPACE_W_SCALING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetViewportWScalingNV) #endif #if defined(VK_NV_COOPERATIVE_MATRIX_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceCooperativeMatrixPropertiesNV) #endif #if defined(VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV) #endif #if defined(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetCheckpointNV) DECLARE_VULKAN_FUNCTION(vkGetQueueCheckpointDataNV) #endif #if defined(VK_NV_DEVICE_GENERATED_COMMANDS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdExecuteGeneratedCommandsNV) DECLARE_VULKAN_FUNCTION(vkCmdPreprocessGeneratedCommandsNV) DECLARE_VULKAN_FUNCTION(vkCmdBindPipelineShaderGroupNV) DECLARE_VULKAN_FUNCTION(vkGetGeneratedCommandsMemoryRequirementsNV) DECLARE_VULKAN_FUNCTION(vkCreateIndirectCommandsLayoutNV) DECLARE_VULKAN_FUNCTION(vkDestroyIndirectCommandsLayoutNV) #endif #if defined(VK_NV_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalImageFormatPropertiesNV) #endif #if defined(VK_NV_EXTERNAL_MEMORY_RDMA_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetMemoryRemoteAddressNV) #endif #if defined(VK_NV_FRAGMENT_SHADING_RATE_ENUMS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetFragmentShadingRateEnumNV) #endif #if defined(VK_NV_MESH_SHADER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdDrawMeshTasksNV) DECLARE_VULKAN_FUNCTION(vkCmdDrawMeshTasksIndirectNV) DECLARE_VULKAN_FUNCTION(vkCmdDrawMeshTasksIndirectCountNV) #endif #if defined(VK_NV_RAY_TRACING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCompileDeferredNV) DECLARE_VULKAN_FUNCTION(vkCreateAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkDestroyAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureMemoryRequirementsNV) DECLARE_VULKAN_FUNCTION(vkBindAccelerationStructureMemoryNV) DECLARE_VULKAN_FUNCTION(vkCmdCopyAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkCmdWriteAccelerationStructuresPropertiesNV) DECLARE_VULKAN_FUNCTION(vkCmdBuildAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkCmdTraceRaysNV) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureHandleNV) DECLARE_VULKAN_FUNCTION(vkCreateRayTracingPipelinesNV) #endif #if defined(VK_NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetExclusiveScissorNV) #endif #if defined(VK_NV_SHADING_RATE_IMAGE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBindShadingRateImageNV) DECLARE_VULKAN_FUNCTION(vkCmdSetViewportShadingRatePaletteNV) DECLARE_VULKAN_FUNCTION(vkCmdSetCoarseSampleOrderNV) #endif #if defined(VK_KHR_VIDEO_DECODE_QUEUE_EXTENSION_NAME) && defined(VK_ENABLE_BETA_EXTENSIONS) DECLARE_VULKAN_FUNCTION(vkCmdDecodeVideoKHR) #endif #if defined(VK_KHR_VIDEO_ENCODE_QUEUE_EXTENSION_NAME) && defined(VK_ENABLE_BETA_EXTENSIONS) DECLARE_VULKAN_FUNCTION(vkCmdEncodeVideoKHR) #endif #if defined(VK_KHR_VIDEO_QUEUE_EXTENSION_NAME) && defined(VK_ENABLE_BETA_EXTENSIONS) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceVideoCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceVideoFormatPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkCreateVideoSessionKHR) DECLARE_VULKAN_FUNCTION(vkDestroyVideoSessionKHR) DECLARE_VULKAN_FUNCTION(vkCreateVideoSessionParametersKHR) DECLARE_VULKAN_FUNCTION(vkUpdateVideoSessionParametersKHR) DECLARE_VULKAN_FUNCTION(vkDestroyVideoSessionParametersKHR) DECLARE_VULKAN_FUNCTION(vkGetVideoSessionMemoryRequirementsKHR) DECLARE_VULKAN_FUNCTION(vkBindVideoSessionMemoryKHR) DECLARE_VULKAN_FUNCTION(vkCmdBeginVideoCodingKHR) DECLARE_VULKAN_FUNCTION(vkCmdControlVideoCodingKHR) DECLARE_VULKAN_FUNCTION(vkCmdEndVideoCodingKHR) #endif #if defined(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) && defined(VK_USE_PLATFORM_ANDROID_KHR) DECLARE_VULKAN_FUNCTION(vkGetAndroidHardwareBufferPropertiesANDROID) DECLARE_VULKAN_FUNCTION(vkGetMemoryAndroidHardwareBufferANDROID) #endif #if defined(VK_ANDROID_NATIVE_BUFFER_EXTENSION_NAME) && defined(VK_USE_PLATFORM_ANDROID_KHR) DECLARE_VULKAN_FUNCTION(vkGetSwapchainGrallocUsageANDROID) DECLARE_VULKAN_FUNCTION(vkGetSwapchainGrallocUsage2ANDROID) DECLARE_VULKAN_FUNCTION(vkAcquireImageANDROID) DECLARE_VULKAN_FUNCTION(vkQueueSignalReleaseImageANDROID) #endif #if defined(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_ANDROID_KHR) DECLARE_VULKAN_FUNCTION(vkCreateAndroidSurfaceKHR) #endif #if defined(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_DIRECTFB_EXT) DECLARE_VULKAN_FUNCTION(vkCreateDirectFBSurfaceEXT) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDirectFBPresentationSupportEXT) #endif #if defined(VK_FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkCreateBufferCollectionFUCHSIA) DECLARE_VULKAN_FUNCTION(vkSetBufferCollectionBufferConstraintsFUCHSIA) DECLARE_VULKAN_FUNCTION(vkSetBufferCollectionImageConstraintsFUCHSIA) DECLARE_VULKAN_FUNCTION(vkDestroyBufferCollectionFUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetBufferCollectionPropertiesFUCHSIA) #endif #if defined(VK_FUCHSIA_EXTERNAL_MEMORY_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetMemoryZirconHandleFUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetMemoryZirconHandlePropertiesFUCHSIA) #endif #if defined(VK_FUCHSIA_EXTERNAL_SEMAPHORE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreZirconHandleFUCHSIA) DECLARE_VULKAN_FUNCTION(vkImportSemaphoreZirconHandleFUCHSIA) #endif #if defined(VK_FUCHSIA_IMAGEPIPE_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkCreateImagePipeSurfaceFUCHSIA) #endif #if defined(VK_GGP_STREAM_DESCRIPTOR_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_GGP) DECLARE_VULKAN_FUNCTION(vkCreateStreamDescriptorSurfaceGGP) #endif #if defined(VK_MVK_IOS_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_IOS_MVK) DECLARE_VULKAN_FUNCTION(vkCreateIOSSurfaceMVK) #endif #if defined(VK_MVK_MACOS_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_MACOS_MVK) DECLARE_VULKAN_FUNCTION(vkCreateMacOSSurfaceMVK) #endif #if defined(VK_EXT_METAL_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_METAL_EXT) DECLARE_VULKAN_FUNCTION(vkCreateMetalSurfaceEXT) #endif #if defined(VK_QNX_SCREEN_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_SCREEN_QNX) DECLARE_VULKAN_FUNCTION(vkCreateScreenSurfaceQNX) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceScreenPresentationSupportQNX) #endif #if defined(VK_NN_VI_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_VI_NN) DECLARE_VULKAN_FUNCTION(vkCreateViSurfaceNN) #endif #if defined(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WAYLAND_KHR) DECLARE_VULKAN_FUNCTION(vkCreateWaylandSurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceWaylandPresentationSupportKHR) #endif #if defined(VK_EXT_FULL_SCREEN_EXCLUSIVE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfacePresentModes2EXT) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupSurfacePresentModes2EXT) DECLARE_VULKAN_FUNCTION(vkAcquireFullScreenExclusiveModeEXT) DECLARE_VULKAN_FUNCTION(vkReleaseFullScreenExclusiveModeEXT) #endif #if defined(VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetFenceWin32HandleKHR) DECLARE_VULKAN_FUNCTION(vkImportFenceWin32HandleKHR) #endif #if defined(VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryWin32HandleKHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryWin32HandlePropertiesKHR) #endif #if defined(VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreWin32HandleKHR) DECLARE_VULKAN_FUNCTION(vkImportSemaphoreWin32HandleKHR) #endif #if defined(VK_KHR_WIN32_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkCreateWin32SurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceWin32PresentationSupportKHR) #endif #if defined(VK_NV_ACQUIRE_WINRT_DISPLAY_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkAcquireWinrtDisplayNV) DECLARE_VULKAN_FUNCTION(vkGetWinrtDisplayNV) #endif #if defined(VK_NV_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryWin32HandleNV) #endif #if defined(VK_KHR_XCB_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_XCB_KHR) DECLARE_VULKAN_FUNCTION(vkCreateXcbSurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceXcbPresentationSupportKHR) #endif #if defined(VK_KHR_XLIB_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_XLIB_KHR) DECLARE_VULKAN_FUNCTION(vkCreateXlibSurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceXlibPresentationSupportKHR) #endif #if defined(VK_EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME) && defined(VK_USE_PLATFORM_XLIB_XRANDR_EXT) DECLARE_VULKAN_FUNCTION(vkAcquireXlibDisplayEXT) DECLARE_VULKAN_FUNCTION(vkGetRandROutputDisplayEXT) #endif } #endif
41.745149
118
0.917165
Sixshaman
5873c52aa895e08e0fd04abb35c5be93a9d23f13
14,972
cpp
C++
src/d3d9/d3d9_swapchain.cpp
dports/dxup
e961838d3d0d5db02cd065b782ad890bf876ceef
[ "Zlib" ]
268
2018-04-27T14:05:01.000Z
2022-03-24T03:55:54.000Z
src/d3d9/d3d9_swapchain.cpp
dports/dxup
e961838d3d0d5db02cd065b782ad890bf876ceef
[ "Zlib" ]
49
2018-04-29T09:39:03.000Z
2019-09-14T12:33:44.000Z
src/d3d9/d3d9_swapchain.cpp
dports/dxup
e961838d3d0d5db02cd065b782ad890bf876ceef
[ "Zlib" ]
28
2018-05-16T12:07:49.000Z
2022-02-26T09:19:18.000Z
#include "d3d9_swapchain.h" #include "d3d9_surface.h" #include "d3d9_renderer.h" #include "d3d9_interface.h" #include <algorithm> namespace dxup { Direct3DSwapChain9Ex::Direct3DSwapChain9Ex(Direct3DDevice9Ex* device, D3DPRESENT_PARAMETERS* presentationParameters, IDXGISwapChain1* swapchain) : Direct3DSwapChain9ExBase{ device } , m_swapchain{ swapchain } , m_rtRequired{ false } { this->Reset(presentationParameters); } HRESULT Direct3DSwapChain9Ex::Reset(D3DPRESENT_PARAMETERS* parameters) { CriticalSection cs(m_device); // Get info and crap! UINT bufferCount = std::max(1u, parameters->BackBufferCount); // Free crap! this->clearResources(); // Set crap! m_presentationParameters = *parameters; DXGI_FORMAT format = convert::format(parameters->BackBufferFormat); format = convert::makeUntypeless(format, false); if (format == DXGI_FORMAT_B8G8R8X8_UNORM) format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is a simple fixup we can do to avoid a blit on both D3D11 native and older DXVK. HRESULT result = m_swapchain->ResizeBuffers( bufferCount, parameters->BackBufferWidth, parameters->BackBufferHeight, format, 0); m_rtRequired = false; // dxvk opt for arbitrary swapchain. if (FAILED(result)) { DXGI_FORMAT forcedFormat = convert::makeSwapchainCompliant(format); log::msg("Reset: using rendertargets as intemediary for swapchain."); m_rtRequired = true; result = m_swapchain->ResizeBuffers( bufferCount, parameters->BackBufferWidth, parameters->BackBufferHeight, forcedFormat, 0); } if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Reset: D3D11 ResizeBuffers failed in swapchain reset."); if (!config::getBool(config::ForceWindowed)) { result = m_swapchain->SetFullscreenState(!parameters->Windowed, nullptr); if (FAILED(result)) log::warn("Reset: failed to change fullscreen state!"); } // Make crap! for (UINT i = 0; i < bufferCount; i++) { Com<ID3D11Texture2D> bufferTexture; HRESULT result = m_swapchain->GetBuffer(i, __uuidof(ID3D11Texture2D), (void**)&bufferTexture); if (FAILED(result)) { log::warn("reset: failed to get swapchain buffer as ID3D11Texture2D."); continue; } DXUPResource* resource = DXUPResource::Create(m_device, bufferTexture.ptr(), D3DUSAGE_RENDERTARGET, D3DFMT_UNKNOWN); if (resource == nullptr) { log::warn("reset: failed to create DXUPResource for backbuffer."); continue; } D3D9ResourceDesc d3d9Desc; d3d9Desc.Discard = false; d3d9Desc.Format = parameters->BackBufferFormat; d3d9Desc.Usage = D3DUSAGE_RENDERTARGET; if (m_buffers[i] != nullptr) m_buffers[i]->SetResource(resource); else m_buffers[i] = Direct3DSurface9::Wrap(0, 0, m_device, this, resource, d3d9Desc); if (m_rtRequired) { D3D11_TEXTURE2D_DESC rtDesc; rtDesc.Width = parameters->BackBufferWidth; rtDesc.Height = parameters->BackBufferHeight; rtDesc.MipLevels = 1; rtDesc.ArraySize = 1; rtDesc.Format = convert::makeTypeless(format); rtDesc.SampleDesc.Count = 1; rtDesc.SampleDesc.Quality = 0; rtDesc.Usage = D3D11_USAGE_DEFAULT; rtDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; rtDesc.CPUAccessFlags = 0; rtDesc.MiscFlags = 0; Com<ID3D11Texture2D> rtTexture; this->GetD3D11Device()->CreateTexture2D(&rtDesc, nullptr, &rtTexture); resource = DXUPResource::Create(m_device, rtTexture.ptr(), D3DUSAGE_RENDERTARGET, D3DFMT_UNKNOWN); if (resource == nullptr) { log::warn("reset: failed to create DXUPResource for rt passthrough."); continue; } } if (m_exposedBuffers[i] != nullptr) m_exposedBuffers[i]->SetResource(resource); else m_exposedBuffers[i] = Direct3DSurface9::Wrap(0, 0, m_device, this, resource, d3d9Desc); } Com<IDXGIOutput> output; result = m_swapchain->GetContainingOutput(&output); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Reset: failed to get IDXGIOutput for swapchain."); result = output->QueryInterface(__uuidof(IDXGIOutput1), (void**)&m_output); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Reset: failed to upgrade IDXGIOutput to IDXGIOutput1 for swapchain."); return D3D_OK; } void Direct3DSwapChain9Ex::clearResources() { m_output = nullptr; for (size_t i = 0; i < m_buffers.size(); i++) { if (m_buffers[i] != nullptr) m_buffers[i]->ClearResource(); } for (size_t i = 0; i < m_exposedBuffers.size(); i++) { if (m_exposedBuffers[i] != nullptr) m_exposedBuffers[i]->ClearResource(); } } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::QueryInterface(REFIID riid, void** ppvObj) { InitReturnPtr(ppvObj); if (!ppvObj) return E_POINTER; if (riid == __uuidof(IDirect3DSwapChain9Ex) || riid == __uuidof(IDirect3DSwapChain9) || riid == __uuidof(IUnknown)) { *ppvObj = ref(this); return D3D_OK; } return E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::Present(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags) { CriticalSection cs(m_device); return this->PresentD3D11(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags, 0, false); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetFrontBufferData(IDirect3DSurface9* pDestSurface) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetFrontBufferData"); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetBackBuffer(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer) { CriticalSection cs(m_device); InitReturnPtr(ppBackBuffer); if (Type != D3DBACKBUFFER_TYPE_MONO) return log::d3derr(D3DERR_INVALIDCALL, "GetBackBuffer: stereo backbuffer requested."); if (!ppBackBuffer || iBackBuffer > D3DPRESENT_BACK_BUFFERS_MAX_EX) return log::d3derr(D3DERR_INVALIDCALL, "GetBackBuffer: backbuffer out of bounds."); if (m_exposedBuffers[iBackBuffer] == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetBackBuffer: invalid backbuffer requested (%d).", iBackBuffer); *ppBackBuffer = ref(m_exposedBuffers[iBackBuffer]); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetRasterStatus(D3DRASTER_STATUS* pRasterStatus) { CriticalSection cs(m_device); if (pRasterStatus == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetRasterStatus: pRasterStatus was nullptr."); // There exists D3DKMTGetScanLine which could implement this. // However the header for it is DDI and it's not supported under Wine. // Just stubbing this for now, but returning something thats should at least make the games happy. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtgetscanline static bool hasWarned = false; if (!hasWarned) { log::warn("GetRasterStatus: returning vblank."); hasWarned = true; } pRasterStatus->InVBlank = true; pRasterStatus->ScanLine = 0; return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetDisplayMode(D3DDISPLAYMODE* pMode) { CriticalSection cs(m_device); if (pMode == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetDisplayMode: pMode was nullptr."); pMode->Width = m_presentationParameters.BackBufferWidth; pMode->Height = m_presentationParameters.BackBufferHeight; pMode->Format = m_presentationParameters.BackBufferFormat; pMode->RefreshRate = m_presentationParameters.FullScreen_RefreshRateInHz; return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetPresentParameters(D3DPRESENT_PARAMETERS* pPresentationParameters) { CriticalSection cs(m_device); if (pPresentationParameters == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetPresentParameters: pPresentationParameters was nullptr."); *pPresentationParameters = m_presentationParameters; return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetLastPresentCount(UINT* pLastPresentCount) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetLastPresentCount"); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetPresentStats(D3DPRESENTSTATS* pPresentationStatistics) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetPresentStats"); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetDisplayModeEx(D3DDISPLAYMODEEX* pMode, D3DDISPLAYROTATION* pRotation) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetDisplayModeEx"); return D3D_OK; } HRESULT Direct3DSwapChain9Ex::WaitForVBlank() { HRESULT result = m_output->WaitForVBlank(); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "WaitForVBlank: IDXGIOutput1::WaitForVBlank failed."); return D3D_OK; } HRESULT Direct3DSwapChain9Ex::TestSwapchain(HWND hDestWindowOverride, bool ex) { return this->PresentD3D11(nullptr, nullptr, hDestWindowOverride, nullptr, 0, DXGI_PRESENT_TEST, ex); } void Direct3DSwapChain9Ex::rtBlit() { // TODO! Do we need to change what buffer we do this with? this->GetD3D9Device()->GetRenderer()->blit(m_buffers[0].ptr(), m_exposedBuffers[0].ptr()); } HRESULT Direct3DSwapChain9Ex::PresentD3D11(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags, UINT d3d11Flags, bool ex) { HRESULT result; if (hDestWindowOverride != nullptr) return log::d3derr(D3DERR_INVALIDCALL, "PresentD3D11: called with window override. Not presenting."); if (m_rtRequired && !(d3d11Flags & DXGI_PRESENT_TEST)) this->rtBlit(); UINT syncInterval = 0; if (config::getBool(config::RespectVSync)) { if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE) syncInterval = 0; else if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_DEFAULT || m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_ONE) syncInterval = 1; else if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_TWO) syncInterval = 2; else if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_THREE) syncInterval = 3; else //if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_FOUR) syncInterval = 4; if (dwFlags & D3DPRESENT_FORCEIMMEDIATE) syncInterval = 0; } if (dwFlags & D3DPRESENT_DONOTWAIT) d3d11Flags |= DXGI_PRESENT_DO_NOT_WAIT; if (d3d11Flags & DXGI_PRESENT_TEST) { result = m_swapchain->Present(syncInterval, d3d11Flags); } else { // We may need to do more here for rects... //m_swapchain->ResizeTarget //m_swapchain->ResizeBuffers result = m_swapchain->Present(syncInterval, d3d11Flags); } if (d3d11Flags & DXGI_PRESENT_TEST && FAILED(result)) return D3DERR_DEVICELOST; else { if (result == DXGI_ERROR_WAS_STILL_DRAWING) return D3DERR_WASSTILLDRAWING; if (result == DXGI_ERROR_DEVICE_REMOVED) return D3DERR_DEVICEREMOVED; if (ex) { if (result == DXGI_ERROR_DEVICE_HUNG) return D3DERR_DEVICEHUNG; if (result == DXGI_ERROR_DEVICE_RESET) return D3DERR_DEVICELOST; } else { if (result == DXGI_ERROR_DEVICE_RESET) return D3DERR_DEVICENOTRESET; } if (FAILED(result)) return D3DERR_DRIVERINTERNALERROR; } return D3D_OK; } HRESULT Direct3DSwapChain9Ex::Create(Direct3DDevice9Ex* device, D3DPRESENT_PARAMETERS* presentationParameters, Direct3DSwapChain9Ex** ppSwapChain) { InitReturnPtr(ppSwapChain); if (!ppSwapChain) return log::d3derr(D3DERR_INVALIDCALL, "CreateAdditionalSwapChain: ppSwapChain was nullptr."); DXGI_SWAP_CHAIN_DESC desc; memset(&desc, 0, sizeof(desc)); UINT backBufferCount = std::max(1u, presentationParameters->BackBufferCount); DXGI_FORMAT format = convert::format(presentationParameters->BackBufferFormat); format = convert::makeUntypeless(format, false); if (format == DXGI_FORMAT_B8G8R8X8_UNORM) format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is a simple fixup we can do to avoid a blit on both D3D11 native and older DXVK. desc.BufferCount = backBufferCount; desc.BufferDesc.Width = presentationParameters->BackBufferWidth; desc.BufferDesc.Height = presentationParameters->BackBufferHeight; desc.BufferDesc.Format = format; desc.BufferDesc.RefreshRate.Numerator = 0; desc.BufferDesc.RefreshRate.Denominator = 1; desc.BufferDesc.Scaling = DXGI_MODE_SCALING_STRETCHED; desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; desc.OutputWindow = device->getWindow(); desc.Windowed = config::getBool(config::ForceWindowed) ? true : presentationParameters->Windowed; desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; //desc.SampleDesc.Count = (UINT)pPresentationParameters->MultiSampleType; //if (desc.SampleDesc.Count == 0) // desc.SampleDesc.Count = 1; //desc.SampleDesc.Quality = pPresentationParameters->MultiSampleQuality; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; Com<Direct3D9Ex> parent; device->GetParent(&parent); Com<IDXGISwapChain> dxgiSwapChain; HRESULT result = parent->GetDXGIFactory()->CreateSwapChain(device->GetD3D11Device(), &desc, &dxgiSwapChain); // dxvk opt. for arbitrary swapchain if (FAILED(result)) { format = convert::makeSwapchainCompliant(format); desc.BufferDesc.Format = format; result = parent->GetDXGIFactory()->CreateSwapChain(device->GetD3D11Device(), &desc, &dxgiSwapChain); } if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Swapchain - Create: failed to make D3D11 swapchain."); Com<IDXGISwapChain1> upgradedSwapchain; result = dxgiSwapChain->QueryInterface(__uuidof(IDXGISwapChain1), (void**)&upgradedSwapchain); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Swapchain - Create: failed to upgrade swapchain to IDXGISwapChain1!"); parent->GetDXGIFactory()->MakeWindowAssociation(device->getWindow(), DXGI_MWA_NO_ALT_ENTER); *ppSwapChain = ref(new Direct3DSwapChain9Ex(device, presentationParameters, upgradedSwapchain.ptr())); return D3D_OK; } }
35.904077
190
0.713799
dports
587a644dfe541b34c737297ed56c478af0f9917d
3,092
cpp
C++
higan/audio/stream.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
higan/audio/stream.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
higan/audio/stream.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
auto Stream::reset(uint channels_, double inputFrequency, double outputFrequency) -> void { this->inputFrequency = inputFrequency; this->outputFrequency = outputFrequency; channels.reset(); channels.resize(channels_); for(auto& channel : channels) { channel.filters.reset(); channel.resampler.reset(inputFrequency, outputFrequency); } } auto Stream::setFrequency(double inputFrequency, maybe<double> outputFrequency) -> void { this->inputFrequency = inputFrequency; if(outputFrequency) this->outputFrequency = outputFrequency(); for(auto& channel : channels) { channel.nyquist.reset(); channel.resampler.reset(this->inputFrequency, this->outputFrequency); } if(this->inputFrequency >= this->outputFrequency * 2) { //add a low-pass filter to prevent aliasing during resampling double cutoffFrequency = min(25000.0, this->outputFrequency / 2.0 - 2000.0); for(auto& channel : channels) { uint passes = 3; for(uint pass : range(passes)) { DSP::IIR::Biquad filter; double q = DSP::IIR::Biquad::butterworth(passes * 2, pass); filter.reset(DSP::IIR::Biquad::Type::LowPass, cutoffFrequency, this->inputFrequency, q); channel.nyquist.append(filter); } } } } auto Stream::addFilter(Filter::Order order, Filter::Type type, double cutoffFrequency, uint passes) -> void { for(auto& channel : channels) { for(uint pass : range(passes)) { Filter filter{order}; if(order == Filter::Order::First) { DSP::IIR::OnePole::Type _type; if(type == Filter::Type::LowPass) _type = DSP::IIR::OnePole::Type::LowPass; if(type == Filter::Type::HighPass) _type = DSP::IIR::OnePole::Type::HighPass; filter.onePole.reset(_type, cutoffFrequency, inputFrequency); } if(order == Filter::Order::Second) { DSP::IIR::Biquad::Type _type; if(type == Filter::Type::LowPass) _type = DSP::IIR::Biquad::Type::LowPass; if(type == Filter::Type::HighPass) _type = DSP::IIR::Biquad::Type::HighPass; double q = DSP::IIR::Biquad::butterworth(passes * 2, pass); filter.biquad.reset(_type, cutoffFrequency, inputFrequency, q); } channel.filters.append(filter); } } } auto Stream::pending() const -> bool { return channels && channels[0].resampler.pending(); } auto Stream::read(double samples[]) -> uint { for(uint c : range(channels.size())) samples[c] = channels[c].resampler.read(); return channels.size(); } auto Stream::write(const double samples[]) -> void { for(auto c : range(channels.size())) { double sample = samples[c] + 1e-25; //constant offset used to suppress denormals for(auto& filter : channels[c].filters) { switch(filter.order) { case Filter::Order::First: sample = filter.onePole.process(sample); break; case Filter::Order::Second: sample = filter.biquad.process(sample); break; } } for(auto& filter : channels[c].nyquist) { sample = filter.process(sample); } channels[c].resampler.write(sample); } audio.process(); }
34.741573
109
0.658797
13824125580
587ac38eca3e3d8623a70c0b7c12fd120038df71
16,655
cpp
C++
UniEngine/src/CameraComponent.cpp
edisonlee0212/UniEngine-deprecated
4b899980c280ac501c3b5fa2746cf1e71cfedd28
[ "MIT" ]
null
null
null
UniEngine/src/CameraComponent.cpp
edisonlee0212/UniEngine-deprecated
4b899980c280ac501c3b5fa2746cf1e71cfedd28
[ "MIT" ]
null
null
null
UniEngine/src/CameraComponent.cpp
edisonlee0212/UniEngine-deprecated
4b899980c280ac501c3b5fa2746cf1e71cfedd28
[ "MIT" ]
1
2021-09-06T08:07:37.000Z
2021-09-06T08:07:37.000Z
#include "pch.h" #include "CameraComponent.h" #include "SerializationManager.h" #include "RenderManager.h" #include "Ray.h" #include "Transforms.h" #include "PostProcessing.h" UniEngine::CameraInfoBlock UniEngine::CameraComponent::m_cameraInfoBlock; std::unique_ptr<UniEngine::GLUBO> UniEngine::CameraComponent::m_cameraUniformBufferBlock; UniEngine::CameraLayerMask::CameraLayerMask() { m_value = 0; } UniEngine::Plane::Plane(): m_a(0), m_b(0), m_c(0), m_d(0) { } void UniEngine::Plane::Normalize() { const float mag = glm::sqrt(m_a * m_a + m_b * m_b + m_c * m_c); m_a /= mag; m_b /= mag; m_c /= mag; m_d /= mag; } void UniEngine::CameraComponent::StoreToJpg(const std::string& path, int resizeX, int resizeY) const { m_colorTexture->StoreToPng(path, resizeX, resizeY); } void UniEngine::CameraComponent::StoreToPng(const std::string& path, int resizeX, int resizeY, bool alphaChannel) const { m_colorTexture->StoreToPng(path, resizeX, resizeY, alphaChannel); } void UniEngine::CameraComponent::CalculatePlanes(std::vector<Plane>& planes, glm::mat4 projection, glm::mat4 view) { glm::mat4 comboMatrix = projection * glm::transpose(view); planes[0].m_a = comboMatrix[3][0] + comboMatrix[0][0]; planes[0].m_b = comboMatrix[3][1] + comboMatrix[0][1]; planes[0].m_c = comboMatrix[3][2] + comboMatrix[0][2]; planes[0].m_d = comboMatrix[3][3] + comboMatrix[0][3]; planes[1].m_a = comboMatrix[3][0] - comboMatrix[0][0]; planes[1].m_b = comboMatrix[3][1] - comboMatrix[0][1]; planes[1].m_c = comboMatrix[3][2] - comboMatrix[0][2]; planes[1].m_d = comboMatrix[3][3] - comboMatrix[0][3]; planes[2].m_a = comboMatrix[3][0] - comboMatrix[1][0]; planes[2].m_b = comboMatrix[3][1] - comboMatrix[1][1]; planes[2].m_c = comboMatrix[3][2] - comboMatrix[1][2]; planes[2].m_d = comboMatrix[3][3] - comboMatrix[1][3]; planes[3].m_a = comboMatrix[3][0] + comboMatrix[1][0]; planes[3].m_b = comboMatrix[3][1] + comboMatrix[1][1]; planes[3].m_c = comboMatrix[3][2] + comboMatrix[1][2]; planes[3].m_d = comboMatrix[3][3] + comboMatrix[1][3]; planes[4].m_a = comboMatrix[3][0] + comboMatrix[2][0]; planes[4].m_b = comboMatrix[3][1] + comboMatrix[2][1]; planes[4].m_c = comboMatrix[3][2] + comboMatrix[2][2]; planes[4].m_d = comboMatrix[3][3] + comboMatrix[2][3]; planes[5].m_a = comboMatrix[3][0] - comboMatrix[2][0]; planes[5].m_b = comboMatrix[3][1] - comboMatrix[2][1]; planes[5].m_c = comboMatrix[3][2] - comboMatrix[2][2]; planes[5].m_d = comboMatrix[3][3] - comboMatrix[2][3]; planes[0].Normalize(); planes[1].Normalize(); planes[2].Normalize(); planes[3].Normalize(); planes[4].Normalize(); planes[5].Normalize(); } void UniEngine::CameraComponent::CalculateFrustumPoints(float nearPlane, float farPlane, glm::vec3 cameraPos, glm::quat cameraRot, glm::vec3* points) const { const glm::vec3 front = cameraRot * glm::vec3(0, 0, -1); const glm::vec3 right = cameraRot * glm::vec3(1, 0, 0); const glm::vec3 up = cameraRot * glm::vec3(0, 1, 0); const glm::vec3 nearCenter = front * nearPlane; const glm::vec3 farCenter = front * farPlane; const float e = tanf(glm::radians(m_fov * 0.5f)); const float near_ext_y = e * nearPlane; const float near_ext_x = near_ext_y * GetResolutionRatio(); const float far_ext_y = e * farPlane; const float far_ext_x = far_ext_y * GetResolutionRatio(); points[0] = cameraPos + nearCenter - right * near_ext_x - up * near_ext_y; points[1] = cameraPos + nearCenter - right * near_ext_x + up * near_ext_y; points[2] = cameraPos + nearCenter + right * near_ext_x + up * near_ext_y; points[3] = cameraPos + nearCenter + right * near_ext_x - up * near_ext_y; points[4] = cameraPos + farCenter - right * far_ext_x - up * far_ext_y; points[5] = cameraPos + farCenter - right * far_ext_x + up * far_ext_y; points[6] = cameraPos + farCenter + right * far_ext_x + up * far_ext_y; points[7] = cameraPos + farCenter + right * far_ext_x - up * far_ext_y; } glm::quat UniEngine::CameraComponent::ProcessMouseMovement(float yawAngle, float pitchAngle, bool constrainPitch) { // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (pitchAngle > 89.0f) pitchAngle = 89.0f; if (pitchAngle < -89.0f) pitchAngle = -89.0f; } glm::vec3 front; front.x = cos(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle)); front.y = sin(glm::radians(pitchAngle)); front.z = sin(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle)); front = glm::normalize(front); const glm::vec3 right = glm::normalize(glm::cross(front, glm::vec3(0.0f, 1.0f, 0.0f))); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. const glm::vec3 up = glm::normalize(glm::cross(right, front)); return glm::quatLookAt(front, up); } void UniEngine::CameraComponent::ReverseAngle(const glm::quat& rotation, float& pitchAngle, float& yawAngle, const bool& constrainPitch) { const auto angle = glm::degrees(glm::eulerAngles(rotation)); pitchAngle = angle.x; yawAngle = glm::abs(angle.z) > 90.0f ? 90.0f - angle.y : -90.0f - angle.y; if (constrainPitch) { if (pitchAngle > 89.0f) pitchAngle = 89.0f; if (pitchAngle < -89.0f) pitchAngle = -89.0f; } } std::shared_ptr<UniEngine::Texture2D> UniEngine::CameraComponent::GetTexture() const { return m_colorTexture; } glm::mat4 UniEngine::CameraComponent::GetProjection() const { return glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance); } glm::vec3 UniEngine::CameraComponent::Project(GlobalTransform& ltw, glm::vec3 position) { return m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view * glm::vec4(position, 1.0f); } glm::vec3 UniEngine::CameraComponent::UnProject(GlobalTransform& ltw, glm::vec3 position) const { glm::mat4 inversed = glm::inverse(m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view); glm::vec4 start = glm::vec4( position, 1.0f); start = inversed * start; return start / start.w; } glm::vec3 UniEngine::CameraComponent::GetMouseWorldPoint(GlobalTransform& ltw, glm::vec2 mousePosition) const { const float halfX = static_cast<float>(m_resolutionX) / 2.0f; const float halfY = static_cast<float>(m_resolutionY) / 2.0f; const glm::vec4 start = glm::vec4( (mousePosition.x - halfX) / halfX, -1 * (mousePosition.y - halfY) / halfY, 0.0f, 1.0f); return start / start.w; } void UniEngine::CameraComponent::SetClearColor(glm::vec3 color) const { m_frameBuffer->ClearColor(glm::vec4(color.x, color.y, color.z, 0.0f)); m_frameBuffer->Clear(); m_frameBuffer->ClearColor(glm::vec4(0.0f)); } UniEngine::Ray UniEngine::CameraComponent::ScreenPointToRay(GlobalTransform& ltw, glm::vec2 mousePosition) const { const auto position = ltw.GetPosition(); const auto rotation = ltw.GetRotation(); const glm::vec3 front = rotation * glm::vec3(0, 0, -1); const glm::vec3 up = rotation * glm::vec3(0, 1, 0); const auto projection = glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance); const auto view = glm::lookAt(position, position + front, up); const glm::mat4 inv = glm::inverse(projection * view); const float halfX = static_cast<float>(m_resolutionX) / 2.0f; const float halfY = static_cast<float>(m_resolutionY) / 2.0f; const auto realX = (mousePosition.x + halfX) / halfX; const auto realY = (mousePosition.y - halfY) / halfY; if (glm::abs(realX) > 1.0f || glm::abs(realY) > 1.0f) return { glm::vec3(FLT_MAX), glm::vec3(FLT_MAX) }; glm::vec4 start = glm::vec4( realX, -1 * realY, -1, 1.0); glm::vec4 end = glm::vec4(realX, -1.0f * realY, 1.0f, 1.0f); start = inv * start; end = inv * end; start /= start.w; end /= end.w; const glm::vec3 dir = glm::normalize(glm::vec3(end - start)); return { glm::vec3(ltw.m_value[3]) + m_nearDistance * dir, glm::vec3(ltw.m_value[3]) + m_farDistance * dir }; } void UniEngine::CameraComponent::GenerateMatrices() { m_cameraUniformBufferBlock = std::make_unique<GLUBO>(); m_cameraUniformBufferBlock->SetData(sizeof(m_cameraInfoBlock), nullptr, GL_STREAM_DRAW); m_cameraUniformBufferBlock->SetBase(0); } void UniEngine::CameraComponent::Serialize(YAML::Emitter& out) { out << YAML::Key << "_ResolutionX" << YAML::Value << m_resolutionX; out << YAML::Key << "_ResolutionY" << YAML::Value << m_resolutionY; out << YAML::Key << "_IsMainCamera" << YAML::Value << m_isMainCamera; out << YAML::Key << "DrawSkyBox" << YAML::Value << m_drawSkyBox; out << YAML::Key << "ClearColor" << YAML::Value << m_clearColor; out << YAML::Key << "NearDistance" << YAML::Value << m_nearDistance; out << YAML::Key << "FarDistance" << YAML::Value << m_farDistance; out << YAML::Key << "FOV" << YAML::Value << m_fov; } void UniEngine::CameraComponent::Deserialize(const YAML::Node& in) { m_resolutionX = in["_ResolutionX"].as<int>(); m_resolutionY = in["_ResolutionY"].as<int>(); m_isMainCamera = in["_IsMainCamera"].as<bool>(); if (m_isMainCamera) RenderManager::SetMainCamera(this); m_drawSkyBox = in["DrawSkyBox"].as<bool>(); m_clearColor.x = in["ClearColor"][0].as<float>(); m_clearColor.y = in["ClearColor"][1].as<float>(); m_clearColor.z = in["ClearColor"][2].as<float>(); m_nearDistance = in["NearDistance"].as<float>(); m_farDistance = in["FarDistance"].as<float>(); m_fov = in["FOV"].as<float>(); } void UniEngine::CameraComponent::ResizeResolution(int x, int y) { if (m_resolutionX == x && m_resolutionY == y) return; m_resolutionX = x > 0 ? x : 1; m_resolutionY = y > 0 ? y : 1; m_gBuffer->SetResolution(m_resolutionX, m_resolutionY); m_gPositionBuffer->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gNormalBuffer->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gColorSpecularBuffer->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gMetallicRoughnessAo->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gDepthBuffer->AllocateStorage(GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY); m_colorTexture->m_texture->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_depthStencilBuffer->ReSize(0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0, m_resolutionX, m_resolutionY); if(GetOwner().HasPrivateComponent<PostProcessing>()) { GetOwner().GetPrivateComponent<PostProcessing>()->ResizeResolution(m_resolutionX, m_resolutionY); } } UniEngine::CameraComponent::CameraComponent() { m_resolutionX = 1; m_resolutionY = 1; m_colorTexture = std::make_shared<Texture2D>(); m_colorTexture->m_name = "CameraTexture"; m_colorTexture->m_texture = std::make_shared<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_colorTexture->m_texture->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_colorTexture->m_texture->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_colorTexture->m_texture->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); AttachTexture(m_colorTexture->m_texture.get(), GL_COLOR_ATTACHMENT0); m_depthStencilBuffer = std::make_unique<GLTexture2D>(0, GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY, false); m_depthStencilBuffer->SetData(0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0); m_depthStencilBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_depthStencilBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_depthStencilBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_depthStencilBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); AttachTexture(m_depthStencilBuffer.get(), GL_DEPTH_STENCIL_ATTACHMENT); m_gBuffer = std::make_unique<RenderTarget>(m_resolutionX, m_resolutionY); m_gDepthBuffer = std::make_unique<GLRenderBuffer>(); m_gDepthBuffer->AllocateStorage(GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY); m_gBuffer->AttachRenderBuffer(m_gDepthBuffer.get(), GL_DEPTH_STENCIL_ATTACHMENT); m_gPositionBuffer = std::make_unique<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gPositionBuffer->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gPositionBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gPositionBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gPositionBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gPositionBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gPositionBuffer.get(), GL_COLOR_ATTACHMENT0); m_gNormalBuffer = std::make_unique <GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gNormalBuffer->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gNormalBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gNormalBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gNormalBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gNormalBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gNormalBuffer.get(), GL_COLOR_ATTACHMENT1); m_gColorSpecularBuffer = std::make_unique<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gColorSpecularBuffer->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gColorSpecularBuffer.get(), GL_COLOR_ATTACHMENT2); m_gMetallicRoughnessAo = std::make_unique<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gMetallicRoughnessAo->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gMetallicRoughnessAo.get(), GL_COLOR_ATTACHMENT3); SetEnabled(true); } UniEngine::CameraComponent::~CameraComponent() { if (RenderManager::GetMainCamera() == this) { RenderManager::SetMainCamera(nullptr); } } void UniEngine::CameraComponent::OnGui() { ImGui::Checkbox("Allow auto resize", &m_allowAutoResize); if(!m_allowAutoResize) { glm::ivec2 resolution = { m_resolutionX, m_resolutionY }; if(ImGui::DragInt2("Resolution", &resolution.x)) { ResizeResolution(resolution.x, resolution.y); } } ImGui::Checkbox("Skybox", &m_drawSkyBox); const bool savedState = m_isMainCamera; ImGui::Checkbox("Main Camera", &m_isMainCamera); if(savedState != m_isMainCamera) { if(m_isMainCamera) { RenderManager::SetMainCamera(this); }else { RenderManager::SetMainCamera(nullptr); } } if(!m_drawSkyBox) { ImGui::ColorEdit3("Clear Color", (float*)(void*)&m_clearColor); } ImGui::DragFloat("Near", &m_nearDistance, m_nearDistance / 10.0f, 0, m_farDistance); ImGui::DragFloat("Far", &m_farDistance, m_farDistance / 10.0f, m_nearDistance); ImGui::DragFloat("FOV", &m_fov, 1.0f, 1, 359); if (ImGui::TreeNode("Content")) { ImGui::Image((ImTextureID)m_colorTexture->Texture()->Id(), ImVec2(m_resolutionX / 5.0f, m_resolutionY / 5.0f), ImVec2(0, 1), ImVec2(1, 0)); if (ImGui::Button("Take Screenshot")) { StoreToJpg("screenshot.jpg"); } if (ImGui::Button("Take Screenshot (with alpha)")) { StoreToPng("greyscale.png", -1, -1, true); } ImGui::TreePop(); } } void UniEngine::CameraInfoBlock::UpdateMatrices(const CameraComponent* camera, glm::vec3 position, glm::quat rotation) { const glm::vec3 front = rotation * glm::vec3(0, 0, -1); const glm::vec3 up = rotation * glm::vec3(0, 1, 0); const auto ratio = camera->GetResolutionRatio(); m_projection = glm::perspective(glm::radians(camera->m_fov * 0.5f), ratio, camera->m_nearDistance, camera->m_farDistance); m_position = glm::vec4(position, 0); m_view = glm::lookAt(position, position + front, up); m_reservedParameters = glm::vec4(camera->m_nearDistance, camera->m_farDistance, glm::tan(camera->m_fov * 0.5f), camera->m_resolutionX / camera->m_resolutionY); m_backGroundColor = glm::vec4(camera->m_clearColor, 1.0f); if (camera->m_skyBox) { m_skybox = camera->m_skyBox->Texture()->GetHandle(); m_skyboxEnabled = true; } else { m_skybox = 0; m_skyboxEnabled = false; } } void UniEngine::CameraInfoBlock::UploadMatrices(const CameraComponent* camera) const { CameraComponent::m_cameraUniformBufferBlock->SubData(0, sizeof(CameraInfoBlock), this); }
40.621951
216
0.735035
edisonlee0212
5880a48731ff360303e1dc551daf9f1b389f0846
1,147
cpp
C++
fizz/tool/Main.cpp
karthikbhargavan/fizz
0d57338a2ff5e3a57ea0aaf1d9c96a8a04a07164
[ "BSD-3-Clause" ]
null
null
null
fizz/tool/Main.cpp
karthikbhargavan/fizz
0d57338a2ff5e3a57ea0aaf1d9c96a8a04a07164
[ "BSD-3-Clause" ]
null
null
null
fizz/tool/Main.cpp
karthikbhargavan/fizz
0d57338a2ff5e3a57ea0aaf1d9c96a8a04a07164
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <fizz/tool/Commands.h> #include <folly/ssl/Init.h> #include <glog/logging.h> #include <iostream> #include <string> #include <vector> using namespace fizz::tool; void showUsage() { std::cerr << "Supported commands:" << std::endl; for (const auto& command : fizzUtilities) { std::cerr << " - " << command.first << std::endl; } std::cerr << std::endl; } int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = 1; folly::ssl::init(); std::vector<std::string> arguments; for (int i = 0; i < argc; i++) { arguments.push_back(argv[i]); } if (arguments.size() < 2) { showUsage(); return 1; } else { if (fizzUtilities.count(arguments[1])) { return fizzUtilities.at(arguments[1])(arguments); } else { std::cerr << "Unknown command '" << arguments[1] << "'." << std::endl; showUsage(); return 1; } } return 0; }
22.94
76
0.617262
karthikbhargavan
58847ea14fe47c6762ba364031a4e47789a884e6
698
cpp
C++
aizu/illumination.test.cpp
hasegawa1/procon-library
9fea96b3f1ebcb44c08e413a2a9ecb22dc7cd39e
[ "MIT" ]
null
null
null
aizu/illumination.test.cpp
hasegawa1/procon-library
9fea96b3f1ebcb44c08e413a2a9ecb22dc7cd39e
[ "MIT" ]
6
2021-07-25T10:37:08.000Z
2021-11-20T14:06:46.000Z
aizu/illumination.test.cpp
hasegawa1/procon-library
9fea96b3f1ebcb44c08e413a2a9ecb22dc7cd39e
[ "MIT" ]
null
null
null
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/challenges/sources/JOI/Final/0603" #include <iostream> #include <vector> #include "../other/run_length_encoding.cpp" using namespace std; int main(void) { cin.tie(nullptr); ios_base::sync_with_stdio(false); int N; cin >> N; vector<int> v(N); for(int i=0; i<N; i++) { cin >> v[i]; } for(int i=0; i<N; i++) { v[i] ^= i%2; } auto v2 = run_length_encoding(v); v2.emplace_back(0, 0); v2.emplace_back(0, 0); int ans = 0; for(int i=0; i+2<v2.size(); i++) { ans = max(ans, v2[i].second + v2[i+1].second + v2[i+2].second); } cout << ans << endl; return 0; }
19.942857
84
0.553009
hasegawa1
5884c25112e4c430c2617967ce7dd9999990dd72
5,389
cpp
C++
source/threads/_unix/vthread_platform.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
2
2019-01-09T19:09:45.000Z
2019-04-02T17:53:49.000Z
source/threads/_unix/vthread_platform.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
17
2015-01-07T02:05:04.000Z
2019-08-30T16:57:42.000Z
source/threads/_unix/vthread_platform.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
3
2016-04-06T19:01:11.000Z
2017-09-20T09:28:00.000Z
/* Copyright c1997-2014 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 4.1 http://www.bombaydigital.com/ License: MIT. See LICENSE.md in the Vault top level directory. */ /** @file */ #include "vthread.h" #include "vtypes_internal_platform.h" #include "vmutex.h" #include "vsemaphore.h" #include "vlogger.h" #include "vinstant.h" #include "vexception.h" #include <sys/time.h> #include <sys/resource.h> // VThread platform-specific functions --------------------------------------- // static void VThread::threadCreate(VThreadID_Type* threadID, bool createDetached, threadMainFunction threadMainProcPtr, void* threadArgument) { int result; pthread_attr_t threadAttributes; result = ::pthread_attr_init(&threadAttributes); if (result != 0) { throw VStackTraceException(VSystemError(result), "VThread::threadCreate: pthread_attr_init() failed."); } result = ::pthread_attr_setdetachstate(&threadAttributes, createDetached ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE); if (result != 0) { throw VStackTraceException(VSystemError(result), "VThread::threadCreate: pthread_attr_setdetachstate() failed."); } result = ::pthread_create(threadID, &threadAttributes, threadMainProcPtr, threadArgument); if (result != 0) { // Usually this means we have hit the limit of threads allowed per process. // Log our statistics. Maybe we have a thread handle leak. throw VStackTraceException(VSystemError(result), "VThread::threadCreate: pthread_create failed. Likely due to lack of resources."); } (void) ::pthread_attr_destroy(&threadAttributes); } // static #ifdef VTHREAD_PTHREAD_SETNAME_SUPPORTED void VThread::_threadStarting(const VThread* thread) { // This API lets us associate our thread name with the native thread resource, so that debugger/crashdump/instruments etc. can see our thread name. (void)/*int result =*/ ::pthread_setname_np(thread->getName()); // "np" indicates API is non-POSIX } #else void VThread::_threadStarting(const VThread* /*thread*/) { // Nothing to do if pthread_setname_np() is not available. } #endif // static void VThread::_threadEnded(const VThread* /*thread*/) { // Nothing to do for unix version. } // static void VThread::threadExit() { ::pthread_exit(NULL); } // static bool VThread::threadJoin(VThreadID_Type threadID, void** value) { return (::pthread_join(threadID, value) == 0); } // static void VThread::threadDetach(VThreadID_Type threadID) { ::pthread_detach(threadID); } // static VThreadID_Type VThread::threadSelf() { return ::pthread_self(); } // static bool VThread::setPriority(int nice) { return (::setpriority(PRIO_PROCESS, 0, nice) == 0); } // static void VThread::sleep(const VDuration& interval) { int milliseconds = static_cast<int>(interval.getDurationMilliseconds()); struct timeval timeout; timeout.tv_sec = interval.getDurationSeconds(); timeout.tv_usec = (milliseconds % 1000) * 1000; (void) ::select(1, NULL, NULL, NULL, &timeout); // 1 means file descriptor [0], will just timeout } // static void VThread::yield() { #ifdef sun // On Solaris there is no yield function. // Simulate by sleeping for 1ms. How to improve? VThread::sleep(VDuration::MILLISECOND()); #else (void) ::sched_yield(); #endif } // VMutex platform-specific functions ---------------------------------------- // static bool VMutex::mutexInit(VMutex_Type* mutex) { return (::pthread_mutex_init(mutex, NULL) == 0); } // static void VMutex::mutexDestroy(VMutex_Type* mutex) { (void) ::pthread_mutex_destroy(mutex); } // static bool VMutex::mutexLock(VMutex_Type* mutex) { return (::pthread_mutex_lock(mutex) == 0); } // static bool VMutex::mutexUnlock(VMutex_Type* mutex) { return (::pthread_mutex_unlock(mutex) == 0); } // VSemaphore platform-specific functions ------------------------------------ // static bool VSemaphore::semaphoreInit(VSemaphore_Type* semaphore) { return (pthread_cond_init(semaphore, NULL) == 0); } // static bool VSemaphore::semaphoreDestroy(VSemaphore_Type* semaphore) { return (pthread_cond_destroy(semaphore) == 0); } // static bool VSemaphore::semaphoreWait(VSemaphore_Type* semaphore, VMutex_Type* mutex, const VDuration& timeoutInterval) { if (timeoutInterval == VDuration::ZERO()) { return (pthread_cond_wait(semaphore, mutex) == 0); } // The timespec is an absolute time (base is 1970 UTC), not an // offset from the current time. VInstant now; VInstant timeoutWhen = now + timeoutInterval; Vs64 timeoutValue = timeoutWhen.getValue(); struct timespec timeoutSpec; // Convert milliseconds to seconds.nanoseconds. e.g., 1234ms = 1sec + 234,000,000ns timeoutSpec.tv_sec = static_cast<time_t>(timeoutValue / CONST_S64(1000)); timeoutSpec.tv_nsec = static_cast<time_t>(CONST_S64(1000000) * (timeoutValue % CONST_S64(1000))); int result = pthread_cond_timedwait(semaphore, mutex, &timeoutSpec); return (result == 0) || (result == ETIMEDOUT); } // static bool VSemaphore::semaphoreSignal(VSemaphore_Type* semaphore) { return (pthread_cond_signal(semaphore) == 0); } // static bool VSemaphore::semaphoreBroadcast(VSemaphore_Type* semaphore) { return (pthread_cond_broadcast(semaphore) == 0); }
29.60989
151
0.698089
xvela
588874aa79c87267650730738315280dd0b803d6
1,126
cpp
C++
engine/source/Actions/ActionRotateTo.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
11
2020-10-21T15:03:41.000Z
2020-11-03T09:15:28.000Z
engine/source/Actions/ActionRotateTo.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
null
null
null
engine/source/Actions/ActionRotateTo.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
1
2020-10-27T00:13:41.000Z
2020-10-27T00:13:41.000Z
///////////////////////////////////////////////////// // 2016 © Max Gittel // ///////////////////////////////////////////////////// // SGEngine #include "ActionRotateTo.h" namespace sge { ActionRotateTo* ActionRotateTo::create(float time, const Vec3& position){ ActionRotateTo* action= new ActionRotateTo(); action->_endRotation=position; action->_duration=time; return action; } void ActionRotateTo::updateEntity(Entity* entity){ float intValue= (_time-_startTime)/_duration; Quaternion quad; Quaternion::slerp(_starRotation, _endRotation, intValue, &quad); entity->transform().setRotation(quad); } void ActionRotateTo::start(Entity* entity){ _starRotation=entity->transform().getRotation(); } void ActionRotateTo::end(Entity* entity){ entity->transform().setRotation(_endRotation); } ActionRotateTo::ActionRotateTo(){} ActionRotateTo:: ~ActionRotateTo(){} }
25.022222
77
0.519538
MaxSigma
58898bbbe8b6a802581d133c7d7b80f629f77d08
892
cpp
C++
PropGen/propgent.cpp
KondeU/QtPropGen
bae8a6c39071618a44ea6f439be66749348bf5af
[ "MIT" ]
null
null
null
PropGen/propgent.cpp
KondeU/QtPropGen
bae8a6c39071618a44ea6f439be66749348bf5af
[ "MIT" ]
null
null
null
PropGen/propgent.cpp
KondeU/QtPropGen
bae8a6c39071618a44ea6f439be66749348bf5af
[ "MIT" ]
null
null
null
#include "propgent.h" PropGenT::PropGenT(QObject *parent) : QObject(parent) { connect(this, &PropGenT::Vec1Changed, this, [](uintptr_t changer, double data) { qDebug() << "Vec1Changed:" << changer << "," << data; }); connect(this, &PropGenT::Vec2Changed, this, [](uintptr_t changer, double u, double v) { qDebug() << "Vec2Changed:" << changer << "," << u << "," << v; }); connect(this, &PropGenT::Vec3Changed, this, [](uintptr_t changer, double x, double y, double z) { qDebug() << "Vec3Changed:" << changer << "," << x << "," << y << "," << z; }); connect(this, &PropGenT::ColorChanged, this, [](uintptr_t changer, int r, int g, int b, int a) { qDebug() << "ColorChanged:" << changer << "," << r << "," << g << "," << b << "," << a; }); }
30.758621
76
0.482063
KondeU
588b0d1eb2031a6d44e325845d5755d0d939fb01
9,603
cc
C++
test/integration/physics_collision.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
5
2017-07-14T19:36:51.000Z
2020-04-01T06:47:59.000Z
test/integration/physics_collision.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
20
2017-07-20T21:04:49.000Z
2017-10-19T19:32:38.000Z
test/integration/physics_collision.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015-2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <map> #include <string> #include <ignition/math/Helpers.hh> #include "gazebo/physics/physics.hh" #include "gazebo/test/ServerFixture.hh" #include "gazebo/test/helper_physics_generator.hh" using namespace gazebo; const double g_big = 1e17; const double g_physics_tol = 1e-2; class PhysicsCollisionTest : public ServerFixture, public testing::WithParamInterface<const char*> { /// \brief Test Collision::GetBoundingBox. /// \param[in] _physicsEngine Type of physics engine to use. public: void GetBoundingBox(const std::string &_physicsEngine); /// \brief Spawn identical models with different collision pose offsets /// and verify that they have matching behavior. /// \param[in] _physicsEngine Type of physics engine to use. public: void PoseOffsets(const std::string &_physicsEngine); }; ///////////////////////////////////////////////// void PhysicsCollisionTest::GetBoundingBox(const std::string &_physicsEngine) { if (_physicsEngine == "simbody" || _physicsEngine == "dart") { gzerr << "Bounding boxes not yet working with " << _physicsEngine << ", see issue #1148" << std::endl; return; } Load("worlds/empty.world", true, _physicsEngine); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // Check bounding box of ground plane { physics::ModelPtr model = world->GetModel("ground_plane"); math::Box box = model->GetBoundingBox(); EXPECT_LT(box.min.x, -g_big); EXPECT_LT(box.min.y, -g_big); EXPECT_LT(box.min.z, -g_big); EXPECT_GT(box.max.x, g_big); EXPECT_GT(box.max.y, g_big); EXPECT_DOUBLE_EQ(box.max.z, 0.0); } } ///////////////////////////////////////////////// void PhysicsCollisionTest::PoseOffsets(const std::string &_physicsEngine) { Load("worlds/empty.world", true, _physicsEngine); auto world = physics::get_world("default"); ASSERT_TRUE(world != nullptr); // Box size const double dx = 0.9; const double dy = 0.4; const double dz = 0.9; const double mass = 10.0; const double angle = IGN_PI / 2.0; const unsigned int testCases = 4; for (unsigned int i = 0; i < testCases; ++i) { // Use msgs::AddBoxLink msgs::Model msgModel; math::Pose modelPose, linkPose, collisionPose; msgModel.set_name(this->GetUniqueString("model")); msgs::AddBoxLink(msgModel, mass, ignition::math::Vector3d(dx, dy, dz)); modelPose.pos.x = i * dz * 5; modelPose.pos.z = dz; double z0 = dz - dy/2; // i=0: rotated model pose // expect collision pose to match model pose if (i == 0) { modelPose.rot.SetFromEuler(angle, 0.0, 0.0); } // i=1: rotated link pose // expect collision pose to match link pose else if (i == 1) { linkPose.rot.SetFromEuler(angle, 0.0, 0.0); } // i=2: rotated collision pose // expect collision pose to differ from link pose else if (i == 2) { collisionPose.rot.SetFromEuler(angle, 0.0, 0.0); } // i=3: offset collision pose // expect collision pose to differ from link pose else if (i == 3) { collisionPose.pos.Set(0, 0, dz); z0 = 1.5 * dz; } { auto msgLink = msgModel.mutable_link(0); auto msgCollision = msgLink->mutable_collision(0); msgs::Set(msgModel.mutable_pose(), modelPose.Ign()); msgs::Set(msgLink->mutable_pose(), linkPose.Ign()); msgs::Set(msgCollision->mutable_pose(), collisionPose.Ign()); } auto model = this->SpawnModel(msgModel); ASSERT_TRUE(model != nullptr); auto link = model->GetLink(); ASSERT_TRUE(link != nullptr); const unsigned int index = 0; auto collision = link->GetCollision(index); ASSERT_TRUE(collision != nullptr); EXPECT_EQ(model->GetWorldPose(), modelPose); EXPECT_EQ(link->GetWorldPose(), linkPose + modelPose); EXPECT_EQ(collision->GetWorldPose(), collisionPose + linkPose + modelPose); // i=0: rotated model pose // expect collision pose to match model pose if (i == 0) { EXPECT_EQ(model->GetWorldPose(), collision->GetWorldPose()); } // i=1: rotated link pose // expect collision pose to match link pose else if (i == 1) { EXPECT_EQ(link->GetWorldPose(), collision->GetWorldPose()); } // i=2: rotated collision pose // expect collision position to match link position else if (i == 2) { EXPECT_EQ(link->GetWorldPose().pos, collision->GetWorldPose().pos); } // i=3: offset collision pose // expect collision postion to match link position plus offset else if (i == 3) { EXPECT_EQ(link->GetWorldPose().pos + collisionPose.pos, collision->GetWorldPose().pos); } auto physics = world->GetPhysicsEngine(); ASSERT_TRUE(physics != nullptr); physics->SetRealTimeUpdateRate(0); const double dt = physics->GetMaxStepSize(); const double g = world->Gravity().Z(); EXPECT_DOUBLE_EQ(dt, 1e-3); ASSERT_DOUBLE_EQ(g, -9.8); const double t0 = 1 + sqrt(2*z0 / (-g)); const int steps = floor(t0 / dt); world->Step(steps); // For 0-2, drop and expect box to rest at specific height if (i <= 2) { EXPECT_NEAR(collision->GetWorldPose().pos.z, dy/2, g_physics_tol); } else { EXPECT_NEAR(collision->GetWorldPose().pos.z, dz/2, g_physics_tol); } } } ///////////////////////////////////////////////// TEST_F(PhysicsCollisionTest, ModelSelfCollide) { // self_collide is only implemented in ODE Load("worlds/model_self_collide.world", true, "ode"); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // check the gravity vector physics::PhysicsEnginePtr physics = world->GetPhysicsEngine(); ASSERT_TRUE(physics != NULL); math::Vector3 g = physics->GetGravity(); // Assume gravity vector points down z axis only. EXPECT_EQ(g.x, 0); EXPECT_EQ(g.y, 0); EXPECT_LE(g.z, -9.8); // get physics time step double dt = physics->GetMaxStepSize(); EXPECT_GT(dt, 0); // 4 models: all_collide, some_collide, no_collide, and explicit_no_collide std::map<std::string, physics::ModelPtr> models; models["all_collide"] = physics::ModelPtr(); models["some_collide"] = physics::ModelPtr(); models["no_collide"] = physics::ModelPtr(); models["explicit_no_collide"] = physics::ModelPtr(); for (auto &iter : models) { gzdbg << "Getting model " << iter.first << std::endl; iter.second = world->GetModel(iter.first); ASSERT_TRUE(iter.second != NULL); } // Step forward 0.2 s double stepTime = 0.2; unsigned int steps = floor(stepTime / dt); world->Step(steps); // Expect boxes to be falling double fallVelocity = g.z * stepTime; for (auto &iter : models) { auto links = iter.second->GetLinks(); for (auto &link : links) { ASSERT_TRUE(link != NULL); gzdbg << "Check falling: " << link->GetScopedName() << std::endl; EXPECT_LT(link->GetWorldLinearVel().z, fallVelocity*(1-g_physics_tol)); } } // Another 3000 steps should put the boxes at rest world->Step(3000); // Expect 3 boxes to be stationary for (auto &iter : models) { auto links = iter.second->GetLinks(); for (auto &link : links) { ASSERT_TRUE(link != NULL); gzdbg << "Check resting: " << link->GetScopedName() << std::endl; EXPECT_NEAR(link->GetWorldLinearVel().z, 0, g_physics_tol); } } gzdbg << "Check resting positions" << std::endl; // link2 of all_collide should have the highest z-coordinate (around 3) EXPECT_NEAR(models["all_collide"]->GetLink("link2")->GetWorldPose().pos.z, 2.5, g_physics_tol); // link2 of some_collide should have a middling z-coordinate (around 2) EXPECT_NEAR(models["some_collide"]->GetLink("link2")->GetWorldPose().pos.z, 1.5, g_physics_tol); // link2 of no_collide should have a low z-coordinate (around 1) EXPECT_NEAR(models["no_collide"]->GetLink("link2")->GetWorldPose().pos.z, 0.5, g_physics_tol); // link2 of explicit_no_collide should have the same z-coordinate as above EXPECT_NEAR(models["no_collide"]->GetLink("link2")->GetWorldPose().pos.z, models["explicit_no_collide"]->GetLink("link2")->GetWorldPose().pos.z, g_physics_tol); Unload(); } ///////////////////////////////////////////////// TEST_P(PhysicsCollisionTest, GetBoundingBox) { GetBoundingBox(GetParam()); } ///////////////////////////////////////////////// TEST_P(PhysicsCollisionTest, PoseOffsets) { PoseOffsets(GetParam()); } INSTANTIATE_TEST_CASE_P(PhysicsEngines, PhysicsCollisionTest, PHYSICS_ENGINE_VALUES); ///////////////////////////////////////////////// int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.680511
77
0.632407
otamachan
58943f71058daf21380fd72fe1f6fd7485044f90
83
cpp
C++
OverEngine/vendor/stb/stb_sprintf.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
159
2020-03-16T14:46:46.000Z
2022-03-31T23:38:14.000Z
OverEngine/vendor/stb/stb_sprintf.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
5
2020-11-22T14:40:20.000Z
2022-01-16T03:45:54.000Z
OverEngine/vendor/stb/stb_sprintf.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
17
2020-06-01T05:58:32.000Z
2022-02-10T17:28:36.000Z
#include "pcheader.h" #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h"
16.6
34
0.807229
larrymason01
58a3084e3860de03ccd87aab8586aee07f3cd3fe
13,904
cxx
C++
IO/AMR/vtkAMREnzoReader.cxx
acamill/VTK
76bc79f6ae38d457b152bdeae34d5236e3aed1e6
[ "BSD-3-Clause" ]
null
null
null
IO/AMR/vtkAMREnzoReader.cxx
acamill/VTK
76bc79f6ae38d457b152bdeae34d5236e3aed1e6
[ "BSD-3-Clause" ]
null
null
null
IO/AMR/vtkAMREnzoReader.cxx
acamill/VTK
76bc79f6ae38d457b152bdeae34d5236e3aed1e6
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkAMREnzoReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAMREnzoReader.h" #include "vtkDataArray.h" #include "vtkDataArraySelection.h" #include "vtkIndent.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include "vtkOverlappingAMR.h" #include "vtkPolyData.h" #include "vtkUniformGrid.h" #include "vtksys/FStream.hxx" #include "vtksys/SystemTools.hxx" #include "vtkCellData.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkLongArray.h" #include "vtkLongLongArray.h" #include "vtkShortArray.h" #include "vtkUnsignedCharArray.h" #include "vtkUnsignedIntArray.h" #include "vtkUnsignedShortArray.h" #define H5_USE_16_API #include "vtk_hdf5.h" #include <cassert> #include <sstream> #include <string> #include <vector> #include "vtkAMREnzoReaderInternal.h" vtkStandardNewMacro(vtkAMREnzoReader); #include "vtkAMRInformation.h" #include <limits> void vtkAMREnzoReader::ComputeStats( vtkEnzoReaderInternal* internal, std::vector<int>& numBlocks, double min[3]) { min[0] = min[1] = min[2] = std::numeric_limits<double>::max(); numBlocks.resize(this->Internal->NumberOfLevels, 0); for (int i = 0; i < internal->NumberOfBlocks; ++i) { vtkEnzoReaderBlock& theBlock = internal->Blocks[i + 1]; double* gridMin = theBlock.MinBounds; if (gridMin[0] < min[0]) { min[0] = gridMin[0]; } if (gridMin[1] < min[1]) { min[1] = gridMin[1]; } if (gridMin[2] < min[2]) { min[2] = gridMin[2]; } numBlocks[theBlock.Level]++; } } //------------------------------------------------------------------------------ vtkAMREnzoReader::vtkAMREnzoReader() { this->Internal = new vtkEnzoReaderInternal(); this->IsReady = false; this->Initialize(); this->ConvertToCGS = 1; } //------------------------------------------------------------------------------ vtkAMREnzoReader::~vtkAMREnzoReader() { delete this->Internal; this->Internal = nullptr; this->BlockMap.clear(); delete[] this->FileName; this->FileName = nullptr; } //------------------------------------------------------------------------------ void vtkAMREnzoReader::PrintSelf(std::ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetIndexFromArrayName(std::string arrayName) { char stringIdx[2]; stringIdx[0] = arrayName.at(arrayName.size() - 2); stringIdx[1] = '\0'; return (atoi(stringIdx)); } //------------------------------------------------------------------------------ double vtkAMREnzoReader::GetConversionFactor(const std::string& name) { if (this->label2idx.find(name) != this->label2idx.end()) { int idx = this->label2idx[name]; if (this->conversionFactors.find(idx) != this->conversionFactors.end()) { return (this->conversionFactors[idx]); } else { return (1.0); } } return (1.0); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ParseLabel(const std::string& labelString, int& idx, std::string& label) { std::vector<std::string> strings; std::istringstream iss(labelString); std::string word; while (iss >> word) { if (!vtksys::SystemTools::StringStartsWith(word.c_str(), "=")) { strings.push_back(word); } } idx = this->GetIndexFromArrayName(strings[0]); label = strings[strings.size() - 1]; } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ParseCFactor(const std::string& labelString, int& idx, double& factor) { std::vector<std::string> strings; std::istringstream iss(labelString); std::string word; while (iss >> word) { if (!vtksys::SystemTools::StringStartsWith(word.c_str(), "=")) { strings.push_back(word); } } idx = this->GetIndexFromArrayName(strings[0]); factor = atof(strings[strings.size() - 1].c_str()); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ParseConversionFactors() { assert("pre: FileName should not be nullptr" && (this->FileName != nullptr)); // STEP 0: Extract the parameters file from the user-supplied filename std::string baseDir = vtksys::SystemTools::GetFilenamePath(std::string(this->FileName)); std::string paramsFile = baseDir + "/" + vtksys::SystemTools::GetFilenameWithoutExtension(std::string(this->FileName)); // STEP 1: Open Parameters file vtksys::ifstream ifs; ifs.open(paramsFile.c_str()); if (!ifs.is_open()) { vtkWarningMacro("Cannot open ENZO parameters file!\n"); return; } // STEP 2: Parsing parameters file std::string line; // temp string to store a line read from the params file std::string label; // stores the attribute name double cf; // stores the conversion factor int idx; // stores the attribute label index while (getline(ifs, line)) { if (vtksys::SystemTools::StringStartsWith(line.c_str(), "DataLabel")) { this->ParseLabel(line, idx, label); this->label2idx[label] = idx; } else if (vtksys::SystemTools::StringStartsWith(line.c_str(), "#DataCGSConversionFactor")) { this->ParseCFactor(line, idx, cf); this->conversionFactors[idx] = cf; } } // STEP 3: Close parameters file ifs.close(); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::SetFileName(const char* fileName) { assert("pre: Internal Enzo AMR Reader is nullptr" && (this->Internal != nullptr)); if (fileName && strcmp(fileName, "") && ((this->FileName == nullptr) || (strcmp(fileName, this->FileName)))) { std::string tempName(fileName); std::string bExtName(".boundary"); std::string hExtName(".hierarchy"); if (tempName.length() > hExtName.length() && tempName.substr(tempName.length() - hExtName.length()) == hExtName) { this->Internal->MajorFileName = tempName.substr(0, tempName.length() - hExtName.length()); this->Internal->HierarchyFileName = tempName; this->Internal->BoundaryFileName = this->Internal->MajorFileName + bExtName; } else if (tempName.length() > bExtName.length() && tempName.substr(tempName.length() - bExtName.length()) == bExtName) { this->Internal->MajorFileName = tempName.substr(0, tempName.length() - bExtName.length()); this->Internal->BoundaryFileName = tempName; this->Internal->HierarchyFileName = this->Internal->MajorFileName + hExtName; } else { vtkErrorMacro("Enzo file has invalid extension!"); return; } this->IsReady = true; this->Internal->DirectoryName = GetEnzoDirectory(this->Internal->MajorFileName.c_str()); } if (this->IsReady) { this->BlockMap.clear(); this->Internal->Blocks.clear(); this->Internal->NumberOfBlocks = 0; this->LoadedMetaData = false; if (this->FileName != nullptr) { delete[] this->FileName; this->FileName = nullptr; this->Internal->SetFileName(nullptr); } this->FileName = new char[strlen(fileName) + 1]; strcpy(this->FileName, fileName); this->FileName[strlen(fileName)] = '\0'; this->Internal->SetFileName(this->FileName); this->ParseConversionFactors(); this->Internal->ReadMetaData(); this->SetUpDataArraySelections(); this->InitializeArraySelections(); } this->Modified(); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ReadMetaData() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return; } this->Internal->ReadMetaData(); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetBlockLevel(const int blockIdx) { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return (-1); } this->Internal->ReadMetaData(); if (blockIdx < 0 || blockIdx >= this->Internal->NumberOfBlocks) { vtkErrorMacro("Block Index (" << blockIdx << ") is out-of-bounds!"); return (-1); } return (this->Internal->Blocks[blockIdx + 1].Level); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetNumberOfBlocks() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return 0; } this->Internal->ReadMetaData(); return (this->Internal->NumberOfBlocks); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetNumberOfLevels() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return 0; } this->Internal->ReadMetaData(); return (this->Internal->NumberOfLevels); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::FillMetaData() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); assert("pre: metadata object is nullptr" && (this->Metadata != nullptr)); if (!this->IsReady) { return 0; } this->Internal->ReadMetaData(); double origin[3]; std::vector<int> blocksPerLevel; this->ComputeStats(this->Internal, blocksPerLevel, origin); this->Metadata->Initialize(static_cast<int>(blocksPerLevel.size()), &blocksPerLevel[0]); this->Metadata->SetGridDescription(VTK_XYZ_GRID); this->Metadata->SetOrigin(origin); std::vector<int> b2level(this->Internal->NumberOfLevels + 1, 0); for (int block = 0; block < this->Internal->NumberOfBlocks; ++block) { vtkEnzoReaderBlock& theBlock = this->Internal->Blocks[block + 1]; int level = theBlock.Level; int internalIdx = block; int id = b2level[level]; // compute spacing double spacing[3]; for (int d = 0; d < 3; ++d) { spacing[d] = (theBlock.BlockNodeDimensions[d] > 1) ? (theBlock.MaxBounds[d] - theBlock.MinBounds[d]) / (theBlock.BlockNodeDimensions[d] - 1.0) : 1.0; } // compute AMRBox vtkAMRBox box(theBlock.MinBounds, theBlock.BlockNodeDimensions, spacing, origin, VTK_XYZ_GRID); // set meta data this->Metadata->SetSpacing(level, spacing); this->Metadata->SetAMRBox(level, id, box); this->Metadata->SetAMRBlockSourceIndex(level, id, internalIdx); b2level[level]++; } this->Metadata->GenerateParentChildInformation(); this->Metadata->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(), this->Internal->DataTime); return (1); } //------------------------------------------------------------------------------ vtkUniformGrid* vtkAMREnzoReader::GetAMRGrid(const int blockIdx) { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return nullptr; } this->Internal->ReadMetaData(); // this->Internal->Blocks includes a pseudo block --- the root as block #0 vtkEnzoReaderBlock& theBlock = this->Internal->Blocks[blockIdx + 1]; double blockMin[3]; double blockMax[3]; double spacings[3]; for (int i = 0; i < 3; ++i) { blockMin[i] = theBlock.MinBounds[i]; blockMax[i] = theBlock.MaxBounds[i]; spacings[i] = (theBlock.BlockNodeDimensions[i] > 1) ? (blockMax[i] - blockMin[i]) / (theBlock.BlockNodeDimensions[i] - 1.0) : 1.0; } vtkUniformGrid* ug = vtkUniformGrid::New(); ug->SetDimensions(theBlock.BlockNodeDimensions); ug->SetOrigin(blockMin[0], blockMin[1], blockMin[2]); ug->SetSpacing(spacings[0], spacings[1], spacings[2]); return (ug); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::GetAMRGridData(const int blockIdx, vtkUniformGrid* block, const char* field) { assert("pre: AMR block is nullptr" && (block != nullptr)); this->Internal->GetBlockAttribute(field, blockIdx, block); if (this->ConvertToCGS == 1) { double conversionFactor = this->GetConversionFactor(field); if (conversionFactor != 1.0) { vtkDataArray* data = block->GetCellData()->GetArray(field); assert("pre: data array is nullptr!" && (data != nullptr)); vtkIdType numTuples = data->GetNumberOfTuples(); for (vtkIdType t = 0; t < numTuples; ++t) { int numComp = data->GetNumberOfComponents(); for (int c = 0; c < numComp; ++c) { double f = data->GetComponent(t, c); data->SetComponent(t, c, f * conversionFactor); } // END for all components } // END for all tuples } // END if the conversion factor is not 1.0 } // END if conversion to CGS units is requested } //------------------------------------------------------------------------------ void vtkAMREnzoReader::SetUpDataArraySelections() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); this->Internal->ReadMetaData(); this->Internal->GetAttributeNames(); int numAttrs = static_cast<int>(this->Internal->BlockAttributeNames.size()); for (int i = 0; i < numAttrs; i++) { this->CellDataArraySelection->AddArray(this->Internal->BlockAttributeNames[i].c_str()); } // END for all attributes }
29.965517
99
0.5958
acamill
58a3f14a1bca9ae134f099f7224a3d89106b753d
1,964
cpp
C++
factories/example/example.cpp
adhithadias/design-patterns-cplusplus
19aef5d1a6c873c157cce27b048896166add01d6
[ "MIT" ]
null
null
null
factories/example/example.cpp
adhithadias/design-patterns-cplusplus
19aef5d1a6c873c157cce27b048896166add01d6
[ "MIT" ]
null
null
null
factories/example/example.cpp
adhithadias/design-patterns-cplusplus
19aef5d1a6c873c157cce27b048896166add01d6
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; enum class PointType { cartesian, polar }; /* 1) here we cannot have 2 Point constructors for cartesian and polar because both of the constructors will have (float, float) arguments we have to introduce enum for type differenciation 2) then we introduce static methods for object creation -- this is called as factory methods 3) Next we add a seperate class called Factory for Point creation In the Gand of 4, there is no Factory class, there is only factory methods and abstracts But we are creating a concrete Factory class (not abstract) 4) We can move the PointFactory inside the Point class to keep the open-close principle intact because we made everything public in Point class Now since PointFactory is inside the Point class, the private members of the Point class are accessible from inside the PointFactory class 5) We can even make the PointFactory class private -- this approach is called Inner Factory and add a public member to the class PointFactory */ class Point { Point (float x, float y) : x(x), y(y) {} // Point (float a, float b, PointType type = PointType::cartesian) { // if (type == PointType::cartesian) { // x = a; // y = b; // } // else { // x = a * cos(b); // y = a * sin(b); // } // } float x, y; public: friend ostream &operator<<(ostream& os, Point &p) { os << "x: " << p.x << ", y: " << p.y; return os; } private: struct PointFactory { PointFactory() {} static Point NewCartesian(float x, float y) { return {x, y}; } static Point NewPolar(float r, float theta) { return { r*cos(theta), r*sin(theta) }; } }; public: static PointFactory Factory; }; int main() { auto p = Point::Factory.NewCartesian(2, 4); cout << p << endl; return 0; }
24.860759
92
0.62831
adhithadias
58a51b05f42a782a36e62239f2a9a36611c42ac9
1,189
cpp
C++
ojgl/src/render/Texture.cpp
OskarPedersen/OJGL
e905a59afc628bc420c510074d0f4174aea4da44
[ "MIT" ]
null
null
null
ojgl/src/render/Texture.cpp
OskarPedersen/OJGL
e905a59afc628bc420c510074d0f4174aea4da44
[ "MIT" ]
null
null
null
ojgl/src/render/Texture.cpp
OskarPedersen/OJGL
e905a59afc628bc420c510074d0f4174aea4da44
[ "MIT" ]
null
null
null
#include "Texture.h" #include "winapi/gl_loader.h" namespace ojgl { Texture::Texture(int width, int height, int channels, unsigned char* img) : _width(width) , _height(height) , _channels(channels) { load(img); } ojstd::shared_ptr<Texture> Texture::construct(int width, int height, int channels, unsigned char* img) { return ojstd::shared_ptr<Texture>(new Texture(width, height, channels, img)); } Texture::~Texture() { glDeleteTextures(1, &_textureID); } unsigned Texture::textureID() { return _textureID; } void Texture::load(unsigned char* img) { glGenTextures(1, &_textureID); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _textureID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, _channels == 3 ? GL_RGB : GL_RGBA, GL_UNSIGNED_BYTE, img); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); } } //namespace ojgl
27.651163
122
0.736754
OskarPedersen
58afa5107ee38f491750a776226f9ccdf8dfb61d
200
cpp
C++
Luogu/P1425.cpp
Rose2073/RoseCppSource
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
[ "Apache-2.0" ]
1
2021-04-05T16:26:00.000Z
2021-04-05T16:26:00.000Z
Luogu/P1425.cpp
Rose2073/RoseCppSource
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
[ "Apache-2.0" ]
null
null
null
Luogu/P1425.cpp
Rose2073/RoseCppSource
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
[ "Apache-2.0" ]
null
null
null
#include<cstdio> int main(){ int h1,m1,h2,m2; scanf("%d %d %d %d",&h1,&m1,&h2,&m2); int h3,m3; m3 = m2 - m1; if(m3 < 0){ h2--; m3 += 60; } h3 = h2- h1; printf("%d %d",h3,m3); return 0; }
13.333333
38
0.485
Rose2073
58b1747958284c0ece6133fb6f452e5db3a30652
750
cpp
C++
sydney-2017-03-29/motivation1c.cpp
cjdb/cpp-conferences
bafe69cf11ca38451367553460e956cb52df3dd2
[ "Apache-2.0" ]
3
2017-09-15T00:10:25.000Z
2018-09-22T12:50:18.000Z
sydney-2017-03-29/motivation1c.cpp
cjdb/cppcon
bafe69cf11ca38451367553460e956cb52df3dd2
[ "Apache-2.0" ]
1
2017-12-04T22:12:16.000Z
2017-12-04T22:12:16.000Z
sydney-2017-03-29/motivation1c.cpp
cjdb/cppcon
bafe69cf11ca38451367553460e956cb52df3dd2
[ "Apache-2.0" ]
1
2017-12-04T10:50:54.000Z
2017-12-04T10:50:54.000Z
#include <algorithm> #include <iterator> #include <iostream> #include <type_traits> #include <vector> template <typename InputIterator, std::enable_if_t< std::is_same<typename InputIterator::iterator_tag_t, typename InputIterator::iterator_tag_t>::value, int> = 0> std::vector<double> make_vector(InputIterator first, InputIterator last) { auto v = std::vector<double>{}; while (first != last) v.push_back(*first++); return v; } std::vector<double> make_vector(std::size_t size, double magnitude) { return std::vector<double>(size, magnitude); } int main() { auto v = make_vector(10, 1); copy(v.begin(), v.end(), std::ostream_iterator<decltype(v)::value_type>{std::cout, " "}); std::cout << '\n'; }
25
92
0.676
cjdb
58b1c412f971463564e3254bbb42efd0dd5684a5
1,491
hh
C++
Config.hh
cndolo/smart_pointers
3586e06e609ddbea6faf3208e09ad40d7f554183
[ "MIT" ]
null
null
null
Config.hh
cndolo/smart_pointers
3586e06e609ddbea6faf3208e09ad40d7f554183
[ "MIT" ]
null
null
null
Config.hh
cndolo/smart_pointers
3586e06e609ddbea6faf3208e09ad40d7f554183
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> struct ImageConfig{ static uint64_t PHYS_BASE; static size_t SIZE; static uint64_t VIRT_BASE; static uint64_t KERN_END; static uint64_t physBase() { return ImageConfig::PHYS_BASE; } static size_t size() { return ImageConfig::SIZE; } static uint64_t virtBase() { return ImageConfig::VIRT_BASE; } static void setPhysBase(uint64_t phys) { ImageConfig::PHYS_BASE = phys; } static void setSize(size_t size) { ImageConfig::SIZE = size; } static void setVirtBase(uint64_t virt) { ImageConfig::VIRT_BASE = virt; } }; struct MMIOConfig{ static uint64_t PHYS_BASE; static size_t SIZE; static uint64_t VIRT_BASE; static uint64_t physBase() { return MMIOConfig::PHYS_BASE; } static size_t size() { return MMIOConfig::SIZE; } static uint64_t virtBase() { return MMIOConfig::VIRT_BASE; } static void setPhysBase(uint64_t phys) { PHYS_BASE = phys; } static void setSize(size_t size) { SIZE = size; } static void setVirtBase(uint64_t virt) { VIRT_BASE = virt; } }; struct KernelConfig{ static uint64_t PHYS_BASE; static size_t SIZE; static uint64_t VIRT_BASE; static uint64_t physBase() { return KernelConfig::PHYS_BASE; } static size_t size() { return KernelConfig::SIZE; } static uint64_t virtBase() { return KernelConfig::VIRT_BASE; } static void setPhysBase(uint64_t phys) { PHYS_BASE = phys; } static void setSize(size_t size) { SIZE = size; } static void setVirtBase(uint64_t virt) { VIRT_BASE = virt ;} };
31.723404
74
0.744467
cndolo
58b5a1499ead2cc7ce06ce342361ef373820b9dc
494
cpp
C++
nowcoder/80C.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
nowcoder/80C.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
nowcoder/80C.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define N 100020 #define mod 998244353 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } int main(int argc, char const *argv[]) { int p = read(); ll res = 1; for (int i = 1; i <= p; i++) res = res * i % mod; res = res * res % mod * 2 % mod; cout << res << endl; return 0; }
24.7
61
0.546559
swwind
58b5da290227a4419b775b445b190b4e906c0a5e
2,267
cpp
C++
main.cpp
MattLigocki/DNNAssist
97801013ac948c6fdd84fa622888c519eed3bc85
[ "MIT" ]
null
null
null
main.cpp
MattLigocki/DNNAssist
97801013ac948c6fdd84fa622888c519eed3bc85
[ "MIT" ]
null
null
null
main.cpp
MattLigocki/DNNAssist
97801013ac948c6fdd84fa622888c519eed3bc85
[ "MIT" ]
null
null
null
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickStyle> #include <QQmlContext> #include <QQuickWindow> #include <memory> #include <QTimer> #include "models/modelObjects/Classifier.h" #include "computerVision/QCvDetectFilter.h" #include "controllers/DataSetsScreenController.h" #include "controllers/MediaScreenController.h" #include "managers/ComputerVisionManager/AiManager.h" #include "managers/HttpManager/HttpManager.h" #include "utils/FileSystemHandler.h" #include "utils/Common.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); app.setApplicationName("DNNAssist"); QQuickStyle::setStyle("Material"); //Register QML types qmlRegisterType<QCvDetectFilter>("com.dnnassist.classes", 1, 0, "CvDetectFilter"); qmlRegisterType<ObjectListModel>("com.dnnassist.classes", 1, 0, "ObjectListModel"); qmlRegisterType<FileSystemHandler>("com.dnnassist.classes", 1, 0, "FileSystemHandler"); QQmlApplicationEngine engine; //Register managers engine.rootContext()->setContextProperty("aiManager", &AiManager::getInstance()); //Register controllers engine.rootContext()->setContextProperty("dataSetsScreenController", &DataSetsScreenController::getInstance()); engine.rootContext()->setContextProperty("mediaScreenController", &MediaScreenController::getInstance()); //Register processed video output engine.rootContext()->engine()->addImageProvider(QLatin1String("NwImageProvider"), MediaScreenController::getInstance().getImageProvider()); engine.rootContext()->setContextProperty("NwImageProvider", MediaScreenController::getInstance().getImageProvider()); engine.rootContext()->setContextProperty("httpManager", new HttpManager()); const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); if (engine.rootObjects().isEmpty()) { qDebug("Empty rootObjects"); return -1; } return app.exec(); }
34.876923
144
0.731804
MattLigocki
58c4e5ac7ba38b36e29a6975398fa189684f2f13
479
cpp
C++
Source/Editor/Private/Customizations/SEComponentClassFilterCustomization.cpp
foobit/SaveExtension
390033bc757f2b694c497e22c324dcac539bcd15
[ "Apache-2.0" ]
110
2018-10-20T21:47:54.000Z
2022-03-14T03:47:58.000Z
Source/Editor/Private/Customizations/SEComponentClassFilterCustomization.cpp
foobit/SaveExtension
390033bc757f2b694c497e22c324dcac539bcd15
[ "Apache-2.0" ]
68
2018-12-19T09:08:56.000Z
2022-03-09T06:43:38.000Z
Source/Editor/Private/Customizations/SEComponentClassFilterCustomization.cpp
foobit/SaveExtension
390033bc757f2b694c497e22c324dcac539bcd15
[ "Apache-2.0" ]
45
2018-12-03T14:35:47.000Z
2022-03-05T01:35:24.000Z
// Copyright 2015-2020 Piperift. All Rights Reserved. #include "Customizations/SEComponentClassFilterCustomization.h" #include "PropertyHandle.h" #define LOCTEXT_NAMESPACE "FSEComponentClassFilterCustomization" TSharedPtr<IPropertyHandle> FSEComponentClassFilterCustomization::GetFilterHandle(TSharedRef<IPropertyHandle> StructPropertyHandle) { return StructHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FSEComponentClassFilter, ClassFilter));; } #undef LOCTEXT_NAMESPACE
31.933333
131
0.860125
foobit
58c6e8c64c29739e6951e1ff66d67fa5ea003393
2,338
cpp
C++
src/imaging/ossimJpegMemDest.cpp
martidi/ossim
44268fa9d7fc5a3038642e702e85ccd339a4ff9f
[ "MIT" ]
null
null
null
src/imaging/ossimJpegMemDest.cpp
martidi/ossim
44268fa9d7fc5a3038642e702e85ccd339a4ff9f
[ "MIT" ]
null
null
null
src/imaging/ossimJpegMemDest.cpp
martidi/ossim
44268fa9d7fc5a3038642e702e85ccd339a4ff9f
[ "MIT" ]
1
2018-10-11T11:36:16.000Z
2018-10-11T11:36:16.000Z
//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Most of code and comments below are from jpeg-6b "example.c" file. See // http://www4.cs.fau.de/Services/Doc/graphics/doc/jpeg/libjpeg.html // // Author: Oscar Kramer (From example by Thomas Lane) //---------------------------------------------------------------------------- // $Id$ #include <ossim/imaging/ossimJpegMemDest.h> #include <cstdlib> /* free, malloc */ /* *** Custom destination manager for JPEG writer *** */ typedef struct { struct jpeg_destination_mgr pub; /* public fields */ std::ostream* stream; /* target stream */ JOCTET* buffer; /* start of buffer */ } cpp_dest_mgr; #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ void init_destination (j_compress_ptr cinfo) { cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest; /* Allocate the output buffer --- it will be released when done with image */ dest->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * sizeof(JOCTET)); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; } boolean empty_output_buffer (j_compress_ptr cinfo) { cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest; dest->stream->write ((char*)dest->buffer, OUTPUT_BUF_SIZE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; return TRUE; } void term_destination (j_compress_ptr cinfo) { cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest; size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; /* Write any data remaining in the buffer */ if (datacount > 0) dest->stream->write ((char*)dest->buffer, datacount); dest->stream->flush(); free (cinfo->dest); } void jpeg_cpp_stream_dest (j_compress_ptr cinfo, std::ostream& stream) { cpp_dest_mgr* dest; /* first time for this JPEG object? */ if (cinfo->dest == NULL) cinfo->dest = (struct jpeg_destination_mgr *) malloc (sizeof(cpp_dest_mgr)); dest = (cpp_dest_mgr*) cinfo->dest; dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; dest->stream = &stream; }
30.363636
103
0.652695
martidi
58ca4902c0172be2c805c0ddf926e800f67b4417
789
hpp
C++
mycenter/center/BaseCenter.hpp
nightli110/mycenter
3d96bf6fa6e3442646f9a416c6fd80c9807590c8
[ "MIT" ]
null
null
null
mycenter/center/BaseCenter.hpp
nightli110/mycenter
3d96bf6fa6e3442646f9a416c6fd80c9807590c8
[ "MIT" ]
null
null
null
mycenter/center/BaseCenter.hpp
nightli110/mycenter
3d96bf6fa6e3442646f9a416c6fd80c9807590c8
[ "MIT" ]
null
null
null
/*** * @Author: nightli * @Date: 2020-10-13 17:15:52 * @LastEditors: nightli * @LastEditTime: 2020-10-14 10:22:11 * @FilePath: /mycenter/MyCenter.hpp * @Emile: [email protected] */ #include <iostream> #include "../App/InferenceAPP.hpp" #include "../datatype/MyData.hpp" using namespace std; class BaseCenter { public: BaseCenter(); BaseCenter(const BaseCenter&); bool ProcessData(Json::Value DataInfoJson); bool PostData(Json::Value request_json); bool CallInferenceOnline(string Inferencename); void InitCenter(InferenceAPPMap* MyAppMap); void UpdateAppdata(); void RunCenter(); private: InferenceAPPMap *CenterAppMap; map<string, DataInfo> DataMsgs; map<string, bool> AppStatus; boost::shared_mutex read_write_mutex; };
19.243902
51
0.698352
nightli110
58cf2bd16dc965f1c4210914a4957cf70c23b1bd
4,432
cpp
C++
libraries/CRC/test/unit_test_crc32.cpp
jantje/Arduino
cd40e51b4eb9f8947aa58f278f61c9121d711fb0
[ "MIT" ]
1,253
2015-01-03T17:07:53.000Z
2022-03-22T11:46:42.000Z
libraries/CRC/test/unit_test_crc32.cpp
henriquerochamattos/Arduino
3ace3a4e7b2b51d52d4c2ea363d23ebaacd9cc68
[ "MIT" ]
134
2015-01-21T20:33:13.000Z
2022-01-05T08:59:33.000Z
libraries/CRC/test/unit_test_crc32.cpp
henriquerochamattos/Arduino
3ace3a4e7b2b51d52d4c2ea363d23ebaacd9cc68
[ "MIT" ]
3,705
2015-01-02T17:03:16.000Z
2022-03-31T13:20:30.000Z
// // FILE: unit_test_crc32.cpp // AUTHOR: Rob Tillaart // DATE: 2021-03-31 // PURPOSE: unit tests for the CRC library // https://github.com/RobTillaart/CRC // https://github.com/Arduino-CI/arduino_ci/blob/master/REFERENCE.md // // supported assertions // ---------------------------- // assertEqual(expected, actual); // a == b // assertNotEqual(unwanted, actual); // a != b // assertComparativeEquivalent(expected, actual); // abs(a - b) == 0 or (!(a > b) && !(a < b)) // assertComparativeNotEquivalent(unwanted, actual); // abs(a - b) > 0 or ((a > b) || (a < b)) // assertLess(upperBound, actual); // a < b // assertMore(lowerBound, actual); // a > b // assertLessOrEqual(upperBound, actual); // a <= b // assertMoreOrEqual(lowerBound, actual); // a >= b // assertTrue(actual); // assertFalse(actual); // assertNull(actual); // // special cases for floats // assertEqualFloat(expected, actual, epsilon); // fabs(a - b) <= epsilon // assertNotEqualFloat(unwanted, actual, epsilon); // fabs(a - b) >= epsilon // assertInfinity(actual); // isinf(a) // assertNotInfinity(actual); // !isinf(a) // assertNAN(arg); // isnan(a) // assertNotNAN(arg); // !isnan(a) #include <ArduinoUnitTests.h> #include "Arduino.h" #include "CRC32.h" char str[24] = "123456789"; uint8_t * data = (uint8_t *) str; unittest_setup() { } unittest_teardown() { } unittest(test_crc32) { fprintf(stderr, "TEST CRC32\n"); CRC32 crc; crc.setPolynome(0x04C11DB7); crc.setStartXOR(0xFFFFFFFF); crc.setEndXOR(0xFFFFFFFF); crc.setReverseIn(true); crc.setReverseOut(true); crc.add(data, 9); assertEqual(0xCBF43926, crc.getCRC()); crc.reset(); crc.setPolynome(0x04C11DB7); crc.setStartXOR(0xFFFFFFFF); crc.setEndXOR(0xFFFFFFFF); crc.add(data, 9); assertEqual(0xFC891918, crc.getCRC()); crc.reset(); crc.setPolynome(0x1EDC6F41); crc.setStartXOR(0xFFFFFFFF); crc.setEndXOR(0xFFFFFFFF); crc.setReverseIn(true); crc.setReverseOut(true); crc.add(data, 9); assertEqual(0xE3069283, crc.getCRC()); crc.reset(); crc.setPolynome(0xA833982B); crc.setStartXOR(0xFFFFFFFF); crc.setEndXOR(0xFFFFFFFF); crc.setReverseIn(true); crc.setReverseOut(true); crc.add(data, 9); assertEqual(0x87315576, crc.getCRC()); crc.reset(); crc.setPolynome(0x04C11DB7); crc.setStartXOR(0xFFFFFFFF); crc.setEndXOR(0x00000000); crc.setReverseIn(false); crc.setReverseOut(false); crc.add(data, 9); assertEqual(0x0376E6E7, crc.getCRC()); crc.reset(); crc.setPolynome(0x04C11DB7); crc.setStartXOR(0x00000000); crc.setEndXOR(0xFFFFFFFF); crc.setReverseIn(false); crc.setReverseOut(false); crc.add(data, 9); assertEqual(0x765E7680, crc.getCRC()); crc.reset(); crc.setPolynome(0x814141AB); crc.setStartXOR(0x00000000); crc.setEndXOR(0x00000000); crc.setReverseIn(false); crc.setReverseOut(false); crc.add(data, 9); assertEqual(0x3010BF7F, crc.getCRC()); crc.reset(); crc.setPolynome(0x04C11DB7); crc.setStartXOR(0xFFFFFFFF); crc.setEndXOR(0x00000000); crc.setReverseIn(true); crc.setReverseOut(true); crc.add(data, 9); assertEqual(0x340BC6D9, crc.getCRC()); crc.reset(); crc.setPolynome(0x000000AF); crc.setStartXOR(0x00000000); crc.setEndXOR(0x00000000); crc.setReverseIn(false); crc.setReverseOut(false); crc.add(data, 9); assertEqual(0xBD0BE338, crc.getCRC()); /* // DONE assertEqual(0xCBF43926, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true)); assertEqual(0xFC891918, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, false)); assertEqual(0xE3069283, crc32(data, 9, 0x1EDC6F41, 0xFFFFFFFF, 0xFFFFFFFF, true, true)); assertEqual(0x87315576, crc32(data, 9, 0xA833982B, 0xFFFFFFFF, 0xFFFFFFFF, true, true)); assertEqual(0x0376E6E7, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0x00000000, false, false)); assertEqual(0x765E7680, crc32(data, 9, 0x04C11DB7, 0x00000000, 0xFFFFFFFF, false, false)); assertEqual(0x3010BF7F, crc32(data, 9, 0x814141AB, 0x00000000, 0x00000000, false, false)); assertEqual(0x340BC6D9, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0x00000000, true, true)); assertEqual(0xBD0BE338, crc32(data, 9, 0x000000AF, 0x00000000, 0x00000000, false, false)); */ } unittest_main() // --------
28.779221
97
0.664486
jantje
58d33bf3fdb8ba76a35b1ccdd46e058876393bec
248
hpp
C++
test/test_mpi.hpp
mirandaconrado/object-archive
e3f43ac8aac86293f642b1a85a6892904ea3714b
[ "MIT" ]
1
2019-12-10T11:38:49.000Z
2019-12-10T11:38:49.000Z
test/test_mpi.hpp
mirandaconrado/object-archive
e3f43ac8aac86293f642b1a85a6892904ea3714b
[ "MIT" ]
null
null
null
test/test_mpi.hpp
mirandaconrado/object-archive
e3f43ac8aac86293f642b1a85a6892904ea3714b
[ "MIT" ]
null
null
null
#ifndef __TASK_DISTRIBUTION__TEST_MPI_HPP__ #define __TASK_DISTRIBUTION__TEST_MPI_HPP__ #include <boost/mpi/environment.hpp> #include <boost/mpi/communicator.hpp> extern boost::mpi::environment env; extern boost::mpi::communicator world; #endif
22.545455
43
0.826613
mirandaconrado
58d4885be4e47bbfc155f2e61d97b3c1a306fce9
573
cpp
C++
156.cpp
R-penguins/UVa-Online-Judge-Solutions
4bb24ab26c207903ff5b6fea6cfe122ae6578d62
[ "MIT" ]
null
null
null
156.cpp
R-penguins/UVa-Online-Judge-Solutions
4bb24ab26c207903ff5b6fea6cfe122ae6578d62
[ "MIT" ]
null
null
null
156.cpp
R-penguins/UVa-Online-Judge-Solutions
4bb24ab26c207903ff5b6fea6cfe122ae6578d62
[ "MIT" ]
null
null
null
/** * AOAPC II Example 5-4 Ananagrams */ #include <bits/stdc++.h> using namespace std; int main() { map<string, string> trans; string s; while ((cin >> s) && s[0] != '#') { string t = s; for (char &c : t) c = tolower(c); sort(t.begin(), t.end()); if (trans.find(t) == trans.end()) trans[t] = s; else trans[t] = ""; } set<string> ans; for (auto p : trans) if (p.second != "") ans.insert(p.second); for (string s : ans) cout << s << "\n"; }
22.038462
41
0.4363
R-penguins
58e8b0f612d52ad89d385c9c65acd7fe2995970b
400
cc
C++
extras/readnewmagres.cc
dch0ph/pNMRsim
2420e618c7bff9b38b43e7c2ac684c5c28b61787
[ "MIT" ]
null
null
null
extras/readnewmagres.cc
dch0ph/pNMRsim
2420e618c7bff9b38b43e7c2ac684c5c28b61787
[ "MIT" ]
null
null
null
extras/readnewmagres.cc
dch0ph/pNMRsim
2420e618c7bff9b38b43e7c2ac684c5c28b61787
[ "MIT" ]
null
null
null
#include "magres.h" using namespace MagRes; int main(int argc, const char **argv) { try { MagresFile magres; magres.parse_from_file(argv[1]); std::cout << magres; } catch (exception_t& exc) { std::cerr << "Parsing failed: " << exc << '\n'; return 1; } catch (notmagres_exception_t&) { std::cerr << "Not a new format magres file\n"; return 2; } return 0; }
19.047619
51
0.6
dch0ph
58e999a3c5fd31dcf3b51b5996d50a3880d74664
530
cpp
C++
CodeChef June Contest 2020/Chef-and-String-Problem.cpp
Shiv-sharma-111/CodeChef-Contest
93594692ba0818cb30ac3dd15addd67246e987ff
[ "MIT" ]
null
null
null
CodeChef June Contest 2020/Chef-and-String-Problem.cpp
Shiv-sharma-111/CodeChef-Contest
93594692ba0818cb30ac3dd15addd67246e987ff
[ "MIT" ]
null
null
null
CodeChef June Contest 2020/Chef-and-String-Problem.cpp
Shiv-sharma-111/CodeChef-Contest
93594692ba0818cb30ac3dd15addd67246e987ff
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int T; cin>>T; while(T--) { string S; //getline(cin,S); cin>>S; int n = S.length(); int count=0; if(n==1) { cout<<"0"<<"\n"; } else { for(int i=0;i<n;i++) { if((S[i]=='x' && S[i+1]=='y') || (S[i]=='y' && S[i+1]=='x')) { count++; i++; } } cout<<count<<"\n"; } } return 0; }
15.142857
68
0.39434
Shiv-sharma-111
58eb71bbe291896006a7ff8e7e255045e4e2abf4
8,781
cpp
C++
ntUPSd/CommandProcessor.cpp
6XGate/ntUPSd
7a3d7301a78db632c93c8eb9665c9d039137d835
[ "MIT" ]
20
2016-04-11T12:22:59.000Z
2021-12-07T19:38:26.000Z
ntUPSd/CommandProcessor.cpp
6XGate/ntUPSd
7a3d7301a78db632c93c8eb9665c9d039137d835
[ "MIT" ]
1
2016-04-11T12:45:54.000Z
2016-04-13T11:44:45.000Z
ntUPSd/CommandProcessor.cpp
6XGate/ntUPSd
7a3d7301a78db632c93c8eb9665c9d039137d835
[ "MIT" ]
8
2017-11-03T00:57:13.000Z
2021-11-10T14:20:23.000Z
/* Copyright 2016 Matthew Holder Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stdafx.h" #include "CommandProcessor.h" namespace { class CSimpleResult : public CReplResult { public: explicit CSimpleResult(LPCSTR pszStaticResult) : m_pszStaticResult(pszStaticResult) { } STDMETHOD(RenderResult)(CStringA &strResult) noexcept { _ATLTRY { strResult = m_pszStaticResult; return S_OK; } _ATLCATCH(ex) { return ex.m_hr; } _ATLCATCHALL() { return E_FAIL; } } private: LPCSTR m_pszStaticResult; }; } HRESULT CCommandProcessor::Initialize() noexcept { _ATLTRY { if (!m_pszLastError.Allocate(LAST_ERROR_BUFFER_LENGTH)) { return E_OUTOFMEMORY; } m_pBatteries = _ATL_NEW CBatteryCollection; if (m_pBatteries == nullptr) { return E_OUTOFMEMORY; } HRESULT hr = m_pBatteries->LoadBatteries(); if (FAILED(hr)) { return hr; } m_rgErrors.SetAt(S_OK, "OK"); m_rgPrimeHandlers.SetAt("STARTTLS", &CCommandProcessor::OnStartTls); m_rgPrimeHandlers.SetAt("USERNAME", &CCommandProcessor::OnUserName); m_rgPrimeHandlers.SetAt("PASSWORD", &CCommandProcessor::OnPassWord); m_rgPrimeHandlers.SetAt("GET", &CCommandProcessor::OnGet); m_rgPrimeHandlers.SetAt("LIST", &CCommandProcessor::OnList); m_rgPrimeHandlers.SetAt("LOGIN", &CCommandProcessor::OnLogin); m_rgPrimeHandlers.SetAt("LOGOUT", &CCommandProcessor::OnLogout); m_rgGetHandlers.SetAt("VAR", &CCommandProcessor::OnGetVar); m_rgListHandlers.SetAt("UPS", &CCommandProcessor::OnListUps); return S_OK; } _ATLCATCH(ex) { return ex.m_hr; } _ATLCATCHALL() { return E_FAIL; } } HRESULT CCommandProcessor::Eval(_In_z_ LPCSTR pszCommandLine, CComPtr<IReplResult> &rpResult) noexcept { CStringA strCommandLine = pszCommandLine; LPSTR pszParameters = strCommandLine.GetBuffer(); LPCSTR pszCommand = GetPart(pszParameters); HRESULT hr = S_FALSE; if (pszCommand != nullptr) { auto pos = m_rgPrimeHandlers.Lookup(pszCommand); if (pos != nullptr) { auto pfnHandler = m_rgPrimeHandlers.GetValueAt(pos); hr = (this->*pfnHandler)(pszParameters, rpResult); } else { hr = NUT_E_UNKNOWNCMD; } } else { hr = S_OK; } strCommandLine.ReleaseBuffer(); return hr; } LPCSTR CCommandProcessor::ReportError(HRESULT hr, LPCSTR) noexcept { if (!(hr & 0x20000000) || HRESULT_FACILITY(hr) != FACILITY_NUT) { hr = NUT_E_UNREPORTABLE; } if (!::FormatMessageA( FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, hr, 0x0000, m_pszLastError, LAST_ERROR_BUFFER_LENGTH, nullptr)) { StringCchCopyA(m_pszLastError, LAST_ERROR_BUFFER_LENGTH, "UNKNOWN-ERROR"); } return m_pszLastError; } HRESULT CCommandProcessor::DefaultResult(CStringA &strResult) noexcept { _ATLTRY { strResult = "OK"; return S_OK; } _ATLCATCH(ex) { return ex.m_hr; } _ATLCATCHALL() { return E_FAIL; } } LPCSTR CCommandProcessor::GetPart(_Inout_z_ LPSTR &pszLine) noexcept { // A character position alias for pszLine. LPCH &pchPos = pszLine; // This all assumes the lines have been trimmed. if (*pchPos == 0) { return nullptr; } LPCSTR pszResult = nullptr; if (*pchPos == '"') { pszResult = ++pchPos; LPCH pchTo = pchPos; // Quoted part. bool fContinue = true; while (fContinue && *pchPos != '"' && *pchPos != 0) { if (*pchPos == '\\') { // Possible escaped character ++pchPos; switch (*pchPos) { case 0: // Unexpected end-of-line, just leave the back-slash. --pchPos; fContinue = false; break; case '"': case '\\': break; default: // Push the position back, the next character cannot be escaped. --pchPos; break; } } *pchTo++ = *pchPos++; } // Zero out everything between pchTo and pchPos. while (pchTo != pchPos) { *pchTo++ = 0; } // Remove the ending quote. if (*pchPos == '"') { *pchPos++ = 0; } } else { // Find the first non-white-space character. The part start at the beginning. pszResult = pchPos; while (*pchPos != 0) { if (isspace(*pchPos)) { *pchPos++ = 0; break; } ++pchPos; } } // Move past any other white-space characters. while (*pchPos != 0) { if (!isspace(*pchPos)) { break; } ++pchPos; } return pszResult; } HRESULT CCommandProcessor::OnStartTls(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept { UNREFERENCED_PARAMETER(pszParameters); UNREFERENCED_PARAMETER(rpResult); // TLS is currently not supported. return NUT_E_NOTSUPPORTED; } HRESULT CCommandProcessor::OnUserName(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept { UNREFERENCED_PARAMETER(rpResult); _ATLTRY { LPCSTR pszUserName = GetPart(pszParameters); if (pszUserName == nullptr || strlen(pszUserName) == 0) { return NUT_E_INVALIDARG; } if (!m_strUserName.IsEmpty()) { return NUT_E_USERNAME_SET; } m_strUserName = pszUserName; return S_OK; } _ATLCATCH(ex) { return ex.m_hr; } _ATLCATCHALL() { return E_FAIL; } } HRESULT CCommandProcessor::OnPassWord(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept { UNREFERENCED_PARAMETER(rpResult); _ATLTRY { LPCSTR pszPassWord = GetPart(pszParameters); if (pszPassWord == nullptr || strlen(pszPassWord) == 0) { return NUT_E_INVALIDARG; } if (!m_strPassWord.IsEmpty()) { return NUT_E_PASSWORD_SET; } m_strPassWord = pszPassWord; return S_OK; } _ATLCATCH(ex) { return ex.m_hr; } _ATLCATCHALL() { return E_FAIL; } } HRESULT CCommandProcessor::OnGet(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept { HRESULT hr = S_OK; LPCSTR pszCommand = GetPart(pszParameters); if (pszCommand != nullptr) { auto pos = m_rgGetHandlers.Lookup(pszCommand); if (pos != nullptr) { auto pfnHandler = m_rgGetHandlers.GetValueAt(pos); hr = (this->*pfnHandler)(pszParameters, rpResult); } else { hr = NUT_E_INVALIDARG; } } else { hr = NUT_E_INVALIDARG; } return hr; } HRESULT CCommandProcessor::OnList(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept { HRESULT hr = S_OK; LPCSTR pszCommand = GetPart(pszParameters); if (pszCommand != nullptr) { auto pos = m_rgListHandlers.Lookup(pszCommand); if (pos != nullptr) { auto pfnHandler = m_rgListHandlers.GetValueAt(pos); hr = (this->*pfnHandler)(pszParameters, rpResult); } else { hr = NUT_E_INVALIDARG; } } else { hr = NUT_E_INVALIDARG; } return hr; } HRESULT CCommandProcessor::OnLogin(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept { UNREFERENCED_PARAMETER(pszParameters); UNREFERENCED_PARAMETER(rpResult); return S_OK; } HRESULT CCommandProcessor::OnLogout(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept { UNREFERENCED_PARAMETER(pszParameters); rpResult = _ATL_NEW CSimpleResult("OK Goodbye"); if (rpResult == nullptr) { return E_OUTOFMEMORY; } return S_OK; } HRESULT CCommandProcessor::OnGetVar(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept { HRESULT hr = S_OK; LPCSTR pszUps = GetPart(pszParameters); if (pszUps != nullptr) { LPCSTR pszName = GetPart(pszParameters); if (pszName != nullptr) { POSITION pos = m_pBatteries->FindBattery(pszUps); if (pos != NULL) { auto &battery = m_pBatteries->GetAt(pos); hr = battery.GetVariable(pszName, rpResult); } else { hr = NUT_E_UNKNOWN_UPS; } } else { hr = NUT_E_INVALIDARG; } } else { hr = NUT_E_INVALIDARG; } return hr; } HRESULT CCommandProcessor::OnListUps(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept { UNREFERENCED_PARAMETER(pszParameters); rpResult = m_pBatteries; return S_OK; }
20.468531
106
0.705045
6XGate
58f07777fde724228ad81e8451d775f50a07359f
484
cc
C++
src/test/ndpc/test_fact.cc
abu-bakar-nu/nautilus
9c5046d714e2ff2a00f757ba42dc887024365be6
[ "MIT" ]
28
2018-10-12T17:44:54.000Z
2022-01-27T19:30:56.000Z
src/test/ndpc/test_fact.cc
abu-bakar-nu/nautilus
9c5046d714e2ff2a00f757ba42dc887024365be6
[ "MIT" ]
31
2018-12-08T19:39:32.000Z
2021-01-19T18:37:57.000Z
src/test/ndpc/test_fact.cc
abu-bakar-nu/nautilus
9c5046d714e2ff2a00f757ba42dc887024365be6
[ "MIT" ]
26
2018-08-04T03:58:13.000Z
2022-03-02T18:53:09.000Z
#define NDPC_NAUTILUS_KERNEL #include "ndpc_glue.h" #include "fact.hh" // //using namespace std; NDPC_TEST(fact) { int input=5; int output; NDPC_PRINTF("Testing factorial example\n"); ndpc_init_preempt_threads(); if (fact(output,input)) { NDPC_PRINTF("function call failed\n"); } else { NDPC_PRINTF("fact(%d) = %d\n",input,output); } ndpc_deinit_preempt_threads(); NDPC_PRINTF("Done testing factorial example\n"); return 0; }
15.125
52
0.654959
abu-bakar-nu
58f24871922634cdd3c0013179c13807f95ee6ee
648
hpp
C++
src/agl/opengl/function/texture/parameter.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/opengl/function/texture/parameter.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/opengl/function/texture/parameter.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
#pragma once #include "agl/opengl/enum/texture_parameter.hpp" #include "agl/opengl/name/all.hpp" namespace agl { inline void parameter(Texture t, TextureParameter tp, GLfloat param) { glTextureParameterf( t, static_cast<GLenum>(tp), param); } inline void parameter(Texture t, TextureParameter tp, GLint param) { glTextureParameteri( t, static_cast<GLenum>(tp), param); } inline void mag_filter(Texture t, GLint param) { parameter(t, TextureParameter::mag_filter, param); } inline void min_filter(Texture t, GLint param) { parameter(t, TextureParameter::min_filter, param); } }
18.514286
63
0.688272
the-last-willy
58f34c122d02d04fb94eb84d5d64a621e9add997
974
cpp
C++
Week16/1235.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
101
2021-02-26T14:32:37.000Z
2022-03-16T18:46:37.000Z
Week16/1235.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
null
null
null
Week16/1235.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
30
2021-03-09T05:16:48.000Z
2022-03-16T21:16:33.000Z
bool sortFunc(const vector<int>& p1, const vector<int>& p2) { return p1[0] < p2[0]; } class Solution { public: int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) { vector<vector<int>> contain; int max_end=0; for(int i=0; i<startTime.size(); i++){ contain.push_back({endTime[i], startTime[i], profit[i]}); max_end=max(max_end, endTime[i]); } sort(contain.begin(), contain.end(), sortFunc); int last=0; vector<int> dp(max_end+1, 0); for(int i=0; i<contain.size(); i++){ for(int j=last+1; j<=contain[i][0]; j++){ dp[j]=max(dp[j-1], dp[j]); } dp[contain[i][0]]=max(dp[contain[i][1]]+contain[i][2], dp[contain[i][0]]); last=contain[i][0]; } int maxx=0; for(int i=0; i<=max_end; i++){ maxx=max(maxx, dp[i]); } return maxx; } };
32.466667
90
0.501027
bobsingh149
58f507e211a425fdce51de03e2388d46b27b8c6a
26,140
cpp
C++
Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPropertyRelationRuleBase.h" #include <mitkDataNode.h> #include <mitkExceptionMacro.h> #include <mitkNodePredicateBase.h> #include <mitkStringProperty.h> #include <mitkUIDGenerator.h> #include <mutex> #include <regex> #include <algorithm> bool mitk::PropertyRelationRuleBase::IsAbstract() const { return true; } bool mitk::PropertyRelationRuleBase::IsSourceCandidate(const IPropertyProvider *owner) const { return owner != nullptr; } bool mitk::PropertyRelationRuleBase::IsDestinationCandidate(const IPropertyProvider *owner) const { return owner != nullptr; } mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRootKeyPath() { return PropertyKeyPath().AddElement("MITK").AddElement("Relations"); } bool mitk::PropertyRelationRuleBase::IsSupportedRuleID(const RuleIDType& ruleID) const { return ruleID == this->GetRuleID(); } mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIPropertyKeyPath(const std::string propName, const InstanceIDType& instanceID) { auto path = GetRootKeyPath(); if (instanceID.empty()) { path.AddAnyElement(); } else { path.AddElement(instanceID); } if (!propName.empty()) { path.AddElement(propName); } return path; } std::string mitk::PropertyRelationRuleBase::GetRIIPropertyRegEx(const std::string propName, const InstanceIDType &instanceID) const { return PropertyKeyPathToPropertyRegEx(GetRIIPropertyKeyPath(propName, instanceID)); } mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIRelationUIDPropertyKeyPath(const InstanceIDType& instanceID) { return GetRIIPropertyKeyPath("relationUID", instanceID); } mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIRuleIDPropertyKeyPath(const InstanceIDType& instanceID) { return GetRIIPropertyKeyPath("ruleID", instanceID); } mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIDestinationUIDPropertyKeyPath(const InstanceIDType& instanceID) { return GetRIIPropertyKeyPath("destinationUID", instanceID); } //workaround until T24729 is done. Please remove if T24728 is done //then could directly use owner->GetPropertyKeys() again. std::vector<std::string> mitk::PropertyRelationRuleBase::GetPropertyKeys(const mitk::IPropertyProvider *owner) { std::vector<std::string> keys; auto sourceCasted = dynamic_cast<const mitk::DataNode*>(owner); if (sourceCasted) { auto sourceData = sourceCasted->GetData(); if (sourceData) { keys = sourceData->GetPropertyKeys(); } else { keys = sourceCasted->GetPropertyKeys(); } } else { keys = owner->GetPropertyKeys(); } return keys; } //end workaround for T24729 bool mitk::PropertyRelationRuleBase::IsSource(const IPropertyProvider *owner) const { return !this->GetExistingRelations(owner).empty(); } bool mitk::PropertyRelationRuleBase::HasRelation( const IPropertyProvider* source, const IPropertyProvider* destination, RelationType requiredRelation) const { auto relTypes = this->GetRelationTypes(source, destination); if (requiredRelation == RelationType::None) { return !relTypes.empty(); } RelationVectorType allowedTypes = { RelationType::Complete }; if (requiredRelation == RelationType::Data) { allowedTypes.emplace_back(RelationType::Data); } else if (requiredRelation == RelationType::ID) { allowedTypes.emplace_back(RelationType::ID); } return relTypes.end() != std::find_first_of(relTypes.begin(), relTypes.end(), allowedTypes.begin(), allowedTypes.end()); } mitk::PropertyRelationRuleBase::RelationVectorType mitk::PropertyRelationRuleBase::GetRelationTypes( const IPropertyProvider* source, const IPropertyProvider* destination) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } if (!destination) { mitkThrow() << "Error. Passed owner pointer is NULL"; } auto instanceIDs_IDLayer = this->GetInstanceID_IDLayer(source, destination); auto relIDs_dataLayer = this->GetRelationUIDs_DataLayer(source, destination, {}); if (relIDs_dataLayer.size() > 1) { MITK_WARN << "Property relation on data level is ambiguous. First relation is used. Relation UID: " << relIDs_dataLayer.front().first; } bool hasComplete = instanceIDs_IDLayer.end() != std::find_if(instanceIDs_IDLayer.begin(), instanceIDs_IDLayer.end(), [&](const InstanceIDVectorType::value_type& instanceID) { auto relID_IDlayer = this->GetRelationUIDByInstanceID(source, instanceID); auto ruleID_IDlayer = this->GetRuleIDByInstanceID(source, instanceID); return relIDs_dataLayer.end() != std::find_if(relIDs_dataLayer.begin(), relIDs_dataLayer.end(), [&](const DataRelationUIDVectorType::value_type& relID) { return relID.first == relID_IDlayer && relID.second == ruleID_IDlayer; }); }); bool hasID = instanceIDs_IDLayer.end() != std::find_if(instanceIDs_IDLayer.begin(), instanceIDs_IDLayer.end(), [&](const InstanceIDVectorType::value_type& instanceID) { auto relID_IDlayer = this->GetRelationUIDByInstanceID(source, instanceID); auto ruleID_IDlayer = this->GetRuleIDByInstanceID(source, instanceID); return relIDs_dataLayer.end() == std::find_if(relIDs_dataLayer.begin(), relIDs_dataLayer.end(), [&](const DataRelationUIDVectorType::value_type& relID) { return relID.first == relID_IDlayer && relID.second == ruleID_IDlayer; }); }); bool hasData = relIDs_dataLayer.end() != std::find_if(relIDs_dataLayer.begin(), relIDs_dataLayer.end(), [&](const DataRelationUIDVectorType::value_type& relID) { return instanceIDs_IDLayer.end() == std::find_if(instanceIDs_IDLayer.begin(), instanceIDs_IDLayer.end(), [&](const InstanceIDVectorType::value_type& instanceID) { auto relID_IDlayer = this->GetRelationUIDByInstanceID(source, instanceID); auto ruleID_IDlayer = this->GetRuleIDByInstanceID(source, instanceID); return relID.first == relID_IDlayer && relID.second == ruleID_IDlayer; }); }); RelationVectorType result; if (hasData) { result.emplace_back(RelationType::Data); } if (hasID) { result.emplace_back(RelationType::ID); } if (hasComplete) { result.emplace_back(RelationType::Complete); } return result; } mitk::PropertyRelationRuleBase::RelationUIDVectorType mitk::PropertyRelationRuleBase::GetExistingRelations( const IPropertyProvider *source, RelationType layer) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } RelationUIDVectorType relationUIDs; InstanceIDVectorType instanceIDs; if (layer != RelationType::Data) { auto ruleIDRegExStr = this->GetRIIPropertyRegEx("ruleID"); auto regEx = std::regex(ruleIDRegExStr); //workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed. const auto keys = GetPropertyKeys(source); //end workaround for T24729 for (const auto& key : keys) { if (std::regex_match(key, regEx)) { auto idProp = source->GetConstProperty(key); auto ruleID = idProp->GetValueAsString(); if (this->IsSupportedRuleID(ruleID)) { auto instanceID = this->GetInstanceIDByPropertyName(key); instanceIDs.emplace_back(instanceID); relationUIDs.push_back(this->GetRelationUIDByInstanceID(source, instanceID)); } } } } if (layer == RelationType::ID) { return relationUIDs; } DataRelationUIDVectorType relationUIDandRuleID_Data; if (layer != RelationType::ID) { relationUIDandRuleID_Data = this->GetRelationUIDs_DataLayer(source, nullptr, instanceIDs); } RelationUIDVectorType relationUIDs_Data; std::transform(relationUIDandRuleID_Data.begin(), relationUIDandRuleID_Data.end(), std::back_inserter(relationUIDs_Data), [](const DataRelationUIDVectorType::value_type& v) { return v.first; }); if (layer == RelationType::Data) { return relationUIDs_Data; } std::sort(relationUIDs.begin(), relationUIDs.end()); std::sort(relationUIDs_Data.begin(), relationUIDs_Data.end()); RelationUIDVectorType result; if (layer == RelationType::Complete) { std::set_intersection(relationUIDs.begin(), relationUIDs.end(), relationUIDs_Data.begin(), relationUIDs_Data.end(), std::back_inserter(result)); } else { std::set_union(relationUIDs.begin(), relationUIDs.end(), relationUIDs_Data.begin(), relationUIDs_Data.end(), std::back_inserter(result)); } return result; } mitk::PropertyRelationRuleBase::RelationUIDVectorType mitk::PropertyRelationRuleBase::GetRelationUIDs( const IPropertyProvider *source, const IPropertyProvider *destination) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } if (!destination) { mitkThrow() << "Error. Passed destination pointer is NULL"; } RelationUIDVectorType relUIDs_id; auto instanceIDs = this->GetInstanceID_IDLayer(source, destination); for (const auto& instanceID : instanceIDs) { relUIDs_id.push_back(this->GetRelationUIDByInstanceID(source, instanceID)); } DataRelationUIDVectorType relationUIDandRuleID_Data = this->GetRelationUIDs_DataLayer(source,destination,instanceIDs); RelationUIDVectorType relUIDs_Data; std::transform(relationUIDandRuleID_Data.begin(), relationUIDandRuleID_Data.end(), std::back_inserter(relUIDs_Data), [](const DataRelationUIDVectorType::value_type& v) { return v.first; }); std::sort(relUIDs_id.begin(), relUIDs_id.end()); std::sort(relUIDs_Data.begin(), relUIDs_Data.end()); RelationUIDVectorType result; std::set_union(relUIDs_id.begin(), relUIDs_id.end(), relUIDs_Data.begin(), relUIDs_Data.end(), std::back_inserter(result)); return result; } mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::GetRelationUID(const IPropertyProvider *source, const IPropertyProvider *destination) const { auto result = this->GetRelationUIDs(source, destination); if (result.empty()) { mitkThrowException(NoPropertyRelationException); } else if(result.size()>1) { mitkThrow() << "Cannot return one(!) relation UID. Multiple relations exists for given rule, source and destination."; } return result[0]; } mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::NULL_INSTANCE_ID() { return std::string(); }; mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::GetRelationUIDByInstanceID( const IPropertyProvider *source, const InstanceIDType &instanceID) const { RelationUIDType result; if (instanceID != NULL_INSTANCE_ID()) { auto idProp = source->GetConstProperty( PropertyKeyPathToPropertyName(GetRIIRelationUIDPropertyKeyPath(instanceID))); if (idProp.IsNotNull()) { result = idProp->GetValueAsString(); } } if (result.empty()) { mitkThrowException(NoPropertyRelationException); } return result; } mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::GetInstanceIDByRelationUID( const IPropertyProvider *source, const RelationUIDType &relationUID) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } InstanceIDType result = NULL_INSTANCE_ID(); auto destRegExStr = PropertyKeyPathToPropertyRegEx(GetRIIRelationUIDPropertyKeyPath()); auto regEx = std::regex(destRegExStr); std::smatch instance_matches; //workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed. const auto keys = GetPropertyKeys(source); //end workaround for T24729 for (const auto &key : keys) { if (std::regex_search(key, instance_matches, regEx)) { auto idProp = source->GetConstProperty(key); if (idProp->GetValueAsString() == relationUID) { if (instance_matches.size()>1) { result = instance_matches[1]; break; } } } } return result; } mitk::PropertyRelationRuleBase::InstanceIDVectorType mitk::PropertyRelationRuleBase::GetInstanceID_IDLayer( const IPropertyProvider *source, const IPropertyProvider *destination) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } if (!destination) { mitkThrow() << "Error. Passed destination pointer is NULL"; } auto identifiable = CastProviderAsIdentifiable(destination); InstanceIDVectorType result; if (identifiable) { // check for relations of type Connected_ID; auto destRegExStr = this->GetRIIPropertyRegEx("destinationUID"); auto regEx = std::regex(destRegExStr); std::smatch instance_matches; auto destUID = identifiable->GetUID(); //workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed. const auto keys = GetPropertyKeys(source); //end workaround for T24729 for (const auto &key : keys) { if (std::regex_search(key, instance_matches, regEx)) { auto idProp = source->GetConstProperty(key); if (idProp->GetValueAsString() == destUID) { if (instance_matches.size()>1) { auto instanceID = instance_matches[1]; if (this->IsSupportedRuleID(GetRuleIDByInstanceID(source, instanceID))) { result.push_back(instanceID); } } } } } } return result; } const mitk::Identifiable* mitk::PropertyRelationRuleBase::CastProviderAsIdentifiable(const mitk::IPropertyProvider* destination) const { auto identifiable = dynamic_cast<const Identifiable*>(destination); if (!identifiable) { //This check and pass through to data is needed due to solve T25711. See Task for more information. //This could be removed at the point we can get rid of DataNodes or they get realy transparent. auto node = dynamic_cast<const DataNode*>(destination); if (node && node->GetData()) { identifiable = dynamic_cast<const Identifiable*>(node->GetData()); } } return identifiable; } mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::Connect(IPropertyOwner *source, const IPropertyProvider *destination) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } if (!destination) { mitkThrow() << "Error. Passed destination pointer is NULL"; } if (this->IsAbstract()) { mitkThrow() << "Error. This is an abstract property relation rule. Abstract rule must not make a connection. Please use a concrete rule."; } auto instanceIDs = this->GetInstanceID_IDLayer(source, destination); bool hasIDlayer = !instanceIDs.empty(); auto relUIDs_data = this->GetRelationUIDs_DataLayer(source, destination, {}); if (relUIDs_data.size() > 1) { MITK_WARN << "Property relation on data level is ambiguous. First relation is used. RelationUID ID: " << relUIDs_data.front().first; } bool hasDatalayer = !relUIDs_data.empty(); RelationUIDType relationUID = this->CreateRelationUID(); InstanceIDType instanceID = NULL_INSTANCE_ID(); if (hasIDlayer) { instanceID = instanceIDs.front(); } else if (hasDatalayer) { try { instanceID = this->GetInstanceIDByRelationUID(source, relUIDs_data.front().first); } catch(...) { } } if(instanceID == NULL_INSTANCE_ID()) { instanceID = this->CreateNewRelationInstance(source, relationUID); } auto relUIDKey = PropertyKeyPathToPropertyName(GetRIIRelationUIDPropertyKeyPath(instanceID)); source->SetProperty(relUIDKey, mitk::StringProperty::New(relationUID)); auto ruleIDKey = PropertyKeyPathToPropertyName(GetRIIRuleIDPropertyKeyPath(instanceID)); source->SetProperty(ruleIDKey, mitk::StringProperty::New(this->GetRuleID())); if (!hasIDlayer) { auto identifiable = this->CastProviderAsIdentifiable(destination); if (identifiable) { auto destUIDKey = PropertyKeyPathToPropertyName(GetRIIDestinationUIDPropertyKeyPath(instanceID)); source->SetProperty(destUIDKey, mitk::StringProperty::New(identifiable->GetUID())); } } this->Connect_datalayer(source, destination, instanceID); return relationUID; } void mitk::PropertyRelationRuleBase::Disconnect(IPropertyOwner *source, const IPropertyProvider *destination, RelationType layer) const { if (source == nullptr) { mitkThrow() << "Error. Source is invalid. Cannot disconnect."; } if (destination == nullptr) { mitkThrow() << "Error. Destination is invalid. Cannot disconnect."; } try { const auto relationUIDs = this->GetRelationUIDs(source, destination); for (const auto& relUID: relationUIDs) { this->Disconnect(source, relUID, layer); } } catch (const NoPropertyRelationException &) { // nothing to do and no real error in context of disconnect. } } void mitk::PropertyRelationRuleBase::Disconnect(IPropertyOwner *source, RelationUIDType relationUID, RelationType layer) const { if (source == nullptr) { mitkThrow() << "Error. Source is invalid. Cannot disconnect."; } if (layer == RelationType::Data || layer == RelationType::Complete) { this->Disconnect_datalayer(source, relationUID); } auto instanceID = this->GetInstanceIDByRelationUID(source, relationUID); if ((layer == RelationType::ID || layer == RelationType::Complete) && instanceID != NULL_INSTANCE_ID()) { auto instancePrefix = PropertyKeyPathToPropertyName(GetRootKeyPath().AddElement(instanceID)); //workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed. const auto keys = GetPropertyKeys(source); //end workaround for T24729 for (const auto &key : keys) { if (key.find(instancePrefix) == 0) { source->RemoveProperty(key); } } } } mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::CreateRelationUID() { UIDGenerator generator; return generator.GetUID(); } /**This mutex is used to guard mitk::PropertyRelationRuleBase::CreateNewRelationInstance by a class wide mutex to avoid racing conditions in a scenario where rules are used concurrently. It is not in the class interface itself, because it is an implementation detail. */ std::mutex relationCreationLock; mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::CreateNewRelationInstance( IPropertyOwner *source, const RelationUIDType &relationUID) const { std::lock_guard<std::mutex> guard(relationCreationLock); ////////////////////////////////////// // Get all existing instanc IDs std::vector<int> instanceIDs; InstanceIDType newID = "1"; auto destRegExStr = PropertyKeyPathToPropertyRegEx(GetRIIRelationUIDPropertyKeyPath()); auto regEx = std::regex(destRegExStr); std::smatch instance_matches; //workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed. const auto keys = GetPropertyKeys(source); //end workaround for T24729 for (const auto &key : keys) { if (std::regex_search(key, instance_matches, regEx)) { if (instance_matches.size()>1) { instanceIDs.push_back(std::stoi(instance_matches[1])); } } } ////////////////////////////////////// // Get new ID std::sort(instanceIDs.begin(), instanceIDs.end()); if (!instanceIDs.empty()) { newID = std::to_string(instanceIDs.back() + 1); } ////////////////////////////////////// // reserve new ID auto relUIDKey = PropertyKeyPathToPropertyName(GetRIIRelationUIDPropertyKeyPath(newID)); source->SetProperty(relUIDKey, mitk::StringProperty::New(relationUID)); return newID; } itk::LightObject::Pointer mitk::PropertyRelationRuleBase::InternalClone() const { return Superclass::InternalClone(); } mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::GetInstanceIDByPropertyName(const std::string propName) { auto proppath = PropertyNameToPropertyKeyPath(propName); auto ref = GetRootKeyPath(); if (proppath.GetSize() < 3 || !(proppath.GetFirstNode() == ref.GetFirstNode()) || !(proppath.GetNode(1) == ref.GetNode(1))) { mitkThrow() << "Property name is not for a RII property or containes no instance ID. Wrong name: " << propName; } return proppath.GetNode(2).name; } mitk::PropertyRelationRuleBase::RuleIDType mitk::PropertyRelationRuleBase::GetRuleIDByInstanceID(const IPropertyProvider *source, const InstanceIDType &instanceID) const { if (!source) { mitkThrow() << "Error. Source is invalid. Cannot deduce rule ID"; } auto path = GetRIIRuleIDPropertyKeyPath(instanceID); auto name = PropertyKeyPathToPropertyName(path); const auto prop = source->GetConstProperty(name); std::string result; if (prop.IsNotNull()) { result = prop->GetValueAsString(); } if (result.empty()) { mitkThrowException(NoPropertyRelationException) << "Error. Source has no property relation with the passed instance ID. Instance ID: " << instanceID; } return result; } std::string mitk::PropertyRelationRuleBase::GetDestinationUIDByInstanceID(const IPropertyProvider* source, const InstanceIDType& instanceID) const { if (!source) { mitkThrow() << "Error. Source is invalid. Cannot deduce rule ID"; } auto path = GetRIIDestinationUIDPropertyKeyPath(instanceID); auto name = PropertyKeyPathToPropertyName(path); const auto prop = source->GetConstProperty(name); std::string result; if (prop.IsNotNull()) { result = prop->GetValueAsString(); } return result; } namespace mitk { /** * \brief Predicate used to wrap rule checks. * * \ingroup DataStorage */ class NodePredicateRuleFunction : public NodePredicateBase { public: using FunctionType = std::function<bool(const mitk::IPropertyProvider *, const mitk::PropertyRelationRuleBase *)>; mitkClassMacro(NodePredicateRuleFunction, NodePredicateBase) mitkNewMacro2Param(NodePredicateRuleFunction, const FunctionType &, PropertyRelationRuleBase::ConstPointer) ~NodePredicateRuleFunction() override = default; bool CheckNode(const mitk::DataNode *node) const override { if (!node) { return false; } return m_Function(node, m_Rule); }; protected: explicit NodePredicateRuleFunction(const FunctionType &function, PropertyRelationRuleBase::ConstPointer rule) : m_Function(function), m_Rule(rule) { }; FunctionType m_Function; PropertyRelationRuleBase::ConstPointer m_Rule; }; } // namespace mitk mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetSourceCandidateIndicator() const { auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) { return rule->IsSourceCandidate(node); }; return NodePredicateRuleFunction::New(check, this).GetPointer(); } mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationCandidateIndicator() const { auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) { return rule->IsDestinationCandidate(node); }; return NodePredicateRuleFunction::New(check, this).GetPointer(); } mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetConnectedSourcesDetector() const { auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) { return rule->IsSource(node); }; return NodePredicateRuleFunction::New(check, this).GetPointer(); } mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetSourcesDetector( const IPropertyProvider *destination, RelationType exclusiveRelation) const { if (!destination) { mitkThrow() << "Error. Passed destination pointer is NULL"; } auto check = [destination, exclusiveRelation](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) { return rule->HasRelation(node, destination, exclusiveRelation); }; return NodePredicateRuleFunction::New(check, this).GetPointer(); } mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationsDetector( const IPropertyProvider *source, RelationType exclusiveRelation) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } auto check = [source, exclusiveRelation](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) { return rule->HasRelation(source, node, exclusiveRelation); }; return NodePredicateRuleFunction::New(check, this).GetPointer(); } mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationDetector( const IPropertyProvider *source, RelationUIDType relationUID) const { if (!source) { mitkThrow() << "Error. Passed source pointer is NULL"; } auto relUIDs = this->GetExistingRelations(source); if (std::find(relUIDs.begin(), relUIDs.end(), relationUID) == relUIDs.end()) { mitkThrow() << "Error. Passed relationUID does not identify a relation instance of the passed source for this rule instance."; }; auto check = [source, relationUID](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) { try { auto relevantUIDs = rule->GetRelationUIDs(source, node); for (const auto& aUID : relevantUIDs) { if (aUID == relationUID) { return true; } } } catch(const NoPropertyRelationException &) { return false; } return false; }; return NodePredicateRuleFunction::New(check, this).GetPointer(); }
29.977064
174
0.714575
zhaomengxiao
58f61a8cce9d5594b07bcc61457d49ed308d10a8
1,182
hpp
C++
cpp/src/datacentric/dc/types/record/root_key.hpp
datacentricorg/datacentric
b9e2dedfac35759ea09bb5653095daba5861512e
[ "Apache-2.0" ]
1
2019-08-08T01:27:47.000Z
2019-08-08T01:27:47.000Z
cpp/src/datacentric/dc/types/record/root_key.hpp
datacentricorg/datacentric
b9e2dedfac35759ea09bb5653095daba5861512e
[ "Apache-2.0" ]
null
null
null
cpp/src/datacentric/dc/types/record/root_key.hpp
datacentricorg/datacentric
b9e2dedfac35759ea09bb5653095daba5861512e
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2013-present The DataCentric Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <dc/declare.hpp> #include <dc/types/record/key.hpp> namespace dc { template <typename TKey, typename TRecord> class root_key_impl; template <typename TKey, typename TRecord> using root_key = dot::ptr<root_key_impl<TKey, TRecord>>; template <typename TKey, typename TRecord> class key_impl; template <typename TKey, typename TRecord> using key = dot::ptr<key_impl<TKey, TRecord>>; /// Root record is recorded without a dataset. template <typename TKey, typename TRecord> class root_key_impl : public virtual key_impl<TKey, TRecord> { }; }
33.771429
103
0.753807
datacentricorg
58f8610cdf0420bd3597b10a1403e8b2ad46cf17
7,256
cpp
C++
src/stores/GOG/gog_library.cpp
ColonelGerdauf/SKIF
ae0b300c0ededbc5437bd26c37be4f0b8fb8cfaa
[ "MIT" ]
null
null
null
src/stores/GOG/gog_library.cpp
ColonelGerdauf/SKIF
ae0b300c0ededbc5437bd26c37be4f0b8fb8cfaa
[ "MIT" ]
null
null
null
src/stores/GOG/gog_library.cpp
ColonelGerdauf/SKIF
ae0b300c0ededbc5437bd26c37be4f0b8fb8cfaa
[ "MIT" ]
null
null
null
#include <stores/gog/gog_library.h> #include <wtypes.h> #include <filesystem> /* GOG Galaxy / Offline Installers shared registry struture Root Key: HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\GOG.com\Games\ Each game is stored in a separate key beneath, named after the Game ID/Product ID of the game. Each key have a bunch of values with some basic data of the game, its location, and launch options. Registry values and the data they contain: exe -- Full path to game executable exeFile -- Filename of game executable gameID -- App ID of the game gameName -- Title of the game launchCommand -- Default launch full path and parameter of the game launchParam -- Default launch parameter of the game path -- Path to the game folder productID -- Same as App ID of the game ? uninstallCommand -- Full path to the uninstaller of the game workingDir -- Working directory of the game There are more values, but they aren't listed here. GOG Galaxy Custom Default Launch Option: To launch a game using the Galaxy user's customized launch option, it's enough to launch the game through Galaxy like the start menu shortcuts does, like this: "D:\Games\GOG Galaxy\GalaxyClient.exe" /command=runGame /gameId=1895572517 /path="D:\Games\GOG Games\AI War 2" */ void SKIF_GOG_GetInstalledAppIDs (std::vector <std::pair < std::string, app_record_s > > *apps) { HKEY hKey; DWORD dwIndex = 0, dwResult, dwSize; WCHAR szSubKey[MAX_PATH]; WCHAR szData[MAX_PATH]; /* Load GOG titles from registry */ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, LR"(SOFTWARE\GOG.com\Games\)", 0, KEY_READ | KEY_WOW64_32KEY, &hKey) == ERROR_SUCCESS) { if (RegQueryInfoKeyW(hKey, NULL, NULL, NULL, &dwResult, NULL, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { do { dwSize = sizeof(szSubKey) / sizeof(WCHAR); dwResult = RegEnumKeyExW(hKey, dwIndex, szSubKey, &dwSize, NULL, NULL, NULL, NULL); if (dwResult == ERROR_NO_MORE_ITEMS) break; if (dwResult == ERROR_SUCCESS) { dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"dependsOn", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS && wcslen(szData) == 0) // Only handles items without a dependency (skips DLCs) { dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"GameID", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) { int appid = _wtoi(szData); app_record_s record(appid); record.store = "GOG"; record.type = "Game"; //GOG_record.extended_config.vac.enabled = false; record._status.installed = true; dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"GameName", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) record.names.normal = SK_WideCharToUTF8(szData); // Strip null terminators // moved to later -- performed for all installed games as part of manage_games.cpp //GOG_record.names.normal.erase(std::find(GOG_record.names.normal.begin(), GOG_record.names.normal.end(), '\0'), GOG_record.names.normal.end()); // Add (GOG) at the end of the name //GOG_record.names.normal = GOG_record.names.normal + " (GOG)"; record.names.all_upper = record.names.normal; std::for_each(record.names.all_upper.begin(), record.names.all_upper.end(), ::toupper); dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"path", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) record.install_dir = szData; dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"exeFile", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) { app_record_s::launch_config_s lc; lc.id = 0; lc.store = L"GOG"; lc.executable = szData; // lc.working_dir = record.install_dir; dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"exe", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) lc.executable_path = szData; dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"workingDir", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) lc.working_dir = szData; dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"launchParam", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) lc.launch_options = szData; record.launch_configs[0] = lc; /* dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, szSubKey, L"exeFile", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) record.specialk.profile_dir = szData; */ record.specialk.profile_dir = lc.executable; record.specialk.injection.injection.type = sk_install_state_s::Injection::Type::Global; std::pair <std::string, app_record_s> GOG(record.names.normal, record); apps->emplace_back(GOG); } } } } dwIndex++; } while (1); } RegCloseKey(hKey); // If an item was read, see if we can detect GOG Galaxy as well if (dwIndex > 0) { if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, LR"(SOFTWARE\GOG.com\GalaxyClient\)", 0, KEY_READ | KEY_WOW64_32KEY, &hKey) == ERROR_SUCCESS) { dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, NULL, L"clientExecutable", RRF_RT_REG_SZ, NULL, szData, &dwSize) == ERROR_SUCCESS) { extern std::wstring GOGGalaxy_Path; extern std::wstring GOGGalaxy_Folder; extern bool GOGGalaxy_Installed; GOGGalaxy_Folder = szData; dwSize = sizeof(szData) / sizeof(WCHAR); if (RegGetValueW(hKey, L"paths", L"client", RRF_RT_REG_SZ, NULL, szData, &dwSize) == ERROR_SUCCESS) { GOGGalaxy_Path = SK_FormatStringW(LR"(%ws\%ws)", szData, GOGGalaxy_Folder.c_str()); if (PathFileExistsW(GOGGalaxy_Path.c_str())) GOGGalaxy_Installed = true; } } RegCloseKey(hKey); // Galaxy User ID extern std::wstring GOGGalaxy_UserID; dwSize = sizeof(szData) / sizeof(WCHAR); if (RegOpenKeyExW(HKEY_CURRENT_USER, LR"(SOFTWARE\GOG.com\Galaxy\settings\)", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { if (RegGetValueW(hKey, NULL, L"userId", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS) GOGGalaxy_UserID = szData; RegCloseKey(hKey); } } } } }
38.595745
158
0.598953
ColonelGerdauf
58f8e7b49afbd778b849e3052f126235103b460c
816
cpp
C++
luogu/CF977F.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
1
2020-07-24T03:07:08.000Z
2020-07-24T03:07:08.000Z
luogu/CF977F.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
luogu/CF977F.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
// // Created by yangtao on 20-11-8. // // // Created by yangtao on 2020/11/1. // #include<iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <map> using namespace std; const int N = 2e5 + 5; int n, ans , v; int a[N]; map<int, int> mm; int main() { cin >> n; for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); mm[a[i]] = max(mm[a[i]], mm[a[i]-1] + 1); if( mm[a[i]] > ans ) ans = mm[a[i]], v = a[i]; } //// map<int,int>::iterator it = mm.begin(); // auto it = mm.begin(); // for(; it != mm.end(); it++) { // cout << it->first << " " << it->second<< endl; // } cout << ans << endl; for(int i = 1; i <= n; i++) { if( a[i] == v - ans + 1) { cout << i << " "; ans--; } } return 0; }
20.4
56
0.436275
delphi122
58fef46ff52b59a4abbdafc630afa4314be7880a
1,111
cpp
C++
lib/save_obj.cpp
CraGL/SubdivisionSkinning
c593a7a4e38a49716e9d3981824871a7b6c29324
[ "Apache-2.0" ]
19
2017-03-29T00:14:00.000Z
2021-11-27T15:44:44.000Z
lib/save_obj.cpp
Myzhencai/SubdivisionSkinning
c593a7a4e38a49716e9d3981824871a7b6c29324
[ "Apache-2.0" ]
1
2019-05-08T21:48:11.000Z
2019-05-08T21:48:11.000Z
lib/save_obj.cpp
Myzhencai/SubdivisionSkinning
c593a7a4e38a49716e9d3981824871a7b6c29324
[ "Apache-2.0" ]
5
2017-04-23T17:52:44.000Z
2020-06-28T18:00:26.000Z
#include "save_obj.h" #include <iostream> #include <fstream> namespace save_obj { void save_mesh( const std::string& out_path, const std::vector< std::vector< int > >& faces, const std::vector< std::vector< real_t > >& vertices, const std::string& header_message ) { std::ofstream out( out_path ); save_mesh( out, faces, vertices, header_message ); std::cout << "Saved a mesh to: " << out_path << '\n'; } void save_mesh( std::ostream& out, const std::vector< std::vector< int > >& faces, const std::vector< std::vector< real_t > >& vertices, const std::string& header_message ) { // Save an optional header message. out << header_message; // Save vertices. for( const auto& vert: vertices ) { out << "v"; for( const auto& coord: vert ) { out << ' ' << coord; } out << '\n'; } out << '\n'; for( const auto& f: faces ) { out << 'f'; for( const auto& vi : f ) { // Vertices are 1-indexed. out << ' ' << (vi+1); } out << '\n'; } } }
25.25
182
0.531953
CraGL
4500146138fdc658e2e90b3d655f9689fe73331b
11,131
cpp
C++
src/tpcc/DBtxnNewOrder.cpp
bailuding/centiman
213eab0bd391822cbc9a01644979f8409440c376
[ "Apache-2.0" ]
4
2016-07-14T18:11:39.000Z
2021-04-14T01:27:38.000Z
src/tpcc/DBtxnNewOrder.cpp
bailuding/centiman
213eab0bd391822cbc9a01644979f8409440c376
[ "Apache-2.0" ]
null
null
null
src/tpcc/DBtxnNewOrder.cpp
bailuding/centiman
213eab0bd391822cbc9a01644979f8409440c376
[ "Apache-2.0" ]
1
2015-11-23T17:23:43.000Z
2015-11-23T17:23:43.000Z
// // DBtxnNewOrder.cpp // centiman TPCC // // Created by Alan Demers on 11/1/12. // Copyright (c) 2012 ademers. All rights reserved. // //#include <unordered_set> #include <set> #include <tpcc/Tables.h> #include <tpcc/DB.h> #include <util/const.h> namespace TPCC { /* * New Order Transaction ... */ int DB::txnNewOrder() { int ans; uint16_t theW_ID = terminal_w_id; uint16_t theT_ID = terminal_id; time_t now = time(0); /* * generate the input data ... */ uint16_t theD_ID = dg.uniformInt(0, numDISTRICTs_per_WAREHOUSE); uint32_t theC_ID = dg.NURand(dg.A_for_C_ID, 1, numCUSTOMERs_per_DISTRICT, dg.C_for_C_ID) - 1; // in [0..numCUSTOMERs_per_DISTRICT) uint16_t theOL_CNT = dg.uniformInt(5, 16); /* choose items, quantities and supplying warehouses ... */ uint32_t i_ids[15]; uint16_t supply_w_ids[15]; uint16_t ol_quantities[15]; uint16_t all_local = 1; { /* do not order the same item twice ... */ // std::unordered_set<uint32_t> i_id_set; std::set<uint32_t> i_id_set; int ol = 0; while( ol < theOL_CNT ) { uint32_t tmp_i_id = dg.NURand(dg.A_for_OL_I_ID, 1, numITEMs, dg.C_for_OL_I_ID) - 1; // in [0..numITEMs) if (i_id_set.find(tmp_i_id) != i_id_set.end()) continue; // if( i_id_set.count(tmp_i_id) > 0 ) continue; i_id_set.insert(tmp_i_id); i_ids[ol] = tmp_i_id; supply_w_ids[ol] = theW_ID; if( (numWAREHOUSEs > 1) && dg.flip(0.01) ) /* nonlocal warehouse */ { all_local = 0; do { supply_w_ids[ol] = dg.uniformInt(0, numWAREHOUSEs); } while( supply_w_ids[ol] == theW_ID ); } ol_quantities[ol] = dg.uniformInt(1, 11); ol++; } } /* TODO: force rollback 1% of time ... */ // if( dg.flip(0.01) ) { i_ids[theOL_CNT-1] = (uint32_t)(-1); } /* * issue reads ... */ /* WAREHOUSE table ... */ TblWAREHOUSE::Key * pkW = new TblWAREHOUSE::Key(theW_ID); ans = conn.requestRead(pkW); /* DISTRICT table ... */ /* TblDISTRICT::Key * pkD = new TblDISTRICT::Key(theW_ID, theD_ID); ans = conn.requestRead(pkD); pkD = 0;*/ /* DISTRICT_NEXT_O_ID table ... */ TblDISTRICT_NEXT_O_ID::Key * pkD_NEXT_O_ID = new TblDISTRICT_NEXT_O_ID::Key(theW_ID, theD_ID, theT_ID); ans = conn.requestRead(pkD_NEXT_O_ID); delete pkD_NEXT_O_ID; /* CUSTOMER table ... */ TblCUSTOMER::Key * pkC = new TblCUSTOMER::Key(theW_ID, theD_ID, theC_ID); ans = conn.requestRead(pkC); delete pkC; /* ITEM and STOCK tables ... */ for( int ol = 0; ol < theOL_CNT; ol++ ) { TblITEM::Key * pkI = new TblITEM::Key(i_ids[ol]); ans = conn.requestRead(pkI); delete pkI; TblSTOCK::Key * pkS = new TblSTOCK::Key(supply_w_ids[ol], i_ids[ol]); ans = conn.requestRead(pkS); delete pkS; } /* * Get and process read results in the order they were issued ... */ uint32_t o_id; double d_tax; double c_discount; char * c_last = 0; char c_credit[2]; // 'BC' or 'GC' double c_credit_lim; /* WAREHOUSE table ... */ TblWAREHOUSE::Row * prW = 0; Seqnum * pSeqnum = NULL; ans = conn.getReadResult( ((::Value **)(&prW)), &pSeqnum ); if (*pSeqnum == Const::SEQNUM_NULL) { pkW->print(); } assert( !(prW->isNULL() || *pSeqnum == Const::SEQNUM_NULL) ); assert( !prW->isNULL(TblWAREHOUSE::Row::W_TAX) ); double w_tax = prW->getCol_double(TblWAREHOUSE::Row::W_TAX); /* DISTRICT table ... */ /* TblDISTRICT::Row * prD = 0; ans = conn.getReadResult( ((::Value **)(&prD)), &pSeqnum ); assert( !(prD->isNULL() || *pSeqnum == Const::SEQNUM_NULL) ); assert( !prD->isNULL(TblDISTRICT::Row::D_TAX) ); d_tax = prD->getCol_double(TblDISTRICT::Row::D_TAX); assert( !prD->isNULL(TblDISTRICT::Row::D_NEXT_O_ID) );*/ /* DISTRICT_NEXT_O_ID table ... */ TblDISTRICT::Row * prD_NEXT_O_ID = 0; ans = conn.getReadResult( ((::Value **)(&prD_NEXT_O_ID)), &pSeqnum ); o_id = prD_NEXT_O_ID->getCol_uint32(TblDISTRICT_NEXT_O_ID::Row::D_NEXT_O_ID); prD_NEXT_O_ID->putCol_uint32(TblDISTRICT_NEXT_O_ID::Row::D_NEXT_O_ID, o_id+1); pkD_NEXT_O_ID = new TblDISTRICT_NEXT_O_ID::Key(theW_ID, theD_ID, theT_ID); ans = conn.requestWrite(pkD_NEXT_O_ID, prD_NEXT_O_ID); delete pkD_NEXT_O_ID; /* CUSTOMER table ... */ TblCUSTOMER::Row * prC = 0; ans = conn.getReadResult( ((::Value **)(&prC)), &pSeqnum ); assert( !(prC->isNULL() || *pSeqnum == Const::SEQNUM_NULL)); assert( !prC->isNULL(TblCUSTOMER::Row::C_DISCOUNT) ); c_discount = prC->getCol_double(TblCUSTOMER::Row::C_DISCOUNT); assert( !prC->isNULL(TblCUSTOMER::Row::C_LAST) ); c_last = prC->getCol_cString(TblCUSTOMER::Row::C_LAST); assert( !prC->isNULL(TblCUSTOMER::Row::C_CREDIT) ); ans = prC->getCol(TblCUSTOMER::Row::C_CREDIT, ((uint8_t *)(&c_credit[0])), (sizeof c_credit)); assert( ans == 2 ); assert( !prC->isNULL(TblCUSTOMER::Row::C_CREDIT_LIM) ); c_credit_lim = prC->getCol_double(TblCUSTOMER::Row::C_CREDIT_LIM); /* create and write new rows for ORDER, ORDER_INDEX, NEW_ORDER ... */ TblORDER::Key * pkO = new TblORDER::Key( theW_ID, theD_ID, o_id, theT_ID ); TblORDER::Row * prO = new TblORDER::Row; prO->reset(); prO->putCol_time(TblORDER::Row::O_ENTRY_D, now); prO->putCol_uint16(TblORDER::Row::O_OL_CNT, theOL_CNT); prO->putCol_uint16(TblORDER::Row::O_ALL_LOCAL, all_local); ans = conn.requestWrite(pkO, prO); delete pkO; delete prO; TblORDER_INDEX::Key * pkOX = new TblORDER_INDEX::Key( theW_ID, theD_ID, theC_ID, theT_ID ); TblORDER_INDEX::Row * prOX = new TblORDER_INDEX::Row; prOX->reset(); prOX->putCol_uint32(TblORDER_INDEX::Row::OX_O_ID, o_id); ans = conn.requestWrite(pkOX, prOX); delete pkOX; delete prOX; TblNEW_ORDER::Key * pkNO = new TblNEW_ORDER::Key( theW_ID, theD_ID, o_id, theT_ID ); TblNEW_ORDER::Row * prNO = new TblNEW_ORDER::Row; prNO->reset(); ans = conn.requestWrite(pkNO, prNO); delete pkNO; delete prNO; /* process ordered items, writing ORDER_LINE rows and updating STOCK table as needed ... */ double total_amount = 0.0; for( int ol = 0; ol < theOL_CNT; ol++ ) { /* retrieve ITEM and STOCK read results ... */ TblITEM::Row * prI = 0; ans = conn.getReadResult( ((::Value **)(&prI)), &pSeqnum ); if( (prI->isNULL() || *pSeqnum == Const::SEQNUM_NULL)) /* request for unused item */ { ans = (-1); goto Out; } assert( !(prI->isNULL(TblITEM::Row::I_PRICE)) ); double i_price = prI->getCol_double(TblITEM::Row::I_PRICE); assert( !(prI->isNULL(TblITEM::Row::I_NAME)) ); char * i_name = prI->getCol_cString(TblITEM::Row::I_NAME); assert( !(prI->isNULL(TblITEM::Row::I_DATA)) ); char * i_data = prI->getCol_cString(TblITEM::Row::I_DATA); TblSTOCK::Row * prS = 0; ans = conn.getReadResult( ((::Value **)(&prS)), &pSeqnum); assert( !(prS->isNULL() || *pSeqnum == Const::SEQNUM_NULL) ); assert( !(prS->isNULL(TblSTOCK::Row::S_DIST_01+supply_w_ids[ol])) ); char * s_dist_xx = prS->getCol_cString(TblSTOCK::Row::S_DIST_01+supply_w_ids[ol]); assert( !(prS->isNULL(TblSTOCK::Row::S_DATA)) ); char * s_data = prS->getCol_cString(TblSTOCK::Row::S_DATA); assert( !(prS->isNULL(TblSTOCK::Row::S_QUANTITY)) ); uint16_t s_quantity = prS->getCol_uint16(NULL, TblSTOCK::Row::S_QUANTITY); assert( !(prS->isNULL(TblSTOCK::Row::S_YTD)) ); uint32_t s_ytd = prS->getCol_uint32(TblSTOCK::Row::S_YTD); assert( !(prS->isNULL(TblSTOCK::Row::S_ORDER_CNT)) ); uint16_t s_order_cnt = prS->getCol_uint16(NULL, TblSTOCK::Row::S_ORDER_CNT); assert( !(prS->isNULL(TblSTOCK::Row::S_REMOTE_CNT)) ); uint16_t s_remote_cnt = prS->getCol_uint16(NULL, TblSTOCK::Row::S_REMOTE_CNT); /* update the STOCK row ... */ if( s_quantity >= (ol_quantities[ol] + 10) ) { prS->putCol_uint16( TblSTOCK::Row::S_QUANTITY, s_quantity - ol_quantities[ol] ); } else { prS->putCol_uint16( TblSTOCK::Row::S_QUANTITY, s_quantity + 91 - ol_quantities[ol] ); } prS->putCol_uint32(TblSTOCK::Row::S_YTD, s_ytd + ol_quantities[ol]); prS->putCol_uint16(TblSTOCK::Row::S_ORDER_CNT, s_order_cnt+1); if( supply_w_ids[ol] != theW_ID ) { prS->putCol_uint16( TblSTOCK::Row::S_REMOTE_CNT, s_remote_cnt+1 ); } TblSTOCK::Key * pkS = new TblSTOCK::Key(supply_w_ids[ol], i_ids[ol]); ans = conn.requestWrite(pkS, prS); delete pkS; /* insert an ORDER_LINE row ... */ TblORDER_LINE::Key * pkOL = new TblORDER_LINE::Key(theW_ID, theD_ID, o_id, ol, theT_ID); TblORDER_LINE::Row * prOL = new TblORDER_LINE::Row; prOL->reset(); double ol_amount = ol_quantities[ol] * i_price; prOL->putCol_uint32(TblORDER_LINE::Row::OL_I_ID, i_ids[ol]); prOL->putCol_uint16(TblORDER_LINE::Row::OL_SUPPLY_W_ID, supply_w_ids[ol]); // OL_DELIVERY_D is NULL prOL->putCol_uint16(TblORDER_LINE::Row::OL_QUANTITY, ol_quantities[ol]); prOL->putCol_double(TblORDER_LINE::Row::OL_AMOUNT, ol_amount); prOL->putCol(TblORDER_LINE::Row::OL_DIST_INFO, (uint8_t *)(s_dist_xx), strlen(s_dist_xx)); ans = conn.requestWrite(pkOL, prOL); delete pkOL; delete prOL; /* accumulate total_amount ... */ total_amount += ol_amount * (1.0 - c_discount) * (1.0 + w_tax + d_tax); /* the funky "brand-generic" test ... */ char brand_generic = 'B'; if( (strstr(i_data, "ORIGINAL") == 0) || (strstr(i_data, "ORIGINAL") == 0) ) { brand_generic = 'G'; } /* clean up */ delete [] i_name; delete [] i_data; delete [] s_dist_xx; delete [] s_data; } ans = 0; Out: ; /* clean up */ delete [] c_last; /* clean keys */ delete pkW; return ans; } };
45.247967
138
0.55844
bailuding
4504f9adfd0c992fe47af0cbffea8e9a38dc2442
573
cpp
C++
week1/fileIO.cpp
shaili-regmi/cpp-examples
66c8813b6ef301604c5003b103c1f11d5ee7519b
[ "MIT" ]
null
null
null
week1/fileIO.cpp
shaili-regmi/cpp-examples
66c8813b6ef301604c5003b103c1f11d5ee7519b
[ "MIT" ]
null
null
null
week1/fileIO.cpp
shaili-regmi/cpp-examples
66c8813b6ef301604c5003b103c1f11d5ee7519b
[ "MIT" ]
4
2021-02-18T18:34:47.000Z
2021-03-03T18:05:26.000Z
// Bryn Mawr College, 2021 #include <iostream> #include <fstream> #include <sstream> #include <vector> using namespace std; int main(int argc, char** argv) { string filename = "../files/grades.txt"; ifstream file(filename); if (!file) // true if the file is valid { cout << "Cannot load file: " << filename << endl; return 1; } int num = 0; float sum = 0; while (file) { int grade; file >> grade; sum += grade; num++; } cout << "The average is " << sum/num << endl; file.close(); return 0; }
16.371429
55
0.558464
shaili-regmi
4505c2df666176b029ee7d913f366e9ea6e34bdd
303
hpp
C++
States.hpp
nvg-ict/StateMachineTemplate
abae3222535d20bea2aa82ba4aca83ebab1081dc
[ "Apache-2.0" ]
null
null
null
States.hpp
nvg-ict/StateMachineTemplate
abae3222535d20bea2aa82ba4aca83ebab1081dc
[ "Apache-2.0" ]
null
null
null
States.hpp
nvg-ict/StateMachineTemplate
abae3222535d20bea2aa82ba4aca83ebab1081dc
[ "Apache-2.0" ]
null
null
null
/* * States.hpp * * Created on: Mar 4, 2017 * Author: nico */ #ifndef STATES_HPP_ #define STATES_HPP_ /** * @brief States for the statemachine */ namespace States { enum Events { evInitReady, evTask, evTaskDone, evSTOP, evSTOPdisable }; } #endif /* STATES_HPP_ */
10.448276
37
0.613861
nvg-ict
450bfb405f75a9351e7c5860d6e97269891d2bc6
235
cpp
C++
src/0189.cpp
shuihan0555/LeetCode-Solutions-in-Cpp17
8bb69fc546486c5e73839431204927626601dd18
[ "MIT" ]
null
null
null
src/0189.cpp
shuihan0555/LeetCode-Solutions-in-Cpp17
8bb69fc546486c5e73839431204927626601dd18
[ "MIT" ]
null
null
null
src/0189.cpp
shuihan0555/LeetCode-Solutions-in-Cpp17
8bb69fc546486c5e73839431204927626601dd18
[ "MIT" ]
null
null
null
class Solution { public: void rotate(vector<int>& nums, int k) { k %= size(nums); reverse(begin(nums), end(nums)); reverse(begin(nums), begin(nums) + k); reverse(begin(nums) + k, end(nums)); } };
26.111111
46
0.544681
shuihan0555
450e2111cdbc102af7b01657673639af2fa38c9c
505
hh
C++
CppPool/cpp_d09/ex04/Priest.hh
667MARTIN/Epitech
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
[ "MIT" ]
40
2018-01-28T14:23:27.000Z
2022-03-05T15:57:47.000Z
CppPool/cpp_d09/ex04/Priest.hh
667MARTIN/Epitech
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
[ "MIT" ]
1
2021-10-05T09:03:51.000Z
2021-10-05T09:03:51.000Z
CppPool/cpp_d09/ex04/Priest.hh
667MARTIN/Epitech
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
[ "MIT" ]
73
2019-01-07T18:47:00.000Z
2022-03-31T08:48:38.000Z
// // Priest.hh for Priest in /home/gwendoline/Epitech/Tek2/Piscine_cpp/piscine_cpp_d09/ex02 // // Made by Gwendoline Rodriguez // Login <[email protected]> // // Started on Thu Jan 14 16:50:20 2016 Gwendoline Rodriguez // Last update Thu Jan 14 18:54:34 2016 Gwendoline Rodriguez // #ifndef _PRIEST_HH #define _PRIEST_HH #include "Mage.hh" class Priest : public Mage { public: explicit Priest(const std::string&, int); ~Priest(); int CloseAttack(); void Heal(); }; #endif
18.035714
89
0.69901
667MARTIN
451157df0d6dc6e5135e7f9ce2b8f510befffa7c
2,765
cpp
C++
Code/Modules/mutalisk/dx9/dx9Helpers.cpp
mrneo240/suicide-barbie
c8b01f9c04755e7f6d1d261fc4a1600cd6705b96
[ "MIT" ]
57
2021-01-02T00:18:22.000Z
2022-03-27T14:40:25.000Z
Code/Modules/mutalisk/dx9/dx9Helpers.cpp
mrneo240/suicide-barbie
c8b01f9c04755e7f6d1d261fc4a1600cd6705b96
[ "MIT" ]
1
2021-01-05T20:43:02.000Z
2021-01-11T23:04:41.000Z
Code/Modules/mutalisk/dx9/dx9Helpers.cpp
mrneo240/suicide-barbie
c8b01f9c04755e7f6d1d261fc4a1600cd6705b96
[ "MIT" ]
8
2021-01-01T22:34:43.000Z
2022-03-22T01:21:26.000Z
#include "dx9Helpers.h" #include <string> #include <stdlib.h> #include "../errors.h" using namespace dx; unsigned calcTextureSize(IDirect3DTexture9 const& texture) { IDirect3DTexture9& tex = const_cast<IDirect3DTexture9&>(texture); const int mipMapLevels = tex.GetLevelCount(); // // Size calculated by this equation: // 1. in case of uncompressed textures - width*height*bytesPerPixel. // 2. in case of compressed textures - max(1, width/4)*max(1, height/4)*(DXTver == 1 ? 8 : 16). // To treat both compressed and uncompressed textures uniformly lets use - // bytes = max(1,width/divisor)*max(1,height/divisor)*multiplier, and in case of // uncompressed textures use 1 for divisor and bytesPerPixel in place of multiplier. // int multiplier = 0; int divisor = 1; // Get first mip map level description: D3DSURFACE_DESC sd; tex.GetLevelDesc( 0, &sd ); // Initialize multiplier and divisor to match actual format: switch (sd.Format) { // 64 bpp??? case D3DFMT_A16B16G16R16: multiplier = 8; break; // 32 bpp: case D3DFMT_A2W10V10U10: case D3DFMT_V16U16: case D3DFMT_X8L8V8U8: case D3DFMT_Q8W8V8U8: case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: case D3DFMT_A2B10G10R10: case D3DFMT_A8B8G8R8: case D3DFMT_X8B8G8R8: case D3DFMT_G16R16: case D3DFMT_A2R10G10B10: multiplier = 4; break; // 24 bpp: case D3DFMT_R8G8B8: multiplier = 3; break; // 16 bpp: case D3DFMT_V8U8: case D3DFMT_L6V5U5: case D3DFMT_A8P8: case D3DFMT_A8L8: case D3DFMT_R5G6B5: case D3DFMT_X1R5G5B5: case D3DFMT_A1R5G5B5: case D3DFMT_A4R4G4B4: case D3DFMT_A8R3G3B2: case D3DFMT_X4R4G4B4: multiplier = 2; break; // 8 bpp: case D3DFMT_A4L4: case D3DFMT_P8: case D3DFMT_L8: case D3DFMT_R3G3B2: case D3DFMT_A8: multiplier = 1; break; // Compressed: case D3DFMT_DXT1: divisor = 4; multiplier = 8; break; case D3DFMT_DXT2: case D3DFMT_DXT3: case D3DFMT_DXT4: case D3DFMT_DXT5: divisor = 4; multiplier = 16; break; // UNKNOWN FORMAT! default: return 0; }; unsigned bytes = 0; // Calculate size: for ( int i = 0; i < mipMapLevels; ++i ) { tex.GetLevelDesc( i, &sd ); bytes += max( 1, sd.Width / divisor ) * max( 1, sd.Height / divisor ) * multiplier; } return bytes; } ResultCheck::ResultCheck( char const* errorMessage_, char const* messagePrefix_, char const* messagePostfix_ ) : errorMessage( errorMessage_ ), messagePrefix( messagePrefix_ ), messagePostfix( messagePostfix_ ) { } ResultCheck& ResultCheck ::operator= ( HRESULT result ) { if( FAILED(result) ) { THROW_DXERROR( result, std::string( messagePrefix ) + std::string( errorMessage ) + std::string( messagePostfix ) ); } return *this; }
21.10687
110
0.692586
mrneo240
4511e68cd54adac8baea46b169c0a8a6b659ed9d
904
cpp
C++
Algorithmic-Toolbox/Extra_Poly_Mul.cpp
saddhu1005/Coursera-DataStructuresAlgorithms
847508c1e93246900700a63b981033ec84d85031
[ "MIT" ]
1
2019-04-01T20:05:25.000Z
2019-04-01T20:05:25.000Z
Algorithmic-Toolbox/Extra_Poly_Mul.cpp
saddhu1005/Coursera-DataStructuresAlgorithms
847508c1e93246900700a63b981033ec84d85031
[ "MIT" ]
null
null
null
Algorithmic-Toolbox/Extra_Poly_Mul.cpp
saddhu1005/Coursera-DataStructuresAlgorithms
847508c1e93246900700a63b981033ec84d85031
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll * multp(ll a[],ll b[],ll n,ll l, ll r) { ll *rs=new ll[n*2-1]; for(ll i=0;i<n*2-1;++i) rs[i]=0; if(n==1) { rs[0]=a[l]*b[l]; return rs; } rs=multp(a,b,n/2,l,r); rs=multp(a,b,n/2,l+n/2,r+n/2); ll *d0e=new ll[n/2]; for(ll i=0;i<n/2;++i) d0e[i]=0; d0e=multp(a,b,n/2,l,r+n/2); ll *d1e=new ll[n/2]; for(ll i=0;i<n/2;++i) d1e[i]=0; d1e=multp(a,b,n/2,l+n/2,r); for(ll i=n/2;i<n+n/2;++i) { rs[i]+=d1e[i-n/2]+d0e[i-n/2]; } return rs; } int main() { ll n; cin>>n; ll a[n+1],b[n+1]; ll i; for(i=0;i<n;++i) { cin>>a[i]; } for(i=0;i<n;++i) { cin>>b[i]; } ll *r=new ll[2*n-1]; r=multp(a,b,4,0,0); for(i=2*n-2;i>=0;--i) { cout<<r[i]<<" "; } cout<<endl; }
17.72549
41
0.409292
saddhu1005
45159869f3605b62595dd52d902b9c1c8b35a7ef
2,804
hpp
C++
include/pmath/Matrix2.hpp
M4T1A5/ProbablyMath
fbf907ebfcb5a4d59c89fa240c20a1bb876b74be
[ "MIT" ]
null
null
null
include/pmath/Matrix2.hpp
M4T1A5/ProbablyMath
fbf907ebfcb5a4d59c89fa240c20a1bb876b74be
[ "MIT" ]
null
null
null
include/pmath/Matrix2.hpp
M4T1A5/ProbablyMath
fbf907ebfcb5a4d59c89fa240c20a1bb876b74be
[ "MIT" ]
null
null
null
#pragma once #ifndef MATRIX2_PMATH_H #define MATRIX2_PMATH_H #include "Vector2.hpp" #include <iostream> #include <string> namespace pmath { template<typename T> class Matrix2 { public: Matrix2(); Matrix2(const T& a11, const T& a12, const T& a21, const T& a22); Matrix2(const Vector2<T>& row1, const Vector2<T>& row2); Matrix2(const Matrix2& matrix); template<typename T2> Matrix2(const Matrix2<T2>& matrix); ~Matrix2(); static const Matrix2 identity; bool isIdentity() const; T determinant() const; Matrix2 transpose() const; static Matrix2 transpose(const Matrix2& matrix); Matrix2 cofactor() const; static Matrix2 cofactor(const Matrix2& matrix); Matrix2 inverse() const; static Matrix2 inverse(const Matrix2& matrix); const T* ptr() const; static Matrix2 createRotation(const T& angle); static Matrix2 createScaling(const T& x, const T& y); static Matrix2 createScaling(const Vector2<T>& scale); std::string toString() const; #pragma region Operators // Comparison bool operator ==(const Matrix2& right) const; bool operator !=(const Matrix2& right) const; // Assignment Matrix2& operator =(const Matrix2& right); Matrix2& operator +=(const Matrix2& right); Matrix2& operator -=(const Matrix2& right); Matrix2& operator *=(const T& right); Matrix2& operator *=(const Matrix2& right); Matrix2& operator /=(const T& right); // Arithmetic Matrix2 operator +(const Matrix2& right) const; Matrix2 operator -(const Matrix2& right) const; Matrix2 operator *(const Matrix2& right) const; Matrix2 operator *(const T& right) const; Vector2<T> operator *(const Vector2<T>& right) const; Matrix2 operator /(const T& right) const; // Member access Vector2<T>& operator [](const unsigned int index); const Vector2<T>& operator [](const unsigned int index) const; #pragma endregion static const unsigned int COLUMNS = 2; static const unsigned int ROWS = 2; private: Vector2<T> r1, r2; }; template<typename T> Matrix2<T> operator *(const T& left, const Matrix2<T>& right); template<typename T> Vector2<T>& operator *=(Vector2<T>& left, const Matrix2<T>& right); template<typename T> std::ostream& operator<<(std::ostream& out, const Matrix2<T>& right); typedef Matrix2<float> Mat2; typedef Matrix2<double> Mat2d; typedef Matrix2<int> Mat2i; typedef Matrix2<unsigned int> Mat2u; } #include "inl/Matrix2.inl" #endif
28.323232
73
0.614836
M4T1A5
4516b87899f4583240c9c086372d0fa0537d24c4
241
cc
C++
build/ARM/python/m5/internal/param_ThermalResistor.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
build/ARM/python/m5/internal/param_ThermalResistor.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
build/ARM/python/m5/internal/param_ThermalResistor.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" extern "C" { void init_param_ThermalResistor(); } EmbeddedSwig embed_swig_param_ThermalResistor(init_param_ThermalResistor, "m5.internal._param_ThermalResistor");
26.777778
120
0.643154
Jakgn
931f7a28603651a2203a309bde1bea50b5fcfdca
2,002
cpp
C++
source/log/Layout.cpp
intive/StudyBox_CV
5ea9b643177667ebdc9809f28db6705b308409f4
[ "Apache-2.0" ]
3
2016-03-07T09:40:49.000Z
2018-05-29T16:13:10.000Z
source/log/Layout.cpp
intive/StudyBox_CV
5ea9b643177667ebdc9809f28db6705b308409f4
[ "Apache-2.0" ]
38
2016-03-06T20:44:46.000Z
2016-05-18T19:16:40.000Z
source/log/Layout.cpp
blstream/StudyBox_CV
5ea9b643177667ebdc9809f28db6705b308409f4
[ "Apache-2.0" ]
10
2016-03-10T21:30:18.000Z
2016-04-20T07:01:12.000Z
#define _CRT_SECURE_NO_WARNINGS #include "Layout.h" #include <iomanip> #include <sstream> LoggerInfo::LoggerInfo(std::size_t id, std::string name) : loggerId(id), loggerName(name) { } std::size_t LoggerInfo::id() const { return loggerId; } const std::string& LoggerInfo::name() const { return loggerName; } ThreadInfo::ThreadInfo(std::thread::id id, std::size_t number) : threadId(id), threadNumber(number) { } std::thread::id ThreadInfo::id() const { return threadId; } std::size_t ThreadInfo::number() const { return threadNumber; } EventLogLevel::EventLogLevel(LogConfig::LogLevel level) : level(level) { } const std::string& EventLogLevel::name() const { return LogConfig::LogLevelStrings[LogConfig::GetIndexForLevel(level)]; } LogConfig::LogLevel EventLogLevel::value() const { return level; } Time::Time(std::tm* time) : time(time) { } int Time::hour() const { return time->tm_hour; } int Time::minute() const { return time->tm_min; } int Time::second() const { return time->tm_sec; } int Time::millisecond() const { return 0; // TODO } Date::Date(std::time_t timeTicks) : tmtime(std::localtime(&timeTicks)), time(tmtime) { } int Date::year() const { return 1900 + tmtime->tm_year; } int Date::month() const { return tmtime->tm_mon; } int Date::day() const { return tmtime->tm_wday; } std::string Date::toString(const std::string& format, const std::locale& locale) const { std::ostringstream ss; ss.imbue(locale); ss << std::put_time(tmtime, format.c_str()); return ss.str(); } std::string Date::toIso8601() const { return toString("%FT%TZ"); } Timestamp::Timestamp(std::time_t timeTicks) : timeTicks(timeTicks), date(timeTicks) { } std::time_t Timestamp::ticks() const { return timeTicks; } Message::Message(std::size_t id, std::string message) : messageId(id), message(message) { } std::size_t Message::id() const { return messageId; } std::string Message::what() const { return message; }
16.683333
99
0.681818
intive
9326fea7cfefb0a2788b7d56c1eb06e083e1505c
499
cpp
C++
src/TEMA VACANTA 2/#11/main.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
2
2021-11-27T18:29:32.000Z
2021-11-28T14:35:47.000Z
src/TEMA VACANTA 2/#11/main.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
null
null
null
src/TEMA VACANTA 2/#11/main.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
null
null
null
#include <iostream> /*11) Se dă un şir cu n numere naturale. Să se afişeze suma primilor n termeni din şir, apoi suma primilor n-1 termeni din şir, şi aşa mai departe.*/ using namespace std; int main() { int i, n, v[100], s=0; cout<<"Scrie nr de elem: "; cin>>n; cout<<"Scrie elem vect.: "; for(i=0; i<n; i++) { cin>>v[i]; s=s+v[i]; } cout<<s<<endl; for(i=n-1; i>0; i--) { cout<<s-v[i]<<endl; s=s-v[i]; } return 0; }
19.192308
97
0.513026
andrew-miroiu
9333c21b1adced91325809aac79ac9d81c887635
123
cpp
C++
examples/op_new_arr_reinterpret_cast.cpp
typegrind/clang-typegrind
6aa58997883d7973e14644563dc59ff9c34e8ffb
[ "MIT" ]
2
2016-04-12T20:41:15.000Z
2019-08-26T12:51:51.000Z
examples/op_new_arr_reinterpret_cast.cpp
typegrind/clang-typegrind
6aa58997883d7973e14644563dc59ff9c34e8ffb
[ "MIT" ]
null
null
null
examples/op_new_arr_reinterpret_cast.cpp
typegrind/clang-typegrind
6aa58997883d7973e14644563dc59ff9c34e8ffb
[ "MIT" ]
null
null
null
int main(void) { int* pT = reinterpret_cast<int*>(::operator new[](100)); ::operator delete[](pT); return 0; }
20.5
60
0.585366
typegrind
9335e297ab7455c1f85517ef1b2d632f562ed884
3,367
cpp
C++
src/wcl/geometry/LineSegment.cpp
WearableComputerLab/LibWCL
e1687a8fd2f96bfec3a84221044cfb8b7126a79c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/wcl/geometry/LineSegment.cpp
WearableComputerLab/LibWCL
e1687a8fd2f96bfec3a84221044cfb8b7126a79c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/wcl/geometry/LineSegment.cpp
WearableComputerLab/LibWCL
e1687a8fd2f96bfec3a84221044cfb8b7126a79c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/*- * Copyright (c) 2008 Michael Marner <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sstream> #include <iostream> #include <cstdlib> #include <config.h> #include <wcl/geometry/LineSegment.h> #include <wcl/geometry/Intersection.h> namespace wcl { LineSegment::LineSegment(const wcl::Vector& start, const wcl::Vector& end) : Line(start, end - start), startPos(start), endPos(end) { } wcl::Intersection LineSegment::intersect(const LineSegment& s) { wcl::Intersection ip = Line::intersect((wcl::Line)s); if ( ip.intersects == wcl::Intersection::YES ) { // Check whether or not the intersection point is on the segment. if (!(this->isOnSegment(ip.point) && s.isOnSegment(ip.point))) { ip.intersects = wcl::Intersection::NO; } } return ip; } bool LineSegment::isOnSegment(const wcl::Vector& point) const { wcl::Vector ba = endPos - startPos; wcl::Vector ca = point - startPos; wcl::Vector cross = ba.crossProduct(ca); if ( abs(cross.length()) < TOL ) { return false; } double dot = ba.dot(ca); if ( dot < 0 ) return false; if ( dot > ( endPos.distance(startPos) * endPos.distance(startPos) ) ) return false; return true; } std::string LineSegment::toString() { std::stringstream ss; ss << "LineSegment. Start: (" << startPos[0] << ", " << startPos[1] << ", " << startPos[2]; ss << ") End: (" << endPos[0] << ", " << endPos[1] << ", " << endPos[2] << ")" << std::endl; return ss.str(); } // Taken from Mathematics for Games and Interactive Applications wcl::Vector LineSegment::closestPoint(const wcl::Vector& point) const { Vector w = point - startPos; wcl::Vector direction = (endPos - startPos); double proj = w.dot(direction); if (proj <=0) { return startPos; } else { double vsq = direction.dot(direction); if (proj >= vsq) return startPos + direction; else return startPos + (proj/vsq)*direction; } } }
32.68932
94
0.665281
WearableComputerLab
93420c8cdc83e0718039a9b1fe1d15a10bced00f
1,484
hpp
C++
include/math/constants.hpp
tomreddell/Hamilton
eec6e423f829a559237583803d11fbe06489a9b9
[ "MIT" ]
1
2020-09-19T14:48:32.000Z
2020-09-19T14:48:32.000Z
include/math/constants.hpp
tomreddell/Hamilton
eec6e423f829a559237583803d11fbe06489a9b9
[ "MIT" ]
null
null
null
include/math/constants.hpp
tomreddell/Hamilton
eec6e423f829a559237583803d11fbe06489a9b9
[ "MIT" ]
1
2021-01-01T02:23:55.000Z
2021-01-01T02:23:55.000Z
#pragma once #include "math/core_math.hpp" /** * @file constants.hpp */ /// Speed of light in vacuum (m/s) constexpr double SPEED_LIGHT = 299792458.0; namespace Earth { /// Earth mass (kg) constexpr double MASS = 5.9722E24; /// Earth gravitational constant (m3/s2) constexpr double GRAVITATIONAL_CONSTANT = 3.986004418E14; /// Length of earth stellar day (s) as defined by the International /// Celestial Reference Frame constexpr double IERS_DAY_SECONDS = 86164.098903691; /// Earth equatorial rotational rate (rad/s) constexpr double ROTATIONAL_RATE = 7.2921150E-5; /// Earth standard gravity (m/s2) constexpr double EQUATORIAL_GRAVITY = 9.7803253359; namespace WGS84 { /// Earth WGS84 Equatorial Radius (m) constexpr double SEMI_MAJOR_AXIS = 6378137.0; /// Earth WGS84 Polar Radius (m) constexpr double SEMI_MINOR_AXIS = 6356752.314245; /// Earth flattening (-) constexpr double FLATTENING = 1.0 / 298.2572235630; /// Earth eccentricity (-) constexpr double ECCENTRICITY = 0.08181919084261345; /// Earth Eccentricity Squared (-) constexpr double ECCSQ = 1.0 - (SEMI_MINOR_AXIS / SEMI_MAJOR_AXIS) * (SEMI_MINOR_AXIS / SEMI_MAJOR_AXIS); } }
30.916667
76
0.582884
tomreddell
9343a5d6ea3bdc05162932d0111c8febf06d086d
4,414
cc
C++
src/kudu/tserver/tablet_server_options.cc
luqun/kuduraft
a0746471a6a85e9d8ccb947a866eaf1a60159f8f
[ "Apache-2.0" ]
null
null
null
src/kudu/tserver/tablet_server_options.cc
luqun/kuduraft
a0746471a6a85e9d8ccb947a866eaf1a60159f8f
[ "Apache-2.0" ]
null
null
null
src/kudu/tserver/tablet_server_options.cc
luqun/kuduraft
a0746471a6a85e9d8ccb947a866eaf1a60159f8f
[ "Apache-2.0" ]
null
null
null
// 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 "kudu/tserver/tablet_server_options.h" #include <ostream> #include <string> #include <gflags/gflags.h> #include <glog/logging.h> #include "kudu/consensus/raft_consensus.h" #include "kudu/gutil/macros.h" #ifdef FB_DO_NOT_REMOVE #include "kudu/master/master.h" #endif #include "kudu/server/rpc_server.h" #include "kudu/tserver/tablet_server.h" #include "kudu/util/flag_tags.h" #include "kudu/util/status.h" #include <boost/algorithm/string.hpp> // TODO - iRitwik ( please refine these mechanisms to a standard way of // passing all the properties of an instance ) DEFINE_string(tserver_addresses, "", "Comma-separated list of the RPC addresses belonging to all " "instances in this cluster. " "NOTE: if not specified, configures a non-replicated Master."); TAG_FLAG(tserver_addresses, stable); DEFINE_string(tserver_regions, "", "Comma-separated list of regions which is parallel to tserver_addresses."); TAG_FLAG(tserver_regions, stable); DEFINE_string(tserver_bbd, "", "Comma-separated list of bool strings to specify Backed by " "Database(non-witness). Runs parallel to tserver_addresses."); TAG_FLAG(tserver_bbd, stable); namespace kudu { namespace tserver { TabletServerOptions::TabletServerOptions() { rpc_opts.default_port = TabletServer::kDefaultPort; if (!FLAGS_tserver_addresses.empty()) { Status s = HostPort::ParseStrings(FLAGS_tserver_addresses, TabletServer::kDefaultPort, &tserver_addresses); if (!s.ok()) { LOG(FATAL) << "Couldn't parse the tserver_addresses flag('" << FLAGS_tserver_addresses << "'): " << s.ToString(); } #ifdef FB_DO_NOT_REMOVE // to simplify in FB, we allow rings with single instances. if (tserver_addresses.size() < 2) { LOG(FATAL) << "At least 2 tservers are required for a distributed config, but " "tserver_addresses flag ('" << FLAGS_tserver_addresses << "') only specifies " << tserver_addresses.size() << " tservers."; } #endif // TODO(wdberkeley): Un-actionable warning. Link to docs, once they exist. if (tserver_addresses.size() <= 2) { LOG(WARNING) << "Only 2 tservers are specified by tserver_addresses_flag ('" << FLAGS_tserver_addresses << "'), but minimum of 3 are required to tolerate failures" " of any one tserver. It is recommended to use at least 3 tservers."; } } if (!FLAGS_tserver_regions.empty()) { boost::split(tserver_regions, FLAGS_tserver_regions, boost::is_any_of(",")); if (tserver_regions.size() != tserver_addresses.size()) { LOG(FATAL) << "The number of tserver regions has to be same as tservers: " << FLAGS_tserver_regions << " " << FLAGS_tserver_addresses; } } if (!FLAGS_tserver_bbd.empty()) { std::vector<std::string> bbds; boost::split(bbds, FLAGS_tserver_bbd, boost::is_any_of(",")); if (bbds.size() != tserver_addresses.size()) { LOG(FATAL) << "The number of tserver bbd tags has to be same as tservers: " << FLAGS_tserver_bbd << " " << FLAGS_tserver_addresses; } for (auto tsbbd: bbds) { if (tsbbd == "true") { tserver_bbd.push_back(true); } else if (tsbbd == "false") { tserver_bbd.push_back(false); } else { LOG(FATAL) << "tserver bbd tags has to be bool true|false : " << FLAGS_tserver_bbd; } } } } bool TabletServerOptions::IsDistributed() const { return !tserver_addresses.empty(); } } // namespace tserver } // namespace kudu
37.40678
102
0.678749
luqun
9348d26c132c0f094f2739746278bbe6311ecb15
523
cpp
C++
C++/camera.cpp
Galaco/BTLRN_XTRM
c55405d5a36a44a8b1e3def555de9ec10027625b
[ "Unlicense" ]
null
null
null
C++/camera.cpp
Galaco/BTLRN_XTRM
c55405d5a36a44a8b1e3def555de9ec10027625b
[ "Unlicense" ]
null
null
null
C++/camera.cpp
Galaco/BTLRN_XTRM
c55405d5a36a44a8b1e3def555de9ec10027625b
[ "Unlicense" ]
null
null
null
#include "camera.h" float zCamPos = -250.0; Camera::Camera(){ posX = 0; posY = 0; } void Camera::zoom( int d ){ zCamPos += d; if ( ( zCamPos > CAMERAMINZOOM ) || ( zCamPos < CAMERAMAXZOOM ) ) // Check bounds for min and max camera distance { zCamPos -= d; } } void Camera::update( float x , float y ){ glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef( - x , - y - YOFFSET , zCamPos ); // Translate the camera in the X and Y direction. } Camera::~Camera(){ }
19.37037
117
0.58891
Galaco
934924abe6cb1e79d292b4d63694dadc739b48f3
1,106
cpp
C++
src/engine/graphics/vulkan/validationlayers.cpp
dmfedorin/ubiquitility
f3a1062d2489ffd48889bff5fc8062c05706a946
[ "MIT" ]
null
null
null
src/engine/graphics/vulkan/validationlayers.cpp
dmfedorin/ubiquitility
f3a1062d2489ffd48889bff5fc8062c05706a946
[ "MIT" ]
null
null
null
src/engine/graphics/vulkan/validationlayers.cpp
dmfedorin/ubiquitility
f3a1062d2489ffd48889bff5fc8062c05706a946
[ "MIT" ]
null
null
null
#include "validationlayers.hpp" ValidationLayers::ValidationLayers(bool enabled) : enabled(enabled) { } auto ValidationLayers::is_enabled(void) const noexcept -> bool { return enabled; } auto ValidationLayers::check_layer_support(void) const -> void { uint32_t avl_layer_cnt; vkEnumerateInstanceLayerProperties(&avl_layer_cnt, nullptr); std::vector<VkLayerProperties> avl_layers{ avl_layer_cnt }; vkEnumerateInstanceLayerProperties(&avl_layer_cnt, avl_layers.data()); uint32_t req_layer_cnt = required_layers.size(); for (const auto &req_layer : required_layers) { for (const auto &avl_layer : avl_layers) { if (strcmp(req_layer, avl_layer.layerName) == 0) req_layer_cnt--; } } if (req_layer_cnt > 0) { throw std::runtime_error{ "validation layers not supported" }; } } auto ValidationLayers::get_required_layers( void) const noexcept -> const std::vector<const char *> & { return required_layers; }
28.358974
78
0.637432
dmfedorin
9352b47a643cade9cfedd9552c153be445a4b29f
11,258
hpp
C++
examples/segway_dynamics.hpp
yamaha-bps/cbr_control
c2faf79673d46c950dd7590f1072fc7decafad06
[ "MIT" ]
null
null
null
examples/segway_dynamics.hpp
yamaha-bps/cbr_control
c2faf79673d46c950dd7590f1072fc7decafad06
[ "MIT" ]
null
null
null
examples/segway_dynamics.hpp
yamaha-bps/cbr_control
c2faf79673d46c950dd7590f1072fc7decafad06
[ "MIT" ]
null
null
null
// Copyright Yamaha 2021 // MIT License // https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE #ifndef SEGWAY_DYNAMICS_HPP_ #define SEGWAY_DYNAMICS_HPP_ #include <Eigen/Dense> // template here over some type template<typename T1, typename T2> auto segway_dynamics(const Eigen::MatrixBase<T1> & x, const Eigen::MatrixBase<T2> & u) { // Define nx, nu constexpr auto nx = T1::RowsAtCompileTime; constexpr auto nu = T2::RowsAtCompileTime; // Initialize Parameters constexpr double mb = 44.798; constexpr double mw = 2.485; constexpr double Jw = 0.055936595310797; constexpr double a2 = -0.02322718759275; constexpr double c2 = 0.166845864363019; constexpr double A2 = 3.604960049044268; constexpr double B2 = 3.836289730154863; constexpr double C2 = 1.069672194414735; constexpr double K = 1.261650363363571; constexpr double r = 0.195; constexpr double L = 0.5; constexpr double gGravity = 9.81; constexpr double FricCoeffViscous = 0.; constexpr double velEps = 1.0e-3; constexpr double FricCoeff = 1.225479467549329; using T = typename decltype(x * u.transpose())::EvalReturnType::Scalar; // xDot = f(x) + g(x)*u Eigen::Matrix<T, nx, 1> xDot; Eigen::Matrix<typename T1::Scalar, nx, 1> f; Eigen::Matrix<typename T1::Scalar, nx, nu> g; Eigen::Map<Eigen::Matrix<typename T1::Scalar, nx, 1>> g1(g.data()); Eigen::Map<Eigen::Matrix<typename T1::Scalar, nx, 1>> g2(g.data() + nx); // Extract States const auto & theta = x[2]; const auto & v = x[3]; const auto & thetaDot = x[4]; const auto & psi = x[5]; const auto & psiDot = x[6]; const auto Fric = FricCoeff * tanh((v - psiDot * r) / velEps) + FricCoeffViscous * (v - psiDot * r); f[0] = v * cos(theta); f[1] = v * sin(theta); f[2] = thetaDot; f[3] = (1 / 2) * r * (1 / (4 * B2 * Jw + 4 * pow( a2, 2) * Jw * mb + 4 * pow( c2, 2) * Jw * mb + 2 * B2 * mb * pow( r, 2) + pow( a2, 2) * pow( mb, 2) * pow( r, 2) + pow( c2, 2) * pow(mb, 2) * pow(r, 2) + 4 * B2 * mw * pow(r, 2) + 4 * pow(a2, 2) * mb * mw * pow(r, 2) + 4 * pow( c2, 2) * mb * mw * pow( r, 2) + (pow( a2, 2) + (-1) * pow( c2, 2)) * pow( mb, 2) * pow( r, 2) * cos(2 * psi) + 2 * a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi))) * ((-8) * B2 * Fric + (-8) * pow(a2, 2) * Fric * mb + (-8) * pow( c2, 2) * Fric * mb + mb * r * ((-8) * c2 * Fric + a2 * ((-1) * A2 + C2) * pow(thetaDot, 2) + 4 * a2 * B2 * (pow(psiDot, 2) + pow(thetaDot, 2)) + pow( a2, 3) * mb * (4 * pow( psiDot, 2) + 3 * pow( thetaDot, 2)) + a2 * pow( c2, 2) * mb * (4 * pow( psiDot, 2) + 3 * pow( thetaDot, 2))) * cos(psi) + (-4) * a2 * c2 * gGravity * pow(mb, 2) * r * cos(2 * psi) + a2 * A2 * mb * r * pow(thetaDot, 2) * cos(3 * psi) + (-1) * a2 * C2 * mb * r * pow( thetaDot, 2) * cos(3 * psi) + pow( a2, 3) * pow( mb, 2) * r * pow( thetaDot, 2) * cos(3 * psi) + (-3) * a2 * pow(c2, 2) * pow(mb, 2) * r * pow(thetaDot, 2) * cos(3 * psi) + 8 * a2 * Fric * mb * r * sin( psi) + 4 * B2 * c2 * mb * pow(psiDot, 2) * r * sin(psi) + 4 * pow( a2, 2) * c2 * pow( mb, 2) * pow( psiDot, 2) * r * sin(psi) + 4 * pow( c2, 3) * pow( mb, 2) * pow( psiDot, 2) * r * sin(psi) + A2 * c2 * mb * r * pow( thetaDot, 2) * sin(psi) + 4 * B2 * c2 * mb * r * pow(thetaDot, 2) * sin(psi) + (-1) * c2 * C2 * mb * r * pow(thetaDot, 2) * sin(psi) + 3 * pow( a2, 2) * c2 * pow(mb, 2) * r * pow(thetaDot, 2) * sin(psi) + 3 * pow(c2, 3) * pow(mb, 2) * r * pow( thetaDot, 2) * sin(psi) + 2 * pow(a2, 2) * gGravity * pow(mb, 2) * r * sin(2 * psi) + (-2) * pow(c2, 2) * gGravity * pow( mb, 2) * r * sin(2 * psi) + A2 * c2 * mb * r * pow(thetaDot, 2) * sin(3 * psi) + (-1) * c2 * C2 * mb * r * pow( thetaDot, 2) * sin(3 * psi) + 3 * pow( a2, 2) * c2 * pow( mb, 2) * r * pow( thetaDot, 2) * sin(3 * psi) + (-1) * pow(c2, 3) * pow(mb, 2) * r * pow(thetaDot, 2) * sin(3 * psi)); f[4] = pow( r, 2) * thetaDot * ((-2) * a2 * mb * v * cos(psi) + (-4) * a2 * c2 * mb * psiDot * cos(2 * psi) + (-2) * (c2 * mb * v + (A2 + (-1) * C2 + (-2) * pow( a2, 2) * mb + 2 * pow( c2, 2) * mb) * psiDot * cos(psi)) * sin(psi)) * (1 / (Jw * pow(L, 2) + pow(L, 2) * mw * pow(r, 2) + 2 * (C2 + pow( a2, 2) * mb) * pow( r, 2) * pow( cos(psi), 2) + 2 * (A2 + pow(c2, 2) * mb) * pow(r, 2) * pow(sin(psi), 2) + 2 * a2 * c2 * mb * pow(r, 2) * sin(2 * psi))); f[5] = psiDot; f[6] = (1 / (4 * B2 * Jw + 4 * pow( a2, 2) * Jw * mb + 4 * pow( c2, 2) * Jw * mb + 2 * B2 * mb * pow( r, 2) + pow( a2, 2) * pow( mb, 2) * pow( r, 2) + pow( c2, 2) * pow( mb, 2) * pow( r, 2) + 4 * B2 * mw * pow( r, 2) + 4 * pow( a2, 2) * mb * mw * pow( r, 2) + 4 * pow( c2, 2) * mb * mw * pow(r, 2) + (pow(a2, 2) + (-1) * pow(c2, 2)) * pow(mb, 2) * pow(r, 2) * cos(2 * psi) + 2 * a2 * c2 * pow( mb, 2) * pow( r, 2) * sin(2 * psi))) * (8 * Fric * Jw + 4 * Fric * mb * pow( r, 2) + 8 * Fric * mw * pow( r, 2) + 2 * mb * (2 * c2 * Fric * r + a2 * gGravity * (2 * Jw + (mb + 2 * mw) * pow(r, 2))) * cos(psi) + (-2) * a2 * c2 * mb * (mb * pow(psiDot, 2) * pow(r, 2) + (-2) * (Jw + mw * pow(r, 2)) * pow(thetaDot, 2)) * cos(2 * psi) + 4 * c2 * gGravity * Jw * mb * sin( psi) + (-4) * a2 * Fric * mb * r * sin(psi) + 2 * c2 * gGravity * pow(mb, 2) * pow(r, 2) * sin(psi) + 4 * c2 * gGravity * mb * mw * pow(r, 2) * sin(psi) + pow( a2, 2) * pow( mb, 2) * pow( psiDot, 2) * pow( r, 2) * sin(2 * psi) + (-1) * pow( c2, 2) * pow( mb, 2) * pow(psiDot, 2) * pow(r, 2) * sin(2 * psi) + (-2) * A2 * Jw * pow(thetaDot, 2) * sin( 2 * psi) + 2 * C2 * Jw * pow( thetaDot, 2) * sin(2 * psi) + (-2) * pow(a2, 2) * Jw * mb * pow(thetaDot, 2) * sin(2 * psi) + 2 * pow( c2, 2) * Jw * mb * pow( thetaDot, 2) * sin(2 * psi) + (-1) * A2 * mb * pow( r, 2) * pow( thetaDot, 2) * sin(2 * psi) + C2 * mb * pow( r, 2) * pow( thetaDot, 2) * sin(2 * psi) + (-2) * A2 * mw * pow( r, 2) * pow(thetaDot, 2) * sin(2 * psi) + 2 * C2 * mw * pow(r, 2) * pow(thetaDot, 2) * sin(2 * psi) + (-2) * pow( a2, 2) * mb * mw * pow(r, 2) * pow(thetaDot, 2) * sin(2 * psi) + 2 * pow(c2, 2) * mb * mw * pow( r, 2) * pow(thetaDot, 2) * sin(2 * psi)); g1[0] = 0; g2[0] = 0; g1[1] = 0; g2[1] = 0; g1[2] = 0; g2[2] = 0; g1[3] = K * r * (B2 + pow( a2, 2) * mb + pow( c2, 2) * mb + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) * (1 / (2 * B2 * Jw + 2 * pow(a2, 2) * Jw * mb + 2 * pow(c2, 2) * Jw * mb + B2 * mb * pow(r, 2) + pow( a2, 2) * pow( mb, 2) * pow( r, 2) + pow( c2, 2) * pow( mb, 2) * pow( r, 2) + 2 * B2 * mw * pow(r, 2) + 2 * pow(a2, 2) * mb * mw * pow(r, 2) + 2 * pow(c2, 2) * mb * mw * pow(r, 2) + (-1) * pow( c2, 2) * pow( mb, 2) * pow( r, 2) * pow( cos(psi), 2) + (-1) * pow( a2, 2) * pow(mb, 2) * pow(r, 2) * pow(sin(psi), 2) + a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi))); g2[3] = K * r * (B2 + pow( a2, 2) * mb + pow( c2, 2) * mb + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) * (1 / (2 * B2 * Jw + 2 * pow(a2, 2) * Jw * mb + 2 * pow(c2, 2) * Jw * mb + B2 * mb * pow(r, 2) + pow( a2, 2) * pow( mb, 2) * pow( r, 2) + pow( c2, 2) * pow( mb, 2) * pow( r, 2) + 2 * B2 * mw * pow(r, 2) + 2 * pow(a2, 2) * mb * mw * pow(r, 2) + 2 * pow(c2, 2) * mb * mw * pow(r, 2) + (-1) * pow( c2, 2) * pow( mb, 2) * pow( r, 2) * pow( cos(psi), 2) + (-1) * pow( a2, 2) * pow(mb, 2) * pow(r, 2) * pow(sin(psi), 2) + a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi))); g1[4] = (-1) * K * L * (1 / (Jw * pow( L, 2) * 1 / r + pow( L, 2) * mw * r + 2 * (C2 + pow( a2, 2) * mb) * r * pow( cos(psi), 2) + 2 * (A2 + pow(c2, 2) * mb) * r * pow(sin(psi), 2) + 2 * a2 * c2 * mb * r * sin(2 * psi))); g2[4] = K * L * (1 / (Jw * pow( L, 2) * 1 / r + pow( L, 2) * mw * r + 2 * (C2 + pow( a2, 2) * mb) * r * pow( cos(psi), 2) + 2 * (A2 + pow(c2, 2) * mb) * r * pow(sin(psi), 2) + 2 * a2 * c2 * mb * r * sin(2 * psi))); g1[5] = 0; g2[5] = 0; g1[6] = (-2) * K * (2 * Jw + mb * pow( r, 2) + 2 * mw * pow( r, 2) + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) * (1 / (4 * B2 * Jw + 4 * pow(a2, 2) * Jw * mb + 4 * pow(c2, 2) * Jw * mb + 2 * B2 * mb * pow(r, 2) + pow( a2, 2) * pow( mb, 2) * pow( r, 2) + pow( c2, 2) * pow(mb, 2) * pow(r, 2) + 4 * B2 * mw * pow(r, 2) + 4 * pow(a2, 2) * mb * mw * pow(r, 2) + 4 * pow( c2, 2) * mb * mw * pow( r, 2) + (pow( a2, 2) + (-1) * pow( c2, 2)) * pow(mb, 2) * pow(r, 2) * cos(2 * psi) + 2 * a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi))); g2[6] = (-2) * K * (2 * Jw + mb * pow( r, 2) + 2 * mw * pow( r, 2) + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) * (1 / (4 * B2 * Jw + 4 * pow(a2, 2) * Jw * mb + 4 * pow(c2, 2) * Jw * mb + 2 * B2 * mb * pow(r, 2) + pow( a2, 2) * pow( mb, 2) * pow( r, 2) + pow( c2, 2) * pow( mb, 2) * pow( r, 2) + 4 * B2 * mw * pow(r, 2) + 4 * pow(a2, 2) * mb * mw * pow(r, 2) + 4 * pow(c2, 2) * mb * mw * pow(r, 2) + (pow( a2, 2) + (-1) * pow( c2, 2)) * pow(mb, 2) * pow(r, 2) * cos(2 * psi) + 2 * a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi))); xDot = f + g * u; return xDot; } #endif // SEGWAY_DYNAMICS_HPP_
20.211849
100
0.373601
yamaha-bps
9354b445599df8416c9c0a56d46a23ac4e56edfc
600
cpp
C++
tutoriat-04-virtual-rtti/Subiecte examen/rezolvate/2.cpp
Tutoring-OOP-RM/Tutoring-OOP
f8709acbbe4a0fc0f869d95e3666c15f0332ddb8
[ "MIT" ]
4
2021-03-11T09:34:07.000Z
2021-03-11T16:11:34.000Z
tutoriat-04-virtual-rtti/Subiecte examen/rezolvate/2.cpp
Tutoring-OOP-RM/Tutoring-OOP
f8709acbbe4a0fc0f869d95e3666c15f0332ddb8
[ "MIT" ]
null
null
null
tutoriat-04-virtual-rtti/Subiecte examen/rezolvate/2.cpp
Tutoring-OOP-RM/Tutoring-OOP
f8709acbbe4a0fc0f869d95e3666c15f0332ddb8
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class B { public: int x; B(int i = 16) { x = i; } B f(B ob) { return x + ob.x; } }; class D : public B { public: D(int i = 25) { x = i; } D f(D ob) { return x + ob.x + 1; } void afisare() { cout << x; } }; int main() { D *p1 = new D; // LA p2 SE INCEARCA UN DOWNCAST GRESIT! // D *p2 = new B; // a value of type "B *" cannot be used to initialize an entity of type "D *"!! // error: invalid conversion from ‘B*’ to ‘D*’ D *p2 = new D; D *p3 = new D(p1->f(*p2)); // 51 daca pt p2 pun D in D cout << p3->x; return 0; }
20.689655
102
0.525
Tutoring-OOP-RM
935ae248a1bcee611fae546b2d549b2905f20536
9,797
cc
C++
aku/vtln.cc
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
null
null
null
aku/vtln.cc
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
null
null
null
aku/vtln.cc
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
null
null
null
#include <math.h> #include <string> #include "io.hh" #include "str.hh" #include "conf.hh" #include "HmmSet.hh" #include "FeatureGenerator.hh" #include "PhnReader.hh" #include "Recipe.hh" #include "SpeakerConfig.hh" using namespace aku; #define TINY 1e-10 std::string save_summary_file; int info; float grid_start; float grid_step; int grid_size; bool relative_grid; conf::Config config; Recipe recipe; HmmSet model; FeatureGenerator fea_gen; SpeakerConfig speaker_conf(fea_gen, &model); VtlnModule *vtln_module; std::string cur_speaker; int cur_warp_index; typedef struct { float center; // Center warp value std::vector<float> warp_factors; std::vector<double> log_likelihoods; } SpeakerStats; typedef std::map<std::string, SpeakerStats> SpeakerStatsMap; SpeakerStatsMap speaker_stats; void set_speaker(std::string speaker, std::string utterance, int grid_iter) { float new_warp; int i; cur_speaker = speaker; assert(cur_speaker.size() > 0); speaker_conf.set_speaker(speaker); if (utterance.size() > 0) speaker_conf.set_utterance(utterance); SpeakerStatsMap::iterator it = speaker_stats.find(speaker); if (it == speaker_stats.end()) { // New speaker encountered SpeakerStats new_speaker; if (relative_grid) new_speaker.center = vtln_module->get_warp_factor(); else new_speaker.center = 1; speaker_stats[cur_speaker] = new_speaker; } new_warp = speaker_stats[cur_speaker].center + grid_start + grid_iter * grid_step; vtln_module->set_warp_factor(new_warp); for (i = 0; i < (int) speaker_stats[cur_speaker].warp_factors.size(); i++) { if (fabs(new_warp - speaker_stats[cur_speaker].warp_factors[i]) < TINY) break; } if (i == (int) speaker_stats[cur_speaker].warp_factors.size()) { // New warp factor speaker_stats[cur_speaker].warp_factors.push_back(new_warp); speaker_stats[cur_speaker].log_likelihoods.push_back(0); } cur_warp_index = i; } void compute_vtln_log_likelihoods(Segmentator *seg, std::string &speaker, std::string &utterance) { int grid_iter; for (grid_iter = 0; grid_iter < grid_size; grid_iter++) { set_speaker(speaker, utterance, grid_iter); seg->reset(); seg->init_utterance_segmentation(); while (seg->next_frame()) { const Segmentator::IndexProbMap &pdfs = seg->pdf_probs(); FeatureVec fea_vec = fea_gen.generate(seg->current_frame()); if (fea_gen.eof()) break; // EOF in FeatureGenerator for (Segmentator::IndexProbMap::const_iterator it = pdfs.begin(); it != pdfs.end(); ++it) { // Get probabilities speaker_stats[cur_speaker].log_likelihoods[cur_warp_index] += util::safe_log((*it).second*model.pdf_likelihood((*it).first, fea_vec)); } } } } void save_vtln_stats(FILE *fp) { for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) { fprintf(fp, "[%s]\n", (*it).first.c_str()); for (int i = 0; i < (int) (*it).second.warp_factors.size(); i++) { fprintf(fp, "%.3f: %.3f\n", (*it).second.warp_factors[i], (*it).second.log_likelihoods[i]); } fprintf(fp, "\n"); } } void find_best_warp_factors(void) { for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) { assert( (*it).second.warp_factors.size() > 0 && (*it).second.warp_factors.size() == (*it).second.log_likelihoods.size()); float best_wf = (*it).second.warp_factors[0]; double best_ll = (*it).second.log_likelihoods[0]; for (int i = 1; i < (int) (*it).second.warp_factors.size(); i++) { if ((*it).second.log_likelihoods[i] > best_ll) { best_ll = (*it).second.log_likelihoods[i]; best_wf = (*it).second.warp_factors[i]; } } speaker_conf.set_speaker((*it).first); vtln_module->set_warp_factor(best_wf); } } int main(int argc, char *argv[]) { PhnReader *phn_reader; try { config("usage: vtln [OPTION...]\n") ('h', "help", "", "", "display help") ('b', "base=BASENAME", "arg", "", "base filename for model files") ('g', "gk=FILE", "arg", "", "Gaussian kernels") ('m', "mc=FILE", "arg", "", "kernel indices for states") ('p', "ph=FILE", "arg", "", "HMM definitions") ('c', "config=FILE", "arg must", "", "feature configuration") ('r', "recipe=FILE", "arg must", "", "recipe file") ('O', "ophn", "", "", "use output phns for VTLN") ('v', "vtln=MODULE", "arg must", "", "VTLN module name") ('S', "speakers=FILE", "arg must", "", "speaker configuration input file") ('o', "out=FILE", "arg", "", "output speaker configuration file") ('s', "savesum=FILE", "arg", "", "save summary information (loglikelihoods)") ('\0', "snl", "", "", "phn-files with state number labels") ('\0', "rsamp", "", "", "phn sample numbers are relative to start time") ('\0', "grid-size=INT", "arg", "21", "warping grid size (default: 21/5)") ('\0', "grid-rad=FLOAT", "arg", "0.1", "radius of warping grid (default: 0.1/0.03)") ('\0', "relative", "", "", "relative warping grid (and smaller grid defaults)") ('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe") ('I', "bindex=INT", "arg", "0", "batch process index") ('i', "info=INT", "arg", "0", "info level"); config.default_parse(argc, argv); info = config["info"].get_int(); fea_gen.load_configuration(io::Stream(config["config"].get_str())); if (config["base"].specified) { model.read_all(config["base"].get_str()); } else if (config["gk"].specified && config["mc"].specified && config["ph"].specified) { model.read_gk(config["gk"].get_str()); model.read_mc(config["mc"].get_str()); model.read_ph(config["ph"].get_str()); } else { throw std::string( "Must give either --base or all --gk, --mc and --ph"); } if (config["savesum"].specified) save_summary_file = config["savesum"].get_str(); if (config["batch"].specified ^ config["bindex"].specified) throw std::string("Must give both --batch and --bindex"); // Read recipe file recipe.read(io::Stream(config["recipe"].get_str()), config["batch"].get_int(), config["bindex"].get_int(), true); vtln_module = dynamic_cast<VtlnModule*> (fea_gen.module( config["vtln"].get_str())); if (vtln_module == NULL) throw std::string("Module ") + config["vtln"].get_str() + std::string(" is not a VTLN module"); grid_start = config["grid-rad"].get_float(); grid_size = std::max(config["grid-size"].get_int(), 1); grid_step = 2 * grid_start / std::max(grid_size - 1, 1); relative_grid = config["relative"].specified; if (relative_grid) { if (!config["grid-rad"].specified) grid_start = 0.03; if (!config["grid-size"].specified) grid_size = 5; grid_step = 2 * grid_start / std::max(grid_size - 1, 1); } grid_start = -grid_start; // Check the dimension if (model.dim() != fea_gen.dim()) { throw str::fmt(128, "gaussian dimension is %d but feature dimension is %d", model.dim(), fea_gen.dim()); } speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str())); for (int f = 0; f < (int) recipe.infos.size(); f++) { if (info > 0) { fprintf(stderr, "Processing file: %s", recipe.infos[f].audio_path.c_str()); if (recipe.infos[f].start_time || recipe.infos[f].end_time) fprintf(stderr, " (%.2f-%.2f)", recipe.infos[f].start_time, recipe.infos[f].end_time); fprintf(stderr, "\n"); } // Open the audio and phn files from the given list. phn_reader = recipe.infos[f].init_phn_files(&model, config["rsamp"].specified, config["snl"].specified, config["ophn"].specified, &fea_gen, NULL); if (recipe.infos[f].speaker_id.size() == 0) throw std::string("Speaker ID is missing"); compute_vtln_log_likelihoods(phn_reader, recipe.infos[f].speaker_id, recipe.infos[f].utterance_id); fea_gen.close(); phn_reader->close(); delete phn_reader; } // Find the best warp factors from statistics find_best_warp_factors(); if (config["savesum"].specified) { // Save the statistics save_vtln_stats(io::Stream(save_summary_file, "w")); } // Write new speaker configuration if (config["out"].specified) { std::set<std::string> *speaker_set = NULL, *utterance_set = NULL; std::set<std::string> speakers, empty_ut; if (config["batch"].get_int() > 1) { if (config["bindex"].get_int() == 1) speakers.insert(std::string("default")); for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) speakers.insert((*it).first); speaker_set = &speakers; utterance_set = &empty_ut; } speaker_conf.write_speaker_file( io::Stream(config["out"].get_str(), "w"), speaker_set, utterance_set); } } catch (HmmSet::UnknownHmm &e) { fprintf(stderr, "Unknown HMM in transcription\n"); abort(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } }
32.656667
101
0.597224
phsmit
935c99d810297c48a0b863ea0ae967f368f9a7a7
330
cpp
C++
HDU/20/hdu2030.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2017-08-19T16:02:15.000Z
2017-08-19T16:02:15.000Z
HDU/20/hdu2030.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
null
null
null
HDU/20/hdu2030.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2018-01-05T23:37:23.000Z
2018-01-05T23:37:23.000Z
#include <stdio.h> #include <string.h> int main(void) { int n; int count; char c; scanf("%d%*c", &n); while (n--) { count = 0; while ((c = getchar()) != '\n') { if (c < 0) count++; } printf("%d\n", count / 2); } return 0; }
12.222222
39
0.360606
bilibiliShen
93625ea160c92b5193dbc25e890a27fb6f2d3c33
1,658
cpp
C++
src/ui/components/frontiers_renderer.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/ui/components/frontiers_renderer.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/ui/components/frontiers_renderer.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, [email protected]. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file frontiers_renderer.cpp * \author Collin Johnson * * Definition of FrontiersRenderer. */ #include "ui/components/frontiers_renderer.h" #include "hssh/local_topological/frontier.h" #include "ui/common/gl_shapes.h" #include <GL/gl.h> #include <algorithm> namespace vulcan { namespace ui { void draw_frontier(const hssh::Frontier& frontier); void FrontiersRenderer::setRenderColor(const GLColor& frontierColor) { this->frontierColor = frontierColor; } void FrontiersRenderer::render(const std::vector<hssh::Frontier>& frontiers) { // Set the color here so it doesn't need to be passed into the draw_frontier function, as all colors are the same // right now frontierColor.set(); std::for_each(frontiers.begin(), frontiers.end(), [](const hssh::Frontier& frontier) { draw_frontier(frontier); }); } void draw_frontier(const hssh::Frontier& frontier) { const float LINE_WIDTH = 2.0f; glLineWidth(LINE_WIDTH); glBegin(GL_LINES); glVertex2f(frontier.boundary.a.x, frontier.boundary.a.y); glVertex2f(frontier.boundary.b.x, frontier.boundary.b.y); glEnd(); gl_draw_small_arrow(frontier.exitPoint, length(frontier.boundary) * 0.75, frontier.direction, LINE_WIDTH); } } // namespace ui } // namespace vulcan
26.741935
117
0.728589
anuranbaka
9364ef2b32068883c5690a74afafab760d044879
636
cpp
C++
7/char*replace.cpp
tangxiangru/NOIP
6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4
[ "MIT" ]
1
2020-10-12T12:00:08.000Z
2020-10-12T12:00:08.000Z
7/char*replace.cpp
tangxiangru/NOIP
6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4
[ "MIT" ]
null
null
null
7/char*replace.cpp
tangxiangru/NOIP
6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> char *Replace(char *str, char *substr, char *newstr); void main() { char a[80], b[80], c[80], *d; gets(a); gets(b); gets(c); d = Replace(a, b, c); printf("%s", a); } char *Replace(char *str, char *substr, char *newstr) { int a, b, i, j, k, flag = 1; a = strlen (str); b = strlen (substr); for (i = 0; i < a; i++) { if(str[i] == substr[0]) flag = 0; for (j = i+1, k = 1; k < b; j++,k++) if (str[j] != substr[k]) flag = 1; if (flag == 0) for (j = 0; j < b; j++) { str[i] = newstr[j]; i += 1; } } return str; }
17.666667
54
0.45283
tangxiangru
9369374d15e2f717b63c5f7961f1fa454a2199d8
5,412
hpp
C++
src/utils/utils.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2020-04-10T14:39:00.000Z
2021-02-11T15:52:16.000Z
src/utils/utils.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2019-12-17T08:50:20.000Z
2020-02-03T09:37:56.000Z
src/utils/utils.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
1
2020-08-19T03:06:52.000Z
2020-08-19T03:06:52.000Z
#ifndef NINJACLOWN_UTILS_UTILS_HPP #define NINJACLOWN_UTILS_UTILS_HPP #include <algorithm> #include <charconv> #include <functional> #include <optional> #include <string_view> #include <type_traits> #include <cstddef> namespace utils { using ssize_t = std::make_signed_t<std::size_t>; inline bool starts_with(std::string_view str, std::string_view prefix) { return std::mismatch(str.begin(), str.end(), prefix.begin(), prefix.end()).second == prefix.end(); } template <typename T> struct add_const_s { using type = T const; }; template <typename T> struct add_const_s<T &> { using type = T const &; }; template <typename T> using add_const = typename add_const_s<T>::type; template <typename T> struct remove_const_s { using type = std::remove_const_t<T>; }; template <typename T> struct remove_const_s<T &> { using type = std::remove_const_t<T> &; }; template <typename T> using remove_const = typename remove_const_s<T>::type; template <typename T> std::optional<T> from_chars(std::string_view str) { T value; auto result = std::from_chars(str.data(), str.data() + str.size(), value); if (result.ptr != str.data() + str.size() || result.ec != std::errc{}) { return {}; } return value; } // std::invoke is not constexpr in c++17 namespace detail { template <class T> struct is_reference_wrapper: std::false_type {}; template <typename U> struct is_reference_wrapper<std::reference_wrapper<U>>: std::true_type {}; template <typename T> constexpr bool is_reference_wrapper_v = is_reference_wrapper<T>::value; template <typename T, typename Type, typename T1, typename... Args> constexpr decltype(auto) do_invoke(Type T::*f, T1 &&t1, Args &&... args) { if constexpr (std::is_member_function_pointer_v<decltype(f)>) { if constexpr (std::is_base_of_v<T, std::decay_t<T1>>) return (std::forward<T1>(t1).*f)(std::forward<Args>(args)...); else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>) return (t1.get().*f)(std::forward<Args>(args)...); else return ((*std::forward<T1>(t1)).*f)(std::forward<Args>(args)...); } else { static_assert(std::is_member_object_pointer_v<decltype(f)>); static_assert(sizeof...(args) == 0); if constexpr (std::is_base_of_v<T, std::decay_t<T1>>) return std::forward<T1>(t1).*f; else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>) return t1.get().*f; else return (*std::forward<T1>(t1)).*f; } } template <class F, class... Args> constexpr decltype(auto) do_invoke(F &&f, Args &&... args) { return std::forward<F>(f)(std::forward<Args>(args)...); } } // namespace detail template <class F, class... Args> constexpr std::invoke_result_t<F, Args...> invoke(F &&f, Args &&... args) noexcept(std::is_nothrow_invocable_v<F, Args...>) { return detail::do_invoke(std::forward<F>(f), std::forward<Args>(args)...); } // std::not_fn is not constexpr in c++17 namespace details { template <typename Func> struct not_fn_t { template <typename... Args> constexpr auto operator()(Args &&... args) & -> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func> &, Args...>>()) { return !utils::invoke(f, std::forward<Args>(args)...); } template <class... Args> constexpr auto operator()(Args &&... args) const & -> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func> const &, Args...>>()) { return !utils::invoke(f, std::forward<Args>(args)...); } template <class... Args> constexpr auto operator()(Args &&... args) && -> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func>, Args...>>()) { return !utils::invoke(std::move(f), std::forward<Args>(args)...); } template <class... Args> constexpr auto operator()(Args &&... args) const && -> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func> const, Args...>>()) { return !utils::invoke(std::move(f), std::forward<Args>(args)...); } Func f; }; } // namespace details template <typename Func> constexpr auto not_fn(Func &&f) noexcept { return details::not_fn_t<Func>{std::forward<Func>(f)}; } // std::is_sorted is not constexpr in c++17 template <typename ForwardIt, typename Compare> constexpr bool is_sorted(ForwardIt begin, ForwardIt end, Compare comp) { if (begin == end) { return true; } auto current = std::next(begin); auto previous = begin; while (current != end) { if (!comp(*previous++, *current++)) { return false; } } return true; } template <typename ForwardIt> constexpr bool is_sorted(ForwardIt begin, ForwardIt end) { return utils::is_sorted(begin, end, std::less<void>{}); } // std::unique is not constexpr in c++17 template <typename ForwardIt, typename Predicate> constexpr bool unique(ForwardIt begin, ForwardIt end, Predicate pred) { return utils::is_sorted(begin, end, utils::not_fn(pred)); } // std::unique is not constexpr in c++17 template <typename ForwardIt> constexpr bool unique(ForwardIt begin, ForwardIt end) { return utils::is_sorted(begin, end, utils::not_fn(std::equal_to<void>{})); } // checks that a collection contains all number sorted from 0 to max, exactly once template <typename T> constexpr bool has_all_sorted(const T &values, typename T::value_type max) { return values.size() == max + 1 && values.back() == max && utils::is_sorted(values.begin(), values.end()) && utils::unique(values.begin(), values.end()); } } // namespace utils #endif //NINJACLOWN_UTILS_UTILS_HPP
30.234637
130
0.68422
TiWinDeTea
936dc75b3cfc04cdf53f38c65ad4f277d5e998a9
1,513
cc
C++
skiko/src/commonMain/cpp/generated/PathSegmentIterator.cc
sellmair/skiko
9ccc6234799558386ccfa00630600e02c8eb62f9
[ "Apache-2.0" ]
842
2020-07-27T11:38:31.000Z
2022-03-30T17:37:21.000Z
skiko/src/commonMain/cpp/generated/PathSegmentIterator.cc
sellmair/skiko
9ccc6234799558386ccfa00630600e02c8eb62f9
[ "Apache-2.0" ]
127
2020-09-17T08:12:40.000Z
2022-03-31T08:56:56.000Z
skiko/src/commonMain/cpp/generated/PathSegmentIterator.cc
sellmair/skiko
9ccc6234799558386ccfa00630600e02c8eb62f9
[ "Apache-2.0" ]
49
2020-07-27T16:48:56.000Z
2022-03-24T14:15:33.000Z
#include "SkPath.h" #include "common.h" SKIKO_EXPORT KNativePointer org_jetbrains_skia_PathSegmentIterator__1nMake (KNativePointer pathPtr, KBoolean forceClose) { SkPath* path = reinterpret_cast<SkPath*>(pathPtr); SkPath::Iter* iter = new SkPath::Iter(*path, forceClose); return reinterpret_cast<KNativePointer>(iter); } static void deletePathSegmentIterator(SkPath::Iter* iter) { // std::cout << "Deleting [SkPathSegmentIterator " << path << "]" << std::endl; delete iter; } SKIKO_EXPORT KNativePointer org_jetbrains_skia_PathSegmentIterator__1nGetFinalizer() { return reinterpret_cast<KNativePointer>((&deletePathSegmentIterator)); } SKIKO_EXPORT void org_jetbrains_skia_PathSegmentIterator__1nNext(KNativePointer ptr, KInt* data) { SkPath::Iter* instance = reinterpret_cast<SkPath::Iter*>(ptr); SkPoint pts[4]; SkPath::Verb verb = instance->next(pts); data[0] = rawBits(pts[0].fX); data[1] = rawBits(pts[0].fY); data[2] = rawBits(pts[1].fX); data[3] = rawBits(pts[1].fY); data[4] = rawBits(pts[2].fX); data[5] = rawBits(pts[2].fY); data[6] = rawBits(pts[3].fX); data[7] = rawBits(pts[3].fY); // Otherwise it's null. if (verb == SkPath::Verb::kConic_Verb) data[8] = rawBits(instance->conicWeight()); int context = verb; if (instance -> isClosedContour()) { context = context | (1 << 7); } if (instance -> isCloseLine()) { context = context | (1 << 6); } data[9] = context; }
30.26
98
0.66226
sellmair
936f32f4905b9a290905efd784be3b3828368b0d
178,176
cc
C++
libcpp/Include/Proto/Qot_StockFilter.pb.cc
stephenlyu/gofutuapi
1a60310dd142ac7049c9ef9cf22c7d78d0f880ef
[ "MIT" ]
2
2020-11-27T04:53:13.000Z
2021-11-15T02:15:27.000Z
libcpp/Include/Proto/Qot_StockFilter.pb.cc
stephenlyu/gofutuapi
1a60310dd142ac7049c9ef9cf22c7d78d0f880ef
[ "MIT" ]
null
null
null
libcpp/Include/Proto/Qot_StockFilter.pb.cc
stephenlyu/gofutuapi
1a60310dd142ac7049c9ef9cf22c7d78d0f880ef
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Qot_StockFilter.proto #include "Qot_StockFilter.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace Qot_StockFilter { class BaseFilterDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BaseFilter> _instance; } _BaseFilter_default_instance_; class AccumulateFilterDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AccumulateFilter> _instance; } _AccumulateFilter_default_instance_; class FinancialFilterDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FinancialFilter> _instance; } _FinancialFilter_default_instance_; class BaseDataDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BaseData> _instance; } _BaseData_default_instance_; class AccumulateDataDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AccumulateData> _instance; } _AccumulateData_default_instance_; class FinancialDataDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FinancialData> _instance; } _FinancialData_default_instance_; class StockDataDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<StockData> _instance; } _StockData_default_instance_; class C2SDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<C2S> _instance; } _C2S_default_instance_; class S2CDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<S2C> _instance; } _S2C_default_instance_; class RequestDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Request> _instance; } _Request_default_instance_; class ResponseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Response> _instance; } _Response_default_instance_; } // namespace Qot_StockFilter namespace protobuf_Qot_5fStockFilter_2eproto { void InitDefaultsBaseFilterImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::Qot_StockFilter::_BaseFilter_default_instance_; new (ptr) ::Qot_StockFilter::BaseFilter(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::BaseFilter::InitAsDefaultInstance(); } void InitDefaultsBaseFilter() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBaseFilterImpl); } void InitDefaultsAccumulateFilterImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::Qot_StockFilter::_AccumulateFilter_default_instance_; new (ptr) ::Qot_StockFilter::AccumulateFilter(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::AccumulateFilter::InitAsDefaultInstance(); } void InitDefaultsAccumulateFilter() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAccumulateFilterImpl); } void InitDefaultsFinancialFilterImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::Qot_StockFilter::_FinancialFilter_default_instance_; new (ptr) ::Qot_StockFilter::FinancialFilter(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::FinancialFilter::InitAsDefaultInstance(); } void InitDefaultsFinancialFilter() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFinancialFilterImpl); } void InitDefaultsBaseDataImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::Qot_StockFilter::_BaseData_default_instance_; new (ptr) ::Qot_StockFilter::BaseData(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::BaseData::InitAsDefaultInstance(); } void InitDefaultsBaseData() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBaseDataImpl); } void InitDefaultsAccumulateDataImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::Qot_StockFilter::_AccumulateData_default_instance_; new (ptr) ::Qot_StockFilter::AccumulateData(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::AccumulateData::InitAsDefaultInstance(); } void InitDefaultsAccumulateData() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAccumulateDataImpl); } void InitDefaultsFinancialDataImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::Qot_StockFilter::_FinancialData_default_instance_; new (ptr) ::Qot_StockFilter::FinancialData(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::FinancialData::InitAsDefaultInstance(); } void InitDefaultsFinancialData() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFinancialDataImpl); } void InitDefaultsStockDataImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_Qot_5fCommon_2eproto::InitDefaultsSecurity(); protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseData(); protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateData(); protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialData(); { void* ptr = &::Qot_StockFilter::_StockData_default_instance_; new (ptr) ::Qot_StockFilter::StockData(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::StockData::InitAsDefaultInstance(); } void InitDefaultsStockData() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsStockDataImpl); } void InitDefaultsC2SImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_Qot_5fCommon_2eproto::InitDefaultsSecurity(); protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseFilter(); protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateFilter(); protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialFilter(); { void* ptr = &::Qot_StockFilter::_C2S_default_instance_; new (ptr) ::Qot_StockFilter::C2S(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::C2S::InitAsDefaultInstance(); } void InitDefaultsC2S() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsC2SImpl); } void InitDefaultsS2CImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_Qot_5fStockFilter_2eproto::InitDefaultsStockData(); { void* ptr = &::Qot_StockFilter::_S2C_default_instance_; new (ptr) ::Qot_StockFilter::S2C(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::S2C::InitAsDefaultInstance(); } void InitDefaultsS2C() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsS2CImpl); } void InitDefaultsRequestImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_Qot_5fStockFilter_2eproto::InitDefaultsC2S(); { void* ptr = &::Qot_StockFilter::_Request_default_instance_; new (ptr) ::Qot_StockFilter::Request(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::Request::InitAsDefaultInstance(); } void InitDefaultsRequest() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsRequestImpl); } void InitDefaultsResponseImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_Qot_5fStockFilter_2eproto::InitDefaultsS2C(); { void* ptr = &::Qot_StockFilter::_Response_default_instance_; new (ptr) ::Qot_StockFilter::Response(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Qot_StockFilter::Response::InitAsDefaultInstance(); } void InitDefaultsResponse() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsResponseImpl); } ::google::protobuf::Metadata file_level_metadata[11]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[5]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, field_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, filtermin_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, filtermax_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, isnofilter_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, sortdir_), 1, 0, 3, 2, 4, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, field_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, filtermin_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, filtermax_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, isnofilter_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, sortdir_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, days_), 1, 0, 3, 2, 4, 5, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, field_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, filtermin_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, filtermax_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, isnofilter_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, sortdir_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, quarter_), 1, 0, 3, 2, 4, 5, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, field_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, value_), 1, 0, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, field_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, value_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, days_), 1, 0, 2, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, field_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, value_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, quarter_), 1, 0, 2, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, security_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, basedatalist_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, accumulatedatalist_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, financialdatalist_), 1, 0, ~0u, ~0u, ~0u, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, begin_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, num_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, market_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, plate_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, basefilterlist_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, accumulatefilterlist_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, financialfilterlist_), 1, 2, 3, 0, ~0u, ~0u, ~0u, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, lastpage_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, allcount_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, datalist_), 0, 1, ~0u, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Request, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Request, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Request, c2s_), 0, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, rettype_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, retmsg_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, errcode_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, s2c_), 3, 0, 2, 1, }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, 10, sizeof(::Qot_StockFilter::BaseFilter)}, { 15, 26, sizeof(::Qot_StockFilter::AccumulateFilter)}, { 32, 43, sizeof(::Qot_StockFilter::FinancialFilter)}, { 49, 56, sizeof(::Qot_StockFilter::BaseData)}, { 58, 66, sizeof(::Qot_StockFilter::AccumulateData)}, { 69, 77, sizeof(::Qot_StockFilter::FinancialData)}, { 80, 90, sizeof(::Qot_StockFilter::StockData)}, { 95, 107, sizeof(::Qot_StockFilter::C2S)}, { 114, 122, sizeof(::Qot_StockFilter::S2C)}, { 125, 131, sizeof(::Qot_StockFilter::Request)}, { 132, 141, sizeof(::Qot_StockFilter::Response)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_BaseFilter_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_AccumulateFilter_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_FinancialFilter_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_BaseData_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_AccumulateData_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_FinancialData_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_StockData_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_C2S_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_S2C_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_Request_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_Response_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "Qot_StockFilter.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 11); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\025Qot_StockFilter.proto\022\017Qot_StockFilter" "\032\014Common.proto\032\020Qot_Common.proto\"f\n\nBase" "Filter\022\r\n\005field\030\001 \002(\005\022\021\n\tfilterMin\030\002 \001(\001" "\022\021\n\tfilterMax\030\003 \001(\001\022\022\n\nisNoFilter\030\004 \001(\010\022" "\017\n\007sortDir\030\005 \001(\005\"z\n\020AccumulateFilter\022\r\n\005" "field\030\001 \002(\005\022\021\n\tfilterMin\030\002 \001(\001\022\021\n\tfilter" "Max\030\003 \001(\001\022\022\n\nisNoFilter\030\004 \001(\010\022\017\n\007sortDir" "\030\005 \001(\005\022\014\n\004days\030\006 \002(\005\"|\n\017FinancialFilter\022" "\r\n\005field\030\001 \002(\005\022\021\n\tfilterMin\030\002 \001(\001\022\021\n\tfil" "terMax\030\003 \001(\001\022\022\n\nisNoFilter\030\004 \001(\010\022\017\n\007sort" "Dir\030\005 \001(\005\022\017\n\007quarter\030\006 \002(\005\"(\n\010BaseData\022\r" "\n\005field\030\001 \002(\005\022\r\n\005value\030\002 \002(\001\"<\n\016Accumula" "teData\022\r\n\005field\030\001 \002(\005\022\r\n\005value\030\002 \002(\001\022\014\n\004" "days\030\003 \002(\005\">\n\rFinancialData\022\r\n\005field\030\001 \002" "(\005\022\r\n\005value\030\002 \002(\001\022\017\n\007quarter\030\003 \002(\005\"\352\001\n\tS" "tockData\022&\n\010security\030\001 \002(\0132\024.Qot_Common." "Security\022\014\n\004name\030\002 \002(\t\022/\n\014baseDataList\030\003" " \003(\0132\031.Qot_StockFilter.BaseData\022;\n\022accum" "ulateDataList\030\004 \003(\0132\037.Qot_StockFilter.Ac" "cumulateData\0229\n\021financialDataList\030\005 \003(\0132" "\036.Qot_StockFilter.FinancialData\"\213\002\n\003C2S\022" "\r\n\005begin\030\001 \002(\005\022\013\n\003num\030\002 \002(\005\022\016\n\006market\030\003 " "\002(\005\022#\n\005plate\030\004 \001(\0132\024.Qot_Common.Security" "\0223\n\016baseFilterList\030\005 \003(\0132\033.Qot_StockFilt" "er.BaseFilter\022\?\n\024accumulateFilterList\030\006 " "\003(\0132!.Qot_StockFilter.AccumulateFilter\022=" "\n\023financialFilterList\030\007 \003(\0132 .Qot_StockF" "ilter.FinancialFilter\"W\n\003S2C\022\020\n\010lastPage" "\030\001 \002(\010\022\020\n\010allCount\030\002 \002(\005\022,\n\010dataList\030\003 \003" "(\0132\032.Qot_StockFilter.StockData\",\n\007Reques" "t\022!\n\003c2s\030\001 \002(\0132\024.Qot_StockFilter.C2S\"e\n\010" "Response\022\025\n\007retType\030\001 \002(\005:\004-400\022\016\n\006retMs" "g\030\002 \001(\t\022\017\n\007errCode\030\003 \001(\005\022!\n\003s2c\030\004 \001(\0132\024." "Qot_StockFilter.S2C*\234\004\n\nStockField\022\026\n\022St" "ockField_Unknown\020\000\022\030\n\024StockField_StockCo" "de\020\001\022\030\n\024StockField_StockName\020\002\022\027\n\023StockF" "ield_CurPrice\020\003\022,\n(StockField_CurPriceTo" "Highest52WeeksRatio\020\004\022+\n\'StockField_CurP" "riceToLowest52WeeksRatio\020\005\022-\n)StockField" "_HighPriceToHighest52WeeksRatio\020\006\022+\n\'Sto" "ckField_LowPriceToLowest52WeeksRatio\020\007\022\032" "\n\026StockField_VolumeRatio\020\010\022\032\n\026StockField" "_BidAskRatio\020\t\022\027\n\023StockField_LotPrice\020\n\022" "\030\n\024StockField_MarketVal\020\013\022\027\n\023StockField_" "PeAnnual\020\014\022\024\n\020StockField_PeTTM\020\r\022\025\n\021Stoc" "kField_PbRate\020\016\022\035\n\031StockField_ChangeRate" "5min\020\017\022\"\n\036StockField_ChangeRateBeginYear" "\020\020*\311\001\n\017AccumulateField\022\033\n\027AccumulateFiel" "d_Unknown\020\000\022\036\n\032AccumulateField_ChangeRat" "e\020\001\022\035\n\031AccumulateField_Amplitude\020\002\022\032\n\026Ac" "cumulateField_Volume\020\003\022\034\n\030AccumulateFiel" "d_Turnover\020\004\022 \n\034AccumulateField_Turnover" "Rate\020\005*\307\002\n\016FinancialField\022\032\n\026FinancialFi" "eld_Unknown\020\000\022\034\n\030FinancialField_NetProfi" "t\020\001\022\"\n\036FinancialField_NetProfitGrowth\020\002\022" " \n\034FinancialField_SumOfBusiness\020\003\022&\n\"Fin" "ancialField_SumOfBusinessGrowth\020\004\022 \n\034Fin" "ancialField_NetProfitRate\020\005\022\"\n\036Financial" "Field_GrossProfitRate\020\006\022 \n\034FinancialFiel" "d_DebtAssetRate\020\007\022%\n!FinancialField_Retu" "rnOnEquityRate\020\010*\331\001\n\020FinancialQuarter\022\034\n" "\030FinancialQuarter_Unknown\020\000\022\033\n\027Financial" "Quarter_Annual\020\001\022!\n\035FinancialQuarter_Fir" "stQuarter\020\002\022\034\n\030FinancialQuarter_Interim\020" "\003\022!\n\035FinancialQuarter_ThirdQuarter\020\004\022&\n\"" "FinancialQuarter_MostRecentQuarter\020\005*B\n\007" "SortDir\022\016\n\nSortDir_No\020\000\022\022\n\016SortDir_Ascen" "d\020\001\022\023\n\017SortDir_Descend\020\002B\025\n\023com.futu.ope" "napi.pb" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 2727); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "Qot_StockFilter.proto", &protobuf_RegisterTypes); ::protobuf_Common_2eproto::AddDescriptors(); ::protobuf_Qot_5fCommon_2eproto::AddDescriptors(); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_Qot_5fStockFilter_2eproto namespace Qot_StockFilter { const ::google::protobuf::EnumDescriptor* StockField_descriptor() { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[0]; } bool StockField_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: return true; default: return false; } } const ::google::protobuf::EnumDescriptor* AccumulateField_descriptor() { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[1]; } bool AccumulateField_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: return true; default: return false; } } const ::google::protobuf::EnumDescriptor* FinancialField_descriptor() { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[2]; } bool FinancialField_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: return true; default: return false; } } const ::google::protobuf::EnumDescriptor* FinancialQuarter_descriptor() { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[3]; } bool FinancialQuarter_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: return true; default: return false; } } const ::google::protobuf::EnumDescriptor* SortDir_descriptor() { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[4]; } bool SortDir_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } // =================================================================== void BaseFilter::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BaseFilter::kFieldFieldNumber; const int BaseFilter::kFilterMinFieldNumber; const int BaseFilter::kFilterMaxFieldNumber; const int BaseFilter::kIsNoFilterFieldNumber; const int BaseFilter::kSortDirFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BaseFilter::BaseFilter() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseFilter(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.BaseFilter) } BaseFilter::BaseFilter(const BaseFilter& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&filtermin_, &from.filtermin_, static_cast<size_t>(reinterpret_cast<char*>(&sortdir_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(sortdir_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.BaseFilter) } void BaseFilter::SharedCtor() { _cached_size_ = 0; ::memset(&filtermin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&sortdir_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(sortdir_)); } BaseFilter::~BaseFilter() { // @@protoc_insertion_point(destructor:Qot_StockFilter.BaseFilter) SharedDtor(); } void BaseFilter::SharedDtor() { } void BaseFilter::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* BaseFilter::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const BaseFilter& BaseFilter::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseFilter(); return *internal_default_instance(); } BaseFilter* BaseFilter::New(::google::protobuf::Arena* arena) const { BaseFilter* n = new BaseFilter; if (arena != NULL) { arena->Own(n); } return n; } void BaseFilter::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.BaseFilter) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 31u) { ::memset(&filtermin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&sortdir_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(sortdir_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool BaseFilter::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.BaseFilter) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 field = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_field(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &field_))); } else { goto handle_unusual; } break; } // optional double filterMin = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { set_has_filtermin(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &filtermin_))); } else { goto handle_unusual; } break; } // optional double filterMax = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) { set_has_filtermax(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &filtermax_))); } else { goto handle_unusual; } break; } // optional bool isNoFilter = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { set_has_isnofilter(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &isnofilter_))); } else { goto handle_unusual; } break; } // optional int32 sortDir = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { set_has_sortdir(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &sortdir_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.BaseFilter) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.BaseFilter) return false; #undef DO_ } void BaseFilter::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.BaseFilter) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output); } // optional double filterMin = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->filtermin(), output); } // optional double filterMax = 3; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->filtermax(), output); } // optional bool isNoFilter = 4; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->isnofilter(), output); } // optional int32 sortDir = 5; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->sortdir(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.BaseFilter) } ::google::protobuf::uint8* BaseFilter::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.BaseFilter) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target); } // optional double filterMin = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->filtermin(), target); } // optional double filterMax = 3; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->filtermax(), target); } // optional bool isNoFilter = 4; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->isnofilter(), target); } // optional int32 sortDir = 5; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->sortdir(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.BaseFilter) return target; } size_t BaseFilter::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.BaseFilter) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } // required int32 field = 1; if (has_field()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); } // optional double filterMin = 2; if (has_filtermin()) { total_size += 1 + 8; } if (_has_bits_[0 / 32] & 28u) { // optional bool isNoFilter = 4; if (has_isnofilter()) { total_size += 1 + 1; } // optional double filterMax = 3; if (has_filtermax()) { total_size += 1 + 8; } // optional int32 sortDir = 5; if (has_sortdir()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->sortdir()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void BaseFilter::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.BaseFilter) GOOGLE_DCHECK_NE(&from, this); const BaseFilter* source = ::google::protobuf::internal::DynamicCastToGenerated<const BaseFilter>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.BaseFilter) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.BaseFilter) MergeFrom(*source); } } void BaseFilter::MergeFrom(const BaseFilter& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.BaseFilter) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 31u) { if (cached_has_bits & 0x00000001u) { filtermin_ = from.filtermin_; } if (cached_has_bits & 0x00000002u) { field_ = from.field_; } if (cached_has_bits & 0x00000004u) { isnofilter_ = from.isnofilter_; } if (cached_has_bits & 0x00000008u) { filtermax_ = from.filtermax_; } if (cached_has_bits & 0x00000010u) { sortdir_ = from.sortdir_; } _has_bits_[0] |= cached_has_bits; } } void BaseFilter::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.BaseFilter) if (&from == this) return; Clear(); MergeFrom(from); } void BaseFilter::CopyFrom(const BaseFilter& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.BaseFilter) if (&from == this) return; Clear(); MergeFrom(from); } bool BaseFilter::IsInitialized() const { if ((_has_bits_[0] & 0x00000002) != 0x00000002) return false; return true; } void BaseFilter::Swap(BaseFilter* other) { if (other == this) return; InternalSwap(other); } void BaseFilter::InternalSwap(BaseFilter* other) { using std::swap; swap(filtermin_, other->filtermin_); swap(field_, other->field_); swap(isnofilter_, other->isnofilter_); swap(filtermax_, other->filtermax_); swap(sortdir_, other->sortdir_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata BaseFilter::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void AccumulateFilter::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int AccumulateFilter::kFieldFieldNumber; const int AccumulateFilter::kFilterMinFieldNumber; const int AccumulateFilter::kFilterMaxFieldNumber; const int AccumulateFilter::kIsNoFilterFieldNumber; const int AccumulateFilter::kSortDirFieldNumber; const int AccumulateFilter::kDaysFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 AccumulateFilter::AccumulateFilter() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateFilter(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.AccumulateFilter) } AccumulateFilter::AccumulateFilter(const AccumulateFilter& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&filtermin_, &from.filtermin_, static_cast<size_t>(reinterpret_cast<char*>(&days_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(days_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.AccumulateFilter) } void AccumulateFilter::SharedCtor() { _cached_size_ = 0; ::memset(&filtermin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&days_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(days_)); } AccumulateFilter::~AccumulateFilter() { // @@protoc_insertion_point(destructor:Qot_StockFilter.AccumulateFilter) SharedDtor(); } void AccumulateFilter::SharedDtor() { } void AccumulateFilter::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* AccumulateFilter::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const AccumulateFilter& AccumulateFilter::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateFilter(); return *internal_default_instance(); } AccumulateFilter* AccumulateFilter::New(::google::protobuf::Arena* arena) const { AccumulateFilter* n = new AccumulateFilter; if (arena != NULL) { arena->Own(n); } return n; } void AccumulateFilter::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.AccumulateFilter) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 63u) { ::memset(&filtermin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&days_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(days_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool AccumulateFilter::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.AccumulateFilter) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 field = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_field(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &field_))); } else { goto handle_unusual; } break; } // optional double filterMin = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { set_has_filtermin(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &filtermin_))); } else { goto handle_unusual; } break; } // optional double filterMax = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) { set_has_filtermax(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &filtermax_))); } else { goto handle_unusual; } break; } // optional bool isNoFilter = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { set_has_isnofilter(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &isnofilter_))); } else { goto handle_unusual; } break; } // optional int32 sortDir = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { set_has_sortdir(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &sortdir_))); } else { goto handle_unusual; } break; } // required int32 days = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { set_has_days(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &days_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.AccumulateFilter) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.AccumulateFilter) return false; #undef DO_ } void AccumulateFilter::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.AccumulateFilter) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output); } // optional double filterMin = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->filtermin(), output); } // optional double filterMax = 3; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->filtermax(), output); } // optional bool isNoFilter = 4; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->isnofilter(), output); } // optional int32 sortDir = 5; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->sortdir(), output); } // required int32 days = 6; if (cached_has_bits & 0x00000020u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->days(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.AccumulateFilter) } ::google::protobuf::uint8* AccumulateFilter::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.AccumulateFilter) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target); } // optional double filterMin = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->filtermin(), target); } // optional double filterMax = 3; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->filtermax(), target); } // optional bool isNoFilter = 4; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->isnofilter(), target); } // optional int32 sortDir = 5; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->sortdir(), target); } // required int32 days = 6; if (cached_has_bits & 0x00000020u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->days(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.AccumulateFilter) return target; } size_t AccumulateFilter::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.AccumulateFilter) size_t total_size = 0; if (has_field()) { // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); } if (has_days()) { // required int32 days = 6; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->days()); } return total_size; } size_t AccumulateFilter::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.AccumulateFilter) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000022) ^ 0x00000022) == 0) { // All required fields are present. // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); // required int32 days = 6; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->days()); } else { total_size += RequiredFieldsByteSizeFallback(); } // optional double filterMin = 2; if (has_filtermin()) { total_size += 1 + 8; } if (_has_bits_[0 / 32] & 28u) { // optional bool isNoFilter = 4; if (has_isnofilter()) { total_size += 1 + 1; } // optional double filterMax = 3; if (has_filtermax()) { total_size += 1 + 8; } // optional int32 sortDir = 5; if (has_sortdir()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->sortdir()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void AccumulateFilter::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.AccumulateFilter) GOOGLE_DCHECK_NE(&from, this); const AccumulateFilter* source = ::google::protobuf::internal::DynamicCastToGenerated<const AccumulateFilter>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.AccumulateFilter) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.AccumulateFilter) MergeFrom(*source); } } void AccumulateFilter::MergeFrom(const AccumulateFilter& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.AccumulateFilter) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 63u) { if (cached_has_bits & 0x00000001u) { filtermin_ = from.filtermin_; } if (cached_has_bits & 0x00000002u) { field_ = from.field_; } if (cached_has_bits & 0x00000004u) { isnofilter_ = from.isnofilter_; } if (cached_has_bits & 0x00000008u) { filtermax_ = from.filtermax_; } if (cached_has_bits & 0x00000010u) { sortdir_ = from.sortdir_; } if (cached_has_bits & 0x00000020u) { days_ = from.days_; } _has_bits_[0] |= cached_has_bits; } } void AccumulateFilter::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.AccumulateFilter) if (&from == this) return; Clear(); MergeFrom(from); } void AccumulateFilter::CopyFrom(const AccumulateFilter& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.AccumulateFilter) if (&from == this) return; Clear(); MergeFrom(from); } bool AccumulateFilter::IsInitialized() const { if ((_has_bits_[0] & 0x00000022) != 0x00000022) return false; return true; } void AccumulateFilter::Swap(AccumulateFilter* other) { if (other == this) return; InternalSwap(other); } void AccumulateFilter::InternalSwap(AccumulateFilter* other) { using std::swap; swap(filtermin_, other->filtermin_); swap(field_, other->field_); swap(isnofilter_, other->isnofilter_); swap(filtermax_, other->filtermax_); swap(sortdir_, other->sortdir_); swap(days_, other->days_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata AccumulateFilter::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void FinancialFilter::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FinancialFilter::kFieldFieldNumber; const int FinancialFilter::kFilterMinFieldNumber; const int FinancialFilter::kFilterMaxFieldNumber; const int FinancialFilter::kIsNoFilterFieldNumber; const int FinancialFilter::kSortDirFieldNumber; const int FinancialFilter::kQuarterFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FinancialFilter::FinancialFilter() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialFilter(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.FinancialFilter) } FinancialFilter::FinancialFilter(const FinancialFilter& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&filtermin_, &from.filtermin_, static_cast<size_t>(reinterpret_cast<char*>(&quarter_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(quarter_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.FinancialFilter) } void FinancialFilter::SharedCtor() { _cached_size_ = 0; ::memset(&filtermin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&quarter_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(quarter_)); } FinancialFilter::~FinancialFilter() { // @@protoc_insertion_point(destructor:Qot_StockFilter.FinancialFilter) SharedDtor(); } void FinancialFilter::SharedDtor() { } void FinancialFilter::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* FinancialFilter::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const FinancialFilter& FinancialFilter::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialFilter(); return *internal_default_instance(); } FinancialFilter* FinancialFilter::New(::google::protobuf::Arena* arena) const { FinancialFilter* n = new FinancialFilter; if (arena != NULL) { arena->Own(n); } return n; } void FinancialFilter::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.FinancialFilter) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 63u) { ::memset(&filtermin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&quarter_) - reinterpret_cast<char*>(&filtermin_)) + sizeof(quarter_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool FinancialFilter::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.FinancialFilter) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 field = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_field(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &field_))); } else { goto handle_unusual; } break; } // optional double filterMin = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { set_has_filtermin(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &filtermin_))); } else { goto handle_unusual; } break; } // optional double filterMax = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) { set_has_filtermax(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &filtermax_))); } else { goto handle_unusual; } break; } // optional bool isNoFilter = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { set_has_isnofilter(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &isnofilter_))); } else { goto handle_unusual; } break; } // optional int32 sortDir = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { set_has_sortdir(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &sortdir_))); } else { goto handle_unusual; } break; } // required int32 quarter = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { set_has_quarter(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &quarter_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.FinancialFilter) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.FinancialFilter) return false; #undef DO_ } void FinancialFilter::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.FinancialFilter) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output); } // optional double filterMin = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->filtermin(), output); } // optional double filterMax = 3; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->filtermax(), output); } // optional bool isNoFilter = 4; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->isnofilter(), output); } // optional int32 sortDir = 5; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->sortdir(), output); } // required int32 quarter = 6; if (cached_has_bits & 0x00000020u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->quarter(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.FinancialFilter) } ::google::protobuf::uint8* FinancialFilter::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.FinancialFilter) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target); } // optional double filterMin = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->filtermin(), target); } // optional double filterMax = 3; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->filtermax(), target); } // optional bool isNoFilter = 4; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->isnofilter(), target); } // optional int32 sortDir = 5; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->sortdir(), target); } // required int32 quarter = 6; if (cached_has_bits & 0x00000020u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->quarter(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.FinancialFilter) return target; } size_t FinancialFilter::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.FinancialFilter) size_t total_size = 0; if (has_field()) { // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); } if (has_quarter()) { // required int32 quarter = 6; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->quarter()); } return total_size; } size_t FinancialFilter::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.FinancialFilter) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000022) ^ 0x00000022) == 0) { // All required fields are present. // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); // required int32 quarter = 6; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->quarter()); } else { total_size += RequiredFieldsByteSizeFallback(); } // optional double filterMin = 2; if (has_filtermin()) { total_size += 1 + 8; } if (_has_bits_[0 / 32] & 28u) { // optional bool isNoFilter = 4; if (has_isnofilter()) { total_size += 1 + 1; } // optional double filterMax = 3; if (has_filtermax()) { total_size += 1 + 8; } // optional int32 sortDir = 5; if (has_sortdir()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->sortdir()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void FinancialFilter::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.FinancialFilter) GOOGLE_DCHECK_NE(&from, this); const FinancialFilter* source = ::google::protobuf::internal::DynamicCastToGenerated<const FinancialFilter>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.FinancialFilter) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.FinancialFilter) MergeFrom(*source); } } void FinancialFilter::MergeFrom(const FinancialFilter& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.FinancialFilter) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 63u) { if (cached_has_bits & 0x00000001u) { filtermin_ = from.filtermin_; } if (cached_has_bits & 0x00000002u) { field_ = from.field_; } if (cached_has_bits & 0x00000004u) { isnofilter_ = from.isnofilter_; } if (cached_has_bits & 0x00000008u) { filtermax_ = from.filtermax_; } if (cached_has_bits & 0x00000010u) { sortdir_ = from.sortdir_; } if (cached_has_bits & 0x00000020u) { quarter_ = from.quarter_; } _has_bits_[0] |= cached_has_bits; } } void FinancialFilter::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.FinancialFilter) if (&from == this) return; Clear(); MergeFrom(from); } void FinancialFilter::CopyFrom(const FinancialFilter& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.FinancialFilter) if (&from == this) return; Clear(); MergeFrom(from); } bool FinancialFilter::IsInitialized() const { if ((_has_bits_[0] & 0x00000022) != 0x00000022) return false; return true; } void FinancialFilter::Swap(FinancialFilter* other) { if (other == this) return; InternalSwap(other); } void FinancialFilter::InternalSwap(FinancialFilter* other) { using std::swap; swap(filtermin_, other->filtermin_); swap(field_, other->field_); swap(isnofilter_, other->isnofilter_); swap(filtermax_, other->filtermax_); swap(sortdir_, other->sortdir_); swap(quarter_, other->quarter_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FinancialFilter::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void BaseData::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BaseData::kFieldFieldNumber; const int BaseData::kValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BaseData::BaseData() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseData(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.BaseData) } BaseData::BaseData(const BaseData& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&value_, &from.value_, static_cast<size_t>(reinterpret_cast<char*>(&field_) - reinterpret_cast<char*>(&value_)) + sizeof(field_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.BaseData) } void BaseData::SharedCtor() { _cached_size_ = 0; ::memset(&value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&field_) - reinterpret_cast<char*>(&value_)) + sizeof(field_)); } BaseData::~BaseData() { // @@protoc_insertion_point(destructor:Qot_StockFilter.BaseData) SharedDtor(); } void BaseData::SharedDtor() { } void BaseData::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* BaseData::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const BaseData& BaseData::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseData(); return *internal_default_instance(); } BaseData* BaseData::New(::google::protobuf::Arena* arena) const { BaseData* n = new BaseData; if (arena != NULL) { arena->Own(n); } return n; } void BaseData::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.BaseData) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { ::memset(&value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&field_) - reinterpret_cast<char*>(&value_)) + sizeof(field_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool BaseData::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.BaseData) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 field = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_field(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &field_))); } else { goto handle_unusual; } break; } // required double value = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { set_has_value(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &value_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.BaseData) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.BaseData) return false; #undef DO_ } void BaseData::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.BaseData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output); } // required double value = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.BaseData) } ::google::protobuf::uint8* BaseData::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.BaseData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target); } // required double value = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.BaseData) return target; } size_t BaseData::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.BaseData) size_t total_size = 0; if (has_value()) { // required double value = 2; total_size += 1 + 8; } if (has_field()) { // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); } return total_size; } size_t BaseData::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.BaseData) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required double value = 2; total_size += 1 + 8; // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); } else { total_size += RequiredFieldsByteSizeFallback(); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void BaseData::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.BaseData) GOOGLE_DCHECK_NE(&from, this); const BaseData* source = ::google::protobuf::internal::DynamicCastToGenerated<const BaseData>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.BaseData) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.BaseData) MergeFrom(*source); } } void BaseData::MergeFrom(const BaseData& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.BaseData) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { value_ = from.value_; } if (cached_has_bits & 0x00000002u) { field_ = from.field_; } _has_bits_[0] |= cached_has_bits; } } void BaseData::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.BaseData) if (&from == this) return; Clear(); MergeFrom(from); } void BaseData::CopyFrom(const BaseData& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.BaseData) if (&from == this) return; Clear(); MergeFrom(from); } bool BaseData::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; return true; } void BaseData::Swap(BaseData* other) { if (other == this) return; InternalSwap(other); } void BaseData::InternalSwap(BaseData* other) { using std::swap; swap(value_, other->value_); swap(field_, other->field_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata BaseData::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void AccumulateData::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int AccumulateData::kFieldFieldNumber; const int AccumulateData::kValueFieldNumber; const int AccumulateData::kDaysFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 AccumulateData::AccumulateData() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateData(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.AccumulateData) } AccumulateData::AccumulateData(const AccumulateData& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&value_, &from.value_, static_cast<size_t>(reinterpret_cast<char*>(&days_) - reinterpret_cast<char*>(&value_)) + sizeof(days_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.AccumulateData) } void AccumulateData::SharedCtor() { _cached_size_ = 0; ::memset(&value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&days_) - reinterpret_cast<char*>(&value_)) + sizeof(days_)); } AccumulateData::~AccumulateData() { // @@protoc_insertion_point(destructor:Qot_StockFilter.AccumulateData) SharedDtor(); } void AccumulateData::SharedDtor() { } void AccumulateData::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* AccumulateData::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const AccumulateData& AccumulateData::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateData(); return *internal_default_instance(); } AccumulateData* AccumulateData::New(::google::protobuf::Arena* arena) const { AccumulateData* n = new AccumulateData; if (arena != NULL) { arena->Own(n); } return n; } void AccumulateData::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.AccumulateData) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 7u) { ::memset(&value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&days_) - reinterpret_cast<char*>(&value_)) + sizeof(days_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool AccumulateData::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.AccumulateData) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 field = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_field(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &field_))); } else { goto handle_unusual; } break; } // required double value = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { set_has_value(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &value_))); } else { goto handle_unusual; } break; } // required int32 days = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { set_has_days(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &days_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.AccumulateData) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.AccumulateData) return false; #undef DO_ } void AccumulateData::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.AccumulateData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output); } // required double value = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output); } // required int32 days = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->days(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.AccumulateData) } ::google::protobuf::uint8* AccumulateData::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.AccumulateData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target); } // required double value = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target); } // required int32 days = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->days(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.AccumulateData) return target; } size_t AccumulateData::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.AccumulateData) size_t total_size = 0; if (has_value()) { // required double value = 2; total_size += 1 + 8; } if (has_field()) { // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); } if (has_days()) { // required int32 days = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->days()); } return total_size; } size_t AccumulateData::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.AccumulateData) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required double value = 2; total_size += 1 + 8; // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); // required int32 days = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->days()); } else { total_size += RequiredFieldsByteSizeFallback(); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void AccumulateData::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.AccumulateData) GOOGLE_DCHECK_NE(&from, this); const AccumulateData* source = ::google::protobuf::internal::DynamicCastToGenerated<const AccumulateData>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.AccumulateData) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.AccumulateData) MergeFrom(*source); } } void AccumulateData::MergeFrom(const AccumulateData& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.AccumulateData) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { value_ = from.value_; } if (cached_has_bits & 0x00000002u) { field_ = from.field_; } if (cached_has_bits & 0x00000004u) { days_ = from.days_; } _has_bits_[0] |= cached_has_bits; } } void AccumulateData::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.AccumulateData) if (&from == this) return; Clear(); MergeFrom(from); } void AccumulateData::CopyFrom(const AccumulateData& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.AccumulateData) if (&from == this) return; Clear(); MergeFrom(from); } bool AccumulateData::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; return true; } void AccumulateData::Swap(AccumulateData* other) { if (other == this) return; InternalSwap(other); } void AccumulateData::InternalSwap(AccumulateData* other) { using std::swap; swap(value_, other->value_); swap(field_, other->field_); swap(days_, other->days_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata AccumulateData::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void FinancialData::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FinancialData::kFieldFieldNumber; const int FinancialData::kValueFieldNumber; const int FinancialData::kQuarterFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FinancialData::FinancialData() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialData(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.FinancialData) } FinancialData::FinancialData(const FinancialData& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&value_, &from.value_, static_cast<size_t>(reinterpret_cast<char*>(&quarter_) - reinterpret_cast<char*>(&value_)) + sizeof(quarter_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.FinancialData) } void FinancialData::SharedCtor() { _cached_size_ = 0; ::memset(&value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&quarter_) - reinterpret_cast<char*>(&value_)) + sizeof(quarter_)); } FinancialData::~FinancialData() { // @@protoc_insertion_point(destructor:Qot_StockFilter.FinancialData) SharedDtor(); } void FinancialData::SharedDtor() { } void FinancialData::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* FinancialData::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const FinancialData& FinancialData::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialData(); return *internal_default_instance(); } FinancialData* FinancialData::New(::google::protobuf::Arena* arena) const { FinancialData* n = new FinancialData; if (arena != NULL) { arena->Own(n); } return n; } void FinancialData::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.FinancialData) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 7u) { ::memset(&value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&quarter_) - reinterpret_cast<char*>(&value_)) + sizeof(quarter_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool FinancialData::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.FinancialData) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 field = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_field(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &field_))); } else { goto handle_unusual; } break; } // required double value = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { set_has_value(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &value_))); } else { goto handle_unusual; } break; } // required int32 quarter = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { set_has_quarter(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &quarter_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.FinancialData) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.FinancialData) return false; #undef DO_ } void FinancialData::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.FinancialData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output); } // required double value = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output); } // required int32 quarter = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->quarter(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.FinancialData) } ::google::protobuf::uint8* FinancialData::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.FinancialData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 field = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target); } // required double value = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target); } // required int32 quarter = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->quarter(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.FinancialData) return target; } size_t FinancialData::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.FinancialData) size_t total_size = 0; if (has_value()) { // required double value = 2; total_size += 1 + 8; } if (has_field()) { // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); } if (has_quarter()) { // required int32 quarter = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->quarter()); } return total_size; } size_t FinancialData::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.FinancialData) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required double value = 2; total_size += 1 + 8; // required int32 field = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->field()); // required int32 quarter = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->quarter()); } else { total_size += RequiredFieldsByteSizeFallback(); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void FinancialData::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.FinancialData) GOOGLE_DCHECK_NE(&from, this); const FinancialData* source = ::google::protobuf::internal::DynamicCastToGenerated<const FinancialData>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.FinancialData) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.FinancialData) MergeFrom(*source); } } void FinancialData::MergeFrom(const FinancialData& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.FinancialData) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { value_ = from.value_; } if (cached_has_bits & 0x00000002u) { field_ = from.field_; } if (cached_has_bits & 0x00000004u) { quarter_ = from.quarter_; } _has_bits_[0] |= cached_has_bits; } } void FinancialData::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.FinancialData) if (&from == this) return; Clear(); MergeFrom(from); } void FinancialData::CopyFrom(const FinancialData& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.FinancialData) if (&from == this) return; Clear(); MergeFrom(from); } bool FinancialData::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; return true; } void FinancialData::Swap(FinancialData* other) { if (other == this) return; InternalSwap(other); } void FinancialData::InternalSwap(FinancialData* other) { using std::swap; swap(value_, other->value_); swap(field_, other->field_); swap(quarter_, other->quarter_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FinancialData::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void StockData::InitAsDefaultInstance() { ::Qot_StockFilter::_StockData_default_instance_._instance.get_mutable()->security_ = const_cast< ::Qot_Common::Security*>( ::Qot_Common::Security::internal_default_instance()); } void StockData::clear_security() { if (security_ != NULL) security_->Clear(); clear_has_security(); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int StockData::kSecurityFieldNumber; const int StockData::kNameFieldNumber; const int StockData::kBaseDataListFieldNumber; const int StockData::kAccumulateDataListFieldNumber; const int StockData::kFinancialDataListFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 StockData::StockData() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsStockData(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.StockData) } StockData::StockData(const StockData& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), basedatalist_(from.basedatalist_), accumulatedatalist_(from.accumulatedatalist_), financialdatalist_(from.financialdatalist_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } if (from.has_security()) { security_ = new ::Qot_Common::Security(*from.security_); } else { security_ = NULL; } // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.StockData) } void StockData::SharedCtor() { _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); security_ = NULL; } StockData::~StockData() { // @@protoc_insertion_point(destructor:Qot_StockFilter.StockData) SharedDtor(); } void StockData::SharedDtor() { name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete security_; } void StockData::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* StockData::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const StockData& StockData::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsStockData(); return *internal_default_instance(); } StockData* StockData::New(::google::protobuf::Arena* arena) const { StockData* n = new StockData; if (arena != NULL) { arena->Own(n); } return n; } void StockData::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.StockData) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; basedatalist_.Clear(); accumulatedatalist_.Clear(); financialdatalist_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); (*name_.UnsafeRawStringPointer())->clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(security_ != NULL); security_->Clear(); } } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool StockData::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.StockData) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required .Qot_Common.Security security = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_security())); } else { goto handle_unusual; } break; } // required string name = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormat::PARSE, "Qot_StockFilter.StockData.name"); } else { goto handle_unusual; } break; } // repeated .Qot_StockFilter.BaseData baseDataList = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_basedatalist())); } else { goto handle_unusual; } break; } // repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_accumulatedatalist())); } else { goto handle_unusual; } break; } // repeated .Qot_StockFilter.FinancialData financialDataList = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_financialdatalist())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.StockData) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.StockData) return false; #undef DO_ } void StockData::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.StockData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required .Qot_Common.Security security = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->security_, output); } // required string name = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "Qot_StockFilter.StockData.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->name(), output); } // repeated .Qot_StockFilter.BaseData baseDataList = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->basedatalist_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->basedatalist(static_cast<int>(i)), output); } // repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4; for (unsigned int i = 0, n = static_cast<unsigned int>(this->accumulatedatalist_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->accumulatedatalist(static_cast<int>(i)), output); } // repeated .Qot_StockFilter.FinancialData financialDataList = 5; for (unsigned int i = 0, n = static_cast<unsigned int>(this->financialdatalist_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->financialdatalist(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.StockData) } ::google::protobuf::uint8* StockData::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.StockData) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required .Qot_Common.Security security = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, *this->security_, deterministic, target); } // required string name = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "Qot_StockFilter.StockData.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->name(), target); } // repeated .Qot_StockFilter.BaseData baseDataList = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->basedatalist_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->basedatalist(static_cast<int>(i)), deterministic, target); } // repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4; for (unsigned int i = 0, n = static_cast<unsigned int>(this->accumulatedatalist_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, this->accumulatedatalist(static_cast<int>(i)), deterministic, target); } // repeated .Qot_StockFilter.FinancialData financialDataList = 5; for (unsigned int i = 0, n = static_cast<unsigned int>(this->financialdatalist_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 5, this->financialdatalist(static_cast<int>(i)), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.StockData) return target; } size_t StockData::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.StockData) size_t total_size = 0; if (has_name()) { // required string name = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } if (has_security()) { // required .Qot_Common.Security security = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *this->security_); } return total_size; } size_t StockData::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.StockData) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required string name = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); // required .Qot_Common.Security security = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *this->security_); } else { total_size += RequiredFieldsByteSizeFallback(); } // repeated .Qot_StockFilter.BaseData baseDataList = 3; { unsigned int count = static_cast<unsigned int>(this->basedatalist_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->basedatalist(static_cast<int>(i))); } } // repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4; { unsigned int count = static_cast<unsigned int>(this->accumulatedatalist_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->accumulatedatalist(static_cast<int>(i))); } } // repeated .Qot_StockFilter.FinancialData financialDataList = 5; { unsigned int count = static_cast<unsigned int>(this->financialdatalist_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->financialdatalist(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void StockData::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.StockData) GOOGLE_DCHECK_NE(&from, this); const StockData* source = ::google::protobuf::internal::DynamicCastToGenerated<const StockData>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.StockData) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.StockData) MergeFrom(*source); } } void StockData::MergeFrom(const StockData& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.StockData) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; basedatalist_.MergeFrom(from.basedatalist_); accumulatedatalist_.MergeFrom(from.accumulatedatalist_); financialdatalist_.MergeFrom(from.financialdatalist_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { set_has_name(); name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } if (cached_has_bits & 0x00000002u) { mutable_security()->::Qot_Common::Security::MergeFrom(from.security()); } } } void StockData::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.StockData) if (&from == this) return; Clear(); MergeFrom(from); } void StockData::CopyFrom(const StockData& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.StockData) if (&from == this) return; Clear(); MergeFrom(from); } bool StockData::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; if (!::google::protobuf::internal::AllAreInitialized(this->basedatalist())) return false; if (!::google::protobuf::internal::AllAreInitialized(this->accumulatedatalist())) return false; if (!::google::protobuf::internal::AllAreInitialized(this->financialdatalist())) return false; if (has_security()) { if (!this->security_->IsInitialized()) return false; } return true; } void StockData::Swap(StockData* other) { if (other == this) return; InternalSwap(other); } void StockData::InternalSwap(StockData* other) { using std::swap; basedatalist_.InternalSwap(&other->basedatalist_); accumulatedatalist_.InternalSwap(&other->accumulatedatalist_); financialdatalist_.InternalSwap(&other->financialdatalist_); name_.Swap(&other->name_); swap(security_, other->security_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata StockData::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void C2S::InitAsDefaultInstance() { ::Qot_StockFilter::_C2S_default_instance_._instance.get_mutable()->plate_ = const_cast< ::Qot_Common::Security*>( ::Qot_Common::Security::internal_default_instance()); } void C2S::clear_plate() { if (plate_ != NULL) plate_->Clear(); clear_has_plate(); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int C2S::kBeginFieldNumber; const int C2S::kNumFieldNumber; const int C2S::kMarketFieldNumber; const int C2S::kPlateFieldNumber; const int C2S::kBaseFilterListFieldNumber; const int C2S::kAccumulateFilterListFieldNumber; const int C2S::kFinancialFilterListFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 C2S::C2S() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsC2S(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.C2S) } C2S::C2S(const C2S& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), basefilterlist_(from.basefilterlist_), accumulatefilterlist_(from.accumulatefilterlist_), financialfilterlist_(from.financialfilterlist_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_plate()) { plate_ = new ::Qot_Common::Security(*from.plate_); } else { plate_ = NULL; } ::memcpy(&begin_, &from.begin_, static_cast<size_t>(reinterpret_cast<char*>(&market_) - reinterpret_cast<char*>(&begin_)) + sizeof(market_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.C2S) } void C2S::SharedCtor() { _cached_size_ = 0; ::memset(&plate_, 0, static_cast<size_t>( reinterpret_cast<char*>(&market_) - reinterpret_cast<char*>(&plate_)) + sizeof(market_)); } C2S::~C2S() { // @@protoc_insertion_point(destructor:Qot_StockFilter.C2S) SharedDtor(); } void C2S::SharedDtor() { if (this != internal_default_instance()) delete plate_; } void C2S::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* C2S::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const C2S& C2S::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsC2S(); return *internal_default_instance(); } C2S* C2S::New(::google::protobuf::Arena* arena) const { C2S* n = new C2S; if (arena != NULL) { arena->Own(n); } return n; } void C2S::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.C2S) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; basefilterlist_.Clear(); accumulatefilterlist_.Clear(); financialfilterlist_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(plate_ != NULL); plate_->Clear(); } if (cached_has_bits & 14u) { ::memset(&begin_, 0, static_cast<size_t>( reinterpret_cast<char*>(&market_) - reinterpret_cast<char*>(&begin_)) + sizeof(market_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool C2S::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.C2S) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 begin = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_begin(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &begin_))); } else { goto handle_unusual; } break; } // required int32 num = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { set_has_num(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &num_))); } else { goto handle_unusual; } break; } // required int32 market = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { set_has_market(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &market_))); } else { goto handle_unusual; } break; } // optional .Qot_Common.Security plate = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_plate())); } else { goto handle_unusual; } break; } // repeated .Qot_StockFilter.BaseFilter baseFilterList = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_basefilterlist())); } else { goto handle_unusual; } break; } // repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_accumulatefilterlist())); } else { goto handle_unusual; } break; } // repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_financialfilterlist())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.C2S) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.C2S) return false; #undef DO_ } void C2S::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.C2S) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 begin = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->begin(), output); } // required int32 num = 2; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->num(), output); } // required int32 market = 3; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->market(), output); } // optional .Qot_Common.Security plate = 4; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->plate_, output); } // repeated .Qot_StockFilter.BaseFilter baseFilterList = 5; for (unsigned int i = 0, n = static_cast<unsigned int>(this->basefilterlist_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->basefilterlist(static_cast<int>(i)), output); } // repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6; for (unsigned int i = 0, n = static_cast<unsigned int>(this->accumulatefilterlist_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 6, this->accumulatefilterlist(static_cast<int>(i)), output); } // repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->financialfilterlist_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 7, this->financialfilterlist(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.C2S) } ::google::protobuf::uint8* C2S::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.C2S) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 begin = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->begin(), target); } // required int32 num = 2; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->num(), target); } // required int32 market = 3; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->market(), target); } // optional .Qot_Common.Security plate = 4; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, *this->plate_, deterministic, target); } // repeated .Qot_StockFilter.BaseFilter baseFilterList = 5; for (unsigned int i = 0, n = static_cast<unsigned int>(this->basefilterlist_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 5, this->basefilterlist(static_cast<int>(i)), deterministic, target); } // repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6; for (unsigned int i = 0, n = static_cast<unsigned int>(this->accumulatefilterlist_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 6, this->accumulatefilterlist(static_cast<int>(i)), deterministic, target); } // repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->financialfilterlist_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 7, this->financialfilterlist(static_cast<int>(i)), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.C2S) return target; } size_t C2S::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.C2S) size_t total_size = 0; if (has_begin()) { // required int32 begin = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->begin()); } if (has_num()) { // required int32 num = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->num()); } if (has_market()) { // required int32 market = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->market()); } return total_size; } size_t C2S::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.C2S) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x0000000e) ^ 0x0000000e) == 0) { // All required fields are present. // required int32 begin = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->begin()); // required int32 num = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->num()); // required int32 market = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->market()); } else { total_size += RequiredFieldsByteSizeFallback(); } // repeated .Qot_StockFilter.BaseFilter baseFilterList = 5; { unsigned int count = static_cast<unsigned int>(this->basefilterlist_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->basefilterlist(static_cast<int>(i))); } } // repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6; { unsigned int count = static_cast<unsigned int>(this->accumulatefilterlist_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->accumulatefilterlist(static_cast<int>(i))); } } // repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7; { unsigned int count = static_cast<unsigned int>(this->financialfilterlist_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->financialfilterlist(static_cast<int>(i))); } } // optional .Qot_Common.Security plate = 4; if (has_plate()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *this->plate_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void C2S::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.C2S) GOOGLE_DCHECK_NE(&from, this); const C2S* source = ::google::protobuf::internal::DynamicCastToGenerated<const C2S>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.C2S) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.C2S) MergeFrom(*source); } } void C2S::MergeFrom(const C2S& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.C2S) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; basefilterlist_.MergeFrom(from.basefilterlist_); accumulatefilterlist_.MergeFrom(from.accumulatefilterlist_); financialfilterlist_.MergeFrom(from.financialfilterlist_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 15u) { if (cached_has_bits & 0x00000001u) { mutable_plate()->::Qot_Common::Security::MergeFrom(from.plate()); } if (cached_has_bits & 0x00000002u) { begin_ = from.begin_; } if (cached_has_bits & 0x00000004u) { num_ = from.num_; } if (cached_has_bits & 0x00000008u) { market_ = from.market_; } _has_bits_[0] |= cached_has_bits; } } void C2S::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.C2S) if (&from == this) return; Clear(); MergeFrom(from); } void C2S::CopyFrom(const C2S& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.C2S) if (&from == this) return; Clear(); MergeFrom(from); } bool C2S::IsInitialized() const { if ((_has_bits_[0] & 0x0000000e) != 0x0000000e) return false; if (!::google::protobuf::internal::AllAreInitialized(this->basefilterlist())) return false; if (!::google::protobuf::internal::AllAreInitialized(this->accumulatefilterlist())) return false; if (!::google::protobuf::internal::AllAreInitialized(this->financialfilterlist())) return false; if (has_plate()) { if (!this->plate_->IsInitialized()) return false; } return true; } void C2S::Swap(C2S* other) { if (other == this) return; InternalSwap(other); } void C2S::InternalSwap(C2S* other) { using std::swap; basefilterlist_.InternalSwap(&other->basefilterlist_); accumulatefilterlist_.InternalSwap(&other->accumulatefilterlist_); financialfilterlist_.InternalSwap(&other->financialfilterlist_); swap(plate_, other->plate_); swap(begin_, other->begin_); swap(num_, other->num_); swap(market_, other->market_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata C2S::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void S2C::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int S2C::kLastPageFieldNumber; const int S2C::kAllCountFieldNumber; const int S2C::kDataListFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 S2C::S2C() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsS2C(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.S2C) } S2C::S2C(const S2C& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), datalist_(from.datalist_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&lastpage_, &from.lastpage_, static_cast<size_t>(reinterpret_cast<char*>(&allcount_) - reinterpret_cast<char*>(&lastpage_)) + sizeof(allcount_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.S2C) } void S2C::SharedCtor() { _cached_size_ = 0; ::memset(&lastpage_, 0, static_cast<size_t>( reinterpret_cast<char*>(&allcount_) - reinterpret_cast<char*>(&lastpage_)) + sizeof(allcount_)); } S2C::~S2C() { // @@protoc_insertion_point(destructor:Qot_StockFilter.S2C) SharedDtor(); } void S2C::SharedDtor() { } void S2C::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* S2C::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const S2C& S2C::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsS2C(); return *internal_default_instance(); } S2C* S2C::New(::google::protobuf::Arena* arena) const { S2C* n = new S2C; if (arena != NULL) { arena->Own(n); } return n; } void S2C::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.S2C) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; datalist_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { ::memset(&lastpage_, 0, static_cast<size_t>( reinterpret_cast<char*>(&allcount_) - reinterpret_cast<char*>(&lastpage_)) + sizeof(allcount_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool S2C::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.S2C) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required bool lastPage = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_lastpage(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &lastpage_))); } else { goto handle_unusual; } break; } // required int32 allCount = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { set_has_allcount(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &allcount_))); } else { goto handle_unusual; } break; } // repeated .Qot_StockFilter.StockData dataList = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_datalist())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.S2C) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.S2C) return false; #undef DO_ } void S2C::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.S2C) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required bool lastPage = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteBool(1, this->lastpage(), output); } // required int32 allCount = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->allcount(), output); } // repeated .Qot_StockFilter.StockData dataList = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->datalist_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->datalist(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.S2C) } ::google::protobuf::uint8* S2C::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.S2C) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required bool lastPage = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->lastpage(), target); } // required int32 allCount = 2; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->allcount(), target); } // repeated .Qot_StockFilter.StockData dataList = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->datalist_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->datalist(static_cast<int>(i)), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.S2C) return target; } size_t S2C::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.S2C) size_t total_size = 0; if (has_lastpage()) { // required bool lastPage = 1; total_size += 1 + 1; } if (has_allcount()) { // required int32 allCount = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->allcount()); } return total_size; } size_t S2C::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.S2C) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required bool lastPage = 1; total_size += 1 + 1; // required int32 allCount = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->allcount()); } else { total_size += RequiredFieldsByteSizeFallback(); } // repeated .Qot_StockFilter.StockData dataList = 3; { unsigned int count = static_cast<unsigned int>(this->datalist_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->datalist(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void S2C::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.S2C) GOOGLE_DCHECK_NE(&from, this); const S2C* source = ::google::protobuf::internal::DynamicCastToGenerated<const S2C>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.S2C) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.S2C) MergeFrom(*source); } } void S2C::MergeFrom(const S2C& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.S2C) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; datalist_.MergeFrom(from.datalist_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { lastpage_ = from.lastpage_; } if (cached_has_bits & 0x00000002u) { allcount_ = from.allcount_; } _has_bits_[0] |= cached_has_bits; } } void S2C::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.S2C) if (&from == this) return; Clear(); MergeFrom(from); } void S2C::CopyFrom(const S2C& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.S2C) if (&from == this) return; Clear(); MergeFrom(from); } bool S2C::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; if (!::google::protobuf::internal::AllAreInitialized(this->datalist())) return false; return true; } void S2C::Swap(S2C* other) { if (other == this) return; InternalSwap(other); } void S2C::InternalSwap(S2C* other) { using std::swap; datalist_.InternalSwap(&other->datalist_); swap(lastpage_, other->lastpage_); swap(allcount_, other->allcount_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata S2C::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void Request::InitAsDefaultInstance() { ::Qot_StockFilter::_Request_default_instance_._instance.get_mutable()->c2s_ = const_cast< ::Qot_StockFilter::C2S*>( ::Qot_StockFilter::C2S::internal_default_instance()); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Request::kC2SFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Request::Request() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsRequest(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.Request) } Request::Request(const Request& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_c2s()) { c2s_ = new ::Qot_StockFilter::C2S(*from.c2s_); } else { c2s_ = NULL; } // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.Request) } void Request::SharedCtor() { _cached_size_ = 0; c2s_ = NULL; } Request::~Request() { // @@protoc_insertion_point(destructor:Qot_StockFilter.Request) SharedDtor(); } void Request::SharedDtor() { if (this != internal_default_instance()) delete c2s_; } void Request::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Request::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Request& Request::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsRequest(); return *internal_default_instance(); } Request* Request::New(::google::protobuf::Arena* arena) const { Request* n = new Request; if (arena != NULL) { arena->Own(n); } return n; } void Request::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.Request) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(c2s_ != NULL); c2s_->Clear(); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool Request::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.Request) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required .Qot_StockFilter.C2S c2s = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_c2s())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.Request) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.Request) return false; #undef DO_ } void Request::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.Request) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required .Qot_StockFilter.C2S c2s = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->c2s_, output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.Request) } ::google::protobuf::uint8* Request::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.Request) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required .Qot_StockFilter.C2S c2s = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, *this->c2s_, deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.Request) return target; } size_t Request::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.Request) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } // required .Qot_StockFilter.C2S c2s = 1; if (has_c2s()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *this->c2s_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Request::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.Request) GOOGLE_DCHECK_NE(&from, this); const Request* source = ::google::protobuf::internal::DynamicCastToGenerated<const Request>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.Request) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.Request) MergeFrom(*source); } } void Request::MergeFrom(const Request& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.Request) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_c2s()) { mutable_c2s()->::Qot_StockFilter::C2S::MergeFrom(from.c2s()); } } void Request::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.Request) if (&from == this) return; Clear(); MergeFrom(from); } void Request::CopyFrom(const Request& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.Request) if (&from == this) return; Clear(); MergeFrom(from); } bool Request::IsInitialized() const { if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; if (has_c2s()) { if (!this->c2s_->IsInitialized()) return false; } return true; } void Request::Swap(Request* other) { if (other == this) return; InternalSwap(other); } void Request::InternalSwap(Request* other) { using std::swap; swap(c2s_, other->c2s_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Request::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void Response::InitAsDefaultInstance() { ::Qot_StockFilter::_Response_default_instance_._instance.get_mutable()->s2c_ = const_cast< ::Qot_StockFilter::S2C*>( ::Qot_StockFilter::S2C::internal_default_instance()); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Response::kRetTypeFieldNumber; const int Response::kRetMsgFieldNumber; const int Response::kErrCodeFieldNumber; const int Response::kS2CFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Response::Response() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsResponse(); } SharedCtor(); // @@protoc_insertion_point(constructor:Qot_StockFilter.Response) } Response::Response(const Response& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); retmsg_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_retmsg()) { retmsg_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.retmsg_); } if (from.has_s2c()) { s2c_ = new ::Qot_StockFilter::S2C(*from.s2c_); } else { s2c_ = NULL; } ::memcpy(&errcode_, &from.errcode_, static_cast<size_t>(reinterpret_cast<char*>(&rettype_) - reinterpret_cast<char*>(&errcode_)) + sizeof(rettype_)); // @@protoc_insertion_point(copy_constructor:Qot_StockFilter.Response) } void Response::SharedCtor() { _cached_size_ = 0; retmsg_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&s2c_, 0, static_cast<size_t>( reinterpret_cast<char*>(&errcode_) - reinterpret_cast<char*>(&s2c_)) + sizeof(errcode_)); rettype_ = -400; } Response::~Response() { // @@protoc_insertion_point(destructor:Qot_StockFilter.Response) SharedDtor(); } void Response::SharedDtor() { retmsg_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete s2c_; } void Response::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Response::descriptor() { ::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Response& Response::default_instance() { ::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsResponse(); return *internal_default_instance(); } Response* Response::New(::google::protobuf::Arena* arena) const { Response* n = new Response; if (arena != NULL) { arena->Own(n); } return n; } void Response::Clear() { // @@protoc_insertion_point(message_clear_start:Qot_StockFilter.Response) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(!retmsg_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); (*retmsg_.UnsafeRawStringPointer())->clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(s2c_ != NULL); s2c_->Clear(); } } if (cached_has_bits & 12u) { errcode_ = 0; rettype_ = -400; } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool Response::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Qot_StockFilter.Response) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 retType = 1 [default = -400]; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_rettype(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &rettype_))); } else { goto handle_unusual; } break; } // optional string retMsg = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_retmsg())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->retmsg().data(), static_cast<int>(this->retmsg().length()), ::google::protobuf::internal::WireFormat::PARSE, "Qot_StockFilter.Response.retMsg"); } else { goto handle_unusual; } break; } // optional int32 errCode = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { set_has_errcode(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &errcode_))); } else { goto handle_unusual; } break; } // optional .Qot_StockFilter.S2C s2c = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_s2c())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Qot_StockFilter.Response) return true; failure: // @@protoc_insertion_point(parse_failure:Qot_StockFilter.Response) return false; #undef DO_ } void Response::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Qot_StockFilter.Response) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 retType = 1 [default = -400]; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->rettype(), output); } // optional string retMsg = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->retmsg().data(), static_cast<int>(this->retmsg().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "Qot_StockFilter.Response.retMsg"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->retmsg(), output); } // optional int32 errCode = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->errcode(), output); } // optional .Qot_StockFilter.S2C s2c = 4; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->s2c_, output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:Qot_StockFilter.Response) } ::google::protobuf::uint8* Response::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.Response) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 retType = 1 [default = -400]; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->rettype(), target); } // optional string retMsg = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->retmsg().data(), static_cast<int>(this->retmsg().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "Qot_StockFilter.Response.retMsg"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->retmsg(), target); } // optional int32 errCode = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->errcode(), target); } // optional .Qot_StockFilter.S2C s2c = 4; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, *this->s2c_, deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.Response) return target; } size_t Response::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.Response) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } // required int32 retType = 1 [default = -400]; if (has_rettype()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->rettype()); } if (_has_bits_[0 / 32] & 7u) { // optional string retMsg = 2; if (has_retmsg()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->retmsg()); } // optional .Qot_StockFilter.S2C s2c = 4; if (has_s2c()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *this->s2c_); } // optional int32 errCode = 3; if (has_errcode()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->errcode()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Response::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.Response) GOOGLE_DCHECK_NE(&from, this); const Response* source = ::google::protobuf::internal::DynamicCastToGenerated<const Response>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.Response) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.Response) MergeFrom(*source); } } void Response::MergeFrom(const Response& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.Response) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 15u) { if (cached_has_bits & 0x00000001u) { set_has_retmsg(); retmsg_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.retmsg_); } if (cached_has_bits & 0x00000002u) { mutable_s2c()->::Qot_StockFilter::S2C::MergeFrom(from.s2c()); } if (cached_has_bits & 0x00000004u) { errcode_ = from.errcode_; } if (cached_has_bits & 0x00000008u) { rettype_ = from.rettype_; } _has_bits_[0] |= cached_has_bits; } } void Response::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.Response) if (&from == this) return; Clear(); MergeFrom(from); } void Response::CopyFrom(const Response& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.Response) if (&from == this) return; Clear(); MergeFrom(from); } bool Response::IsInitialized() const { if ((_has_bits_[0] & 0x00000008) != 0x00000008) return false; if (has_s2c()) { if (!this->s2c_->IsInitialized()) return false; } return true; } void Response::Swap(Response* other) { if (other == this) return; InternalSwap(other); } void Response::InternalSwap(Response* other) { using std::swap; retmsg_.Swap(&other->retmsg_); swap(s2c_, other->s2c_); swap(errcode_, other->errcode_); swap(rettype_, other->rettype_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Response::GetMetadata() const { protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace Qot_StockFilter // @@protoc_insertion_point(global_scope)
35.191784
131
0.700336
stephenlyu
937ef1f4b01111547029f076d6f0900bb2256e10
6,244
hpp
C++
utils/convsym/input/AS_Listing.hpp
vladikcomper/md-modules
24f652a036dc63f295173369dddfffb3be89bdd7
[ "MIT" ]
9
2018-01-22T06:44:43.000Z
2022-03-26T18:57:40.000Z
utils/convsym/input/AS_Listing.hpp
vladikcomper/md-modules
24f652a036dc63f295173369dddfffb3be89bdd7
[ "MIT" ]
null
null
null
utils/convsym/input/AS_Listing.hpp
vladikcomper/md-modules
24f652a036dc63f295173369dddfffb3be89bdd7
[ "MIT" ]
null
null
null
/* ------------------------------------------------------------ * * ConvSym utility version 2.7 * * Input wrapper for the AS listing format * * ------------------------------------------------------------ */ struct Input__AS_Listing : public InputWrapper { Input__AS_Listing() : InputWrapper() { // Constructor } ~Input__AS_Listing() { // Destructor } /** * Interface for input file parsing * * @param path Input file path * @param baseOffset Base offset for the parsed records (subtracted from the fetched offsets to produce internal offsets) * @param offsetLeftBoundary Left boundary for the calculated offsets * @param offsetRightBoundary Right boundary for the calculated offsets * @param offsetMask Mask applied to offset after base offset subtraction * * @return Sorted associative array (map) of found offsets and their corresponding symbol names */ std::multimap<uint32_t, std::string> parse( const char *fileName, uint32_t baseOffset = 0x000000, uint32_t offsetLeftBoundary = 0x000000, uint32_t offsetRightBoundary = 0x3FFFFF, uint32_t offsetMask = 0xFFFFFF, const char * opts = "" ) { const int sBufferSize = 1024; // Variables uint8_t sBuffer[ sBufferSize ]; std::multimap<uint32_t, std::string> SymbolMap; IO::FileInput input = IO::FileInput( fileName, IO::text ); if ( !input.good() ) { throw "Couldn't open input file"; } uint32_t lastSymbolOffset = -1; // tracks symbols offsets to ignore sections where PC is reset (mainly Z80 stuff) // For every string in a listing file ... while ( input.readLine( sBuffer, sBufferSize ) >= 0 ) { // Known issues for the Sonic 2 disassembly: // * Some macros somehow define labels that looks like global ones (notably, _MOVE and such) // * Labels from injected Z80 code sometimes make it to the list ... uint8_t* ptr = sBuffer; // WARNING: dereffed type should be UNSIGNED, as it's used for certain range-based optimizations // Check if this line has file idention number (pattern: "(d)", where d is a decimal digit) if ( *ptr == '(' ) { bool foundDigits = false; ptr++; // Cycle through as long as found characters are digits while ( (unsigned)(*ptr-'0')<10 ) { foundDigits=true; ptr++; } // If digit pattern doesn't end with ")" as expected, or no digits were found at all, stop if ( *ptr++ != ')' || !foundDigits ) continue; } // Ensure line has a proper number (pattern: "ddddd/", where d is any digit) { bool foundDigits = false; while ( *ptr == ' ' ) { ptr++; } // skip spaces, if present // Cycle through as long as found characters are digits while ( (unsigned)(*ptr-'0')<10 ) { foundDigits=true; ptr++; } // If digit pattern doesn't end with "/" as expected, or no digits were found at all, stop if ( *ptr++ != '/' || !foundDigits ) continue; } // Ensure line has a proper offset (pattern: "hhhh :", where h is a hexidecimal character) while ( *ptr == ' ' ) { ptr++; } // skip spaces, if present uint8_t* const sOffset = ptr; // remember location, where offset should presumably start { bool foundHexDigits = false; // Cycle though as longs as proper hexidecimal characters are fetched while ( (unsigned)(*ptr-'0')<10 || (unsigned)(*ptr-'A')<6 ) { foundHexDigits = true; ptr++; } if ( *ptr == 0x00 ) continue; // break if end of line was reached *ptr++ = 0x00; // separate string pointered by "offset" variable from the rest of the line while ( *ptr == ' ' ) { ptr++; } // skip spaces ... // If offset pattern doesn't end with ":" as expected, or no hex characters were found at all, stop if ( *ptr++ != ':' || !foundHexDigits ) continue; } // Check if line matches a label definition ... if ( *ptr == ' ' && *(ptr+1) == '(' ) continue; while ( *ptr && (ptr-sBuffer < 40) ) { ptr++; } // align to column 40 (where line starts) while ( *ptr==' ' || *ptr=='\t' ) { ptr++; } // skip spaces or tabs, if present uint8_t* const label = ptr; // remember location, where label presumably starts... // The first character should be a latin letter (A..Z or a..z) if ( (unsigned)(*ptr-'A')<26 || (unsigned)(*ptr-'a')<26 ) { // Other characters should be letters are digits or _ char while ( (unsigned)(*ptr-'A')<26 || (unsigned)(*ptr-'a')<26 || (unsigned)(*ptr-'0')<10 || *ptr=='_' ) { ptr++; } // If the word is the only on the line and it ends with ":", treat it as a label if ( *ptr==':' ) { *ptr++ = 0x00; // separate string pointered by "label" variable from the rest of the line // Convert offset to uint32_t uint32_t offset = 0; for ( uint8_t* c = sOffset; *c; c++ ) { offset = offset*0x10 + (((unsigned)(*c-'0')<10) ? (*c-'0') : (*c-('A'-10))); } // Add label to the symbols table, if: // 1) Its absolute offset is higher than the previous offset successfully added // 2) When base offset is subtracted and the mask is applied, the resulting offset is within allowed boundaries if ( (lastSymbolOffset == (uint32_t)-1) || (offset >= lastSymbolOffset) ) { // Check if this is a label after ds or rs macro ... while ( *ptr==' ' || *ptr=='\t' ) { ptr++; } // skip spaces or tabs, if present if ( *ptr == 'd' && *(ptr+1) == 's' && *(ptr+2)=='.' ) continue; if ( *ptr == 'r' && *(ptr+1) == 's' && *(ptr+2)=='.' ) continue; // Add label to the symbols table uint32_t converted_offset = (offset - baseOffset) & offsetMask; if ( converted_offset >= offsetLeftBoundary && converted_offset <= offsetRightBoundary ) { // if offset is within range, add it ... // Add label to the symbols map SymbolMap.insert({converted_offset, std::string((const char*)label)}); lastSymbolOffset = offset; // stores an absolute offset, not the converted one ... } } else { IO::Log( IO::debug, "Symbol %s at offset %X ignored: its offset is less than the previous symbol successfully fetched", label, offset ); } } } } return SymbolMap; } };
39.27044
142
0.603459
vladikcomper
937f520ec2e8b59618931f94b3c31d1372db1b4e
97
cpp
C++
cpp-old/lib/html/uri_map.cpp
boryas/hcppd
86e7418bb5b6852e448d1f1a60029d2798c0b838
[ "MIT" ]
1
2018-08-25T08:10:07.000Z
2018-08-25T08:10:07.000Z
cpp-old/lib/html/uri_map.cpp
boryas/hcppd
86e7418bb5b6852e448d1f1a60029d2798c0b838
[ "MIT" ]
22
2016-09-21T05:46:18.000Z
2016-12-18T04:05:18.000Z
cpp-old/lib/html/uri_map.cpp
boryas/ssfs
86e7418bb5b6852e448d1f1a60029d2798c0b838
[ "MIT" ]
null
null
null
#include "uri_map.h" namespace ssfs { namespace html { } // namespace html } // namespace ssfs
12.125
20
0.690722
boryas
93836cdfcd44be54ec3a233732f609adb087e450
2,317
cpp
C++
Source/Scene/LightProbeNode.cpp
PolyAH/RealTimeGI
372638568ff22a4dea9c1ff448cec42e3e25aaf2
[ "MIT" ]
6
2021-10-31T14:43:04.000Z
2022-03-12T12:56:27.000Z
Source/Scene/LightProbeNode.cpp
PolyAH/RealTimeGI
372638568ff22a4dea9c1ff448cec42e3e25aaf2
[ "MIT" ]
null
null
null
Source/Scene/LightProbeNode.cpp
PolyAH/RealTimeGI
372638568ff22a4dea9c1ff448cec42e3e25aaf2
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Ammar Herzallah // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "LightProbeNode.h" #include "Render/RenderData/RenderLight.h" #include "Render/RenderData/RenderTypes.h" LightProbeNode::LightProbeNode() : mRadius(100.0f) , mIsSelected(false) { mType = ENodeType::LightProbe; } LightProbeNode::~LightProbeNode() { if (mRenderLightProbe) mRenderLightProbe->Destroy(); } void LightProbeNode::SetRadius(float radius) { mRadius = radius; if (mRenderLightProbe) { mRenderLightProbe->SetRadius(mRadius); mRenderLightProbe->SetDirty(true); } } glm::vec3 LightProbeNode::GetPosition() const { return GetTransform().GetTranslate(); } void LightProbeNode::OnTransform() { if (mRenderLightProbe) { mRenderLightProbe->SetPosition(GetTransform().GetTranslate()); mRenderLightProbe->SetDirty(true); } } void LightProbeNode::UpdateRenderLightProbe() { CHECK(!mRenderLightProbe); mRenderLightProbe = UniquePtr<RenderLightProbe>(new RenderLightProbe()); mRenderLightProbe->Create(); mRenderLightProbe->SetDirty(INVALID_INDEX); mRenderLightProbe->SetRadius(mRadius); mRenderLightProbe->SetPosition(GetTransform().GetTranslate()); } void LightProbeNode::SetDirty() { mRenderLightProbe->SetDirty(LIGHT_PROBES_BOUNCES); }
23.40404
81
0.761761
PolyAH
938b6958a01ceaf9e93de67c5cf8d79b78e5fdfb
7,668
cpp
C++
test/oauth1_unittests.cpp
ColdOrange/http-cpp
dda4f41032485d23bc33200834e3cb2957212da3
[ "MIT" ]
3
2016-05-17T11:40:55.000Z
2018-06-05T11:06:44.000Z
test/oauth1_unittests.cpp
ColdOrange/http-cpp
dda4f41032485d23bc33200834e3cb2957212da3
[ "MIT" ]
3
2015-01-06T09:36:27.000Z
2018-09-03T20:10:37.000Z
test/oauth1_unittests.cpp
ColdOrange/http-cpp
dda4f41032485d23bc33200834e3cb2957212da3
[ "MIT" ]
9
2015-01-06T02:00:21.000Z
2022-02-21T14:47:08.000Z
// // The MIT License (MIT) // // Copyright (c) 2013 by Konstantin (Kosta) Baumann & Autodesk Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include <cute/cute.hpp> #include <http-cpp/oauth1/client.hpp> #include <http-cpp/oauth1/utils.hpp> CUTE_TEST( "Test http::oauth1::create_oauth_parameters() method work properly", "[http],[oauth1],[create_oauth_parameters]" ) { auto const consumer_key = "xvz1evFS4wEEPTGEFPHBog"; auto const token_key = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"; auto const timestamp = "1318622958"; auto const nonce = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"; auto const signature = "tnnArxj06cWHq44gCs1OSKk/jLY="; auto const sig_method = "HMAC-SHA1"; auto const version = "1.0"; auto const header_key_expected = "Authorization"; auto const header_value_expected = "" "OAuth " "oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", " "oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", " "oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", " "oauth_signature_method=\"HMAC-SHA1\", " "oauth_timestamp=\"1318622958\", " "oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", " "oauth_version=\"1.0\""; auto params = http::oauth1::create_oauth_parameters( consumer_key, token_key, timestamp, nonce, signature ); auto header = http::oauth1::create_oauth_header(params); CUTE_ASSERT(params["oauth_consumer_key"] == consumer_key); CUTE_ASSERT(params["oauth_token"] == token_key); CUTE_ASSERT(params["oauth_timestamp"] == timestamp); CUTE_ASSERT(params["oauth_nonce"] == nonce); CUTE_ASSERT(params["oauth_signature"] == signature); CUTE_ASSERT(params["oauth_signature_method"] == sig_method); CUTE_ASSERT(params["oauth_version"] == version); CUTE_ASSERT(header.first == header_key_expected); CUTE_ASSERT(header.second == header_value_expected); } CUTE_TEST( "Test http::oauth1::create_signature_base() method work properly", "[http],[oauth1],[create_signature_base]" ) { auto const http_method = http::OP_POST(); auto const base_url = "https://api.twitter.com/1/statuses/update.json"; auto const consumer_key = "xvz1evFS4wEEPTGEFPHBog"; auto const token_key = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"; auto const timestamp = "1318622958"; auto const nonce = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"; auto params = http::parameters(); params["include_entities"] = "true"; params["status"] = "Hello Ladies + Gentlemen, a signed OAuth request!"; auto const sig_base_expected = "" "POST&" "https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&" "include_entities%3Dtrue%26" "oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26" "oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26" "oauth_signature_method%3DHMAC-SHA1%26" "oauth_timestamp%3D1318622958%26" "oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26" "oauth_version%3D1.0%26" "status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521"; auto sig_base = http::oauth1::create_signature_base( http_method, base_url, params, consumer_key, token_key, timestamp, nonce ); CUTE_ASSERT(sig_base == sig_base_expected); } CUTE_TEST( "Test http::oauth1::create_signature() method work properly", "[http],[oauth1],[create_signature]" ) { auto const consumer_secret = "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw"; auto const token_secret = "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE"; auto const sig_expected = "tnnArxj06cWHq44gCs1OSKk/jLY="; auto const sig_base = "" "POST&" "https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&" "include_entities%3Dtrue%26" "oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26" "oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26" "oauth_signature_method%3DHMAC-SHA1%26" "oauth_timestamp%3D1318622958%26" "oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26" "oauth_version%3D1.0%26" "status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521"; auto sig = http::oauth1::create_signature( sig_base, consumer_secret, token_secret ); CUTE_ASSERT(sig == sig_expected); } CUTE_TEST( "Test http::oauth1::create_oauth_header() method works properly for a fully configured client object and a POST request", "[http],[oauth1],[create_oauth_header][POST]" ) { auto client = http::oauth1::client(); client.consumer_key = "xvz1evFS4wEEPTGEFPHBog"; client.consumer_secret = "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw"; client.token_key = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"; client.token_secret = "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE"; auto const timestamp = "1318622958"; auto const nonce = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"; auto const http_method = http::OP_POST(); auto const url = "" "https://api.twitter.com/1/statuses/update.json?" "include_entities=true&" "status=Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request%21"; auto const header_key_expected = "Authorization"; auto const header_value_expected = "" "OAuth " "oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", " "oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", " "oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", " "oauth_signature_method=\"HMAC-SHA1\", " "oauth_timestamp=\"1318622958\", " "oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", " "oauth_version=\"1.0\""; auto const header = http::oauth1::create_oauth_header( client, url, http_method, timestamp, nonce ); CUTE_ASSERT(header.first == header_key_expected); CUTE_ASSERT(header.second == header_value_expected); } CUTE_TEST( "Test http::oauth1::create_nonce() method does not create the same value for two consecutive calls", "[http],[oauth1],[create_nonce]" ) { auto nonce1 = http::oauth1::create_nonce(); auto nonce2 = http::oauth1::create_nonce(); CUTE_ASSERT(nonce1 != nonce2); }
44.323699
125
0.700052
ColdOrange
939325fe795f85146d7d143f1a4f39c67c941ad5
30,206
cc
C++
inet/src/inet/routing/ospfv3/neighbor/Ospfv3Neighbor.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/src/inet/routing/ospfv3/neighbor/Ospfv3Neighbor.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/src/inet/routing/ospfv3/neighbor/Ospfv3Neighbor.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
1
2021-07-02T13:32:40.000Z
2021-07-02T13:32:40.000Z
#include "inet/routing/ospfv3/neighbor/Ospfv3Neighbor.h" #include "inet/routing/ospfv3/neighbor/Ospfv3NeighborStateDown.h" namespace inet { namespace ospfv3 { // FIXME!!! Should come from a global unique number generator module. unsigned long Ospfv3Neighbor::ddSequenceNumberInitSeed = 0; Ospfv3Neighbor::Ospfv3Neighbor(Ipv4Address newId, Ospfv3Interface* parent) { EV_DEBUG << "$$$$$$ New Ospfv3Neighbor has been created\n"; this->neighborId = newId; this->state = new Ospfv3NeighborStateDown; this->containingInterface = parent; this->neighborsDesignatedRouter = NULL_IPV4ADDRESS; this->neighborsBackupDesignatedRouter = NULL_IPV4ADDRESS; this->neighborsRouterDeadInterval = DEFAULT_DEAD_INTERVAL; //this is always only link local address this->neighborIPAddress = Ipv6Address::UNSPECIFIED_ADDRESS; if (this->getInterface()->getArea()->getInstance()->getAddressFamily() == IPV6INSTANCE) { this->neighborsDesignatedIP = Ipv6Address::UNSPECIFIED_ADDRESS; this->neighborsBackupIP = Ipv6Address::UNSPECIFIED_ADDRESS; } else { this->neighborsDesignatedIP = Ipv4Address::UNSPECIFIED_ADDRESS; this->neighborsBackupIP = Ipv4Address::UNSPECIFIED_ADDRESS; } inactivityTimer = new cMessage("Ospfv3Neighbor::NeighborInactivityTimer", NEIGHBOR_INACTIVITY_TIMER); inactivityTimer->setContextPointer(this); pollTimer = new cMessage("Ospfv3Neighbor::NeighborPollTimer", NEIGHBOR_POLL_TIMER); pollTimer->setContextPointer(this); ddRetransmissionTimer = new cMessage("Ospfv3Neighbor::NeighborDDRetransmissionTimer", NEIGHBOR_DD_RETRANSMISSION_TIMER); ddRetransmissionTimer->setContextPointer(this); updateRetransmissionTimer = new cMessage("Ospfv3Neighbor::Neighbor::NeighborUpdateRetransmissionTimer", NEIGHBOR_UPDATE_RETRANSMISSION_TIMER); updateRetransmissionTimer->setContextPointer(this); requestRetransmissionTimer = new cMessage("Ospfv3sNeighbor::NeighborRequestRetransmissionTimer", NEIGHBOR_REQUEST_RETRANSMISSION_TIMER); requestRetransmissionTimer->setContextPointer(this); }//constructor Ospfv3Neighbor::~Ospfv3Neighbor() { reset(); Ospfv3Process *proc = this->getInterface()->getArea()->getInstance()->getProcess(); proc->clearTimer(inactivityTimer); proc->clearTimer(pollTimer); proc->clearTimer(ddRetransmissionTimer); proc->clearTimer(updateRetransmissionTimer); proc->clearTimer(requestRetransmissionTimer); delete inactivityTimer; delete pollTimer; delete ddRetransmissionTimer; delete updateRetransmissionTimer; delete requestRetransmissionTimer; if (previousState != nullptr) { delete previousState; } delete state; }//destructor Ospfv3Neighbor::Ospfv3NeighborStateType Ospfv3Neighbor::getState() const { return state->getState(); } void Ospfv3Neighbor::processEvent(Ospfv3Neighbor::Ospfv3NeighborEventType event) { EV_DEBUG << "Passing event number " << event << " to state\n"; this->state->processEvent(this, event); } void Ospfv3Neighbor::changeState(Ospfv3NeighborState *newState, Ospfv3NeighborState *currentState) { if (this->previousState != nullptr) { EV_DEBUG << "Changing neighbor from state" << currentState->getNeighborStateString() << " to " << newState->getNeighborStateString() << "\n"; delete this->previousState; } this->state = newState; this->previousState = currentState; } void Ospfv3Neighbor::reset() { EV_DEBUG << "Reseting the neighbor " << this->getNeighborID() << "\n"; for (auto retIt = linkStateRetransmissionList.begin(); retIt != linkStateRetransmissionList.end(); retIt++) { delete (*retIt); } linkStateRetransmissionList.clear(); for (auto it = databaseSummaryList.begin(); it != databaseSummaryList.end(); it++) { delete (*it); } databaseSummaryList.clear(); for (auto it = linkStateRequestList.begin(); it != linkStateRequestList.end(); it++) { delete (*it); } linkStateRequestList.clear(); this->getInterface()->getArea()->getInstance()->getProcess()->clearTimer(ddRetransmissionTimer); clearUpdateRetransmissionTimer(); clearRequestRetransmissionTimer(); if (lastTransmittedDDPacket != nullptr) { delete lastTransmittedDDPacket; lastTransmittedDDPacket = nullptr; } } bool Ospfv3Neighbor::needAdjacency() { Ospfv3Interface::Ospfv3InterfaceType interfaceType = this->getInterface()->getType(); Ipv4Address routerID = this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID(); Ipv4Address dRouter = this->getInterface()->getDesignatedID(); Ipv4Address backupDRouter = this->getInterface()->getBackupID(); if ((interfaceType == Ospfv3Interface::POINTTOPOINT_TYPE) || (interfaceType == Ospfv3Interface::POINTTOMULTIPOINT_TYPE) || (interfaceType == Ospfv3Interface::VIRTUAL_TYPE) || (dRouter == routerID) || (backupDRouter == routerID) || (!designatedRoutersSetUp && neighborsDesignatedRouter == NULL_IPV4ADDRESS)|| (this->getNeighborID() == dRouter) || (this->getNeighborID() == backupDRouter)) { EV_DEBUG << "I need an adjacency with router " << this->getNeighborID()<<"\n"; return true; } else { return false; } } void Ospfv3Neighbor::initFirstAdjacency() { ddSequenceNumber = getUniqueULong(); firstAdjacencyInited = true; } unsigned long Ospfv3Neighbor::getUniqueULong() { return ddSequenceNumberInitSeed++; } void Ospfv3Neighbor::startUpdateRetransmissionTimer() { this->getInterface()->getArea()->getInstance()->getProcess()->setTimer(this->getUpdateRetransmissionTimer(), this->getInterface()->getRetransmissionInterval()); this->updateRetransmissionTimerActive = true; EV_DEBUG << "Starting UPDATE TIMER\n"; } void Ospfv3Neighbor::clearUpdateRetransmissionTimer() { this->getInterface()->getArea()->getInstance()->getProcess()->clearTimer(this->getUpdateRetransmissionTimer()); this->updateRetransmissionTimerActive = false; } void Ospfv3Neighbor::startRequestRetransmissionTimer() { this->getInterface()->getArea()->getInstance()->getProcess()->setTimer(this->requestRetransmissionTimer, this->getInterface()->getRetransmissionInterval()); this->requestRetransmissionTimerActive = true; } void Ospfv3Neighbor::clearRequestRetransmissionTimer() { this->getInterface()->getArea()->getInstance()->getProcess()->clearTimer(this->getRequestRetransmissionTimer()); this->requestRetransmissionTimerActive = false; } void Ospfv3Neighbor::sendDDPacket(bool init) { EV_DEBUG << "Start of function send DD Packet\n"; const auto& ddPacket = makeShared<Ospfv3DatabaseDescriptionPacket>(); //common header first ddPacket->setType(ospf::DATABASE_DESCRIPTION_PACKET); ddPacket->setRouterID(this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID()); ddPacket->setAreaID(this->getInterface()->getArea()->getAreaID()); ddPacket->setInstanceID(this->getInterface()->getArea()->getInstance()->getInstanceID()); //DD packet next Ospfv3Options options; memset(&options, 0, sizeof(Ospfv3Options)); options.eBit = this->getInterface()->getArea()->getExternalRoutingCapability(); ddPacket->setOptions(options); ddPacket->setInterfaceMTU(this->getInterface()->getInterfaceMTU()); Ospfv3DdOptions ddOptions; ddPacket->setSequenceNumber(this->ddSequenceNumber); B packetSize = OSPFV3_HEADER_LENGTH + OSPFV3_DD_HEADER_LENGTH; if (init || databaseSummaryList.empty()) { ddPacket->setLsaHeadersArraySize(0); } else { while (!this->databaseSummaryList.empty()) {/// && (packetSize <= (maxPacketSize - OSPF_LSA_HEADER_LENGTH))) { unsigned long headerCount = ddPacket->getLsaHeadersArraySize(); Ospfv3LsaHeader *lsaHeader = *(databaseSummaryList.begin()); ddPacket->setLsaHeadersArraySize(headerCount + 1); ddPacket->setLsaHeaders(headerCount, *lsaHeader); delete lsaHeader; databaseSummaryList.pop_front(); packetSize += OSPFV3_LSA_HEADER_LENGTH; } } EV_DEBUG << "DatabaseSummatyListCount = " << this->getDatabaseSummaryListCount() << endl; if (init) { ddOptions.iBit = true; ddOptions.mBit = true; ddOptions.msBit = true; } else { ddOptions.iBit = false; ddOptions.mBit = (databaseSummaryList.empty()) ? false : true; ddOptions.msBit = (databaseExchangeRelationship == Ospfv3Neighbor::MASTER) ? true : false; } ddPacket->setDdOptions(ddOptions); ddPacket->setPacketLengthField(packetSize.get()); ddPacket->setChunkLength(packetSize); Packet *pk = new Packet(); pk->insertAtBack(ddPacket); //TODO - ddPacket does not include Virtual Links and HopLimit. Also Checksum is not calculated if (this->getInterface()->getType() == Ospfv3Interface::POINTTOPOINT_TYPE) { EV_DEBUG << "(P2P link ) Send DD Packet to OSPF MCAST\n"; this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,Ipv6Address::ALL_OSPF_ROUTERS_MCAST, this->getInterface()->getIntName().c_str()); } else { EV_DEBUG << "Send DD Packet to " << this->getNeighborIP() << "\n"; this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,this->getNeighborIP(), this->getInterface()->getIntName().c_str()); } } void Ospfv3Neighbor::sendLinkStateRequestPacket() { const auto& requestPacket = makeShared<Ospfv3LinkStateRequestPacket>(); requestPacket->setType(ospf::LINKSTATE_REQUEST_PACKET); requestPacket->setRouterID(this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID()); requestPacket->setAreaID(this->getInterface()->getArea()->getAreaID()); requestPacket->setInstanceID(this->getInterface()->getArea()->getInstance()->getInstanceID()); //long maxPacketSize = (((IP_MAX_HEADER_BYTES + OSPF_HEADER_LENGTH + OSPF_REQUEST_LENGTH) > parentInterface->getMTU()) ? // IPV4_DATAGRAM_LENGTH : // parentInterface->getMTU()) - IP_MAX_HEADER_BYTES; B packetSize = OSPFV3_HEADER_LENGTH; if (linkStateRequestList.empty()) { requestPacket->setRequestsArraySize(0); } else { auto it = linkStateRequestList.begin(); while (it != linkStateRequestList.end()) { //TODO - maxpacketsize unsigned long requestCount = requestPacket->getRequestsArraySize(); Ospfv3LsaHeader *requestHeader = (*it); Ospfv3LsRequest request; request.lsaType = requestHeader->getLsaType(); request.lsaID = requestHeader->getLinkStateID(); request.advertisingRouter = requestHeader->getAdvertisingRouter(); requestPacket->setRequestsArraySize(requestCount + 1); requestPacket->setRequests(requestCount, request); packetSize += OSPFV3_LSR_LENGTH; it++; } } requestPacket->setChunkLength(packetSize); //TODO - TTL and Checksum calculation for LS Request is not implemented yet Packet *pk = new Packet(); pk->insertAtBack(requestPacket); if (this->getInterface()->getType() == Ospfv3Interface::POINTTOPOINT_TYPE) { this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,Ipv6Address::ALL_OSPF_ROUTERS_MCAST, this->getInterface()->getIntName().c_str()); } else { this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,this->getNeighborIP(), this->getInterface()->getIntName().c_str()); } } void Ospfv3Neighbor::createDatabaseSummary() { Ospfv3Area* area = this->getInterface()->getArea(); int routerLSACount = area->getRouterLSACount(); for (int i=0; i<routerLSACount; i++) { Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getRouterLSA(i)->getHeader()); this->databaseSummaryList.push_back(lsaHeader); } int networkLSACount = area->getNetworkLSACount(); for (int i=0; i<networkLSACount; i++) { Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getNetworkLSA(i)->getHeader()); this->databaseSummaryList.push_back(lsaHeader); } int interAreaPrefixCount = area->getInterAreaPrefixLSACount(); for (int i=0; i<interAreaPrefixCount; i++) { Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getInterAreaPrefixLSA(i)->getHeader()); this->databaseSummaryList.push_back(lsaHeader); } int linkLsaCount = this->getInterface()->getLinkLSACount(); for (int i=0; i<linkLsaCount; i++) { Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(this->getInterface()->getLinkLSA(i)->getHeader()); this->databaseSummaryList.push_back(lsaHeader); } int intraAreaPrefixCnt = area->getIntraAreaPrefixLSACount(); for (int i=0; i<intraAreaPrefixCnt; i++) { Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getIntraAreaPrefixLSA(i)->getHeader()); this->databaseSummaryList.push_back(lsaHeader); } } void Ospfv3Neighbor::retransmitUpdatePacket() { EV_DEBUG << "Retransmitting update packet\n"; const auto& updatePacket = makeShared<Ospfv3LinkStateUpdatePacket>(); updatePacket->setType(ospf::LINKSTATE_UPDATE_PACKET); updatePacket->setRouterID(this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID()); updatePacket->setAreaID(this->getInterface()->getArea()->getAreaID()); updatePacket->setInstanceID(this->getInterface()->getArea()->getInstance()->getInstanceID()); bool packetFull = false; unsigned short lsaCount = 0; B packetLength = OSPFV3_HEADER_LENGTH + OSPFV3_LSA_HEADER_LENGTH; auto it = linkStateRetransmissionList.begin(); while (!packetFull && (it != linkStateRetransmissionList.end())) { uint16_t lsaType = (*it)->getHeader().getLsaType(); const Ospfv3RouterLsa *routerLSA = (lsaType == ROUTER_LSA) ? dynamic_cast<Ospfv3RouterLsa *>(*it) : nullptr; const Ospfv3NetworkLsa *networkLSA = (lsaType == NETWORK_LSA) ? dynamic_cast<Ospfv3NetworkLsa *>(*it) : nullptr; const Ospfv3LinkLsa *linkLSA = (lsaType == LINK_LSA) ? dynamic_cast<Ospfv3LinkLsa *>(*it) : nullptr; const Ospfv3InterAreaPrefixLsa *interAreaPrefixLSA = (lsaType == INTER_AREA_PREFIX_LSA) ? dynamic_cast<Ospfv3InterAreaPrefixLsa *>(*it) : nullptr; const Ospfv3IntraAreaPrefixLsa *intraAreaPrefixLSA = (lsaType == INTRA_AREA_PREFIX_LSA) ? dynamic_cast<Ospfv3IntraAreaPrefixLsa *>(*it) : nullptr; // OSPFASExternalLSA *asExternalLSA = (lsaType == AS_EXTERNAL_LSA_TYPE) ? dynamic_cast<OSPFASExternalLSA *>(*it) : nullptr; B lsaSize; bool includeLSA = false; switch (lsaType) { case ROUTER_LSA: if (routerLSA != nullptr) { lsaSize = calculateLSASize(routerLSA); } break; case NETWORK_LSA: if (networkLSA != nullptr) { lsaSize = calculateLSASize(networkLSA); } break; case INTER_AREA_PREFIX_LSA: if (interAreaPrefixLSA != nullptr) { lsaSize = calculateLSASize(interAreaPrefixLSA); } break; // case AS_EXTERNAL_LSA_TYPE: // if (asExternalLSA != nullptr) { // lsaSize = calculateLSASize(asExternalLSA); // } // break; // // default: // break; case LINK_LSA: if (linkLSA != nullptr) lsaSize = calculateLSASize(linkLSA); break; case INTRA_AREA_PREFIX_LSA: if (intraAreaPrefixLSA != nullptr) { lsaSize = calculateLSASize(intraAreaPrefixLSA); } break; } if (B(packetLength + lsaSize).get() < this->getInterface()->getInterfaceMTU()) { includeLSA = true; lsaCount++; } else { if ((lsaCount == 0) && (packetLength + lsaSize < IPV6_DATAGRAM_LENGTH)) { includeLSA = true; lsaCount++; packetFull = true; } } if (includeLSA) { packetLength += lsaSize; switch (lsaType) { case ROUTER_LSA: if (routerLSA != nullptr) { unsigned int routerLSACount = updatePacket->getRouterLSAsArraySize(); updatePacket->setRouterLSAsArraySize(routerLSACount + 1); updatePacket->setRouterLSAs(routerLSACount, *routerLSA); unsigned short lsAge = updatePacket->getRouterLSAs(routerLSACount).getHeader().getLsaAge(); if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) { updatePacket->getRouterLSAsForUpdate(routerLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval()); } else { updatePacket->getRouterLSAsForUpdate(routerLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE); } } break; case NETWORK_LSA: if (networkLSA != nullptr) { unsigned int networkLSACount = updatePacket->getNetworkLSAsArraySize(); updatePacket->setNetworkLSAsArraySize(networkLSACount + 1); updatePacket->setNetworkLSAs(networkLSACount, *networkLSA); unsigned short lsAge = updatePacket->getNetworkLSAs(networkLSACount).getHeader().getLsaAge(); if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) { updatePacket->getNetworkLSAsForUpdate(networkLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval()); } else { updatePacket->getNetworkLSAsForUpdate(networkLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE); } } break; case INTER_AREA_PREFIX_LSA: if (interAreaPrefixLSA != nullptr) { unsigned int interAreaPrefixLSACount = updatePacket->getInterAreaPrefixLSAsArraySize(); updatePacket->setInterAreaPrefixLSAsArraySize(interAreaPrefixLSACount + 1); updatePacket->setInterAreaPrefixLSAs(interAreaPrefixLSACount, *interAreaPrefixLSA); unsigned short lsAge = updatePacket->getInterAreaPrefixLSAs(interAreaPrefixLSACount).getHeader().getLsaAge(); if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) { updatePacket->getInterAreaPrefixLSAsForUpdate(interAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval()); } else { updatePacket->getInterAreaPrefixLSAsForUpdate(interAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE); } } break; // case AS_EXTERNAL_LSA_TYPE: // if (asExternalLSA != nullptr) { // unsigned int asExternalLSACount = updatePacket->getAsExternalLSAsArraySize(); // // updatePacket->setAsExternalLSAsArraySize(asExternalLSACount + 1); // updatePacket->setAsExternalLSAs(asExternalLSACount, *asExternalLSA); // // unsigned short lsAge = updatePacket->getAsExternalLSAs(asExternalLSACount).getHeader().getLsAge(); // if (lsAge < MAX_AGE - parentInterface->getTransmissionDelay()) { // updatePacket->getAsExternalLSAs(asExternalLSACount).getHeader().setLsAge(lsAge + parentInterface->getTransmissionDelay()); // } // else { // updatePacket->getAsExternalLSAs(asExternalLSACount).getHeader().setLsAge(MAX_AGE); // } // } // break; case LINK_LSA: if (linkLSA != nullptr) { unsigned int linkLSACount = updatePacket->getLinkLSAsArraySize(); updatePacket->setLinkLSAsArraySize(linkLSACount + 1); updatePacket->setLinkLSAs(linkLSACount, *linkLSA); unsigned short lsAge = updatePacket->getLinkLSAs(linkLSACount).getHeader().getLsaAge(); if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) { updatePacket->getLinkLSAsForUpdate(linkLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval()); } else { updatePacket->getLinkLSAsForUpdate(linkLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE); } } break; case INTRA_AREA_PREFIX_LSA: if (intraAreaPrefixLSA != nullptr) { unsigned int intraAreaPrefixLSACount = updatePacket->getIntraAreaPrefixLSAsArraySize(); updatePacket->setIntraAreaPrefixLSAsArraySize(intraAreaPrefixLSACount + 1); updatePacket->setIntraAreaPrefixLSAs(intraAreaPrefixLSACount, *intraAreaPrefixLSA); unsigned short lsAge = updatePacket->getIntraAreaPrefixLSAs(intraAreaPrefixLSACount).getHeader().getLsaAge(); if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) { updatePacket->getIntraAreaPrefixLSAsForUpdate(intraAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval()); } else { updatePacket->getIntraAreaPrefixLSAsForUpdate(intraAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE); } } break; default: break; } } it++; } EV_DEBUG << "Retransmit - packet length: "<<packetLength<<"\n"; updatePacket->setChunkLength(B(packetLength)); //IPV6 HEADER BYTES Packet *pk = new Packet(); pk->insertAtBack(updatePacket); this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk, this->getNeighborIP(), this->getInterface()->getIntName().c_str()); //TODO // int ttl = (parentInterface->getType() == Interface::VIRTUAL) ? VIRTUAL_LINK_TTL : 1; // messageHandler->sendPacket(updatePacket, neighborIPAddress, parentInterface->getIfIndex(), ttl); } void Ospfv3Neighbor::addToRetransmissionList(const Ospfv3Lsa *lsa) { auto it = linkStateRetransmissionList.begin(); for ( ; it != linkStateRetransmissionList.end(); it++) { if (((*it)->getHeader().getLinkStateID() == lsa->getHeader().getLinkStateID()) && ((*it)->getHeader().getAdvertisingRouter().getInt() == lsa->getHeader().getAdvertisingRouter().getInt())) { break; } } Ospfv3Lsa *lsaCopy = lsa->dup(); // switch (lsaC->getHeader().getLsaType()) { // case ROUTER_LSA: // lsaCopy = new Ospfv3RouterLsa((const_cast<Ospfv3Lsa*>(lsaC)))); // break; // // case NETWORK_LSA: // lsaCopy = new Ospfv3NetworkLsa(*(check_and_cast<Ospfv3NetworkLsa *>(const_cast<Ospfv3Lsa*>(lsaC)))); // break; // // case INTER_AREA_PREFIX_LSA: // lsaCopy = new Ospfv3InterAreaPrefixLsa(*(check_and_cast<Ospfv3InterAreaPrefixLsa* >(const_cast<Ospfv3Lsa*>(lsaC)))); // break; //// case AS_EXTERNAL_LSA_TYPE: //// lsaCopy = new OSPFASExternalLSA(*(check_and_cast<OSPFASExternalLSA *>(lsa))); //// break; // // case LINK_LSA: // lsaCopy = new Ospfv3LinkLsa(*(check_and_cast<Ospfv3LinkLsa *>(const_cast<Ospfv3Lsa*>(lsaC)))); // break; // // case INTRA_AREA_PREFIX_LSA: // lsaCopy = new Ospfv3IntraAreaPrefixLsa(*(check_and_cast<Ospfv3IntraAreaPrefixLsa *>(const_cast<Ospfv3Lsa*>(lsaC)))); // break; // // default: // ASSERT(false); // error // break; // } // if LSA is on retransmission list then replace it if (it != linkStateRetransmissionList.end()) { delete (*it); *it = static_cast<Ospfv3Lsa *>(lsaCopy); } else { //if not then add it linkStateRetransmissionList.push_back(static_cast<Ospfv3Lsa *>(lsaCopy)); } } void Ospfv3Neighbor::removeFromRetransmissionList(LSAKeyType lsaKey) { auto it = linkStateRetransmissionList.begin(); int counter = 0; while (it != linkStateRetransmissionList.end()) { EV_DEBUG << counter++ << " - HEADER in retransmition list:\n" << (*it)->getHeader() << "\n"; if (((*it)->getHeader().getLinkStateID() == lsaKey.linkStateID) && ((*it)->getHeader().getAdvertisingRouter() == lsaKey.advertisingRouter)) { delete (*it); it = linkStateRetransmissionList.erase(it); } else { it++; } } }//removeFromRetransmissionList bool Ospfv3Neighbor::isLinkStateRequestListEmpty(LSAKeyType lsaKey) const { for (auto lsa : linkStateRetransmissionList) { if ((lsa->getHeader().getLinkStateID() == lsaKey.linkStateID) && (lsa->getHeader().getAdvertisingRouter() == lsaKey.advertisingRouter)) { return true; } } return false; } Ospfv3Lsa *Ospfv3Neighbor::findOnRetransmissionList(LSAKeyType lsaKey) { for (auto & elem : linkStateRetransmissionList) { if (((elem)->getHeader().getLinkStateID() == lsaKey.linkStateID) && ((elem)->getHeader().getAdvertisingRouter() == lsaKey.advertisingRouter)) { return elem; } } return nullptr; } bool Ospfv3Neighbor::retransmitDatabaseDescriptionPacket() { EV_DEBUG << "Retransmitting DD Packet\n"; if (lastTransmittedDDPacket != nullptr) { Packet *ddPacket = new Packet(*lastTransmittedDDPacket); this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(ddPacket, this->getNeighborIP(), this->getInterface()->getIntName().c_str()); return true; } else { EV_DEBUG << "But no packet is in the line\n"; return false; } } void Ospfv3Neighbor::addToRequestList(const Ospfv3LsaHeader *lsaHeader) { linkStateRequestList.push_back(new Ospfv3LsaHeader(*lsaHeader)); EV_DEBUG << "Currently on request list:\n"; for (auto it = linkStateRequestList.begin(); it != linkStateRequestList.end(); it++) { EV_DEBUG << "\tType: "<<(*it)->getLsaType() << ", ID: " << (*it)->getLinkStateID() << ", Adv: " << (*it)->getAdvertisingRouter() << "\n"; } } bool Ospfv3Neighbor::isLSAOnRequestList(LSAKeyType lsaKey) { if (findOnRequestList(lsaKey)==nullptr) return false; return true; } Ospfv3LsaHeader* Ospfv3Neighbor::findOnRequestList(LSAKeyType lsaKey) { //linkStateRequestList - list of LSAs that need to be received from the neighbor for (auto it = linkStateRequestList.begin(); it != linkStateRequestList.end(); it++) { if (((*it)->getLinkStateID() == lsaKey.linkStateID) && ((*it)->getAdvertisingRouter() == lsaKey.advertisingRouter)) { return *it; } } return nullptr; } void Ospfv3Neighbor::removeFromRequestList(LSAKeyType lsaKey) { auto it = linkStateRequestList.begin(); while (it != linkStateRequestList.end()) { if (((*it)->getLinkStateID() == lsaKey.linkStateID) && ((*it)->getAdvertisingRouter() == lsaKey.advertisingRouter)) { delete (*it); it = linkStateRequestList.erase(it); } else { it++; } } if ((getState() == Ospfv3Neighbor::LOADING_STATE) && (linkStateRequestList.empty())) { clearRequestRetransmissionTimer(); processEvent(Ospfv3Neighbor::LOADING_DONE); } }//removeFromRequestList void Ospfv3Neighbor::addToTransmittedLSAList(LSAKeyType lsaKey) { TransmittedLSA transmit; transmit.lsaKey = lsaKey; transmit.age = 0; transmittedLSAs.push_back(transmit); }//addToTransmittedLSAList bool Ospfv3Neighbor::isOnTransmittedLSAList(LSAKeyType lsaKey) const { for (std::list<TransmittedLSA>::const_iterator it = transmittedLSAs.begin(); it != transmittedLSAs.end(); it++) { if ((it->lsaKey.linkStateID == lsaKey.linkStateID) && (it->lsaKey.advertisingRouter == lsaKey.advertisingRouter)) { return true; } } return false; }//isOnTransmittedLSAList void Ospfv3Neighbor::ageTransmittedLSAList() { auto it = transmittedLSAs.begin(); while ((it != transmittedLSAs.end()) && (it->age == MIN_LS_ARRIVAL)) { transmittedLSAs.pop_front(); it = transmittedLSAs.begin(); } // for (long i = 0; i < transmittedLSAs.size(); i++) // { // transmittedLSAs[i].age++; // } for (it = transmittedLSAs.begin(); it != transmittedLSAs.end(); it++) { it->age++; } }//ageTransmittedLSAList void Ospfv3Neighbor::deleteLastSentDDPacket() { if (lastTransmittedDDPacket != nullptr) { delete lastTransmittedDDPacket; lastTransmittedDDPacket = nullptr; } }//deleteLastSentDDPacket } // namespace ospfv3 } // namespace inet
41.378082
185
0.63782
ntanetani
9399c81a999864698b991e622d333e5335e5ca59
906
cpp
C++
Duno/Duno-Core/Graphics/renderEngine/GLEntityReflectiveRenderer.cpp
DunoGameEngine/Duno
f6c0fd5371a73ccb5ea1ba78540854b831b75b7f
[ "Apache-2.0" ]
null
null
null
Duno/Duno-Core/Graphics/renderEngine/GLEntityReflectiveRenderer.cpp
DunoGameEngine/Duno
f6c0fd5371a73ccb5ea1ba78540854b831b75b7f
[ "Apache-2.0" ]
null
null
null
Duno/Duno-Core/Graphics/renderEngine/GLEntityReflectiveRenderer.cpp
DunoGameEngine/Duno
f6c0fd5371a73ccb5ea1ba78540854b831b75b7f
[ "Apache-2.0" ]
null
null
null
#include "GLEntityReflectiveRenderer.h" #include "GLTextureLoader.h" #include <iostream> using namespace std; /* Define all uniform location handles */ #define CUBE_MAP 6 #define CAMERA_POSITION 7 GLEntityReflectiveRenderer::GLEntityReflectiveRenderer(GLTexture* cubeMap): GLEntityRenderer("entity/reflective", 2), m_cube_map(cubeMap) { /* Map all uniforms */ getShader()->setLocation(CUBE_MAP, "cubeMap"); getShader()->setLocation(CAMERA_POSITION, "cameraPosition"); /* Load the cube map to texture unit 2 */ getShader()->bind(); getShader()->loadInt(2, CUBE_MAP); getShader()->unbind(); } /* Extends Render Model Function */ void GLEntityReflectiveRenderer::addRenderModel(DunoGameObject* model, DunoCamera* cam) { /* Bind the cube map texture */ GLTextureLoader::bindTextureCube(m_cube_map, 2); getShader()->loadVector(cam->getPosition(), CAMERA_POSITION); }
30.2
88
0.735099
DunoGameEngine
939c55a2b6c312de1bdc90ecd3bb4d66bd403efe
98
cpp
C++
Arrays/test.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
Arrays/test.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
Arrays/test.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstring> #include<algorithm> using namespace std; int main() { }
8.166667
20
0.704082
sans712
4d36b3887a70c499e0c5783f4c75ed2fe0b3bd5b
226
cpp
C++
sumofdigits.cpp
deepanshu1422/450Questions
614a6bcb66f3202a62c375c0c0a63365e1021110
[ "Apache-2.0" ]
null
null
null
sumofdigits.cpp
deepanshu1422/450Questions
614a6bcb66f3202a62c375c0c0a63365e1021110
[ "Apache-2.0" ]
null
null
null
sumofdigits.cpp
deepanshu1422/450Questions
614a6bcb66f3202a62c375c0c0a63365e1021110
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int sumofdigits(int a) { if(a/10==0) { return a; } int sum=a%10+sumofdigits(a/10); return sum; } int main() { int b =sumofdigits(123); cout<<b; }
10.761905
35
0.553097
deepanshu1422
4d36bae1fed44345c75187bc870290e0a6a85b3e
1,486
cpp
C++
Sid's Levels/Level - 2/Matrix/MedianInRowSortedMatrix.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 2/Matrix/MedianInRowSortedMatrix.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 2/Matrix/MedianInRowSortedMatrix.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
// { Driver Code Starts //Initial template for C++ #include <bits/stdc++.h> using namespace std; // } Driver Code Ends //User function template for C++ class Solution{ public: //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA int median(vector<vector<int>> &a, int r, int c){ //we need to find the min and max element int min = INT_MAX; int max = INT_MIN; for(int i = 0; i < r; i++) { if(a[i][0] < min) min = a[i][0]; if(a[i][c-1] > max) max = a[i][c-1]; } int desired = (r*c + 1)/2; while(min < max) { int place = 0; int mid = (min + max)/2; for(int i = 0; i < r; i++) { place += upper_bound(a[i].begin(), a[i].end(), mid) - a[i].begin(); } if(place < desired) min = mid + 1; else max = mid; } return min; } }; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int r, c; cin>>r>>c; vector<vector<int>> matrix(r, vector<int>(c)); for(int i=0;i<r;++i) for(int j=0;j<c;++j) cin>>matrix[i][j]; Solution obj; cout<<obj.median(matrix, r, c)<<endl; } return 0; } // } Driver Code Ends
21.536232
83
0.446164
Tiger-Team-01
4d37043ea5d0e06ef78be33c6c267f27286a6ca8
6,383
cpp
C++
src/obproxy/prometheus/ob_prometheus_convert.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
74
2021-05-31T15:23:49.000Z
2022-03-12T04:46:39.000Z
src/obproxy/prometheus/ob_prometheus_convert.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
16
2021-05-31T15:26:38.000Z
2022-03-30T06:02:43.000Z
src/obproxy/prometheus/ob_prometheus_convert.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
64
2021-05-31T15:25:36.000Z
2022-02-23T08:43:58.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX PROXY #include "prometheus/ob_prometheus_convert.h" #include "prometheus/ob_prometheus_exporter.h" using namespace prometheus; using namespace oceanbase::common; namespace oceanbase { namespace obproxy { namespace prometheus { void ObProxyPrometheusConvert::build_label_map(std::map<std::string, std::string>& label_map, const ObVector<ObPrometheusLabel> &label_array) { for (int i = 0; i< label_array.size(); i++) { ObPrometheusLabel &label = label_array[i]; std::string key(label.get_key().ptr(), label.get_key().length()); std::string value(label.get_value().ptr(), label.get_value().length()); label_map.insert(std::pair<std::string, std::string>(key, value)); } } int ObProxyPrometheusConvert::get_or_create_exporter_family(const ObString &name, const ObString &help, const ObVector<ObPrometheusLabel> &constant_label_array, const ObPrometheusMetricType metric_type, void *&family) { int ret = OB_SUCCESS; std::string name_str(name.ptr(), name.length()); std::string help_str(help.ptr(), help.length()); std::map<std::string, std::string> constant_label_map; build_label_map(constant_label_map, constant_label_array); switch (metric_type) { case PROMETHEUS_TYPE_COUNTER: ret = get_obproxy_prometheus_exporter().get_or_create_counter_family(name_str, help_str, constant_label_map, family); break; case PROMETHEUS_TYPE_GAUGE: ret = get_obproxy_prometheus_exporter().get_or_create_gauge_family(name_str, help_str, constant_label_map, family); break; case PROMETHEUS_TYPE_HISTOGRAM: ret = get_obproxy_prometheus_exporter().get_or_create_histogram_family(name_str, help_str, constant_label_map, family); break; default: break; } if (OB_FAIL(ret)) { LOG_WARN("fail to get or create faimyl", K(name), K(metric_type), K(ret)); } return ret; } int ObProxyPrometheusConvert::create_counter_metric(void *family, const ObVector<ObPrometheusLabel> &label_array, void *&metric) { int ret = OB_SUCCESS; std::map<std::string, std::string> label_map; build_label_map(label_map, label_array); if (OB_FAIL(get_obproxy_prometheus_exporter().create_metric<Counter>(family, label_map, metric))) { LOG_WARN("fail to create metric", KP(family), K(label_array), K(ret)); } return ret; } int ObProxyPrometheusConvert::create_gauge_metric(void *family, const ObVector<ObPrometheusLabel> &label_array, void *&metric) { int ret = OB_SUCCESS; std::map<std::string, std::string> label_map; build_label_map(label_map, label_array); if (OB_FAIL(get_obproxy_prometheus_exporter().create_metric<Gauge>(family, label_map, metric))) { LOG_WARN("fail to create metric", KP(family), K(label_array), K(ret)); } return ret; } int ObProxyPrometheusConvert::create_histogram_metric(void *family, const ObVector<ObPrometheusLabel> &label_array, const ObSortedVector<int64_t> &ob_bucket_boundaries, void *&metric) { int ret = OB_SUCCESS; std::map<std::string, std::string> label_map; build_label_map(label_map, label_array); std::vector<double> bucket_boundaries; for (int i = 0; i< ob_bucket_boundaries.size(); i++) { bucket_boundaries.push_back(static_cast<double>(ob_bucket_boundaries[i])); } if (OB_FAIL(get_obproxy_prometheus_exporter().create_metric<Histogram>(family, label_map, metric, bucket_boundaries))) { LOG_WARN("fail to create metric", KP(family), K(label_array), K(ret)); } return ret; } int ObProxyPrometheusConvert::remove_metric(void* family, void* metric, const ObPrometheusMetricType metric_type) { int ret = OB_SUCCESS; switch (metric_type) { case PROMETHEUS_TYPE_COUNTER: ret = get_obproxy_prometheus_exporter().remove_metric<Counter>(family, metric); break; case PROMETHEUS_TYPE_GAUGE: ret = get_obproxy_prometheus_exporter().remove_metric<Gauge>(family, metric); break; case PROMETHEUS_TYPE_HISTOGRAM: ret = get_obproxy_prometheus_exporter().remove_metric<Histogram>(family, metric); break; default: break; } if (OB_FAIL(ret)) { LOG_WARN("fail to remove metric", KP(family), KP(metric), K(metric_type), K(ret)); } return ret; } int ObProxyPrometheusConvert::handle_counter(void *metric, const int64_t value) { return get_obproxy_prometheus_exporter().handle_counter(metric, static_cast<double>(value)); } int ObProxyPrometheusConvert::handle_gauge(void *metric, const double value) { return get_obproxy_prometheus_exporter().handle_gauge(metric, value); } int ObProxyPrometheusConvert::handle_gauge(void *metric, const int64_t value) { return get_obproxy_prometheus_exporter().handle_gauge(metric, static_cast<double>(value)); } int ObProxyPrometheusConvert::handle_histogram(void *metric, const int64_t sum, const ObVector<int64_t> &ob_bucket_counts) { std::vector<double> bucket_counts; for (int i = 0; i< ob_bucket_counts.size(); i++) { bucket_counts.push_back(static_cast<double>(ob_bucket_counts[i])); } return get_obproxy_prometheus_exporter().handle_histogram(metric, static_cast<double>(sum), bucket_counts); } } // end of namespace prometheus } // end of namespace obproxy } // end of namespace oceanbase
35.265193
125
0.674448
stutiredboy
4d385212911a25588c981d9a91d6b2406b043228
2,757
hpp
C++
gloom/src/scene_graph/util.hpp
Stektpotet/gloom
fcb6e031d573be029dd829d8e4fc0a97feb22687
[ "MIT" ]
null
null
null
gloom/src/scene_graph/util.hpp
Stektpotet/gloom
fcb6e031d573be029dd829d8e4fc0a97feb22687
[ "MIT" ]
null
null
null
gloom/src/scene_graph/util.hpp
Stektpotet/gloom
fcb6e031d573be029dd829d8e4fc0a97feb22687
[ "MIT" ]
null
null
null
#pragma once #include "../mesh.hpp" #include "SceneNode.hpp" // Creates an empty SceneNode instance. template<typename TNode, typename... Args> TNode* createSceneNode(Args... ctorArgs) { return new TNode(std::forward<Args>(ctorArgs)...); } // Transfer the mesh to the GPU template<typename TNode> void TransferMesh(Mesh& mesh, TNode* node) { node->vertexArray.bind(); GLuint positionsByteSize = static_cast<GLuint>(mesh.vertices.size() * sizeof(float)), normalsByteSize = static_cast<GLuint>(mesh.normals.size() * sizeof(float)), colorsByteSize = static_cast<GLuint>(mesh.colours.size() * sizeof(float)); VertexBuffer vbo = { //create a vbo with enough space for all the attributes static_cast<GLsizeiptr>(positionsByteSize + normalsByteSize + colorsByteSize) }; vbo.update( //upload the positional data 0, positionsByteSize, mesh.vertices.data() ); vbo.update( //upload the normal data positionsByteSize, normalsByteSize, mesh.normals.data() ); vbo.update( //upload the color data positionsByteSize + normalsByteSize, colorsByteSize, mesh.colours.data() ); IndexBuffer<unsigned int> ibo = { static_cast<GLsizeiptr>(mesh.indices.size()), mesh.indices.data() }; ContinuousVertexLayout{ //Attribute layout descriptor // name, size, components, internal type, normalized {"position", positionsByteSize, 3, GL_FLOAT, GL_FALSE}, {"normal", normalsByteSize, 3, GL_FLOAT, GL_TRUE}, {"color", colorsByteSize, 4, GL_FLOAT, GL_TRUE}, }.applyToBuffer(vbo); //Activate the given attributes node->VAOIndexCount = mesh.indices.size(); } void updateTransforms(SceneNode* node, glm::mat4 transformationThusFar = glm::mat4(1)) { // Do transformation computations here glm::mat4 model = glm::translate(glm::mat4(1),node->referencePoint); //move to reference point model = glm::rotate(model, node->rotation.x, { 1, 0, 0 }); //Rotate relative to referencePoint model = glm::rotate(model, node->rotation.y, { 0, 1, 0 }); model = glm::rotate(model, node->rotation.z, { 0, 0, 1 }); model = glm::translate(model, -(node->referencePoint)); //move back into model space model = glm::translate(node->position) * model; node->matTRS = transformationThusFar * model; //model = glm::translate(model, node->position); //Translate relative to referencePoint // Store matrix in the node's currentTransformationMatrix here //node->matTRS = transformationThusFar * model; for (const auto& child : node->children) updateTransforms(child, node->matTRS); }
39.385714
109
0.657236
Stektpotet
4d4076d8d6f4bf2200eaeb83026467c1a9a295ed
2,518
cpp
C++
MSP2007/MSP2007Ppg.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
MSP2007/MSP2007Ppg.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
MSP2007/MSP2007Ppg.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------------------- // COPYRIGHT NOTICE // ---------------------------------------------------------------------------------------- // // The Source Code Store LLC // ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC // ActiveX Control // Copyright (c) 2002-2017 The Source Code Store LLC // // All Rights Reserved. No parts of this file may be reproduced, modified or transmitted // in any form or by any means without the written permission of the author. // // ---------------------------------------------------------------------------------------- #include "stdafx.h" #include "MSP2007.h" #include "MSP2007Ppg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CMSP2007PropPage, COlePropertyPage) ///////////////////////////////////////////////////////////////////////////// // Message map BEGIN_MESSAGE_MAP(CMSP2007PropPage, COlePropertyPage) //{{AFX_MSG_MAP(CMSP2007PropPage) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // Initialize class factory and guid IMPLEMENT_OLECREATE_EX(CMSP2007PropPage, "MSP2007.MSP2007PropPage.1", 0xb00f005e, 0x637c, 0x4bed, 0x8f, 0x10, 0x99, 0x64, 0x71, 0xd2, 0xd9, 0x37) ///////////////////////////////////////////////////////////////////////////// // CMSP2007PropPage::CMSP2007PropPageFactory::UpdateRegistry - // Adds or removes system registry entries for CMSP2007PropPage BOOL CMSP2007PropPage::CMSP2007PropPageFactory::UpdateRegistry(BOOL bRegister) { if (bRegister) return AfxOleRegisterPropertyPageClass(AfxGetInstanceHandle(), m_clsid, IDS_MSP2007_PPG); else return AfxOleUnregisterClass(m_clsid, NULL); } ///////////////////////////////////////////////////////////////////////////// // CMSP2007PropPage::CMSP2007PropPage - Constructor CMSP2007PropPage::CMSP2007PropPage() : COlePropertyPage(IDD, IDS_MSP2007_PPG_CAPTION) { //{{AFX_DATA_INIT(CMSP2007PropPage) //}}AFX_DATA_INIT } ///////////////////////////////////////////////////////////////////////////// // CMSP2007PropPage::DoDataExchange - Moves data between page and properties void CMSP2007PropPage::DoDataExchange(CDataExchange* pDX) { //{{AFX_DATA_MAP(CMSP2007PropPage) //}}AFX_DATA_MAP DDP_PostProcessing(pDX); } ///////////////////////////////////////////////////////////////////////////// // CMSP2007PropPage message handlers
31.08642
92
0.542097
jluzardo1971
4d4145b043ef5da2e8c43bed3e9b748aefd458ec
3,324
cc
C++
hackt_docker/hackt/src/Object/ref/reference_set.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/ref/reference_set.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/ref/reference_set.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/ref/reference_set.cc" $Id: reference_set.cc,v 1.4 2010/04/02 22:18:46 fang Exp $ */ #include "Object/ref/reference_set.hh" #include <iostream> #include <functional> #include <algorithm> #include "Object/entry_collection.hh" #include "Object/traits/instance_traits.hh" #include "util/iterator_more.hh" namespace HAC { namespace entity { using std::for_each; using std::mem_fun_ref; using util::set_inserter; #include "util/using_ostream.hh" //============================================================================= /** Clears all member sets. */ void global_references_set::clear(void) { for_each(&ref_bin[0], &ref_bin[MAX], mem_fun_ref(&ref_bin_type::clear)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** \return true if all sub-sets are empty */ bool global_references_set::empty(void) const { size_t i = 0; do { if (!ref_bin[i].empty()) { return false; } ++i; } while (i<MAX); return true; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Clobbers this set of sets, by taking all sets from the entry collection parameter. */ void global_references_set::import_entry_collection(const entry_collection& c) { #define GRAB_SET(Tag) \ ref_bin[class_traits<Tag>::type_tag_enum_value] = \ c.get_index_set<Tag>(); GRAB_SET(bool_tag) GRAB_SET(int_tag) GRAB_SET(enum_tag) GRAB_SET(channel_tag) GRAB_SET(process_tag) #undef GRAB_SET } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Insert the set differences into the destination set. Difference: this set - src set */ void global_references_set::set_difference(const global_references_set& src, global_references_set& dst) const { size_t i = 0; do { // linear time complexity std::set_difference(ref_bin[i].begin(), ref_bin[i].end(), src.ref_bin[i].begin(), src.ref_bin[i].end(), set_inserter(dst.ref_bin[i])); ++i; } while (i<MAX); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Insert the set intersections into the destination set. */ void global_references_set::set_intersection(const global_references_set& src, global_references_set& dst) const { size_t i = 0; do { // linear time complexity std::set_intersection(ref_bin[i].begin(), ref_bin[i].end(), src.ref_bin[i].begin(), src.ref_bin[i].end(), set_inserter(dst.ref_bin[i])); ++i; } while (i<MAX); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ostream& global_references_set::dump(ostream& o) const { typedef ref_bin_type::const_iterator const_iterator; #define CASE_PRINT_TYPE_TAG_NAME(Tag) \ { \ const ref_bin_type& \ ub(ref_bin[class_traits<Tag>::type_tag_enum_value]); \ const_iterator i(ub.begin()), e(ub.end()); \ for ( ; i!=e; ++i) { \ o << class_traits<Tag>::tag_name << '[' << *i << "], "; \ } \ } CASE_PRINT_TYPE_TAG_NAME(bool_tag) CASE_PRINT_TYPE_TAG_NAME(int_tag) CASE_PRINT_TYPE_TAG_NAME(enum_tag) CASE_PRINT_TYPE_TAG_NAME(channel_tag) CASE_PRINT_TYPE_TAG_NAME(process_tag) #undef CASE_PRINT_TYPE_TAG_NAME return o; } //============================================================================= } // end namespace entity } // end namespace HAC
26.592
79
0.586342
broken-wheel
4d44b1b692af90d9d08a1683c0f764dcef412996
2,975
cpp
C++
Source/Example/example_LuaLibrary.cpp
mf01/luacpp
ff06f2c5062968616d8e50162148f6cd070d124e
[ "MIT" ]
19
2021-08-29T23:16:02.000Z
2022-03-25T13:16:14.000Z
Source/Example/example_LuaLibrary.cpp
mf01/luacpp
ff06f2c5062968616d8e50162148f6cd070d124e
[ "MIT" ]
3
2021-07-23T19:05:05.000Z
2022-02-27T05:33:26.000Z
Source/Example/example_LuaLibrary.cpp
mf01/luacpp
ff06f2c5062968616d8e50162148f6cd070d124e
[ "MIT" ]
8
2021-03-29T07:39:04.000Z
2022-02-24T18:16:42.000Z
/* MIT License Copyright (c) 2021 Jordan Vrtanoski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../LuaCpp.hpp" #include <iostream> #include <stdexcept> using namespace LuaCpp; using namespace LuaCpp::Registry; using namespace LuaCpp::Engine; extern "C" { static int _foo (lua_State *L, int start) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0.0; int i; for (i = start; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushliteral(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum/n); /* first result */ lua_pushnumber(L, sum); /* second result */ return 2; /* number of results */ } static int foo(lua_State *L) { return _foo(L, 1); } static int foo_meta (lua_State *L) { return _foo(L, 2); } } int main(int argc, char **argv) { // Creage Lua context LuaContext lua; // Create library "foo" conatining the "foo" function std::shared_ptr<LuaLibrary> lib = std::make_shared<LuaLibrary>("foolib"); lib->AddCFunction("foo", foo); // Add library to the context lua.AddLibrary(lib); // Compile a code using the new foolib.foo function lua.CompileString("foo_test", "print(\"Result of calling foolib.foo(1,2,3,4) = \" .. foolib.foo(1,2,3,4))"); // Run the context try { lua.Run("foo_test"); } catch (std::runtime_error& e) { std::cout << e.what() << '\n'; } lua.CompileString("test", "print('Calling foo as a metafunction of a usertype ' .. foo(1,2,3,4))"); std::unique_ptr<LuaState> L = lua.newStateFor("test"); LuaTUserData ud(sizeof(LuaTUserData *)); ud.AddMetaFunction("__call", foo_meta); ud.PushGlobal(*L, "foo"); int res = lua_pcall(*L, 0, LUA_MULTRET, 0); if (res != LUA_OK ) { std::cout << "Error Executing " << res << " " << lua_tostring(*L,1) << "\n"; } }
30.050505
109
0.660504
mf01
4d4a6fde5107b9e9cb6b393324dddcb1d7745fa5
963
cpp
C++
src/QtAVPlayer/qavsubtitlecodec.cpp
valbok/QAVPlayer
6138dc7a2df8aef2bf8c40d004b115af538c627c
[ "MIT" ]
null
null
null
src/QtAVPlayer/qavsubtitlecodec.cpp
valbok/QAVPlayer
6138dc7a2df8aef2bf8c40d004b115af538c627c
[ "MIT" ]
null
null
null
src/QtAVPlayer/qavsubtitlecodec.cpp
valbok/QAVPlayer
6138dc7a2df8aef2bf8c40d004b115af538c627c
[ "MIT" ]
null
null
null
/********************************************************* * Copyright (C) 2020, Val Doroshchuk <[email protected]> * * * * This file is part of QtAVPlayer. * * Free Qt Media Player based on FFmpeg. * *********************************************************/ #include "qavsubtitlecodec_p.h" #include "qavcodec_p_p.h" #include <QDebug> extern "C" { #include <libavcodec/avcodec.h> } QT_BEGIN_NAMESPACE QAVSubtitleCodec::QAVSubtitleCodec(QObject *parent) : QAVCodec(parent) { } bool QAVSubtitleCodec::decode(const AVPacket *pkt, AVSubtitle *subtitle) const { Q_D(const QAVCodec); int got_output = 0; int ret = avcodec_decode_subtitle2(d->avctx, subtitle, &got_output, const_cast<AVPacket *>(pkt)); if (ret < 0 && ret != AVERROR(EAGAIN)) return false; return got_output; } QT_END_NAMESPACE
25.342105
91
0.519211
valbok
4d4adbd4278c8c0d7d3a851be4f1ff3249f0c1f7
521
cpp
C++
AtCoder/abc084/abc084_c.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
AtCoder/abc084/abc084_c.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
AtCoder/abc084/abc084_c.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int val[501], X[501], Y[501], Z[501]; int main(void){ int n; cin >> n; for(int i = 1; i < n; ++i){ cin >> X[i] >> Y[i] >> Z[i]; } for(int i = 1; i <= n; ++i){ long t = Y[i] + X[i]; for(int j = i + 1; j < n; ++j){ if(t > Y[j]){ t -= Y[j]; if(t % Z[j]){ t /= Z[j]; t++; t *= Z[j]; } t += Y[j]; }else{ t = Y[j]; } t += X[j]; } cout << t << "\n"; } }
16.28125
37
0.314779
itsmevanessi
4d4faa8ae9fef95b76cc139bafe32577e6d9521e
1,012
hpp
C++
example/sim4ana/source/ApplyEnergyResponse.hpp
goroyabu/anlpy
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
[ "MIT" ]
null
null
null
example/sim4ana/source/ApplyEnergyResponse.hpp
goroyabu/anlpy
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
[ "MIT" ]
null
null
null
example/sim4ana/source/ApplyEnergyResponse.hpp
goroyabu/anlpy
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
[ "MIT" ]
null
null
null
/** @file ApplyEnergyResponse.hpp @date 2020/08/24 @author @detail Automatically generated by make_anlpy_project.sh 1.0.0 **/ #ifndef ApplyEnergyResponse_hpp #define ApplyEnergyResponse_hpp #include <VANL_Module.hpp> class ApplyEnergyResponse : public anl::VANL_Module { public: ApplyEnergyResponse(); ~ApplyEnergyResponse(); int mod_bgnrun() override; int mod_ana() override; int mod_endrun() override; private: double randomize_energy_cathode (double energy, double electronics_noise, const std::string& mate); double randomize_energy_anode (double energy, double electronics_noise, const std::string& mate); double energy_resolution_cathode (double energy, double electronics_noise, const std::string& mate); double energy_resolution_anode (double energy, double electronics_noise, const std::string& mate); struct parameter_list { bool is_enabled_randomize; double electronics_noise; } parameter; }; #endif
23
71
0.733202
goroyabu
4d516fee81e17231ea2fe808adcf9608cadf91d1
3,762
cc
C++
test/unit/core/container/shared_data_test.cc
willhemsley/biodynamo
c36830de621f8e105bf5eac913b96405b5c9d75c
[ "Apache-2.0" ]
null
null
null
test/unit/core/container/shared_data_test.cc
willhemsley/biodynamo
c36830de621f8e105bf5eac913b96405b5c9d75c
[ "Apache-2.0" ]
null
null
null
test/unit/core/container/shared_data_test.cc
willhemsley/biodynamo
c36830de621f8e105bf5eac913b96405b5c9d75c
[ "Apache-2.0" ]
null
null
null
// ----------------------------------------------------------------------------- // // Copyright (C) 2021 CERN & Newcastle University for the benefit of the // BioDynaMo collaboration. 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #include "core/container/shared_data.h" #include <gtest/gtest.h> #include <vector> namespace bdm { // Test if resize and size method work correctly. TEST(SharedDataTest, ReSize) { SharedData<int> sdata(10); EXPECT_EQ(10u, sdata.size()); sdata.resize(20); EXPECT_EQ(20u, sdata.size()); } // Test if shared data is occupying full cache lines. TEST(SharedDataTest, CacheLineAlignment) { // Test standard data tyes int, float, double // Test alignment of int EXPECT_EQ( std::alignment_of<typename SharedData<int>::Data::value_type>::value, BDM_CACHE_LINE_SIZE); // Test alignment of float EXPECT_EQ( std::alignment_of<typename SharedData<float>::Data::value_type>::value, BDM_CACHE_LINE_SIZE); // Test alignment of double EXPECT_EQ( std::alignment_of<typename SharedData<double>::Data::value_type>::value, BDM_CACHE_LINE_SIZE); // Test size of vector components int EXPECT_EQ(sizeof(typename SharedData<int>::Data::value_type), BDM_CACHE_LINE_SIZE); // Test size of vector components float EXPECT_EQ(sizeof(typename SharedData<float>::Data::value_type), BDM_CACHE_LINE_SIZE); // Test size of vector components double EXPECT_EQ(sizeof(typename SharedData<double>::Data::value_type), BDM_CACHE_LINE_SIZE); // Test a chache line fully filled with doubles. // Test alignment of double[max_double], e.g. max cache line capacity EXPECT_EQ( std::alignment_of< typename SharedData<double[BDM_CACHE_LINE_SIZE / sizeof(double)]>::Data::value_type>::value, BDM_CACHE_LINE_SIZE); // Test size of vector components double[max_double], e.g. max cache line // capacity EXPECT_EQ( sizeof(typename SharedData< double[BDM_CACHE_LINE_SIZE / sizeof(double)]>::Data::value_type), BDM_CACHE_LINE_SIZE); // Test some custom data structures // Test alignment of data that fills 1 cache line EXPECT_EQ(std::alignment_of<typename SharedData< char[BDM_CACHE_LINE_SIZE - 1]>::Data::value_type>::value, BDM_CACHE_LINE_SIZE); // Test alignment of data that fills 2 cache lines EXPECT_EQ(std::alignment_of<typename SharedData< char[BDM_CACHE_LINE_SIZE + 1]>::Data::value_type>::value, BDM_CACHE_LINE_SIZE); // Test alignment of data that fills 3 cache lines EXPECT_EQ(std::alignment_of<typename SharedData< char[2 * BDM_CACHE_LINE_SIZE + 1]>::Data::value_type>::value, BDM_CACHE_LINE_SIZE); // Test size of data that fills 1 cache line EXPECT_EQ( sizeof( typename SharedData<char[BDM_CACHE_LINE_SIZE - 1]>::Data::value_type), BDM_CACHE_LINE_SIZE); // Test size of data that fills 2 cache lines EXPECT_EQ( sizeof( typename SharedData<char[BDM_CACHE_LINE_SIZE + 1]>::Data::value_type), 2 * BDM_CACHE_LINE_SIZE); // Test size of data that fills 3 cache lines EXPECT_EQ(sizeof(typename SharedData< char[2 * BDM_CACHE_LINE_SIZE + 1]>::Data::value_type), 3 * BDM_CACHE_LINE_SIZE); } } // namespace bdm
38.387755
80
0.662148
willhemsley
4d522a4da74a324d4626bb805ba9fca8290ac038
2,748
cpp
C++
src/StaticControls.cpp
pskowronski97z/EasyWin-GUI
858dc01b025d406dca3007339bb63f82c6996146
[ "MIT" ]
2
2021-03-22T08:17:50.000Z
2021-03-23T10:44:32.000Z
src/StaticControls.cpp
pskowronski97z/WinGUI
858dc01b025d406dca3007339bb63f82c6996146
[ "MIT" ]
null
null
null
src/StaticControls.cpp
pskowronski97z/WinGUI
858dc01b025d406dca3007339bb63f82c6996146
[ "MIT" ]
null
null
null
#include <StaticControls.h> #include <CommCtrl.h> #include <Window.h> WinGUI::Label::Label(const Window& parent, std::string name, const int& x, const int& y) : Control(parent, x, y, std::move(name)) { std::wstring w_name = string_to_wstring(name_); id_= STATIC_CTRL; width_ = w_name.size() * 6; handle_ = CreateWindowEx( 0, L"STATIC", w_name.c_str(), WS_CHILD | WS_VISIBLE | SS_LEFT, x_, y_, width_, FONT_HEIGHT, parent_handle_, (HMENU)id_, parent.get_instance(), 0); SendMessage(handle_, WM_SETFONT, (WPARAM)(HFONT)GetStockObject(DEFAULT_GUI_FONT), MAKELPARAM(TRUE, 0)); } void WinGUI::Label::set_text(std::string name) { name_ = name; std::wstring w_name = string_to_wstring(name_); SetWindowText(handle_,w_name.c_str()); width_ = w_name.size()*6; } int WinGUI::Label::get_width() const noexcept { return width_; } WinGUI::ProgressBar::ProgressBar(const Window& parent, std::string name, const int& x, const int& y, const int& width, const int& height) noexcept : Control(parent,x,y,std::move(name)),width_(width),height_(height),progress_(0.0f) { if (width_ < 0) width_ = 100; id_ = STATIC_CTRL; if(!name.empty()) { Label name_label(parent, name_,x_,y_); y_ += FONT_HEIGHT; } handle_ = CreateWindowEx( WS_EX_CLIENTEDGE, PROGRESS_CLASS, 0, WS_CHILD | WS_VISIBLE | PBS_SMOOTH | PBS_SMOOTHREVERSE, x_, y_, width_, height_, parent_handle_, (HMENU)id_, parent.get_instance(), 0); } int WinGUI::ProgressBar::get_width() const noexcept { return width_; } int WinGUI::ProgressBar::get_height() const noexcept { return height_; } float WinGUI::ProgressBar::get_progress() const noexcept { return progress_; } bool WinGUI::ProgressBar::set_progress(unsigned short progress) noexcept { if (progress < 0 || progress > 100) return false; progress_ = progress; SendMessage(handle_, PBM_SETPOS, (WPARAM)progress_, 0); return true; } WinGUI::GroupBox::GroupBox(const Window& parent, std::string name, const int& x, const int& y, const int& width, const int& height) : Control(parent, x, y, std::move(name)), width_(width), height_(height) { if(width_<=0) width_=100; if(height_<=0) height_=100; std::wstring w_name = string_to_wstring(name_); id_ = STATIC_CTRL; handle_ = CreateWindowEx( 0, L"BUTTON", w_name.c_str(), WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_GROUPBOX, x_, y_, width_, height_, parent_handle_, (HMENU)id_, parent.get_instance(), nullptr); SendMessage(handle_, WM_SETFONT, (WPARAM)((HFONT)GetStockObject(DEFAULT_GUI_FONT)), MAKELPARAM(TRUE, 0)); } int WinGUI::GroupBox::get_width() const noexcept { return width_; } int WinGUI::GroupBox::get_height() const noexcept { return height_; }
23.288136
146
0.699054
pskowronski97z
4d5649a874752696ebeb98383b2e45273a8be0d8
807
cpp
C++
Hashing/Incremental hash/Substring Concatenation.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
7
2019-06-29T08:57:07.000Z
2021-02-13T06:43:40.000Z
Hashing/Incremental hash/Substring Concatenation.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
null
null
null
Hashing/Incremental hash/Substring Concatenation.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
3
2020-06-17T04:26:26.000Z
2021-02-12T04:51:40.000Z
vector<int> Solution::findSubstring(string A, const vector<string> &B) { int l = 0; int n = B[0].size(); map<string, int> Main; map<string, int> checker; for( auto it : B ){ l += it.size(); Main[it]++; } vector<int> ans; for( int i = 0; i < A.size(); i++ ){ checker = Main; int flag = 1; for( int j = i, k = 0; k < l; ){ if( j == A.size() )return ans; string s = ""; for( int m = 0; m < n; m++, j++, k++ ){ s += A[j]; } if( checker.count(s) == 0 ){ flag = 0; break; } checker[s]--; if( checker[s] == 0 )checker.erase(s); } if( flag )ans.push_back(i); } return ans; }
26.032258
72
0.386617
cenation092
4d584cd3d4643561c0529a0bbdcf8228a395b398
7,707
cpp
C++
simxml/xsdgen/QDomNodeModel.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
simxml/xsdgen/QDomNodeModel.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
simxml/xsdgen/QDomNodeModel.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/* Copyright (c) 2011, Stanislaw Adaszewski All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Stanislaw Adaszewski nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANISLAW ADASZEWSKI BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "QDomNodeModel" #include <QDomNode> #include <QDomDocument> #include <QUrl> #include <QVector> #include <QSourceLocation> #include <QVariant> class MyDomNode: public QDomNode { public: MyDomNode(const QDomNode& other): QDomNode(other) { } MyDomNode(QDomNodePrivate *otherImpl): QDomNode(otherImpl) { } QDomNodePrivate* getImpl() { return impl; } }; QDomNodeModel::QDomNodeModel(QXmlNamePool pool, QDomDocument doc): m_Pool(pool), m_Doc(doc) { } QUrl QDomNodeModel::baseUri (const QXmlNodeModelIndex &) const { // TODO: Not implemented. return QUrl(); } QXmlNodeModelIndex::DocumentOrder QDomNodeModel::compareOrder ( const QXmlNodeModelIndex & ni1, const QXmlNodeModelIndex & ni2 ) const { QDomNode n1 = toDomNode(ni1); QDomNode n2 = toDomNode(ni2); if (n1 == n2) return QXmlNodeModelIndex::Is; Path p1 = path(n1); Path p2 = path(n2); for (int i = 1; i < p1.size(); i++) if (p1[i] == n2) return QXmlNodeModelIndex::Follows; for (int i = 1; i < p2.size(); i++) if (p2[i] == n1) return QXmlNodeModelIndex::Precedes; for (int i = 1; i < p1.size(); i++) for (int j = 1; j < p2.size(); j++) { if (p1[i] == p2[j]) // Common ancestor { int ci1 = childIndex(p1[i-1]); int ci2 = childIndex(p2[j-1]); if (ci1 < ci2) return QXmlNodeModelIndex::Precedes; else return QXmlNodeModelIndex::Follows; } } return QXmlNodeModelIndex::Precedes; // Should be impossible! } QUrl QDomNodeModel::documentUri (const QXmlNodeModelIndex&) const { // TODO: Not implemented. return QUrl(); } QXmlNodeModelIndex QDomNodeModel::elementById ( const QXmlName & id ) const { return fromDomNode(m_Doc.elementById(id.toClarkName(m_Pool))); } QXmlNodeModelIndex::NodeKind QDomNodeModel::kind ( const QXmlNodeModelIndex & ni ) const { QDomNode n = toDomNode(ni); if (n.isAttr()) return QXmlNodeModelIndex::Attribute; else if (n.isText()) return QXmlNodeModelIndex::Text; else if (n.isComment()) return QXmlNodeModelIndex::Comment; else if (n.isDocument()) return QXmlNodeModelIndex::Document; else if (n.isElement()) return QXmlNodeModelIndex::Element; else if (n.isProcessingInstruction()) return QXmlNodeModelIndex::ProcessingInstruction; return (QXmlNodeModelIndex::NodeKind) 0; } QXmlName QDomNodeModel::name ( const QXmlNodeModelIndex & ni ) const { QDomNode n = toDomNode(ni); if (n.isAttr() || n.isElement() || n.isProcessingInstruction()){ if (n.localName().isNull()){ //std::cout << n.nodeName().toStdString() << std::endl; //std::cout << n.localName().toStdString() << std::endl; //std::cout << n.namespaceURI().toStdString() << std::endl; //std::cout << n.prefix().toStdString() << std::endl; return QXmlName(m_Pool, n.nodeName(), QString(), QString()); }else{ //std::cout << n.nodeName().toStdString() << std::endl; //std::cout << n.localName().toStdString() << std::endl; //std::cout << n.namespaceURI().toStdString() << std::endl; //std::cout << n.prefix().toStdString() << std::endl; return QXmlName(m_Pool, n.localName(), n.namespaceURI(), n.prefix()); } } return QXmlName(m_Pool, QString(), QString(), QString()); } QVector<QXmlName> QDomNodeModel::namespaceBindings(const QXmlNodeModelIndex&) const { // TODO: Not implemented. return QVector<QXmlName>(); } QVector<QXmlNodeModelIndex> QDomNodeModel::nodesByIdref(const QXmlName&) const { // TODO: Not implemented. return QVector<QXmlNodeModelIndex>(); } QXmlNodeModelIndex QDomNodeModel::root ( const QXmlNodeModelIndex & ni ) const { QDomNode n = toDomNode(ni); while (!n.parentNode().isNull()) n = n.parentNode(); return fromDomNode(n); } QSourceLocation QDomNodeModel::sourceLocation(const QXmlNodeModelIndex&) const { // TODO: Not implemented. return QSourceLocation(); } QString QDomNodeModel::stringValue ( const QXmlNodeModelIndex & ni ) const { QDomNode n = toDomNode(ni); if (n.isProcessingInstruction()) return n.toProcessingInstruction().data(); else if (n.isText()) return n.toText().data(); else if (n.isComment()) return n.toComment().data(); else if (n.isElement()) return n.toElement().text(); else if (n.isDocument()) return n.toDocument().documentElement().text(); else if (n.isAttr()) return n.toAttr().value(); return QString(); } QVariant QDomNodeModel::typedValue ( const QXmlNodeModelIndex & ni ) const { return qVariantFromValue(stringValue(ni)); } QXmlNodeModelIndex QDomNodeModel::fromDomNode(const QDomNode &n) const { if (n.isNull()) return QXmlNodeModelIndex(); return createIndex(MyDomNode(n).getImpl(), 0); } QDomNode QDomNodeModel::toDomNode(const QXmlNodeModelIndex &ni) const { return MyDomNode((QDomNodePrivate*) ni.data()); } QDomNodeModel::Path QDomNodeModel::path(const QDomNode &n) const { Path res; QDomNode cur = n; while (!cur.isNull()) { res.push_back(cur); cur = cur.parentNode(); } return res; } int QDomNodeModel::childIndex(const QDomNode &n) const { QDomNodeList children = n.parentNode().childNodes(); for (int i = 0; i < children.size(); i++) if (children.at(i) == n) return i; return -1; } QVector<QXmlNodeModelIndex> QDomNodeModel::attributes ( const QXmlNodeModelIndex & ni ) const { QDomElement n = toDomNode(ni).toElement(); QDomNamedNodeMap attrs = n.attributes(); QVector<QXmlNodeModelIndex> res; for (int i = 0; i < attrs.size(); i++) { res.push_back(fromDomNode(attrs.item(i))); } return res; } QXmlNodeModelIndex QDomNodeModel::nextFromSimpleAxis ( SimpleAxis axis, const QXmlNodeModelIndex & ni) const { QDomNode n = toDomNode(ni); switch(axis) { case Parent: return fromDomNode(n.parentNode()); case FirstChild: return fromDomNode(n.firstChild()); case PreviousSibling: return fromDomNode(n.previousSibling()); case NextSibling: return fromDomNode(n.nextSibling()); } return QXmlNodeModelIndex(); }
27.525
109
0.688335
bobzabcik
4d5a4b49aae516e4575a364a1d9a0b556a3330ac
24,032
cpp
C++
test/test_server.cpp
CyanicYang/End_to_End_Encryption
a4908d86d3261a9df89d90078623198d7c03c6a8
[ "MIT" ]
1
2021-03-31T16:47:07.000Z
2021-03-31T16:47:07.000Z
test/test_server.cpp
CyanicYang/End_to_End_Encryption
a4908d86d3261a9df89d90078623198d7c03c6a8
[ "MIT" ]
null
null
null
test/test_server.cpp
CyanicYang/End_to_End_Encryption
a4908d86d3261a9df89d90078623198d7c03c6a8
[ "MIT" ]
null
null
null
#include "communicate.hpp" int log_init(std::ofstream &log_stream, const std::string log_name, const Level level, const bool* const log_env, const bool on_screen, const bool is_trunc) { // log_stream must not be opened before getting into this function. if (log_stream.is_open()) { return -1; } if (is_trunc) { log_stream.open(log_name, ios::out|ios::trunc); } else { log_stream.open(log_name, ios::out|ios::app); } if (!log_stream.is_open()) { return -2; } Log::get().setLogStream(log_stream); Log::get().setLevel(level); Log::get().setEnv(log_env); Log::get().setOnScreen(on_screen); return 0; } std::string logify_data(const uint8_t* data, const int len) { std::stringstream ss, ss_word; // ss_word.str(std::string()); int i; for (i = 0; i < len; i++) { if (i % 16 == 0) { ss << ss_word.str() << std::endl; ss_word.clear(); //clear any bits set ss_word.str(std::string()); ss << ' ' << setw(4) << setfill('0') << hex << uppercase << i << ": "; } else if (i % 8 == 0) { ss << "- "; } ss << setw(2) << setfill('0') << hex << uppercase << +data[i] << ' '; // print printable char. char ch = (data[i] > 31 && data[i] < 127) ? data[i] : '.'; ss_word << ch; // ss_word << data[i]; } if (i%16==0){ ss << setw(0) << ss_word.str(); } else { auto interval = 3 * (16 - (i % 16)) + (i % 16 > 8 ? 0 : 2); // cout << "i: " << i << ", interval: " << interval << endl; ss << setw(interval) << setfill(' ') << ' ' << setw(0) << ss_word.str(); } return ss.str(); } void encrypt_auth(u_int& random_num, u_int& svr_time, uint8_t* auth, const int length) { svr_time = (u_int)time(0); svr_time = svr_time ^ (u_int)0xFFFFFFFF; srand(svr_time); random_num = (u_int)rand(); int pos = random_num % 4093; for (int i = 0; i < length; i++) { auth[i] = auth[i] ^ kSecret[pos]; pos = (pos+1)%4093; } } bool decrypt_auth(const u_int random_num, uint8_t* auth, const int length) { const uint8_t c_auth[33] = "yzmond:id*str&to!tongji@by#Auth^"; int pos = random_num % 4093; for (int i = 0; i < length; i++) { auth[i] = auth[i] ^ kSecret[pos]; if (i > length-32 && auth[i] != c_auth[i-length+32]) { return false; } pos = (pos+1)%4093; } return true; } void create_random_str(uint8_t* random_string, const int length) { uint8_t *p = new uint8_t[length]; srand((unsigned)time(NULL)); for(int i = 0; i < length; i++) { p[i] = rand() % 256; } memcpy(random_string, p, length); delete[] p; return; } // return size of the file, if open file error, return 0. // must read no more than maxLength(8191/4095) bytes. int read_dat(const std::string dat_name, char* result, int maxLength) { ifstream ifs; ifs.open(dat_name, std::ifstream::in); if (!ifs.is_open()) { return -1; } // read no more than 8191 bytes. ifs.seekg(0, std::ios::end); int length = ifs.tellg(); length = length > maxLength ? maxLength : length; ifs.seekg(0, std::ios::beg); ifs.read(result, length); ifs.close(); return length; } // TODO: Is this necessary? DevInfo Server::gene_dev_info() { dev.cpu = 2600; dev.ram = 1846; dev.flash = 3723; srand((unsigned)time(NULL)); //'devid' in database //TODO: need unique instID(devid)! and I'm not doing this. dev.instID = rand() % 512; dev.instInnID = 1; dev.devInnerID = rand() % 256; dev.devInnerID = dev.devInnerID << 8; dev.devInnerID += rand() % 256; create_random_str(dev.groupSeq, 16); create_random_str(dev.type, 16); create_random_str(dev.version, 16); return dev; } void Server::push_back_array(vector<uint8_t> & message, uint8_t * array, int length) { for(int i=0; i<length; i++) { message.push_back(array[i]); } return; } void Server::push_back_uint16(vector<uint8_t> & message, uint16_t data) { auto var16 = inet_htons(data); message.push_back((uint8_t)(var16>>8)); message.push_back((uint8_t)(var16)); } void Server::push_back_uint32(vector<uint8_t> & message, uint32_t data) { auto var32 = inet_htonl(data); message.push_back((uint8_t)(var32>>24)); message.push_back((uint8_t)(var32>>16)); message.push_back((uint8_t)(var32>>8)); message.push_back((uint8_t)(var16)); return; } void Server::pop_first_array(vector<uint8_t> & message, uint8_t * array, int length) { for(int i=0; i<length; i++) { array[i] = message.front(); message.erase(message.begin()); } return; } void Server::pop_first_uint8(vector<uint8_t> & message, uint8_t& data) { data = message.front(); message.erase(message.begin()); } void Server::pop_first_uint16(vector<uint8_t> & message, uint16_t& data) { uint8_t raw[2]; raw[1] = message.front(); message.erase(message.begin()); raw[2] = message.front(); message.erase(message.begin()); memcpy(&data, sizeof(data), raw, 2); data = inet_ntohs(data); } void Server::pop_first_uint32(vector<uint8_t> & message, uint32_t& data) { uint8_t raw[4]; raw[1] = message.front(); message.erase(message.begin()); raw[2] = message.front(); message.erase(message.begin()); raw[3] =message.front(); message.erase(message.begin()); raw[4] = message.front(); message.erase(message.begin()); memcpy(&data, sizeof(data), raw, 4); data = inet_ntohl(data); } // TODO: Is this necessary? void Server::push_back_screen_info(vector<uint8_t> & message) { //screen message.push_back((uint8_t)(1 + rand() % 16)); //pad message.push_back((uint8_t)0x00); //remote server port //TODO: HOW TO GET REMOTE PORT?? push_back_uint16(message, (uint16_t)12350); //remote server ip //TODO: HOW TO GET REMOTE IP?? uint32_t ip = (uint32_t)inet_aton("192.168.0.0"); message.push_back((uint8_t)ip >> 24); message.push_back((uint8_t)ip >> 16); message.push_back((uint8_t)ip >> 8); message.push_back((uint8_t)ip); //proto string prot = "专用SSH"; const char tp[12] = {0}; tp = prot.c_str(); push_back_array(message, (uint8_t *)tp, 12); //screen state string state = "已登录"; const char tp[8] = {0}; tp = prot.c_str(); push_back_array(message, (uint8_t *)tp, 8); //screen prompt string promp = "储蓄系统"; const char tp[24] = {0}; tp = promp.c_str(); push_back_array(message, (uint8_t *)tp, 24); //tty type string ttyType = "vt100"; const char tp[12] = {0}; tp = ttyType.c_str(); push_back_array(message, (uint8_t *)tp, 12); //system time push_back_uint32(message, (uint32_t)time(NULL)); //statics push_back_uint32(message, (uint32_t)rand() % 1000000); push_back_uint32(message, (uint32_t)rand() % 1000000); push_back_uint32(message, (uint32_t)rand() % 1000000); push_back_uint32(message, (uint32_t)rand() % 1000000); //Ping statics push_back_uint32(message, (uint32_t)rand() % 123456); push_back_uint32(message, (uint32_t)rand() % 123456); push_back_uint32(message, (uint32_t)rand() % 123456); } // TODO: Rewrite it symmetrically as client_pack message. void Server::server_unpack_message(Options opt) { vector<uint8_t> message; //head message.push_back((uint8_t)0x91); //descriptor message.push_back((uint8_t)type); switch(type) { case PacketType::VersionRequire: //packet length push_back_uint16(message, (uint16_t)12); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)4); //main version push_back_uint16(message, serverMainVersion); //sec 1 version message.push_back(serverSec1Version); //sec 2 version message.push_back(serverSec2Version); break; case PacketType::AuthResponse: //packet length push_back_uint16(message, (uint16_t)116); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)108); //CPU push_back_uint16(message, dev.cpu); //RAM push_back_uint16(message, dev.ram); //FLASH push_back_uint16(message, dev.flash); //dev inner seq push_back_uint16(message, dev.devInnerID); //group seq push_back_array(message, dev.groupSeq, 16); //type push_back_array(message, dev.type, 16); //version push_back_array(message, dev.version,16); //ethernet, usb, printer..., 8 bytes in total for(int ip = 0; ip < 8; ip++) { message.push_back((uint8_t)0); } //instID push_back_uint32(message, dev.instID); //instInnID message.push_back(dev.instInnID); //2 bytes pad for(int ip = 0; ip < 2; ip++) { message.push_back((uint8_t)0); } //authstr vector<uint8_t> tmp; uint8_t tpdata[104]; vector<uint8_t>::iterator it; it = message.begin() + 8; //from CPU for(; it != message.end(); it++) { //to the last uint8_t in current message tmp.push_back(*it); } int n = tmp.size(); if(n != 72) { LOG(Level::Error) << "Descriptor: 0x91" << endl << "PacketType: 0x01" << endl << "the bit num from CPU to AuthStr is not 72!!" << endl; return false; } for(int i = 0; i < 72; i++) { tpdata[i] = tmp[i]; } uint8_t authStr[33] = "yzmond:id*str&to!tongji@by#Auth^"; for(int i = 0; i < 32; i++) { tpdata[72+i] = authStr[i]; } //encrypt u_int random_num=0, svr_time=0; encrypt_auth(random_num, svr_time, tpdata, 104); it = message.begin() + 8; for(int i = 0; i < 72; i++) { // replace old 72 bytes message[i+8] = tpdata[i]; } for(int i = 72; i < 104; i++) { //add new auth str (32 bytes) message.push_back(tpdata[i]); } //random num push_back_uint32(message, (uint32_t)random_num); break; case PacketType::SysInfoResponse: //packet length push_back_uint16(message, (uint16_t)28); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)20); //user CPU time push_back_uint32(message, (uint32_t)5797); //nice CPU time push_back_uint32(message, (uint32_t)0); //system CPU time push_back_uint32(message, (uint32_t)13013); //idle CPU time push_back_uint32(message, (uint32_t)5101426); //freed memory push_back_uint32(message, (uint32_t)2696); break; case PacketType::ConfInfoResponse: //load config.dat char * read_file = new char[8192]; string file_name = "config.dat"; int size = read_dat(file_name, read_file, 8191); if (size < 0) { LOG(Level::ERR) << "No such file: " << file_name << endl; return -1; } LOG(Level::RDATA) << "read test:" << logify_data(reinterpret_cast<uint8_t*>(read_file), size) << endl; LOG(Level::Debug) << "size of data: " << size << endl; // add '\0' to the end of string read_file[size++] = '\0'; //packet length push_back_uint16(message, (uint16_t)size + 8); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)size); //config info push_back_array(message, (uint8_t *)read_file, size); break; case PacketType::ProcInfoResponse: //load config.dat char * read_file = new char[8192]; string file_name = "process.dat"; int size = read_dat(file_name, read_file, 8191); if (size < 0) { LOG(Level::ERR) << "No such file: " << file_name << endl; return -1; } LOG(Level::RDATA) << "read test:" << logify_data(reinterpret_cast<uint8_t*>(read_file), size) << endl; LOG(Level::Debug) << "size of data: " << size << endl; // add '\0' to the end of string read_file[size++] = '\0'; //packet length push_back_uint16(message, (uint16_t)size + 8); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)size); //config info push_back_array(message, (uint8_t *)read_file, size); break; case PacketType::USBfileResponse: //load usefile.dat char * read_file = new char[8192]; string file_name = "usefile.dat"; int size = read_dat(file_name, read_file, 4095); if (size < 0) { LOG(Level::ERR) << "No such file: " << file_name << endl; return -1; } LOG(Level::RDATA) << "read test:" << logify_data(reinterpret_cast<uint8_t*>(read_file), size) << endl; LOG(Level::Debug) << "size of data: " << size << endl; // add '\0' to the end of string read_file[size++] = '\0'; //packet length push_back_uint16(message, (uint16_t)size + 8); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)size); //config info push_back_array(message, (uint8_t *)read_file, size); break; case PacketType::PrintQueueResponse: //packet length push_back_uint16(message, (uint16_t)9); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)1); message.push_back((uint8_t)0); break; case PacketType::TerInfoResponse: uint8_t ttyInfoMap[270] = {0}; //dumb+IP terminal map // for(int i = 0; i < 16; i++) { // ttyInfoMap[i] = 0; // } //no dumb terminal //TODO: get max&min tty amount from Options int maxTNum = stoi(opt.at["最大配置终端数量"]); int minTNum = stoi(opt.at["最小配置终端数量"]); LOG(Level::Debug) << "max tty amount = " << maxSNum << endl; LOG(Level::Debug) << "min tty amount = " << minSNum << endl; int total = minTNum + rand() % (maxTNum - minTNum + 1); int async_term_num = 0; int ipterm_num = total - async_term_num; int randPos; //generate random ttyInfoMap for(int i = 0; i < ipterm_num; i++) { randPos = rand() % 254; while(ttyInfoMap[16 + randPos] == 1) { randPos = rand() % 254; } ttyInfoMap[16 + randPos] = 1; } //16 dumb-terminal, 254 ip-terminal, 2 bytes tty num //packet length push_back_uint16(message, (uint16_t)(8+16+254+2)); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)(16+254+2)); //tty map push_back_array(message, ttyInfoMap, 270); //tty configed push_back_uint16(message, (uint16_t)(total + rand() % (270-total) )); break; case PacketType::DumbTerResponse: int maxSNum = stoi(opt.at["每个终端最大虚屏数量"]); int minSNum = stoi(opt.at["每个终端最小虚屏数量"]); LOG(Level::Debug) << "max screen num = " << maxSNum << endl; LOG(Level::Debug) << "min screen num = " << minSNum << endl; uint8_t screenNum = minSNum + rand() % (maxSNum - minSNum + 1); uint8_t activeScreen = rand() % screenNum; //packet length push_back_uint16(message, (uint16_t)(8 + 28 + screenNum*96)); //dumb terminal number push_back_uint16(message, (uint16_t)(1 + rand() % 16)); //data length push_back_uint16(message, (uint16_t)(28 + screenNum*96)); //port message.push_back((uint8_t)(1 + rand() % 254) ); //asigned port message.push_back((uint8_t)(1 + rand() % 254) ); //active screen message.push_back(activeScreen); //screen numv message.push_back(screenNum); //tty addr push_back_uint32(message, (uint32_t)0); //tty type string ttyType = "串口终端"; const char tp[12] = {0}; tp = ttyType.c_str(); push_back_array(message, (uint8_t *)tp, 12); //tty state string ttyState = "正常"; memset(tp, 0, 12); tp = ttyState.c_str(); push_back_array(message, (uint8_t *)tp, 8); //screen info for(int i = 0; i < screenNum; i++) { push_back_screen_info(message); } break; case PacketType::IPTermResponse: int maxSNum = stoi(opt.at["每个终端最大虚屏数量"]); int minSNum = stoi(opt.at["每个终端最小虚屏数量"]); LOG(Level::Debug) << "max screen num = " << maxSNum << endl; LOG(Level::Debug) << "min screen num = " << minSNum << endl; uint8_t screenNum = minSNum + rand() % (maxSNum - minSNum + 1); uint8_t activeScreen = rand() % screenNum; //packet length push_back_uint16(message, (uint16_t)(8 + 28 + screenNum*96)); //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)(28 + screenNum*96)); //port message.push_back((uint8_t)(1 + rand() % 254) ); //asigned port message.push_back((uint8_t)(1 + rand() % 254) ); //active screen message.push_back(activeScreen); //screen numv message.push_back(screenNum); //tty addr uint32_t ip = (uint32_t)inet_aton("192.168.80.2"); message.push_back((uint8_t)ip >> 24); message.push_back((uint8_t)ip >> 16); message.push_back((uint8_t)ip >> 8); message.push_back((uint8_t)ip); //tty type string ttyType = "IP终端"; const char tp[12] = {0}; tp = ttyType.c_str(); push_back_array(message, (uint8_t *)tp, 12); //tty state string ttyState = "菜单"; memset(tp, 0, 12); tp = ttyState.c_str(); push_back_array(message, (uint8_t *)tp, 8); //screen info for(int i = 0; i < screenNum; i++) { push_back_screen_info(message); } break; case PacketType::End: //packet length push_back_uint16(message, (uint16_t)8; //0x0000 push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)0); break; default: break; } send_message = message; return true; } // TODO: Rewrite it symmetrically as client_unpack message. bool Server::server_pack_message(PacketType type, Options opt) { vector<uint8_t> message; //head message.push_back((uint8_t)0x91); //descriptor message.push_back((uint8_t)type); switch(type) { case PacketType::AuthRequest: //packet length push_back_uint16(message, (uint16_t)60); //padding push_back_uint16(message, (uint16_t)0x0000); //data length push_back_uint16(message, (uint16_t)52); //main version push_back_uint16(message, (uint16_t)3); //sec 1 version message.push_back((uint8_t)0); //sec 2 version message.push_back((uint8_t)0); // 设备连接间隔 push_back_uint16(message, static_cast<uint16_t>(stoi(opt.at["设备连接间隔"])); // 设备采样间隔 push_back_uint16(message, static_cast<uint16_t>(stoi(opt.at["设备采样间隔"])); // 是否允许空终端,强制为1 message.push_back((uint8_t)1); message.push_back((uint8_t)0); push_back_uint16(message, (uint16_t)0); // server_auth, random_num, svr_time uint8_t server_auth[33] = "yzmond:id*str&to!tongji@by#Auth^"; u_int random_num=0, svr_time=0; encrypt_auth(random_num, svr_time, auth, 32); push_back_array(message, server_auth, 32); push_back_uint32(message, static_cast<uint32_t>(random_num)); push_back_uint32(message, static_cast<uint32_t>(svr_time)); return true; // TODO case PacketType::SysInfoRequest: LOG(Level::ENV) << "服务器请求系统信息" << endl; return true; case PacketType::ConfInfoRequest: LOG(Level::ENV) << "服务器请求配置信息" << endl; return true; case PacketType::ProcInfoRequest: LOG(Level::ENV) << "服务器请求进程信息" << endl; return true; case PacketType::EtherInfoRequest: LOG(Level::ENV) << "服务器请求以太网口信息" << endl; return true; case PacketType::USBInfoRequest: LOG(Level::ENV) << "服务器请求USB口信息" << endl; return true; case PacketType::USBfileRequest: LOG(Level::ENV) << "服务器请求U盘信息" << endl; return true; case PacketType::PrintDevRequest: LOG(Level::ENV) << "服务器请求打印口信息" << endl; return true; case PacketType::PrintQueueRequest: LOG(Level::ENV) << "服务器请求打印队列信息" << endl; return true; case PacketType::TerInfoRequest: LOG(Level::ENV) << "服务器请求终端服务信息" << endl; return true; case PacketType::DumbTerRequest: LOG(Level::ENV) << "服务器请求哑终端信息" << endl; pop_first_uint16(message, rawDumbTerFlags); return true; case PacketType::IPTermRequest: LOG(Level::ENV) << "服务器请求IP终端信息" << endl; pop_first_uint16(message, rawIPTerFlags); return true; case PacketType::End: LOG(Level::ENV) << "服务器提示已收到全部包" << endl; return true; default: LOG(Level::ERR) << "不可被识别的包类型" << endl; return false; } } // TODO: now just pseudo. int Server::server_communicate(int socketfd, Options opt) { srand((unsigned)time(NULL)); //block recv(); client_unpack_message(); while(recvPakcet != PacketType::End) { //recv & send message client_pack_message(); send(); recv(); client_unpack_message(); } return 0; }
33.800281
158
0.537908
CyanicYang
4d5f99250b5504e62f3b76b5cd0c8c3186fa04e8
6,042
cpp
C++
Source/USharp/Private/ModulePaths.cpp
MiheevN/USharp
8f0205cd8628b84a66326947d93588a8c8dcbd24
[ "MIT" ]
353
2018-09-29T07:34:40.000Z
2022-03-07T17:03:06.000Z
Source/USharp/Private/ModulePaths.cpp
MiheevN/USharp
8f0205cd8628b84a66326947d93588a8c8dcbd24
[ "MIT" ]
66
2018-09-29T04:08:06.000Z
2020-09-30T22:10:56.000Z
Source/USharp/Private/ModulePaths.cpp
MiheevN/USharp
8f0205cd8628b84a66326947d93588a8c8dcbd24
[ "MIT" ]
64
2018-09-29T02:12:07.000Z
2022-02-18T07:41:45.000Z
#include "ModulePaths.h" #include "USharpPCH.h" #include "Interfaces/IPluginManager.h" #include "Modules/ModuleManifest.h" #include "HAL/PlatformProcess.h" #include "HAL/FileManager.h" #include "Misc/App.h" #include "Misc/Paths.h" DEFINE_LOG_CATEGORY_STATIC(LogModuleManager, Log, All); bool FModulePaths::BuiltDirectories = false; TArray<FString> FModulePaths::GameBinariesDirectories; TArray<FString> FModulePaths::EngineBinariesDirectories; TOptional<TMap<FName, FString>> FModulePaths::ModulePathsCache; TOptional<FString> FModulePaths::BuildId; void FModulePaths::FindModulePaths(const TCHAR* NamePattern, TMap<FName, FString> &OutModulePaths, bool bCanUseCache /*= true*/) { if (!BuiltDirectories) { BuildDirectories(); } if (!ModulePathsCache) { ModulePathsCache.Emplace(); const bool bCanUseCacheWhileGeneratingIt = false; FindModulePaths(TEXT("*"), ModulePathsCache.GetValue(), bCanUseCacheWhileGeneratingIt); } if (bCanUseCache) { // Try to use cache first if (const FString* ModulePathPtr = ModulePathsCache->Find(NamePattern)) { OutModulePaths.Add(FName(NamePattern), *ModulePathPtr); return; } // Wildcard for all items if (FCString::Strcmp(NamePattern, TEXT("*")) == 0) { OutModulePaths = ModulePathsCache.GetValue(); return; } // Wildcard search if (FCString::Strchr(NamePattern, TEXT('*')) || FCString::Strchr(NamePattern, TEXT('?'))) { bool bFoundItems = false; FString NamePatternString(NamePattern); for (const TPair<FName, FString>& CacheIt : ModulePathsCache.GetValue()) { if (CacheIt.Key.ToString().MatchesWildcard(NamePatternString)) { OutModulePaths.Add(CacheIt.Key, *CacheIt.Value); bFoundItems = true; } } if (bFoundItems) { return; } } } // Search through the engine directory FindModulePathsInDirectory(FPlatformProcess::GetModulesDirectory(), false, NamePattern, OutModulePaths); // Search any engine directories for (int Idx = 0; Idx < EngineBinariesDirectories.Num(); Idx++) { FindModulePathsInDirectory(EngineBinariesDirectories[Idx], false, NamePattern, OutModulePaths); } // Search any game directories for (int Idx = 0; Idx < GameBinariesDirectories.Num(); Idx++) { FindModulePathsInDirectory(GameBinariesDirectories[Idx], true, NamePattern, OutModulePaths); } } void FModulePaths::FindModulePathsInDirectory(const FString& InDirectoryName, bool bIsGameDirectory, const TCHAR* NamePattern, TMap<FName, FString> &OutModulePaths) { // Figure out the BuildId if it's not already set. if (!BuildId.IsSet()) { FString FileName = FModuleManifest::GetFileName(FPlatformProcess::GetModulesDirectory(), false); FModuleManifest Manifest; if (!FModuleManifest::TryRead(FileName, Manifest)) { UE_LOG(LogModuleManager, Fatal, TEXT("Unable to read module manifest from '%s'. Module manifests are generated at build time, and must be present to locate modules at runtime."), *FileName) } BuildId = Manifest.BuildId; } // Find all the directories to search through, including the base directory TArray<FString> SearchDirectoryNames; IFileManager::Get().FindFilesRecursive(SearchDirectoryNames, *InDirectoryName, TEXT("*"), false, true); SearchDirectoryNames.Insert(InDirectoryName, 0); // Enumerate the modules in each directory for(const FString& SearchDirectoryName: SearchDirectoryNames) { FModuleManifest Manifest; if (FModuleManifest::TryRead(FModuleManifest::GetFileName(SearchDirectoryName, bIsGameDirectory), Manifest) && Manifest.BuildId == BuildId.GetValue()) { for (const TPair<FString, FString>& Pair : Manifest.ModuleNameToFileName) { if (Pair.Key.MatchesWildcard(NamePattern)) { OutModulePaths.Add(FName(*Pair.Key), *FPaths::Combine(*SearchDirectoryName, *Pair.Value)); } } } } } void FModulePaths::BuildDirectories() { // From Engine\Source\Runtime\Launch\Private\LaunchEngineLoop.cpp if (FApp::HasProjectName()) { const FString ProjectBinariesDirectory = FPaths::Combine(FPlatformMisc::ProjectDir(), TEXT("Binaries"), FPlatformProcess::GetBinariesSubdirectory()); GameBinariesDirectories.Add(*ProjectBinariesDirectory); } // From Engine\Source\Runtime\Projects\Private\PluginManager.cpp for (TSharedRef<IPlugin>& Plugin : IPluginManager::Get().GetDiscoveredPlugins()) { if (Plugin->IsEnabled()) { // Add the plugin binaries directory const FString PluginBinariesPath = FPaths::Combine(*FPaths::GetPath(Plugin->GetDescriptorFileName()), TEXT("Binaries"), FPlatformProcess::GetBinariesSubdirectory()); AddBinariesDirectory(*PluginBinariesPath, Plugin->GetLoadedFrom() == EPluginLoadedFrom::Project); } } // From FModuleManager::Get() //temp workaround for IPlatformFile being used for FPaths::DirectoryExists before main() sets up the commandline. #if PLATFORM_DESKTOP // Ensure that dependency dlls can be found in restricted sub directories const TCHAR* RestrictedFolderNames[] = { TEXT("NoRedist"), TEXT("NotForLicensees"), TEXT("CarefullyRedist") }; FString ModuleDir = FPlatformProcess::GetModulesDirectory(); for (const TCHAR* RestrictedFolderName : RestrictedFolderNames) { FString RestrictedFolder = ModuleDir / RestrictedFolderName; if (FPaths::DirectoryExists(RestrictedFolder)) { AddBinariesDirectory(*RestrictedFolder, false); } } #endif BuiltDirectories = true; } void FModulePaths::AddBinariesDirectory(const TCHAR *InDirectory, bool bIsGameDirectory) { if (bIsGameDirectory) { GameBinariesDirectories.Add(InDirectory); } else { EngineBinariesDirectories.Add(InDirectory); } // Also recurse into restricted sub-folders, if they exist const TCHAR* RestrictedFolderNames[] = { TEXT("NoRedist"), TEXT("NotForLicensees"), TEXT("CarefullyRedist") }; for (const TCHAR* RestrictedFolderName : RestrictedFolderNames) { FString RestrictedFolder = FPaths::Combine(InDirectory, RestrictedFolderName); if (FPaths::DirectoryExists(RestrictedFolder)) { AddBinariesDirectory(*RestrictedFolder, bIsGameDirectory); } } }
33.016393
192
0.75091
MiheevN
4d6281f71e8ce24ab6c75d1b89c61b74bbeb1d95
578
hpp
C++
src/AST/Expressions/FunctionCallExpression.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/AST/Expressions/FunctionCallExpression.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/AST/Expressions/FunctionCallExpression.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
#pragma once #include "ExpressionList.hpp" struct FunctionCallExpression : Expression { std::string id; std::vector<std::shared_ptr<Expression>> args; FunctionCallExpression(char *, ExpressionList *); ~FunctionCallExpression() override = default; void print() const override; bool isConst() const override; std::optional<int> try_fold() override; std::string emitToRegister(SymbolTable &table, RegisterPool &pool) override; void emitTailCall(SymbolTable &table, RegisterPool &pool); type getType(SymbolTable &table) override; };
24.083333
80
0.723183
CarsonFox
4d644f6346992070b3021e1b3d9ca09e77b4e09b
5,262
hpp
C++
include/lbann/layers/loss/cross_entropy.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
include/lbann/layers/loss/cross_entropy.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
include/lbann/layers/loss/cross_entropy.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <[email protected]> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_LAYERS_LOSS_CROSS_ENTROPY_HPP_INCLUDED #define LBANN_LAYERS_LOSS_CROSS_ENTROPY_HPP_INCLUDED #include "lbann/layers/layer.hpp" namespace lbann { /** Cross entropy layer. * Given a predicted distribution \f$y\f$ and ground truth * distribution \f$\hat{y}\f$, the cross entropy is * \f[ * CE(y,\hat{y}) = - \sum\limits_{i} \hat{y}_i \log y_i * \f] */ template <data_layout T_layout, El::Device Dev> class cross_entropy_layer : public Layer { public: cross_entropy_layer(lbann_comm *comm) : Layer(comm) { set_output_dims({1}); // Expects inputs for prediction and ground truth m_expected_num_parent_layers = 2; } cross_entropy_layer(const cross_entropy_layer& other) : Layer(other) { m_workspace.reset(other.m_workspace ? other.m_workspace->Copy() : nullptr); } cross_entropy_layer& operator=(const cross_entropy_layer& other) { Layer::operator=(other); m_workspace.reset(other.m_workspace ? other.m_workspace->Copy() : nullptr); return *this; } cross_entropy_layer* copy() const override { return new cross_entropy_layer(*this); } std::string get_type() const override { return "cross entropy"; } data_layout get_data_layout() const override { return T_layout; } El::Device get_device_allocation() const override { return Dev; } void setup_data() override { Layer::setup_data(); // Initialize workspace const auto& prediction = get_prev_activations(0); switch (get_data_layout()) { case data_layout::DATA_PARALLEL: m_workspace.reset(new StarVCMat<Dev>(prediction.Grid(), prediction.Root())); break; case data_layout::MODEL_PARALLEL: m_workspace.reset(new StarMRMat<Dev>(prediction.Grid(), prediction.Root())); break; default: LBANN_ERROR("invalid data layout"); } #ifdef HYDROGEN_HAVE_CUB if (m_workspace->GetLocalDevice() == El::Device::GPU) { m_workspace->Matrix().SetMemoryMode(1); // CUB memory pool } #endif // HYDROGEN_HAVE_CUB } void fp_compute() override { // Initialize workspace const auto& prediction = get_prev_activations(0); m_workspace->AlignWith(prediction.DistData()); m_workspace->Resize(1, prediction.Width()); // Compute local contributions and accumulate /// @todo Consider reduce rather than allreduce local_fp_compute(get_local_prev_activations(0), get_local_prev_activations(1), m_workspace->Matrix()); m_comm->allreduce(*m_workspace, m_workspace->RedundantComm()); El::Copy(*m_workspace, get_activations()); } void bp_compute() override { // Initialize workspace const auto& prediction = get_prev_activations(0); m_workspace->AlignWith(prediction.DistData()); El::Copy(get_prev_error_signals(), *m_workspace); // Compute local gradients local_bp_compute(get_local_prev_activations(0), get_local_prev_activations(1), m_workspace->LockedMatrix(), get_local_error_signals(0), get_local_error_signals(1)); } private: /** Compute local contributions to cross entropy loss. */ static void local_fp_compute(const AbsMat& local_prediction, const AbsMat& local_ground_truth, AbsMat& local_contribution); /** Compute local gradients. */ static void local_bp_compute(const AbsMat& local_prediction, const AbsMat& local_ground_truth, const AbsMat& local_gradient_wrt_output, AbsMat& local_gradient_wrt_prediction, AbsMat& local_gradient_wrt_ground_truth); /** Workspace matrix. */ std::unique_ptr<AbsDistMat> m_workspace; }; } // namespace lbann #endif // LBANN_LAYERS_LOSS_CROSS_ENTROPY_HPP_INCLUDED
35.08
87
0.640631
andy-yoo
4d6cdafaade749c118cd6a6ef84cfd1af3abc49d
875
cpp
C++
SOLVER/src/core/source/elem_src/solid/SolidForce.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
8
2020-06-05T01:13:20.000Z
2022-02-24T05:11:50.000Z
SOLVER/src/core/source/elem_src/solid/SolidForce.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
24
2020-10-21T19:03:38.000Z
2021-11-17T21:32:02.000Z
SOLVER/src/core/source/elem_src/solid/SolidForce.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
5
2020-06-21T11:54:22.000Z
2021-06-23T01:02:39.000Z
// // SolidForce.cpp // AxiSEM3D // // Created by Kuangdai Leng on 3/5/19. // Copyright © 2019 Kuangdai Leng. All rights reserved. // // force source on solid element #include "SolidForce.hpp" #include "SolidElement.hpp" // constructor SolidForce::SolidForce(std::unique_ptr<STF> &stf, const std::shared_ptr<SolidElement> &element, const eigen::CMatXN3 &pattern): SolidSource(stf, element), mPattern(pattern) { // prepare element->prepareForceSource(); // workspace if (sPattern.rows() < mPattern.rows()) { sPattern.resize(mPattern.rows(), spectral::nPEM * 3); } } // apply source at a time step void SolidForce::apply(double time) const { int nu_1 = (int)mPattern.rows(); sPattern.topRows(nu_1) = mPattern * mSTF->getValue(time); mElement->addForceSource(sPattern, nu_1); }
25.735294
68
0.645714
nicklinyi
4d6dd0144c5203b05354fff0a0fc36d19f466ab1
5,400
hpp
C++
src/context-traits.hpp
YutaroOrikasa/user-thread
2d82ee257115e67630f5743ceb169441854fac22
[ "MIT" ]
null
null
null
src/context-traits.hpp
YutaroOrikasa/user-thread
2d82ee257115e67630f5743ceb169441854fac22
[ "MIT" ]
2
2017-05-02T07:02:23.000Z
2017-05-20T09:32:52.000Z
src/context-traits.hpp
YutaroOrikasa/user-thread
2d82ee257115e67630f5743ceb169441854fac22
[ "MIT" ]
null
null
null
#ifndef USER_THREAD_CONTEXTTRAITS_HPP #define USER_THREAD_CONTEXTTRAITS_HPP #include "mysetjmp.h" #include "user-thread-debug.hpp" #include "splitstackapi.h" #include "stack-address-tools.hpp" #include "thread-data/thread-data.hpp" #include "thread-data/splitstack-thread-data.hpp" #include "call_with_alt_stack_arg3.h" #include "config.h" namespace orks { namespace userthread { namespace detail { namespace baddesign { inline void call_with_alt_stack_arg3(char* altstack, std::size_t altstack_size, void* func, void* arg1, void* arg2, void* arg3) __attribute__((no_split_stack)); inline void call_with_alt_stack_arg3(char* altstack, std::size_t altstack_size, void* func, void* arg1, void* arg2, void* arg3) { void* stack_base = altstack + altstack_size; #ifndef USE_SPLITSTACKS // stack boundary was already changed by caller. // debug output will make memory destorying. debug::printf("func %p\n", func); #endif orks_private_call_with_alt_stack_arg3_impl(arg1, arg2, arg3, stack_base, func); } struct BadDesignContextTraits { #ifdef USE_SPLITSTACKS using ThreadData = splitstack::ThreadData; #endif using Context = ThreadData*; template <typename Fn> static Context make_context(Fn fn) { return ThreadData::create(std::move(fn)); } static Context switch_context(Context next_thread, void* transfer_data = nullptr) { return &switch_context_impl(*next_thread, transfer_data); } static bool is_finished(Context ctx) { return ctx->state == ThreadState::ended; } static void destroy_context(Context ctx) { ThreadData::destroy((*ctx)); } void* get_transferred_data(Context ctx) { return ctx->transferred_data; } private: static ThreadData& switch_context_impl(ThreadData& next_thread, void* transfer_data = nullptr, ThreadData* finished_thread = nullptr) { ThreadData current_thread_ {nullptr, nullptr}; ThreadData* current_thread; if (finished_thread == nullptr) { current_thread = &current_thread_; debug::printf("save current thread at %p\n", current_thread); current_thread->state = ThreadState::running; } else { current_thread = finished_thread; debug::printf("current thread %p is finished\n", current_thread); } ThreadData* previous_thread = 0; next_thread.transferred_data = transfer_data; if (next_thread.state == ThreadState::before_launch) { debug::printf("launch user thread!\n"); previous_thread = &context_switch_new_context(*current_thread, next_thread); } else if (next_thread.state == ThreadState::running) { debug::printf("resume user thread %p!\n", &next_thread); previous_thread = &context_switch(*current_thread, next_thread); } else { debug::out << "next_thread " << &next_thread << " invalid state: " << static_cast<int>(next_thread.state) << "\n"; const auto NEVER_COME_HERE = false; assert(NEVER_COME_HERE); } return *previous_thread; } // always_inline for no split stack __attribute__((always_inline)) static ThreadData& context_switch(ThreadData& from, ThreadData& to) { from.save_extra_context(); if (mysetjmp(from.env)) { from.restore_extra_context(); return *from.pass_on_longjmp; } to.pass_on_longjmp = &from; mylongjmp(to.env); const auto NEVER_COME_HERE = false; assert(NEVER_COME_HERE); } // always_inline for no split stack __attribute__((always_inline)) static ThreadData& context_switch_new_context(ThreadData& from, ThreadData& new_ctx) { from.save_extra_context(); if (mysetjmp(from.env)) { from.restore_extra_context(); return *from.pass_on_longjmp; } new_ctx.pass_on_longjmp = &from; assert(new_ctx.get_stack() != 0); assert(new_ctx.get_stack_size() != 0); char* stack_frame = new_ctx.get_stack(); call_with_alt_stack_arg3(stack_frame, new_ctx.get_stack_size(), reinterpret_cast<void*>(entry_thread), &new_ctx, nullptr, nullptr); const auto NEVER_COME_HERE = false; assert(NEVER_COME_HERE); } __attribute__((no_split_stack)) static void entry_thread(ThreadData& thread_data); }; inline void BadDesignContextTraits::entry_thread(ThreadData& thread_data) { thread_data.initialize_extra_context_at_entry_point(); debug::printf("start thread in new stack frame\n"); debug::out << std::endl; thread_data.state = ThreadState::running; Context next = thread_data.call_func(thread_data.pass_on_longjmp); debug::printf("end thread\n"); thread_data.state = ThreadState::ended; debug::printf("end: %p\n", &thread_data); switch_context_impl(*next, thread_data.transferred_data, &thread_data); // no return // this thread context will be deleted by next thread } } } } } namespace orks { namespace userthread { namespace detail { using BadDesignContextTraits = baddesign::BadDesignContextTraits; } } } #endif //USER_THREAD_CONTEXTTRAITS_HPP
27.272727
153
0.663333
YutaroOrikasa
4d6e580c38cfb906fa4cb8a78141dd1970b0eca3
4,254
cpp
C++
src/glplayer.cpp
felixqin/gltest
51f0dab25700a3fdcfba29e61029d6a98c283747
[ "MIT" ]
null
null
null
src/glplayer.cpp
felixqin/gltest
51f0dab25700a3fdcfba29e61029d6a98c283747
[ "MIT" ]
null
null
null
src/glplayer.cpp
felixqin/gltest
51f0dab25700a3fdcfba29e61029d6a98c283747
[ "MIT" ]
null
null
null
#include <QPainter> #include <QOpenGLShader> #include <QTimerEvent> #include "glplayer.h" #define LOGI printf #define LOGE printf CGLPlayer::CGLPlayer(QWidget* parent, Qt::WindowFlags f) : QOpenGLWidget(parent, f) , mGLInitialized(false) , mProgram(NULL) , mVShader(NULL) , mFShader(NULL) , mTextureLocation(0) , mIdTexture(0) , mWidth(640) , mHeight(360) , mImage(NULL) { initImage(); } CGLPlayer::~CGLPlayer() { free(mImage); makeCurrent(); delete mVShader; delete mFShader; delete mProgram; doneCurrent(); } void CGLPlayer::initImage() { int w = mWidth; int h = mHeight; int bytes = w * h * 3; mImage = (char*)malloc(bytes); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int r = 255, g = 255, b = 255; if (x % 100 != 0 && y % 100 != 0) { r = (x * y) % 255; g = (4 * x) % 255; b = (4 * y) % 255; } int index = (y * w + x) * 3; mImage[index+0] = (GLubyte)r; mImage[index+1] = (GLubyte)g; mImage[index+2] = (GLubyte)b; } } } void CGLPlayer::initializeGL() { initializeOpenGLFunctions(); initShaders(); QColor clearColor(Qt::blue); glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF()); mGLInitialized = true; } //Init Shader void CGLPlayer::initShaders() { // https://blog.csdn.net/su_vast/article/details/52214642 // https://blog.csdn.net/ylbs110/article/details/52074826 // https://www.xuebuyuan.com/2119734.html mVShader = new QOpenGLShader(QOpenGLShader::Vertex, this); const char *vsrc = "#version 120\n" "attribute vec4 vertexIn;\n" "attribute vec2 textureIn;\n" "varying vec2 textureOut;\n" "void main(void)\n" "{\n" " gl_Position = vertexIn;\n" " textureOut = textureIn;\n" "}\n"; mVShader->compileSourceCode(vsrc); mFShader = new QOpenGLShader(QOpenGLShader::Fragment, this); const char *fsrc = "#version 120\n" "varying vec2 textureOut;\n" "uniform sampler2D rgb;\n" "void main(void)\n" "{\n" " gl_FragColor = texture2D(rgb, textureOut);\n" "}\n"; mFShader->compileSourceCode(fsrc); mProgram = new QOpenGLShaderProgram(); mProgram->addShader(mVShader); mProgram->addShader(mFShader); mProgram->link(); mProgram->bind(); GLint vetexInLocation = mProgram->attributeLocation("vertexIn"); GLint textureInLocation = mProgram->attributeLocation("textureIn"); mTextureLocation = mProgram->uniformLocation("rgb"); static const GLfloat vertexVertices[] = { // Triangle Strip -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f }; static const GLfloat textureVertices[] = { 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; glVertexAttribPointer(vetexInLocation, 2, GL_FLOAT, false, 0, vertexVertices); glEnableVertexAttribArray(vetexInLocation); glVertexAttribPointer(textureInLocation, 2, GL_FLOAT, false, 0, textureVertices); glEnableVertexAttribArray(textureInLocation); glGenTextures(1, &mIdTexture); glBindTexture(GL_TEXTURE_2D, mIdTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } void CGLPlayer::paintGL() { if (!mGLInitialized) { LOGE("is not initialized!\n"); return; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, mIdTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, mWidth, mHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, mImage); glUniform1i(mTextureLocation, 0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); }
26.754717
98
0.602257
felixqin
4d703856c91c7aa738c542f8079b22d00ed7ef83
1,337
hpp
C++
include/Entity/States.hpp
cristianglezm/AntFarm
df7551621ad6eda6dae43a2ede56222500be1ae1
[ "Apache-2.0" ]
null
null
null
include/Entity/States.hpp
cristianglezm/AntFarm
df7551621ad6eda6dae43a2ede56222500be1ae1
[ "Apache-2.0" ]
1
2016-03-13T10:55:21.000Z
2016-03-13T10:55:21.000Z
include/Entity/States.hpp
cristianglezm/AntFarm
df7551621ad6eda6dae43a2ede56222500be1ae1
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////// // Copyright 2014 Cristian Glez <[email protected]> // // 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 STATES_HPP #define STATES_HPP #include <bitset> /** * @brief Estados de las entidades * @author Cristian Glez <[email protected]> * @version 0.1 */ namespace States{ using Mask = std::bitset<32>; static constexpr Mask NONE = 0; static constexpr Mask GROUND = 1 << 0; static constexpr Mask FALLING = 1 << 1; static constexpr Mask CLIMBING = 1 << 2; static constexpr Mask BUILDING = 1 << 3; static constexpr Mask ONFIRE = 1 << 4; static constexpr Mask SAVED = 1 << 5; static constexpr Mask UNSAVED = 1 << 6; } #endif // STATES_HPP
33.425
75
0.635004
cristianglezm
4d70c50978d1d23df30eb43b1757f954637c226b
2,002
hpp
C++
include/mos/gfx/model.hpp
morganbengtsson/mo
c719ff6b35478b068988901d0bf7253cb672e87a
[ "MIT" ]
230
2016-02-15T20:46:01.000Z
2022-03-07T11:56:12.000Z
include/mos/gfx/model.hpp
morganbengtsson/mo
c719ff6b35478b068988901d0bf7253cb672e87a
[ "MIT" ]
79
2016-02-07T11:37:04.000Z
2021-09-29T09:14:27.000Z
include/mos/gfx/model.hpp
morganbengtsson/mo
c719ff6b35478b068988901d0bf7253cb672e87a
[ "MIT" ]
14
2018-05-16T13:10:22.000Z
2021-09-28T10:23:31.000Z
#pragma once #include <memory> #include <optional> #include <json.hpp> #include <mos/gfx/assets.hpp> #include <mos/gfx/material.hpp> #include <mos/gfx/mesh.hpp> #include <mos/gfx/models.hpp> #include <mos/gfx/texture_2d.hpp> namespace mos::gfx { class Assets; class Material; namespace gl { class Renderer; } /** Collection of properties for a renderable object. */ class Model final { public: static auto load(const nlohmann::json &json, Assets &assets = *std::make_unique<Assets>(), const glm::mat4 &parent_transform = glm::mat4(1.0f)) -> Model; Model(std::string name, Shared_mesh mesh, glm::mat4 transform = glm::mat4(1.0f), Material material = Material{glm::vec3(1.0f)}); Model() = default; auto name() const -> std::string; auto position() const -> glm::vec3; /** Set position. */ auto position(const glm::vec3 &position) -> void; /** Get centroid position. */ auto centroid() const -> glm::vec3; /** Get radious of bounding sphere */ auto radius() const -> float; /** Set emission of material recursively. */ auto emission(const glm::vec3 &emission) -> void; /** Set alpha of material recursively. */ auto alpha(float alpha) -> void; /** Set ambient occlusion of material recursively. */ auto ambient_occlusion(float ambient_occlusion) -> void; /** set index of refraction of material recursively. */ auto index_of_refraction(float index_of_refraction) -> void; /** set transmission of material recursively. */ auto transmission(float transmission) -> void; /** set roughness of material recursively. */ auto roughness(float roughness) -> void; /** set metallic of material recursively. */ auto metallic(float metallic) -> void; /** Mesh shape. */ Shared_mesh mesh; /** Material. */ Material material; /** Transform. */ glm::mat4 transform{0.0f}; /** Children models. */ Models models; private: std::string name_; }; } // namespace mos::gfx
23.011494
71
0.661339
morganbengtsson
4d74b1aa40359491cb37252c1186ba7298149e78
1,170
cpp
C++
server/sockchat/threadctx.cpp
sockchat/server-historical
34befc2f7c2e310a9b58071633c2da00f5e7e308
[ "Apache-2.0" ]
1
2019-02-10T17:46:27.000Z
2019-02-10T17:46:27.000Z
server/sockchat/threadctx.cpp
sockchat/server-historical
34befc2f7c2e310a9b58071633c2da00f5e7e308
[ "Apache-2.0" ]
null
null
null
server/sockchat/threadctx.cpp
sockchat/server-historical
34befc2f7c2e310a9b58071633c2da00f5e7e308
[ "Apache-2.0" ]
null
null
null
#include "cthread.h" ThreadContext::Connection::Connection(sc::Socket *sock) { this->sock = sock; } ThreadContext::ThreadContext(sc::Socket *sock) { this->pendingConns.push_back(Connection(sock)); } void ThreadContext::Finish() { for(auto i = this->conns.begin(); i != this->conns.end(); ) i = CloseConnection(i); this->done = true; } bool ThreadContext::IsDone() { return this->done; } void ThreadContext::PushSocket(sc::Socket *sock) { this->_pendingConns.lock(); this->pendingConns.push_back(sock); this->_pendingConns.unlock(); } void ThreadContext::HandlePendingConnections() { this->_pendingConns.lock(); for(auto i = this->pendingConns.begin(); i != this->pendingConns.end(); ) { i->sock->SetBlocking(false); this->conns.push_back(*i); i = pendingConns.erase(i); } this->_pendingConns.unlock(); } std::vector<ThreadContext::Connection>::iterator ThreadContext::CloseConnection(std::vector<Connection>::iterator i) { std::cout << i->sock->GetIPAddress() << " disconnected" << std::endl; i->sock->Close(); delete i->sock; return this->conns.erase(i); }
26.590909
118
0.648718
sockchat
4d74e17e57df21d6e4e746c2c207ea6ccdc0245b
191
hpp
C++
pypedream/array_col_reader.hpp
garywu/pipedream
d89a4031d5ee78c05c6845341607a59528f0bd75
[ "BSD-3-Clause" ]
8
2018-02-21T04:13:25.000Z
2020-04-24T20:05:47.000Z
pypedream/array_col_reader.hpp
garywu/pipedream
d89a4031d5ee78c05c6845341607a59528f0bd75
[ "BSD-3-Clause" ]
1
2019-05-13T13:14:32.000Z
2019-05-13T13:14:32.000Z
pypedream/array_col_reader.hpp
garywu/pypedream
d89a4031d5ee78c05c6845341607a59528f0bd75
[ "BSD-3-Clause" ]
null
null
null
#ifndef ARRAY_COL_READER_HPP #define ARRAY_COL_READER_HPP #include <Python.h> #include "parser_defs.hpp" extern PyTypeObject ArrayColReaderType; #endif // #ifndef ARRAY_COL_READER_HPP
13.642857
39
0.806283
garywu