blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1cb411067d65e6e096112b9ae1d3e1fb6e79446c | a90546b830d2c37e5db9284fe099b0f0658e723a | /programs/rodeos/main.cpp | 88ebb5aa39e871df02347703a9179c05e25569c8 | [
"MIT"
] | permissive | NorseGaud/Eden | afba632342c2b56018e8d5d5bb8db38d81189f8f | 56610ebea830c3e7febe3f0c42d8fdc7dec609a5 | refs/heads/main | 2023-05-02T19:20:36.591718 | 2021-05-17T13:36:30 | 2021-05-17T21:39:01 | 365,883,543 | 0 | 0 | MIT | 2021-05-10T01:19:47 | 2021-05-10T01:19:47 | null | UTF-8 | C++ | false | false | 4,536 | cpp | #include <appbase/application.hpp>
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/exception/diagnostic_information.hpp>
// #include <eosio/version/version.hpp>
#include <fc/exception/exception.hpp>
#include <fc/filesystem.hpp>
#include <fc/log/appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include "cloner_plugin.hpp"
#include "config.hpp"
#include "wasm_ql_plugin.hpp"
using namespace appbase;
namespace detail
{
void configure_logging(const bfs::path& config_path)
{
try
{
try
{
fc::configure_logging(config_path);
}
catch (...)
{
elog("Error reloading logging.json");
throw;
}
}
catch (const fc::exception& e)
{ //
elog("${e}", ("e", e.to_detail_string()));
}
catch (const boost::exception& e)
{
elog("${e}", ("e", boost::diagnostic_information(e)));
}
catch (const std::exception& e)
{ //
elog("${e}", ("e", e.what()));
}
catch (...)
{
// empty
}
}
} // namespace detail
void logging_conf_handler()
{
auto config_path = app().get_logging_conf();
if (fc::exists(config_path))
{
ilog("Received HUP. Reloading logging configuration from ${p}.",
("p", config_path.string()));
}
else
{
ilog("Received HUP. No log config found at ${p}, setting to default.",
("p", config_path.string()));
}
::detail::configure_logging(config_path);
fc::log_config::initialize_appenders(app().get_io_service());
}
void initialize_logging()
{
auto config_path = app().get_logging_conf();
if (fc::exists(config_path))
fc::configure_logging(config_path); // intentionally allowing exceptions to escape
fc::log_config::initialize_appenders(app().get_io_service());
app().set_sighup_callback(logging_conf_handler);
}
enum return_codes
{
other_fail = -2,
initialize_fail = -1,
success = 0,
bad_alloc = 1,
};
int main(int argc, char** argv)
{
try
{
app().set_version(b1::rodeos::config::version);
// app().set_version_string(eosio::version::version_client());
// app().set_full_version_string(eosio::version::version_full());
auto root = fc::app_path();
app().set_default_data_dir(root / "eosio" / b1::rodeos::config::rodeos_executable_name /
"data");
app().set_default_config_dir(root / "eosio" / b1::rodeos::config::rodeos_executable_name /
"config");
if (!app().initialize<b1::cloner_plugin, b1::wasm_ql_plugin>(argc, argv))
{
const auto& opts = app().get_options();
if (opts.count("help") || opts.count("version") || opts.count("full-version") ||
opts.count("print-default-config"))
{
return success;
}
return initialize_fail;
}
initialize_logging();
ilog("${name} version ${ver} ${fv}",
("name", b1::rodeos::config::rodeos_executable_name)("ver", app().version_string())(
"fv", app().version_string() == app().full_version_string()
? ""
: app().full_version_string()));
ilog("${name} using configuration file ${c}",
("name", b1::rodeos::config::rodeos_executable_name)(
"c", app().full_config_file_path().string()));
ilog("${name} data directory is ${d}",
("name", b1::rodeos::config::rodeos_executable_name)("d", app().data_dir().string()));
app().startup();
app().set_thread_priority_max();
app().exec();
}
// catch (const fc::std_exception_wrapper& e)
// {
// elog("${e}", ("e", e.to_detail_string()));
// return other_fail;
// }
catch (const fc::exception& e)
{
elog("${e}", ("e", e.to_detail_string()));
return other_fail;
}
catch (const boost::interprocess::bad_alloc& e)
{
elog("bad alloc");
return bad_alloc;
}
catch (const boost::exception& e)
{
elog("${e}", ("e", boost::diagnostic_information(e)));
return other_fail;
}
catch (const std::exception& e)
{
elog("${e}", ("e", e.what()));
return other_fail;
}
catch (...)
{
elog("unknown exception");
return other_fail;
}
ilog("${name} successfully exiting", ("name", b1::rodeos::config::rodeos_executable_name));
return success;
}
| [
"tbfleming@gmail.com"
] | tbfleming@gmail.com |
1202b22f0f0899b8e30b2e17b2ee4b7d26512ac2 | 896b5a6aab6cb6c1e3ee2e59aad0128226471871 | /chrome/browser/web_applications/test/test_install_finalizer.cc | 88cd19cf8f0c6777b7a66336b88e581675fdf8c5 | [
"BSD-3-Clause"
] | permissive | bkueppers/chromium | 86f09d32b7cb418f431b3b01a00ffe018e24de32 | d160b8b58d58120a9b2331671d0bda228d469482 | refs/heads/master | 2023-03-14T10:41:52.563439 | 2019-11-08T13:33:40 | 2019-11-08T13:33:40 | 219,389,734 | 0 | 0 | BSD-3-Clause | 2019-11-04T01:05:37 | 2019-11-04T01:05:37 | null | UTF-8 | C++ | false | false | 4,453 | cc | // 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 <utility>
#include "chrome/browser/web_applications/test/test_install_finalizer.h"
#include "base/callback.h"
#include "base/test/bind_test_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/web_applications/components/web_app_constants.h"
#include "chrome/browser/web_applications/components/web_app_helpers.h"
#include "chrome/common/web_application_info.h"
#include "components/crx_file/id_util.h"
namespace web_app {
// static
AppId TestInstallFinalizer::GetAppIdForUrl(const GURL& url) {
return GenerateAppIdFromURL(url);
}
TestInstallFinalizer::TestInstallFinalizer() {}
TestInstallFinalizer::~TestInstallFinalizer() = default;
void TestInstallFinalizer::FinalizeInstall(
const WebApplicationInfo& web_app_info,
const FinalizeOptions& options,
InstallFinalizedCallback callback) {
finalize_options_list_.push_back(options);
Finalize(web_app_info, InstallResultCode::kSuccessNewInstall,
std::move(callback));
}
void TestInstallFinalizer::FinalizeUpdate(
const WebApplicationInfo& web_app_info,
InstallFinalizedCallback callback) {
Finalize(web_app_info, InstallResultCode::kSuccessAlreadyInstalled,
std::move(callback));
}
void TestInstallFinalizer::FinalizeFallbackInstallAfterSync(
const AppId& app_id,
InstallFinalizedCallback callback) {
NOTREACHED();
}
void TestInstallFinalizer::UninstallExternalWebApp(
const GURL& app_url,
UninstallWebAppCallback callback) {
DCHECK(base::Contains(next_uninstall_external_web_app_results_, app_url));
uninstall_external_web_app_urls_.push_back(app_url);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindLambdaForTesting(
[this, app_url, callback = std::move(callback)]() mutable {
bool result =
next_uninstall_external_web_app_results_[app_url];
next_uninstall_external_web_app_results_.erase(app_url);
std::move(callback).Run(result);
}));
}
void TestInstallFinalizer::UninstallWebApp(const AppId& app_url,
UninstallWebAppCallback callback) {}
bool TestInstallFinalizer::CanAddAppToQuickLaunchBar() const {
return true;
}
void TestInstallFinalizer::AddAppToQuickLaunchBar(const AppId& app_id) {
++num_add_app_to_quick_launch_bar_calls_;
}
bool TestInstallFinalizer::CanReparentTab(const AppId& app_id,
bool shortcut_created) const {
return true;
}
void TestInstallFinalizer::ReparentTab(const AppId& app_id,
bool shortcut_created,
content::WebContents* web_contents) {
++num_reparent_tab_calls_;
}
bool TestInstallFinalizer::CanRevealAppShim() const {
return true;
}
void TestInstallFinalizer::RevealAppShim(const AppId& app_id) {
++num_reveal_appshim_calls_;
}
bool TestInstallFinalizer::CanUserUninstallFromSync(const AppId& app_id) const {
NOTIMPLEMENTED();
return false;
}
void TestInstallFinalizer::SetNextFinalizeInstallResult(
const AppId& app_id,
InstallResultCode code) {
next_app_id_ = app_id;
next_result_code_ = code;
}
void TestInstallFinalizer::SetNextUninstallExternalWebAppResult(
const GURL& app_url,
bool uninstalled) {
DCHECK(!base::Contains(next_uninstall_external_web_app_results_, app_url));
next_uninstall_external_web_app_results_[app_url] = uninstalled;
}
void TestInstallFinalizer::Finalize(const WebApplicationInfo& web_app_info,
InstallResultCode code,
InstallFinalizedCallback callback) {
AppId app_id = GetAppIdForUrl(web_app_info.app_url);
if (next_app_id_.has_value()) {
app_id = next_app_id_.value();
next_app_id_.reset();
}
if (next_result_code_.has_value()) {
code = next_result_code_.value();
next_result_code_.reset();
}
// Store input data copies for inspecting in tests.
web_app_info_copy_ = std::make_unique<WebApplicationInfo>(web_app_info);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), app_id, code));
}
} // namespace web_app
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
7125573f78c8f6e4e9ab1d08bb412a28c46762cd | 027e609d04ac0ab4ee72d557ea1c563d60fe0ca6 | /2014/mi/quark/quark-gen.cpp | 093c32cf56c1cbefc24aed9ece17086423530723 | [] | no_license | x-fer/xfer-natpro | c83fd7bc36c5a9e7728886de87afdd145aefb5ad | bc6243f018af85338c174a1d5eab4947da2b446a | refs/heads/master | 2021-01-20T02:38:26.950376 | 2016-10-21T14:43:25 | 2016-10-21T14:43:25 | 33,113,588 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | #include <cstdio>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
vector<int> a, p;
int main(void){
srand(time(0));
int n = rand() % 1000 + 1;
int total = 0;
for (int i=0; i<n; i++){
int Ai = rand(); a.push_back(Ai);
int Pi = rand() % 1000; p.push_back(Pi);
total += Pi;
}
int k = ((long long)rand()*rand()) % total + 1;
printf ("%d %d\n", n, k);
for (int i=0; i<n; i++)
printf ("%d %d\n", a[i], p[i]);
return 0;
}
| [
"msantl.ck@gmail.com"
] | msantl.ck@gmail.com |
a9c521da1a98e7b5f0d4ffa4d39df0c4d5ad8d7c | 91a97ceb4768d6bd1dc662e85dd1c4f062bf22fc | /abc/0119/a/a.cpp | 10b24277a722b19d8f659013cdf39655fbbbe2e2 | [] | no_license | mmxsrup/atcoder-practice | 050bd262fb21a7dfffc5609de124bd48022c8beb | 0cef9a3984af020310453acac80fbf739070dd77 | refs/heads/master | 2021-11-17T23:17:48.218418 | 2021-09-27T10:51:13 | 2021-09-27T10:51:13 | 164,378,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
const int MOD = 1e9 + 7;
const int INF = 1e9;
const ll INFF = 1e18;
int main(int argc, char const *argv[])
{
string s; cin >> s;
int year = stoi(s.substr(0, 4));
int month = stoi(s.substr(5, 2));
int day = stoi(s.substr(8, 2));
if (year < 2019 || (year == 2019 && month < 4) ||
(year == 2019 && month == 4 && day <= 30)) printf("Heisei\n");
else printf("TBD\n");
return 0;
} | [
"sugiyama98i@gmail.com"
] | sugiyama98i@gmail.com |
ad9ecc66a4c5f6381b23ebb5cbadd8a330a645b1 | 36bec7c240a06794c66fa3bd8d66cc9f6bd4d407 | /tests/testLandmark.cpp | 864ebe32609675fe74a9e4ec66965189d7cf5279 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | Eagleflag88/Kimera-RPGO | 982275aede805dfaa98d5b5819b3b1fa0f84622e | ff00ec2162d0f18ae5652c99202b506f0215f884 | refs/heads/master | 2023-09-05T17:51:00.508839 | 2021-10-31T19:11:50 | 2021-10-31T19:11:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,933 | cpp | /**
* @file testDoOptimize.cpp
* @brief Unit test for pcm and optimize conditions
* @author Yun Chang
*/
#include <CppUnitLite/TestHarness.h>
#include <memory>
#include <random>
#include <vector>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/inference/Symbol.h>
#include "KimeraRPGO/RobustSolver.h"
#include "KimeraRPGO/SolverParams.h"
#include "KimeraRPGO/utils/type_utils.h"
#include "test_config.h"
using namespace KimeraRPGO;
/* ************************************************************************* */
TEST(RobustSolver, LandmarkPcm) {
RobustSolverParams params;
params.setPcm3DParams(5.0, 2.5, Verbosity::QUIET);
std::vector<char> special_symbs{'l'}; // for landmarks
params.specialSymbols = special_symbs;
std::unique_ptr<RobustSolver> pgo =
KimeraRPGO::make_unique<RobustSolver>(params);
static const gtsam::SharedNoiseModel& noise =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::NonlinearFactorGraph nfg;
gtsam::Values est;
// initialize first (w/o prior)
gtsam::Key init_key_a = gtsam::Symbol('a', 0);
gtsam::Values init_vals;
init_vals.insert(init_key_a, gtsam::Pose3());
pgo->update(gtsam::NonlinearFactorGraph(), init_vals);
// add odometries
for (size_t i = 0; i < 2; i++) {
gtsam::Values odom_val;
gtsam::NonlinearFactorGraph odom_factor;
gtsam::Pose3 odom = gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 0, 0));
static const gtsam::SharedNoiseModel& noiseOdom =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::Key key_prev = gtsam::Symbol('a', i);
gtsam::Key key_new = gtsam::Symbol('a', i + 1);
odom_val.insert(key_new, odom);
odom_factor.add(
gtsam::BetweenFactor<gtsam::Pose3>(key_prev, key_new, odom, noiseOdom));
pgo->update(odom_factor, odom_val);
}
// add more odometries a
for (size_t i = 2; i < 5; i++) {
gtsam::Values odom_val;
gtsam::NonlinearFactorGraph odom_factor;
gtsam::Matrix3 R;
R.row(0) << 0, -1, 0;
R.row(1) << 1, 0, 0;
R.row(2) << 0, 0, 1;
gtsam::Pose3 odom = gtsam::Pose3(gtsam::Rot3(R), gtsam::Point3(1, 0, 0));
static const gtsam::SharedNoiseModel& noiseOdom =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::Key key_prev = gtsam::Symbol('a', i);
gtsam::Key key_new = gtsam::Symbol('a', i + 1);
odom_val.insert(key_new, odom);
odom_factor.add(
gtsam::BetweenFactor<gtsam::Pose3>(key_prev, key_new, odom, noiseOdom));
pgo->update(odom_factor, odom_val);
}
// add a good and bad single robot loop closures
gtsam::NonlinearFactorGraph lc_factors;
gtsam::Key a1 = gtsam::Symbol('a', 1);
gtsam::Key a2 = gtsam::Symbol('a', 2);
gtsam::Key a3 = gtsam::Symbol('a', 3);
gtsam::Key a4 = gtsam::Symbol('a', 4);
gtsam::Key a5 = gtsam::Symbol('a', 5);
lc_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a3,
a2,
gtsam::Pose3(gtsam::Rot3::Rz(-1.57), gtsam::Point3(0, 0.9, 0)),
noise));
lc_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a4,
a1,
gtsam::Pose3(gtsam::Rot3::Rz(3.14), gtsam::Point3(2.1, 1.1, 2.5)),
noise));
pgo->update(lc_factors, gtsam::Values());
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(6));
EXPECT(est.size() == size_t(6));
// Now start adding landmarks
// Add first observation
gtsam::Vector6 ldmk_prec;
ldmk_prec.head<3>().setConstant(0); // rotation precision
ldmk_prec.tail<3>().setConstant(25);
static const gtsam::SharedNoiseModel& lmk_noise =
gtsam::noiseModel::Diagonal::Precisions(ldmk_prec);
gtsam::NonlinearFactorGraph landmark_factors;
gtsam::Values landmark_values;
gtsam::Key l0 = gtsam::Symbol('l', 0);
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a1, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, 1, 0)), lmk_noise));
landmark_values.insert(l0,
gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 1, 0)));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(7));
EXPECT(est.size() == size_t(7));
// add a reobservation should be consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a5, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, -1, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(8));
EXPECT(est.size() == size_t(7));
// add a reobservation that's not consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a4, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 0, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(8));
EXPECT(est.size() == size_t(7));
// Add another landmark
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
gtsam::Key l1 = gtsam::Symbol('l', 1);
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a2, l1, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, -1, 0)), lmk_noise));
landmark_values.insert(l1,
gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 1, 0)));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(9));
EXPECT(est.size() == size_t(8));
// add a reobservation should be consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a5, l1, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(2, 0, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(10));
EXPECT(est.size() == size_t(8));
}
/* ************************************************************************* */
TEST(RobustSolver, LandmarkPcmSimple) {
RobustSolverParams params;
params.setPcmSimple3DParams(0.3, 0.05, Verbosity::QUIET);
std::vector<char> special_symbs{'l'}; // for landmarks
params.specialSymbols = special_symbs;
std::unique_ptr<RobustSolver> pgo =
KimeraRPGO::make_unique<RobustSolver>(params);
static const gtsam::SharedNoiseModel& noise =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::NonlinearFactorGraph nfg;
gtsam::Values est;
// initialize first (w/o prior)
gtsam::Key init_key_a = gtsam::Symbol('a', 0);
gtsam::Values init_vals;
init_vals.insert(init_key_a, gtsam::Pose3());
pgo->update(gtsam::NonlinearFactorGraph(), init_vals);
// add odometries
for (size_t i = 0; i < 2; i++) {
gtsam::Values odom_val;
gtsam::NonlinearFactorGraph odom_factor;
gtsam::Pose3 odom = gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 0, 0));
static const gtsam::SharedNoiseModel& noiseOdom =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::Key key_prev = gtsam::Symbol('a', i);
gtsam::Key key_new = gtsam::Symbol('a', i + 1);
odom_val.insert(key_new, odom);
odom_factor.add(
gtsam::BetweenFactor<gtsam::Pose3>(key_prev, key_new, odom, noiseOdom));
pgo->update(odom_factor, odom_val);
}
// add more odometries a
for (size_t i = 2; i < 5; i++) {
gtsam::Values odom_val;
gtsam::NonlinearFactorGraph odom_factor;
gtsam::Matrix3 R;
R.row(0) << 0, -1, 0;
R.row(1) << 1, 0, 0;
R.row(2) << 0, 0, 1;
gtsam::Pose3 odom = gtsam::Pose3(gtsam::Rot3(R), gtsam::Point3(1, 0, 0));
static const gtsam::SharedNoiseModel& noiseOdom =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::Key key_prev = gtsam::Symbol('a', i);
gtsam::Key key_new = gtsam::Symbol('a', i + 1);
odom_val.insert(key_new, odom);
odom_factor.add(
gtsam::BetweenFactor<gtsam::Pose3>(key_prev, key_new, odom, noiseOdom));
pgo->update(odom_factor, odom_val);
}
// add a good and bad single robot loop closures
gtsam::NonlinearFactorGraph lc_factors;
gtsam::Key a1 = gtsam::Symbol('a', 1);
gtsam::Key a2 = gtsam::Symbol('a', 2);
gtsam::Key a3 = gtsam::Symbol('a', 3);
gtsam::Key a4 = gtsam::Symbol('a', 4);
gtsam::Key a5 = gtsam::Symbol('a', 5);
lc_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a3,
a2,
gtsam::Pose3(gtsam::Rot3::Rz(-1.57), gtsam::Point3(0, 0.9, 0)),
noise));
lc_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a4,
a1,
gtsam::Pose3(gtsam::Rot3::Rz(3.14), gtsam::Point3(2.1, 1.1, 2.5)),
noise));
pgo->update(lc_factors, gtsam::Values());
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(6));
EXPECT(est.size() == size_t(6));
// Now start adding landmarks
// Add first observation
gtsam::Vector6 ldmk_prec;
ldmk_prec.head<3>().setConstant(0); // rotation precision
ldmk_prec.tail<3>().setConstant(25);
static const gtsam::SharedNoiseModel& lmk_noise =
gtsam::noiseModel::Diagonal::Precisions(ldmk_prec);
gtsam::NonlinearFactorGraph landmark_factors;
gtsam::Values landmark_values;
gtsam::Key l0 = gtsam::Symbol('l', 0);
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a1, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, 1, 0)), lmk_noise));
landmark_values.insert(l0,
gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 1, 0)));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(7));
EXPECT(est.size() == size_t(7));
// add a reobservation should be consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a5, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, -1, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(8));
EXPECT(est.size() == size_t(7));
// add a reobservation that's not consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a4, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 0, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(8));
EXPECT(est.size() == size_t(7));
// Add another landmark
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
gtsam::Key l1 = gtsam::Symbol('l', 1);
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a2, l1, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, -1, 0)), lmk_noise));
landmark_values.insert(l1,
gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 1, 0)));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(9));
EXPECT(est.size() == size_t(8));
// add a reobservation should be consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a5, l1, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(2, 0, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(10));
EXPECT(est.size() == size_t(8));
}
/* ************************************************************************* */
TEST(RobustSolver, LandmarkNoReject) {
RobustSolverParams params;
params.setNoRejection(Verbosity::QUIET);
std::vector<char> special_symbs{'l'}; // for landmarks
params.specialSymbols = special_symbs;
std::unique_ptr<RobustSolver> pgo =
KimeraRPGO::make_unique<RobustSolver>(params);
static const gtsam::SharedNoiseModel& noise =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::NonlinearFactorGraph nfg;
gtsam::Values est;
// initialize first (w/o prior)
gtsam::Key init_key_a = gtsam::Symbol('a', 0);
gtsam::Values init_vals;
init_vals.insert(init_key_a, gtsam::Pose3());
pgo->update(gtsam::NonlinearFactorGraph(), init_vals);
// add odometries
for (size_t i = 0; i < 2; i++) {
gtsam::Values odom_val;
gtsam::NonlinearFactorGraph odom_factor;
gtsam::Pose3 odom = gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 0, 0));
static const gtsam::SharedNoiseModel& noiseOdom =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::Key key_prev = gtsam::Symbol('a', i);
gtsam::Key key_new = gtsam::Symbol('a', i + 1);
odom_val.insert(key_new, odom);
odom_factor.add(
gtsam::BetweenFactor<gtsam::Pose3>(key_prev, key_new, odom, noiseOdom));
pgo->update(odom_factor, odom_val);
}
// add more odometries a
for (size_t i = 2; i < 5; i++) {
gtsam::Values odom_val;
gtsam::NonlinearFactorGraph odom_factor;
gtsam::Matrix3 R;
R.row(0) << 0, -1, 0;
R.row(1) << 1, 0, 0;
R.row(2) << 0, 0, 1;
gtsam::Pose3 odom = gtsam::Pose3(gtsam::Rot3(R), gtsam::Point3(1, 0, 0));
static const gtsam::SharedNoiseModel& noiseOdom =
gtsam::noiseModel::Isotropic::Variance(6, 0.1);
gtsam::Key key_prev = gtsam::Symbol('a', i);
gtsam::Key key_new = gtsam::Symbol('a', i + 1);
odom_val.insert(key_new, odom);
odom_factor.add(
gtsam::BetweenFactor<gtsam::Pose3>(key_prev, key_new, odom, noiseOdom));
pgo->update(odom_factor, odom_val);
}
// add loop closures
gtsam::NonlinearFactorGraph lc_factors;
gtsam::Key a1 = gtsam::Symbol('a', 1);
gtsam::Key a2 = gtsam::Symbol('a', 2);
gtsam::Key a3 = gtsam::Symbol('a', 3);
gtsam::Key a4 = gtsam::Symbol('a', 4);
gtsam::Key a5 = gtsam::Symbol('a', 5);
lc_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a3,
a2,
gtsam::Pose3(gtsam::Rot3::Rz(-1.57), gtsam::Point3(0, 0.9, 0)),
noise));
lc_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a4,
a1,
gtsam::Pose3(gtsam::Rot3::Rz(3.14), gtsam::Point3(2.1, 1.1, 2.5)),
noise));
pgo->update(lc_factors, gtsam::Values());
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(7));
EXPECT(est.size() == size_t(6));
// Now start adding landmarks
// Add first observation
gtsam::Vector6 ldmk_prec;
ldmk_prec.head<3>().setConstant(0); // rotation precision
ldmk_prec.tail<3>().setConstant(25);
static const gtsam::SharedNoiseModel& lmk_noise =
gtsam::noiseModel::Diagonal::Precisions(ldmk_prec);
gtsam::NonlinearFactorGraph landmark_factors;
gtsam::Values landmark_values;
gtsam::Key l0 = gtsam::Symbol('l', 0);
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a1, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, 1, 0)), lmk_noise));
landmark_values.insert(l0,
gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 1, 0)));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(8));
EXPECT(est.size() == size_t(7));
// add a reobservation should be consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
gtsam::Matrix3 R;
R.row(0) << 0, -1, 0;
R.row(1) << 1, 0, 0;
R.row(2) << 0, 0, 1;
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a5,
l0,
gtsam::Pose3(gtsam::Rot3(R), gtsam::Point3(0, -1, 0)),
lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(9));
EXPECT(est.size() == size_t(7));
// add a reobservation that's not consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a4, l0, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(2, 0, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(10));
EXPECT(est.size() == size_t(7));
// Add another landmark
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
gtsam::Key l1 = gtsam::Symbol('l', 1);
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a2, l1, gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, -1, 0)), lmk_noise));
landmark_values.insert(l1,
gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(1, 1, 0)));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(11));
EXPECT(est.size() == size_t(8));
// add a reobservation should be consistent
landmark_factors = gtsam::NonlinearFactorGraph();
landmark_values = gtsam::Values();
landmark_factors.add(gtsam::BetweenFactor<gtsam::Pose3>(
a5, l1, gtsam::Pose3(gtsam::Rot3(R), gtsam::Point3(2, 0, 0)), lmk_noise));
pgo->update(landmark_factors, landmark_values);
nfg = pgo->getFactorsUnsafe();
est = pgo->calculateEstimate();
EXPECT(nfg.size() == size_t(12));
EXPECT(est.size() == size_t(8));
}
/* ************************************************************************* */
int main() {
TestResult tr;
return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */
| [
"yunchang@mit.edu"
] | yunchang@mit.edu |
47a17ce843aa739c2e6313bf40605324bbea16e6 | 16addc5cd60d79c5309e63bb582fe1870155ef59 | /Castlevania_Game/LargeHeart.h | a22d1bfc3bbca489d10e8a7d2116cf5bf956b384 | [] | no_license | tienthanght96/Directx_Game_2016 | 3b2e2f6182e89de9aea9d83a969a09b8ae50cf59 | 98e6cdabdcbc0dc26d61d81bf51a2d9638314923 | refs/heads/master | 2021-01-12T05:23:19.279433 | 2017-01-03T13:52:52 | 2017-01-03T13:52:52 | 77,919,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | h | #ifndef __LARGE_HEART_H__
#define __LARGE_HEART_H__
#define LARGE_HEART_Y 0.0975F
#define LARGE_HEART "LargeHeart"
#include "SweptAABB.h"
#include "CObject.h"
#include "m2dxbasesprite.h"
#include "Global.h"
#define LARGE_HEART_WIDTH 26
#define LARGE_HEART_HEIGHT 20
#define LARGE_HEART_SPRITE "Resources\\Sprites\\LargeHeart\\LargeHeartSheet.png"
#define LARGE_HEART_SHEET "Resources\\Sprites\\LargeHeart\\LargeHeartSheet"
class LargeHeart : public CObject, M2DXAnimatedSprite
{
public:
LargeHeart(int X, int Y);
SweptAABB *swept = new SweptAABB();
void Update(int DeltaTime);
bool updateCollis(CObject* Ob);
void Draw();
~LargeHeart() {};
protected:
int getAnimateRate() override { return 0; };
string getNextFrame() override { return LARGE_HEART; };
private:
int remainingDead = 4000;
void updateState(int deltaTime);
void updatePosition(int deltaTime);
void updateInfor(int deltaTime);
};
#endif
| [
"trantienthanght96@gmail.com"
] | trantienthanght96@gmail.com |
f0913bcdc1f9e39928f5a2d03f1ca86a78bcc892 | e7f65a2fb4a85acdc26865883268333c17b3d791 | /intern/src/mapthread.cpp | f5f6424e93ee91de0ee94c9701d70dd2958c0525 | [] | no_license | kek112/SmHoEzMa | 129dea4e58ac5099b9c7eae3840e9dab6c1f7bd1 | dab59f5047f1f61a70226661bd0f92139689357b | refs/heads/master | 2021-09-25T02:40:18.851821 | 2018-08-05T13:02:47 | 2018-08-05T13:02:47 | 153,416,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 938 | cpp | #include "mapthread.h"
CMapThread::CMapThread(CDeviceStructure _Devices, QObject *parent)
: QObject(parent)
, m_Devices(_Devices)
{
}
void CMapThread::StopThread()
{
m_StopThread = true;
}
void CMapThread::UpdateDeviceStructure(CDeviceStructure _Devices)
{
m_Devices = _Devices;
}
void CMapThread::checkGPS()
{
m_StopThread = false;
forever
{
if(m_StopThread)
return;
QGeoCoordinate coordinate = m_GPS.getGPSLocation();
int deviceNumber = 0;
for(auto device : m_Devices.returnDevices())
{
if(m_StopThread)
return;
if(device.m_HomecomingActive && m_HomeCoordinate.distanceTo(coordinate) < 100)
{
emit reachedHome(deviceNumber);
}
deviceNumber++;
}
}
}
void CMapThread::SetHome(QGeoCoordinate _coordinate)
{
m_HomeCoordinate = _coordinate;
}
| [
"tobias.m.riess@gmail.com"
] | tobias.m.riess@gmail.com |
ce28a7647699839f9e171f8ca878dd40454a7add | 575731c1155e321e7b22d8373ad5876b292b0b2f | /examples/native/ios/Pods/boost-for-react-native/boost/date_time/local_time/conversion.hpp | 34434c0df4c0144835f4ea5daa9032ac3fb3163c | [
"BSL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Nozbe/zacs | 802a84ffd47413a1687a573edda519156ca317c7 | c3d455426bc7dfb83e09fdf20781c2632a205c04 | refs/heads/master | 2023-06-12T20:53:31.482746 | 2023-06-07T07:06:49 | 2023-06-07T07:06:49 | 201,777,469 | 432 | 10 | MIT | 2023-01-24T13:29:34 | 2019-08-11T14:47:50 | JavaScript | UTF-8 | C++ | false | false | 897 | hpp | #ifndef DATE_TIME_LOCAL_TIME_CONVERSION_HPP__
#define DATE_TIME_LOCAL_TIME_CONVERSION_HPP__
/* Copyright (c) 2003-2004 CrystalClear Software, Inc.
* Subject to the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
* $Date$
*/
#include "boost/date_time/posix_time/conversion.hpp"
#include "boost/date_time/c_time.hpp"
#include "boost/date_time/local_time/local_date_time.hpp"
namespace boost {
namespace local_time {
//! Function that creates a tm struct from a local_date_time
inline
std::tm to_tm(const local_date_time& lt) {
std::tm lt_tm = posix_time::to_tm(lt.local_time());
if(lt.is_dst()){
lt_tm.tm_isdst = 1;
}
else{
lt_tm.tm_isdst = 0;
}
return lt_tm;
}
}} // namespaces
#endif // DATE_TIME_LOCAL_TIME_CONVERSION_HPP__
| [
"radexpl@gmail.com"
] | radexpl@gmail.com |
0d80479f5210d2ace43fd373dc45e9c67632c7ef | 85c2f04c050c3f27d404ae1a71d43efb8cd0769d | /House/House.cpp | dcd9f10b3ef8b571a36b24960adc2bc62463b7a9 | [] | no_license | dmatseku/House_Generator | 3ed82c82e6bbc5c44da797d1cf8936df2c734f14 | 7cff1b4433e456e467e78799921de78d6f375c5c | refs/heads/master | 2020-09-26T07:26:11.676957 | 2019-12-08T14:59:54 | 2019-12-08T14:59:54 | 226,203,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,307 | cpp | #include "House.hpp"
#include <iostream>
#include <regex>
#include <sstream>
namespace
{
int find_apf(int ac, char** av, int porch)
{
std::string expression = "(apf" + std::to_string(porch) + "=)(\\d+)";
std::regex flag(expression);
std::cmatch info;
for (int i = 1; i < ac; i++)
if (std::regex_match(av[i], info, flag))
return (std::stoi(info.str(2)));
return (0);
}
int find_floors(int ac, char** av, int porch)
{
std::string expression = "(floors" + std::to_string(porch) + "=)(\\d+)";
std::regex flag(expression);
std::cmatch info;
for (int i = 1; i < ac; i++)
if (std::regex_match(av[i], info, flag))
return (std::stoi(info.str(2)));
return (0);
}
}
House::House(int ac, char** av):
_porchs(1),
_first_porch(1),
_s_floors(1),
_first_nb(1),
_s_apf(1),
_porchs_data(0)
{
read_data();
int porch = 0;
std::vector<data> p_data(_porchs);
for(data& d : p_data)
{
int apf = find_apf(ac, av, porch + 1);
int floors = find_floors(ac, av, porch + 1);
d.apf = (apf ? apf : _s_apf);
d.floors = (floors ? floors : _s_floors);
porch++;
}
_porchs_data = std::move(p_data);
}
House::House():
_porchs(1),
_first_porch(1),
_s_floors(1),
_first_nb(1),
_s_apf(1),
_porchs_data(0)
{
read_data();
std::vector<data> p_data(_porchs);
for(data& d : p_data)
{
d.apf = _s_apf;
d.floors = _s_floors;
}
_porchs_data = std::move(p_data);
}
void
House::read_data()
{
std::cout << START_PORCH_NB;
std::cin >> _first_porch;
std::cout << PORCHS;
std::cin >> _porchs;
std::cout << FLOORS;
std::cin >> _s_floors;
std::cout << APF;
std::cin >> _s_apf;
std::cout << FIRST_NB;
std::cin >> _first_nb;
std::cout << std::endl;
}
std::string
House::to_string()
{
std::stringstream res;
int actual_nb = _first_nb;
const int end_porch = _first_porch + _porchs;
for (int porch = _first_porch; porch < end_porch; porch++)
{
res << WORD_PORCH << ": " << porch << "\n";
res << create_porch(actual_nb, _porchs_data[porch - _first_porch]);
if (porch < end_porch - 1)
res << "\n\n";
actual_nb += (_porchs_data[porch - _first_porch].floors
* _porchs_data[porch - _first_porch].apf);
}
return (res.str());
}
std::string
House::create_porch(int first_nb, data const & dat)
{
std::stringstream res;
int actual_nb = first_nb;
for (int floor = 0; floor < dat.floors; floor++)
{
res << FLOOR_PREFIX << WORD_FLOOR << ": " << floor + 1 << "\n";
res << FLOOR_PREFIX << create_floor(actual_nb, dat.apf) << "\n\n";
actual_nb += dat.apf;
}
res << FLOOR_PREFIX << WORD_RUDE << ": " << WORD_NO << "\n";
res << FLOOR_PREFIX << WORD_CATEGORICAL << ": " << WORD_NO;
return (res.str());
}
std::string
House::create_floor(int first_nb, int apf)
{
std::stringstream res;
int end_nb = first_nb + apf;
res << APARTMENT_PREFIX << first_nb;
for (int nb = first_nb + 1; nb < end_nb; nb++)
{
res << ", " << nb;
}
return (res.str());
}
| [
"kamikoto.sudzuki@gmail.com"
] | kamikoto.sudzuki@gmail.com |
36b6a2748a6f8a8e96460e052641807cb04edd9a | 6dfe5ed08bc8eccba701cc3d0e1721a89338f3ba | /packages/JSPersimmon/js_page.h | 855e0e91cb7b2ff17491013551d91469812634cf | [] | no_license | XZHSTAX/LS1c_ICcom | e239bf686c8683916813931faf8498c8cfbb9456 | 7e4835d4bad297ef1dcf975c4045761d64722511 | refs/heads/main | 2023-01-11T00:16:33.033191 | 2020-11-15T18:31:32 | 2020-11-15T18:31:32 | 313,072,875 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,376 | h | #pragma once
#include <js_object.h>
#include <pm_page.h>
#include <js_window.h>
#include <string>
class JsPage : public JsObject, public Persimmon::Page
{
public:
JsPage(JsWindow *win, jerry_value_t obj, std::string &xml);
virtual ~JsPage();
void onLoad(jerry_value_t obj);
void onShowPage(void);
void onExit(void);
void onUpdate(jerry_value_t obj);
virtual void initJsObject(void);
virtual void setData(void* data);
virtual void getData(void* data);
void setData(jerry_value_t data);
void getData(jerry_value_t data);
void setExitAnimation(enum AnimType type, rt_uint16_t frames, rt_uint16_t frameInterval)
{
exitAnimType = type;
exitAnimFrames = frames;
exitAnimFrameInterval = frameInterval;
}
void updateExitAnim(void)
{
if (exitAnimType != AnimNone)
{
setAnimation(exitAnimType, exitAnimFrames, exitAnimFrameInterval, true);
}
}
void setJsFunction(jerry_value_t object, const char* func);
void bindTouch(const char *type, const struct rtgui_gesture *gest);
virtual bool handleGestureEvent(struct rtgui_event_gesture *gev, const struct rtgui_gesture *gest);
protected:
private:
enum AnimType exitAnimType;
rt_uint16_t exitAnimFrames, exitAnimFrameInterval;
jerry_value_t jsCallFunc;
jerry_value_t jsObj;
};
| [
"xzhstax@foxmail.com"
] | xzhstax@foxmail.com |
de3f3daa32e4b30d9bbb0c9924911d6400358604 | bd18edfafeec1470d9776f5a696780cbd8c2e978 | /SlimDX/source/directwrite/GlyphRunDW.cpp | 99d0e1b7639360408dd8e7079cc08d43cf272c74 | [
"MIT"
] | permissive | MogreBindings/EngineDeps | 1e37db6cd2aad791dfbdfec452111c860f635349 | 7d1b8ecaa2cbd8e8e21ec47b3ce3a5ab979bdde7 | refs/heads/master | 2023-03-30T00:45:53.489795 | 2020-06-30T10:48:12 | 2020-06-30T10:48:12 | 276,069,149 | 0 | 1 | null | 2021-04-05T16:05:53 | 2020-06-30T10:33:46 | C++ | UTF-8 | C++ | false | false | 2,522 | cpp | /*
* Copyright (c) 2007-2010 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"
#include "../stack_array.h"
#include "GlyphRunDW.h"
using namespace System;
namespace SlimDX
{
namespace DirectWrite
{
DWRITE_GLYPH_RUN GlyphRun::ToUnmanaged(stack_array<UINT16> &indices, stack_array<FLOAT> &advances, stack_array<DWRITE_GLYPH_OFFSET> &offsets)
{
DWRITE_GLYPH_RUN result;
result.fontFace = FontFace->InternalPointer;
result.fontEmSize = FontSize;
result.glyphCount = GlyphCount;
result.isSideways = IsSideways;
result.bidiLevel = BidiLevel;
result.glyphIndices = NULL;
result.glyphAdvances = NULL;
result.glyphOffsets = NULL;
if (GlyphIndices != nullptr && GlyphIndices->Length > 0)
{
pin_ptr<short> pinnedIndices = &GlyphIndices[0];
memcpy(&indices[0], pinnedIndices, sizeof(short) * GlyphIndices->Length);
result.glyphIndices = &indices[0];
}
if (GlyphAdvances != nullptr && GlyphAdvances->Length > 0)
{
pin_ptr<float> pinnedAdvances = &GlyphAdvances[0];
memcpy(&advances[0], pinnedAdvances, sizeof(float) * GlyphAdvances->Length);
result.glyphAdvances = &advances[0];
}
if (GlyphOffsets != nullptr && GlyphOffsets->Length > 0)
{
pin_ptr<GlyphOffset> pinnedOffsets = &GlyphOffsets[0];
memcpy(&offsets[0], pinnedOffsets, sizeof(DWRITE_GLYPH_OFFSET) * GlyphOffsets->Length);
result.glyphOffsets = &offsets[0];
}
return result;
}
}
}
| [
"Michael@localhost"
] | Michael@localhost |
cba8246ec20ec134edeb08cfd98c8b8c2c6459d0 | 04288cac6e3be98d5eb15d405f1a8d17d5091179 | /src/mesh.h | c5d606c64d2089fa89031abf7ee9035ed411a0f6 | [] | no_license | evouga/bristlecopters | 106f3ffb1cc933527339dff9bd9aae450d83aebe | 7f75a4de92bb2560f1dd2397a2b5768d8686b529 | refs/heads/master | 2020-05-17T05:24:00.070387 | 2013-12-10T22:58:37 | 2013-12-10T22:58:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,490 | h | #ifndef MESH_H
#define MESH_H
#include "OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh"
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <QMutex>
#include "elasticenergy.h"
class Controller;
struct MyTraits : public OpenMesh::DefaultTraits
{
typedef OpenMesh::Vec3d Point; // use double-values points
typedef OpenMesh::Vec3d Normal; // use double-values points
EdgeTraits
{
private:
double restlen_;
public:
EdgeT() : restlen_(0) {}
double restlen() const {return restlen_;}
void setRestlen(double l) {restlen_=l;}
};
};
typedef OpenMesh::TriMesh_ArrayKernelT<MyTraits> OMMesh;
struct ProblemParameters : public ElasticParameters
{
// rendering
bool showWireframe;
bool smoothShade;
int curMode;
double animAmplitude;
double animSpeed;
double rho;
};
class Mesh
{
public:
Mesh();
bool findMode();
int numedges() const;
int numdofs() const;
int numverts() const;
const ProblemParameters &getParameters() const;
void setParameters(ProblemParameters params);
double getModeFrequency() const;
// Rendering methods. These run concurrently and must all lock the meshLock before reading from the mesh.
void render(double t);
Eigen::Vector3d centroid();
double radius();
// End rendering methods
bool exportOBJ(const char *filename);
bool importOBJ(const char *filename);
private:
void dofsFromGeometry(Eigen::VectorXd &q, Eigen::VectorXd &g) const;
void dofsToGeometry(const Eigen::VectorXd &q, const Eigen::VectorXd &g);
void setIntrinsicLengthsToCurrentLengths();
void elasticEnergy(const Eigen::VectorXd &q,
const Eigen::VectorXd &g,
double &energyB,
double &energyS,
Eigen::VectorXd &gradq,
Eigen::SparseMatrix<double> &hessq,
Eigen::SparseMatrix<double> &gradggradq,
int derivativesRequested) const;
void edgeEndpoints(OMMesh::EdgeHandle eh, OMMesh::Point &pt1, OMMesh::Point &pt2);
void edgeEndpointsWithMode(OMMesh::EdgeHandle edge, OMMesh::Point &p1, OMMesh::Point &p2, int mode, double amp);
void buildExtendedMassMatrix(const Eigen::VectorXd &q, Eigen::SparseMatrix<double> &M) const;
void buildExtendedInvMassMatrix(const Eigen::VectorXd &q, Eigen::SparseMatrix<double> &M) const;
double barycentricDualArea(const Eigen::VectorXd &q, int vidx) const;
double circumcentricDualArea(const Eigen::VectorXd &q, int vidx) const;
double faceArea(const Eigen::VectorXd &q, int fidx) const;
double pointModeValue(OMMesh::VertexHandle vert, int mode);
double modeAmp(int mode, double time);
void pointWithMode(OMMesh::VertexHandle vert, OMMesh::Point &pt, int mode, double amp);
Eigen::Vector3d colormap(double val) const;
Eigen::Vector3d colormap(double val, double min, double max) const;
Eigen::Vector3d HSLtoRGB(const Eigen::Vector3d &hsl) const;
OMMesh *mesh_;
ProblemParameters params_;
Eigen::MatrixXd modes_;
Eigen::VectorXd modeFrequencies_;
// The rendering thread reads the mesh and its edge data. Any function must lock this before writing to
// to the mesh. (The rendering thread does not write to the mesh so reads from the worker thread do not
// need to lock.)
QMutex meshLock_;
};
#endif // MESH_H
| [
"evouga@gmail.com"
] | evouga@gmail.com |
4d1005454837e3e85060fa6a3fe937dc945e1b7d | f5a8254ab9f6b68768d4309e48a387a142935162 | /CommManipulatorObjects/smartsoft/src-gen/CommManipulatorObjects/CommManipulatorEventParameterCore.hh | 7e63dcdec1e7f2d9e0e3ae515143a3f1468cd3e2 | [
"BSD-3-Clause"
] | permissive | canonical-robots/DomainModelsRepositories | 9839a3f4a305d3a94d4a284d7ba208cd1e5bf87f | 68b9286d84837e5feb7b200833b158ab9c2922a4 | refs/heads/master | 2022-12-26T16:33:58.843240 | 2020-10-02T08:54:50 | 2020-10-02T08:54:50 | 287,251,257 | 0 | 0 | BSD-3-Clause | 2020-08-13T10:39:30 | 2020-08-13T10:39:29 | null | UTF-8 | C++ | false | false | 2,834 | hh | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#ifndef COMMMANIPULATOROBJECTS_COMMMANIPULATOREVENTPARAMETER_CORE_H_
#define COMMMANIPULATOROBJECTS_COMMMANIPULATOREVENTPARAMETER_CORE_H_
#include "CommManipulatorObjects/CommManipulatorEventParameterData.hh"
#include "CommManipulatorObjects/enumManipulatorEvent.hh"
#include <iostream>
#include <string>
#include <list>
namespace CommManipulatorObjects {
class CommManipulatorEventParameterCore {
protected:
// data structure
CommManipulatorObjectsIDL::CommManipulatorEventParameter idl_CommManipulatorEventParameter;
public:
// give a publicly accessible type-name for the template parameter IDL
typedef CommManipulatorObjectsIDL::CommManipulatorEventParameter DATATYPE;
#ifdef ENABLE_HASH
static size_t generateDataHash(const DATATYPE &);
#endif
static const char* getCompiledHash();
static void getAllHashValues(std::list<std::string> &hashes);
static void checkAllHashValues(std::list<std::string> &hashes);
// default constructors
CommManipulatorEventParameterCore();
CommManipulatorEventParameterCore(const DATATYPE &data);
// default destructor
virtual ~CommManipulatorEventParameterCore();
const DATATYPE& get() const { return idl_CommManipulatorEventParameter; }
operator const DATATYPE&() const { return idl_CommManipulatorEventParameter; }
DATATYPE& set() { return idl_CommManipulatorEventParameter; }
static inline std::string identifier(void) { return "CommManipulatorObjects::CommManipulatorEventParameter"; }
// helper method to easily implement output stream in derived classes
void to_ostream(std::ostream &os = std::cout) const;
// convert to xml stream
void to_xml(std::ostream &os, const std::string &indent = "") const;
// restore from xml stream
void from_xml(std::istream &is);
// User Interface
// getter and setter for element Event
inline CommManipulatorObjects::ManipulatorEvent getEvent() const { return CommManipulatorObjects::ManipulatorEvent(idl_CommManipulatorEventParameter.event); }
inline CommManipulatorEventParameterCore& setEvent(const CommManipulatorObjects::ManipulatorEvent &event) { idl_CommManipulatorEventParameter.event = event; return *this; }
};
} /* namespace CommManipulatorObjects */
#endif /* COMMMANIPULATOROBJECTS_COMMMANIPULATOREVENTPARAMETER_CORE_H_ */
| [
"lotz@hs-ulm.de"
] | lotz@hs-ulm.de |
d3d74ff6349d06c8a18617bf4416eb6a81560fc0 | aade1e73011f72554e3bd7f13b6934386daf5313 | /Contest/Opencup/XVII/Siberia/H.cpp | 407b2f14eab712a228ff719c5dc32f0380952445 | [] | no_license | edisonhello/waynedisonitau123 | 3a57bc595cb6a17fc37154ed0ec246b145ab8b32 | 48658467ae94e60ef36cab51a36d784c4144b565 | refs/heads/master | 2022-09-21T04:24:11.154204 | 2022-09-18T15:23:47 | 2022-09-18T15:23:47 | 101,478,520 | 34 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 3,012 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, q;
cin >> n >> q;
vector<int> w(n + 1);
for (int i = 0; i < n + 1; ++i) cin >> w[i];
vector<int> s(n);
vector<vector<int>> g(n + n + 1);
vector<bool> root(n, true);
for (int i = 0; i < n; ++i) {
cin >> s[i];
for (int j = 0; j < 2; ++j) {
int x;
cin >> x;
if (x > 0) {
g[i].push_back(x - 1);
root[x - 1] = false;
} else {
g[i].push_back(-x - 1 + n);
}
}
}
int rt = 0;
while (rt < n && !root[rt]) rt++;
assert(rt < n);
vector<int> fa(n + n + 1);
vector<int> dep(n + n + 1);
vector<int> tin(n + n + 1), tout(n + n + 1);
function<void(int, int)> Dfs = [&](int x, int p) {
static int stamp = 0;
tin[x] = stamp++;
for (int u : g[x]) {
dep[u] = dep[x] + 1;
Dfs(u, x);
}
tout[x] = stamp;
};
Dfs(rt, -1);
int m = n + n + 1;
vector<int64_t> tree(4 * m);
vector<int> rev(n + n + 1);
for (int i = 0; i < n + n + 1; ++i) rev[tin[i]] = i;
auto Build = [&]() {
auto _ = [&](auto self, int l, int r, int o = 0) {
if (r - l == 1) {
if (rev[l] >= n) tree[o] = w[rev[l] - n];
return;
}
int m = (l + r) >> 1;
self(self, l, m, o * 2 + 1);
self(self, m, r, o * 2 + 2);
tree[o] = tree[o * 2 + 1] + tree[o * 2 + 2];
};
_(_, 0, m);
};
auto Query = [&](int ql, int qr) {
auto _ = [&](auto self, int l, int r, int o = 0) -> int64_t {
if (l >= qr || ql >= r) return 0;
if (l >= ql && r <= qr) return tree[o];
int m = (l + r) >> 1;
return self(self, l, m, o * 2 + 1) + self(self, m, r, o * 2 + 2);
};
return _(_, 0, m);
};
auto Modify = [&](int p, int v) {
auto _ = [&](auto self, int l, int r, int o = 0) {
if (r - l == 1) {
tree[o] = v;
return;
}
int m = (l + r) >> 1;
if (p < m) self(self, l, m, o * 2 + 1);
else self(self, m, r, o * 2 + 2);
tree[o] = tree[o * 2 + 1] + tree[o * 2 + 2];
};
_(_, 0, m);
};
Build();
while (q--) {
int t;
cin >> t;
if (t == 2) {
int x;
cin >> x;
x--;
assert(g[x].size() == 2);
int64_t a = Query(tin[g[x][0]], tout[g[x][0]]);
int64_t b = Query(tin[g[x][1]], tout[g[x][1]]);
long double r = (long double)(s[x] * b) / (a + b);
cout << fixed << setprecision(20) << r << "\n";
} else {
int x, v;
cin >> x >> v;
x--;
Modify(tin[x + n], v);
}
}
}
| [
"tu.da.wei@gmail.com"
] | tu.da.wei@gmail.com |
387a0b4abad7cb1c1a5642e2d41ba294050da32a | 5fa1f4a43544d69dee04118d024edad7ee9e592d | /OJ/2001.cpp | af7489764d5b89e15092b71c91f8d339470b1142 | [] | no_license | ImaginationZ/code | 899b34b1c595b0cc4b0f2273295f83c37d12189a | e959bf123117b0687aefd89717d94898401454a0 | refs/heads/master | 2016-09-09T22:52:16.337916 | 2013-07-29T15:52:27 | 2013-07-29T15:52:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | #include <iostream>
using namespace std;
const int MAX=20000;
long seq[MAX];
long sum[MAX] = {0};
int main(){
long n,m,x,y;
cin >> n;
for (long i=0;i<n;++i){
cin >> seq[i+1];
sum[i+1] = sum[i] + seq[i+1];
}
cin >> m;
for (long t=0;t<m;++t){
cin >> x >> y;
cout << sum[y] - sum[x-1] << endl;
}
return 0;
}
| [
"frequencyhzs@gmail.com"
] | frequencyhzs@gmail.com |
2d589f1fbc30b5cdac42545f8a24c3d4541ce0f9 | 9018cdaee3415c86eac31afc98ecf72560522215 | /DAY 15/160a.cpp | ed56d92bc6848850725728852925c30f84f2ef9e | [] | no_license | avishkarhande/21-DAYS-PROGRAMMING-CHALLENGE-ACES | 937d5bff1483eb7a605a45b17c47c479e5f52e52 | 75dc1f4134a3c69610e8cfadcf0d0588ab694391 | refs/heads/main | 2023-01-08T07:22:57.121526 | 2020-10-25T13:36:01 | 2020-10-25T13:36:01 | 301,428,453 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | #include<bits/stdc++.h>
typedef long long ll;
#define vi vector<int>
#define pi pair<int,int>
#define vvi vector<vector<int>>
#define vpi vector<pair<int,int>>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define sq(a) a*a
#define mod 1000000007
#define endl "\n"
#define CIN(i,a,b) for(int i=a;i<b;i++){cin>>arr[i];}
using namespace std;
int main()
{
int n;
cin>>n;
ll arr[n];
// FOR(i,0,n){
// cin>>arr[i];
// }
ll sum=0;
CIN(i,0,n);
FOR(i,0,n){sum+=arr[i];}
sort(arr,arr+n);
ll cur = 0;
ll cnt=1;
ll i=0;
for(int i=n-1;i>=0;i--){
if(cur+arr[i]<=sum-arr[i]){
sum-=arr[i];
cur+=arr[i];
cnt++;
}else{
break;
}
}
cout<<cnt<<endl;
} | [
"noreply@github.com"
] | noreply@github.com |
4623626b099b89b44fff08f6dd1abe2fcc766205 | c97c131b1a9c4f6709d6a6fcff7f79c1e7e346ad | /core/mat44.h | 3bfa665e388f0c03f8082f219764e5269a977911 | [] | no_license | nebogeo/nomadic-engine | f8aed580ba1bbad288bc9262d0243cee767eddfd | 27aa6886ae8e655b59ecc40f62f047ed47936b0a | refs/heads/master | 2020-05-19T09:30:55.966805 | 2013-09-02T22:34:04 | 2013-09-02T22:34:04 | 5,829,744 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,847 | h | // Copyright (C) 2011 Dave Griffiths
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include <math.h>
#include <string.h>
#include "vec3.h"
#ifndef FLX_MAT44
#define FLX_MAT44
static const flx_real TWO_PI=3.141592654*2.0f;
static const flx_real DEG_CONV = 0.017453292f;
static const flx_real RAD_CONV = 1/0.017453292f;
class mat44
{
public:
mat44() { init(); }
mat44(const mat44 &other) { (*this)=other; }
mat44(flx_real m00, flx_real m10, flx_real m20, flx_real m30,
flx_real m01, flx_real m11, flx_real m21, flx_real m31,
flx_real m02, flx_real m12, flx_real m22, flx_real m32,
flx_real m03, flx_real m13, flx_real m23, flx_real m33)
{
m[0][0]=m00; m[1][0]=m10; m[2][0]=m20; m[3][0]=m30;
m[0][1]=m01; m[1][1]=m11; m[2][1]=m21; m[3][1]=m31;
m[0][2]=m02; m[1][2]=m12; m[2][2]=m22; m[3][2]=m32;
m[0][3]=m03; m[1][3]=m13; m[2][3]=m23; m[3][3]=m33;
}
inline void init()
{
zero();
m[0][0]=m[1][1]=m[2][2]=m[3][3]=1.0f;
}
inline void zero()
{
memset(m,0,sizeof(flx_real)*16);
}
inline const mat44 &operator=(mat44 const &rhs)
{
m[0][0]=rhs.m[0][0]; m[0][1]=rhs.m[0][1]; m[0][2]=rhs.m[0][2]; m[0][3]=rhs.m[0][3];
m[1][0]=rhs.m[1][0]; m[1][1]=rhs.m[1][1]; m[1][2]=rhs.m[1][2]; m[1][3]=rhs.m[1][3];
m[2][0]=rhs.m[2][0]; m[2][1]=rhs.m[2][1]; m[2][2]=rhs.m[2][2]; m[2][3]=rhs.m[2][3];
m[3][0]=rhs.m[3][0]; m[3][1]=rhs.m[3][1]; m[3][2]=rhs.m[3][2]; m[3][3]=rhs.m[3][3];
return rhs;
}
inline mat44 operator+(mat44 const &rhs) const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[i][j]+rhs.m[i][j];
}
}
return t;
}
inline mat44 operator-(mat44 const &rhs) const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[i][j]-rhs.m[i][j];
}
}
return t;
}
inline mat44 operator*(mat44 const &rhs) const
{
mat44 t;
t.m[0][0]=m[0][0]*rhs.m[0][0]+m[1][0]*rhs.m[0][1]+m[2][0]*rhs.m[0][2]+m[3][0]*rhs.m[0][3];
t.m[0][1]=m[0][1]*rhs.m[0][0]+m[1][1]*rhs.m[0][1]+m[2][1]*rhs.m[0][2]+m[3][1]*rhs.m[0][3];
t.m[0][2]=m[0][2]*rhs.m[0][0]+m[1][2]*rhs.m[0][1]+m[2][2]*rhs.m[0][2]+m[3][2]*rhs.m[0][3];
t.m[0][3]=m[0][3]*rhs.m[0][0]+m[1][3]*rhs.m[0][1]+m[2][3]*rhs.m[0][2]+m[3][3]*rhs.m[0][3];
t.m[1][0]=m[0][0]*rhs.m[1][0]+m[1][0]*rhs.m[1][1]+m[2][0]*rhs.m[1][2]+m[3][0]*rhs.m[1][3];
t.m[1][1]=m[0][1]*rhs.m[1][0]+m[1][1]*rhs.m[1][1]+m[2][1]*rhs.m[1][2]+m[3][1]*rhs.m[1][3];
t.m[1][2]=m[0][2]*rhs.m[1][0]+m[1][2]*rhs.m[1][1]+m[2][2]*rhs.m[1][2]+m[3][2]*rhs.m[1][3];
t.m[1][3]=m[0][3]*rhs.m[1][0]+m[1][3]*rhs.m[1][1]+m[2][3]*rhs.m[1][2]+m[3][3]*rhs.m[1][3];
t.m[2][0]=m[0][0]*rhs.m[2][0]+m[1][0]*rhs.m[2][1]+m[2][0]*rhs.m[2][2]+m[3][0]*rhs.m[2][3];
t.m[2][1]=m[0][1]*rhs.m[2][0]+m[1][1]*rhs.m[2][1]+m[2][1]*rhs.m[2][2]+m[3][1]*rhs.m[2][3];
t.m[2][2]=m[0][2]*rhs.m[2][0]+m[1][2]*rhs.m[2][1]+m[2][2]*rhs.m[2][2]+m[3][2]*rhs.m[2][3];
t.m[2][3]=m[0][3]*rhs.m[2][0]+m[1][3]*rhs.m[2][1]+m[2][3]*rhs.m[2][2]+m[3][3]*rhs.m[2][3];
t.m[3][0]=m[0][0]*rhs.m[3][0]+m[1][0]*rhs.m[3][1]+m[2][0]*rhs.m[3][2]+m[3][0]*rhs.m[3][3];
t.m[3][1]=m[0][1]*rhs.m[3][0]+m[1][1]*rhs.m[3][1]+m[2][1]*rhs.m[3][2]+m[3][1]*rhs.m[3][3];
t.m[3][2]=m[0][2]*rhs.m[3][0]+m[1][2]*rhs.m[3][1]+m[2][2]*rhs.m[3][2]+m[3][2]*rhs.m[3][3];
t.m[3][3]=m[0][3]*rhs.m[3][0]+m[1][3]*rhs.m[3][1]+m[2][3]*rhs.m[3][2]+m[3][3]*rhs.m[3][3];
return t;
}
inline mat44 operator/(mat44 const &rhs) const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[i][0]/rhs.m[0][j]+
m[i][1]/rhs.m[1][j]+
m[i][2]/rhs.m[2][j]+
m[i][3]/rhs.m[3][j];
}
}
return t;
}
inline mat44 operator+(flx_real rhs) const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[i][j]+rhs;
}
}
return t;
}
inline mat44 operator-(flx_real rhs) const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[i][j]-rhs;
}
}
return t;
}
inline mat44 operator*(flx_real rhs) const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[i][j]*rhs;
}
}
return t;
}
inline mat44 operator/(flx_real rhs) const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[i][j]/rhs;
}
}
return t;
}
inline mat44 &operator+=(mat44 const &rhs)
{
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
m[i][j]+=rhs.m[i][j];
}
}
return *this;
}
inline mat44 &operator-=(mat44 const &rhs)
{
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
m[i][j]-=rhs.m[i][j];
}
}
return *this;
}
inline mat44 &operator*=(mat44 const &rhs)
{
*this=*this*rhs;
return *this;
}
inline mat44 &operator/=(mat44 const &rhs)
{
*this=*this/rhs;
return *this;
}
inline mat44 &translate(flx_real x, flx_real y, flx_real z)
{
mat44 t;
t.m[3][0]=x;
t.m[3][1]=y;
t.m[3][2]=z;
*this=*this*t;
return *this;
}
inline mat44 &translate(vec3 &tr)
{
mat44 t;
t.m[3][0]=tr.x;
t.m[3][1]=tr.y;
t.m[3][2]=tr.z;
*this=*this*t;
return *this;
}
inline void settranslate(const vec3 &tr)
{
m[3][0]=tr.x;
m[3][1]=tr.y;
m[3][2]=tr.z;
}
inline vec3 gettranslate() const
{
return vec3(m[3][0],m[3][1],m[3][2]);
}
//#define USE_FAST_SINCOS
inline mat44 &rotxyz(flx_real x,flx_real y,flx_real z)
{
mat44 t;
if (x!=0.0f)
{
x*=0.017453292f;
#ifdef USE_FAST_SINCOS
flx_real sx,cx;
dSinCos(x,sx,cx);
#else
flx_real sx=sin(x);
flx_real cx=cos(x);
#endif
t.m[1][1]=cx;
t.m[2][1]=-sx;
t.m[1][2]=sx;
t.m[2][2]=cx;
*this=*this*t;
}
if (y!=0.0f)
{
y*=0.017453292f;
#ifdef USE_FAST_SINCOS
flx_real sy,cy;
dSinCos(y,sy,cy);
#else
flx_real sy=sin(y);
flx_real cy=cos(y);
#endif
t.init();
t.m[0][0]=cy;
t.m[2][0]=sy;
t.m[0][2]=-sy;
t.m[2][2]=cy;
*this=*this*t;
}
if (z!=0.0f)
{
z*=0.017453292f;
#ifdef USE_FAST_SINCOS
flx_real sz,cz;
dSinCos(z,sz,cz);
#else
flx_real sz=sin(z);
flx_real cz=cos(z);
#endif
t.init();
t.m[0][0]=cz;
t.m[1][0]=-sz;
t.m[0][1]=sz;
t.m[1][1]=cz;
*this=*this*t;
}
return *this;
}
inline mat44 &rotx(flx_real a)
{
a*=0.017453292f;
mat44 t;
t.m[1][1]=cos(a);
t.m[2][1]=-sin(a);
t.m[1][2]=sin(a);
t.m[2][2]=cos(a);
*this=*this*t;
return *this;
}
inline mat44 &roty(flx_real a)
{
a*=0.017453292f;
mat44 t;
t.m[0][0]=cos(a);
t.m[2][0]=-sin(a);
t.m[0][2]=sin(a);
t.m[2][2]=cos(a);
*this=*this*t;
return *this;
}
inline mat44 &rotz(flx_real a)
{
a*=0.017453292f;
mat44 t;
t.m[0][0]=cos(a);
t.m[1][0]=-sin(a);
t.m[0][1]=sin(a);
t.m[1][1]=cos(a);
*this=*this*t;
return *this;
}
inline mat44 &scale(flx_real x, flx_real y, flx_real z)
{
mat44 t;
t.m[0][0]=x;
t.m[1][1]=y;
t.m[2][2]=z;
*this=*this*t;
return *this;
}
inline mat44& scale(const vec3& s)
{
return scale(s.x, s.y, s.z);
}
inline vec3 transform(vec3 const &p) const
{
vec3 t;
t.x=p.x*m[0][0] + p.y*m[1][0] + p.z*m[2][0] + m[3][0];
t.y=p.x*m[0][1] + p.y*m[1][1] + p.z*m[2][1] + m[3][1];
t.z=p.x*m[0][2] + p.y*m[1][2] + p.z*m[2][2] + m[3][2];
return t;
}
inline vec3 transform_persp(vec3 const &p) const
{
vec3 t;
t.x=p.x*m[0][0] + p.y*m[1][0] + p.z*m[2][0];
t.y=p.x*m[0][1] + p.y*m[1][1] + p.z*m[2][1];
t.z=p.x*m[0][2] + p.y*m[1][2] + p.z*m[2][2];
return t;
}
inline vec3 transform_no_trans(vec3 const &p) const
{
vec3 t;
t.x=p.x*m[0][0] + p.y*m[1][0] + p.z*m[2][0];
t.y=p.x*m[0][1] + p.y*m[1][1] + p.z*m[2][1];
t.z=p.x*m[0][2] + p.y*m[1][2] + p.z*m[2][2];
return t;
}
/*void load_glmatrix(flx_real glm[16])
{
glm[0]= m[0][0]; glm[1]= m[1][0]; glm[2]= m[2][0]; glm[3]= m[3][0];
glm[4]= m[0][1]; glm[5]= m[1][1]; glm[6]= m[2][1]; glm[7]= m[3][1];
glm[8]= m[0][2]; glm[9]= m[1][2]; glm[10]=m[2][2]; glm[11]=m[3][2];
glm[12]=m[0][3]; glm[13]=m[1][3]; glm[14]=m[2][3]; glm[15]=m[3][3];
}*/
inline void load_glmatrix(flx_real glm[16])
{
glm[0]= m[0][0]; glm[4]= m[1][0]; glm[8]= m[2][0]; glm[12]= m[3][0];
glm[1]= m[0][1]; glm[5]= m[1][1]; glm[9]= m[2][1]; glm[13]= m[3][1];
glm[2]= m[0][2]; glm[6]= m[1][2]; glm[10]=m[2][2]; glm[14]=m[3][2];
glm[3]= m[0][3]; glm[7]= m[1][3]; glm[11]=m[2][3]; glm[15]=m[3][3];
}
inline void load_mat44(flx_real glm[16])
{
m[0][0]=glm[0]; m[1][0]=glm[4]; m[2][0]=glm[8]; m[3][0]=glm[12];
m[0][1]=glm[1]; m[1][1]=glm[5]; m[2][1]=glm[9]; m[3][1]=glm[13];
m[0][2]=glm[2]; m[1][2]=glm[6]; m[2][2]=glm[10]; m[3][2]=glm[14];
m[0][3]=glm[3]; m[1][3]=glm[7]; m[2][3]=glm[11]; m[3][3]=glm[15];
}
inline mat44 getTranspose() const
{
mat44 t;
for (u32 i=0; i<4; i++)
{
for (u32 j=0; j<4; j++)
{
t.m[i][j]=m[j][i];
}
}
return t;
}
inline void transpose()
{
*this = getTranspose();
}
inline mat44 inverse() const
{
mat44 temp;
temp.m[0][0] = m[1][2]*m[2][3]*m[3][1] - m[1][3]*m[2][2]*m[3][1] + m[1][3]*m[2][1]*m[3][2] - m[1][1]*m[2][3]*m[3][2] - m[1][2]*m[2][1]*m[3][3] + m[1][1]*m[2][2]*m[3][3];
temp.m[0][1] = m[0][3]*m[2][2]*m[3][1] - m[0][2]*m[2][3]*m[3][1] - m[0][3]*m[2][1]*m[3][2] + m[0][1]*m[2][3]*m[3][2] + m[0][2]*m[2][1]*m[3][3] - m[0][1]*m[2][2]*m[3][3];
temp.m[0][2] = m[0][2]*m[1][3]*m[3][1] - m[0][3]*m[1][2]*m[3][1] + m[0][3]*m[1][1]*m[3][2] - m[0][1]*m[1][3]*m[3][2] - m[0][2]*m[1][1]*m[3][3] + m[0][1]*m[1][2]*m[3][3];
temp.m[0][3] = m[0][3]*m[1][2]*m[2][1] - m[0][2]*m[1][3]*m[2][1] - m[0][3]*m[1][1]*m[2][2] + m[0][1]*m[1][3]*m[2][2] + m[0][2]*m[1][1]*m[2][3] - m[0][1]*m[1][2]*m[2][3];
temp.m[1][0] = m[1][3]*m[2][2]*m[3][0] - m[1][2]*m[2][3]*m[3][0] - m[1][3]*m[2][0]*m[3][2] + m[1][0]*m[2][3]*m[3][2] + m[1][2]*m[2][0]*m[3][3] - m[1][0]*m[2][2]*m[3][3];
temp.m[1][1] = m[0][2]*m[2][3]*m[3][0] - m[0][3]*m[2][2]*m[3][0] + m[0][3]*m[2][0]*m[3][2] - m[0][0]*m[2][3]*m[3][2] - m[0][2]*m[2][0]*m[3][3] + m[0][0]*m[2][2]*m[3][3];
temp.m[1][2] = m[0][3]*m[1][2]*m[3][0] - m[0][2]*m[1][3]*m[3][0] - m[0][3]*m[1][0]*m[3][2] + m[0][0]*m[1][3]*m[3][2] + m[0][2]*m[1][0]*m[3][3] - m[0][0]*m[1][2]*m[3][3];
temp.m[1][3] = m[0][2]*m[1][3]*m[2][0] - m[0][3]*m[1][2]*m[2][0] + m[0][3]*m[1][0]*m[2][2] - m[0][0]*m[1][3]*m[2][2] - m[0][2]*m[1][0]*m[2][3] + m[0][0]*m[1][2]*m[2][3];
temp.m[2][0] = m[1][1]*m[2][3]*m[3][0] - m[1][3]*m[2][1]*m[3][0] + m[1][3]*m[2][0]*m[3][1] - m[1][0]*m[2][3]*m[3][1] - m[1][1]*m[2][0]*m[3][3] + m[1][0]*m[2][1]*m[3][3];
temp.m[2][1] = m[0][3]*m[2][1]*m[3][0] - m[0][1]*m[2][3]*m[3][0] - m[0][3]*m[2][0]*m[3][1] + m[0][0]*m[2][3]*m[3][1] + m[0][1]*m[2][0]*m[3][3] - m[0][0]*m[2][1]*m[3][3];
temp.m[2][2] = m[0][1]*m[1][3]*m[3][0] - m[0][3]*m[1][1]*m[3][0] + m[0][3]*m[1][0]*m[3][1] - m[0][0]*m[1][3]*m[3][1] - m[0][1]*m[1][0]*m[3][3] + m[0][0]*m[1][1]*m[3][3];
temp.m[2][3] = m[0][3]*m[1][1]*m[2][0] - m[0][1]*m[1][3]*m[2][0] - m[0][3]*m[1][0]*m[2][1] + m[0][0]*m[1][3]*m[2][1] + m[0][1]*m[1][0]*m[2][3] - m[0][0]*m[1][1]*m[2][3];
temp.m[3][0] = m[1][2]*m[2][1]*m[3][0] - m[1][1]*m[2][2]*m[3][0] - m[1][2]*m[2][0]*m[3][1] + m[1][0]*m[2][2]*m[3][1] + m[1][1]*m[2][0]*m[3][2] - m[1][0]*m[2][1]*m[3][2];
temp.m[3][1] = m[0][1]*m[2][2]*m[3][0] - m[0][2]*m[2][1]*m[3][0] + m[0][2]*m[2][0]*m[3][1] - m[0][0]*m[2][2]*m[3][1] - m[0][1]*m[2][0]*m[3][2] + m[0][0]*m[2][1]*m[3][2];
temp.m[3][2] = m[0][2]*m[1][1]*m[3][0] - m[0][1]*m[1][2]*m[3][0] - m[0][2]*m[1][0]*m[3][1] + m[0][0]*m[1][2]*m[3][1] + m[0][1]*m[1][0]*m[3][2] - m[0][0]*m[1][1]*m[3][2];
temp.m[3][3] = m[0][1]*m[1][2]*m[2][0] - m[0][2]*m[1][1]*m[2][0] + m[0][2]*m[1][0]*m[2][1] - m[0][0]*m[1][2]*m[2][1] - m[0][1]*m[1][0]*m[2][2] + m[0][0]*m[1][1]*m[2][2];
flx_real d=temp.determinant();
if (d!=0.f)
{
flx_real scale=1.0f/d;
temp.scale(scale,scale,scale);
}
else temp.scale(0,0,0);
return temp;
}
inline flx_real determinant() const
{
return
m[0][3] * m[1][2] * m[2][1] * m[3][0]-m[0][2] * m[1][3] * m[2][1] * m[3][0]-m[0][3] * m[1][1] * m[2][2] * m[3][0]+m[0][1] * m[1][3] * m[2][2] * m[3][0]+
m[0][2] * m[1][1] * m[2][3] * m[3][0]-m[0][1] * m[1][2] * m[2][3] * m[3][0]-m[0][3] * m[1][2] * m[2][0] * m[3][1]+m[0][2] * m[1][3] * m[2][0] * m[3][1]+
m[0][3] * m[1][0] * m[2][2] * m[3][1]-m[0][0] * m[1][3] * m[2][2] * m[3][1]-m[0][2] * m[1][0] * m[2][3] * m[3][1]+m[0][0] * m[1][2] * m[2][3] * m[3][1]+
m[0][3] * m[1][1] * m[2][0] * m[3][2]-m[0][1] * m[1][3] * m[2][0] * m[3][2]-m[0][3] * m[1][0] * m[2][1] * m[3][2]+m[0][0] * m[1][3] * m[2][1] * m[3][2]+
m[0][1] * m[1][0] * m[2][3] * m[3][2]-m[0][0] * m[1][1] * m[2][3] * m[3][2]-m[0][2] * m[1][1] * m[2][0] * m[3][3]+m[0][1] * m[1][2] * m[2][0] * m[3][3]+
m[0][2] * m[1][0] * m[2][1] * m[3][3]-m[0][0] * m[1][2] * m[2][1] * m[3][3]-m[0][1] * m[1][0] * m[2][2] * m[3][3]+m[0][0] * m[1][1] * m[2][2] * m[3][3];
}
inline void aim(vec3 v, const vec3& up)
{
v.normalise();
vec3 l=v.cross(up);
vec3 u=v.cross(l);
l.normalise();
u.normalise();
m[0][0]=v.x; m[0][1]=v.y; m[0][2]=v.z;
m[1][0]=l.x; m[1][1]=l.y; m[1][2]=l.z;
m[2][0]=u.x; m[2][1]=u.y; m[2][2]=u.z;
}
inline void blend(const mat44& other, flx_real amount)
{
for (u32 j=0; j<4; j++)
{
for (u32 i=0; i<4; i++)
{
m[i][j]=(1.0f-amount)*m[i][j]+amount*other.m[i][j];
}
}
}
inline flx_real *arr()
{
return &m[0][0];
}
#ifdef _EE
flx_real m[4][4] __attribute__((__aligned__(16)));
#else
flx_real m[4][4];
#endif
};
#endif
| [
"dave@fo.am"
] | dave@fo.am |
e4920e78d8f3a11cea4277a719d9585b4b8f6bee | 8c7c3046db043da315302ca4aa3fd1074eebb241 | /GraphMatrix/graph.cpp | 1f2b00e8abd8d15b5a93d5fef9bf6c1ce2cc5351 | [] | no_license | D2epu/Datastructure | 33296a06becdabed3feb95bc52a2fe13f3bf899e | a6d23621b4d8d74259208af817cb0a6f833a011c | refs/heads/master | 2021-06-29T19:14:07.117137 | 2017-09-17T10:56:59 | 2017-09-17T10:56:59 | 103,750,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,283 | cpp | ////////////////////////////////////////////////////////
// Descrp : Adjacency Matrix Implementation of Graph
// Author : DipuKumar
// Language : C++
////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <list>
template <typename T>
class Graph
{
private:
int gSize;
typename T Vertices[100];
bool AdjMatrix[100][100];
int GetAdjUnVisited ( int vindex, bool * visited )
{
for ( int i = 0; i < gSize; i++ )
if ( AdjMatrix[vindex][i] && visited[i] == false )
return i;
return -1;
}
public:
Graph () : gSize ( 0 )
{
for ( int i = 0; i < 100; i++ )
for ( int j = 0; j < 100; j++ )
AdjMatrix[i][j] = false;
}
void AddVertex ( const T & data )
{
Vertices[gSize++] = data;
}
void AddEdge ( int src, int dest )
{
AdjMatrix[src][dest] = true;
AdjMatrix[dest][src] = true;
}
void RemoveEdge ( int src, int dest )
{
AdjMatrix[src][dest] = false;
AdjMatrix[dest][src] = false;
}
void DepthFirstSearch ()
{
bool visited[100]; int unvisited;
for ( int i = 0; i < gSize; i++ )
visited[i] = false;
visited[0] = true;
std::cout << Vertices[0] << "\t";
std::stack<int> stk;
stk.push ( 0 );
while ( ! stk.empty () )
{
int unvisited = GetAdjUnVisited ( stk.top (), visited );
if ( unvisited == -1 ) stk.pop ();
else
{
visited[unvisited] = true;
std::cout << Vertices[unvisited] << "\t";
stk.push ( unvisited );
}
}
}
void BreadthFirstSearch ()
{
bool visited[100]; int unvisited;
for ( int i = 0; i < gSize; i++ )
visited[i] = false;
visited[0] = true;
std::cout << Vertices[0] << "\t";
std::queue<int> que;
stk.push ( 0 );
while ( ! stk.empty () )
{
int unvisited = GetAdjUnVisited ( stk.top (), visited );
if ( unvisited == -1 ) stk.pop ();
else
{
visited[unvisited] = true;
std::cout << Vertices[unvisited] << "\t";
stk.push ( unvisited );
}
}
}
bool Empty () const
{
return gSize == 0;
}
int Size () const
{
return gSize;
}
};
int main ()
{
Graph<std::string> gr;
gr.AddVertex ( "DEEPU" );
gr.AddVertex ( "ARYAN" );
gr.AddVertex ( "RINKI" );
gr.AddVertex ( "NIRAJ" );
gr.AddVertex ( "AJEET" );
gr.AddEdge ( 0, 1 );
gr.AddEdge ( 0, 2 );
gr.AddEdge ( 0, 3 );
gr.AddEdge ( 1, 4 );
gr.AddEdge ( 2, 4 );
gr.AddEdge ( 3, 4 );
gr.DepthFirstSearch ();
return 0;
}
| [
"32012773+D2epu@users.noreply.github.com"
] | 32012773+D2epu@users.noreply.github.com |
0f95df7007076aa5002019898ccdd7c8845ac048 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/063/429/CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_74b.cpp | 4efdb15fbc4a08d90a701334db9b41b476ce88af | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,815 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_74b.cpp
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml
Template File: sources-sink-74b.tmpl.cpp
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Point data to a buffer that does not have space for a NULL terminator
* GoodSource: Point data to a buffer that includes space for a NULL terminator
* Sinks: ncpy
* BadSink : Copy string to data using strncpy()
* Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <map>
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING "AAAAAAAAAA"
using namespace std;
namespace CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_74
{
#ifndef OMITBAD
void badSink(map<int, char *> dataMap)
{
/* copy data out of dataMap */
char * data = dataMap[2];
{
char source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
strncpy(data, source, strlen(source) + 1);
printLine(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, char *> dataMap)
{
char * data = dataMap[2];
{
char source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
strncpy(data, source, strlen(source) + 1);
printLine(data);
}
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
c278101057efe5439688b5cecdb36b294ace2a1a | ef8dfc3b694c42371b40f1f94760054e1f6e2073 | /Runner_Nedelec_Marcilloux/Obstacle.cpp | ffb8a564d87918b5f8622d07d7b656f8b03a4a78 | [] | no_license | GuillaumeNed33/RunnerPOO | 4daccbd318b6b4086ff0ed486943274a5433e11b | 5b0a2b29de6a6d8abdbaf36104124837c2dd5575 | refs/heads/master | 2021-01-13T07:33:02.960726 | 2016-11-29T00:56:09 | 2016-11-29T00:56:09 | 71,490,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | cpp | #include "Obstacle.h"
//==================================================================================================================
// Description : Constructeur d'Obstacle
// Auteur : Nicolas Marcilloux
// Date : 10/02/16
// Interêt : permet de creer des Obstacles à partir de 4 float, 2 unsigned int, un TypeObstacles et un HeightElement
//==================================================================================================================
Obstacle::Obstacle(float x, float y, unsigned int w, unsigned int h, float dx, float dy, TypeObstacle type, HeightElement height):
MovableElement{x,y,w,h,dx,dy}, _type{type}
{
_height = height;
}
//=====================================
// Description : Destructeur d'Obstacle
// Auteur : Nicolas Marcilloux
// Date : 10/02/16
// Interêt : permet de detruire l'objet
//=====================================
Obstacle::~Obstacle() {}
//====================================================
// Description : Accesseur du type
// Auteur : Nicolas Marcilloux
// Date : 10/02/16
// Interêt : permet de récupérer le type de l'Obstacle
//====================================================
TypeObstacle Obstacle::get_type() const
{
return _type;
}
//=======================================================
// Description : Accesseur de la hauteur
// Auteur : Nicolas Marcilloux
// Date : 10/02/16
// Interêt : permet de récupérer la hauteur de l'Obstacle
//=======================================================
HeightElement Obstacle::get_height() const
{
return _height;
}
| [
"noreply@github.com"
] | noreply@github.com |
b35d61640087c1e1b5d38caf89e61023a73a017b | dbbbccba214e6a80fac15d7a18dfe5f18ad5fedf | /POJ3253/file.cpp | 94a27c20598b0a08f7b8ecb2e9766e82eddbe3f0 | [] | no_license | Cabbage-Cat/OJ_Solution | 4dbdd76e91138a3c612bc3ab58832632e4f81e61 | 3f60add815e6033af4311ed79aa0ae2dc007d43c | refs/heads/master | 2022-07-03T10:18:50.465704 | 2019-01-31T07:54:43 | 2019-01-31T07:54:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | cpp | #include <cstdio>
#include <cstring>
int N,L[21000];
void solve();
void swap(int*,int*);
int main()
{
scanf("%d",&N);
for (int i=0;i<N;i++)
scanf("%d",&L[i]);
solve();
return 0;
}
void solve()
{
long long int ans = 0;
while (N>1)
{
int min1 = 0,min2 = 1;
if (L[min1] > L[min2])
swap(&L[min1],&L[min2]);
for (int i=2;i<N;i++)
{
if (L[i] < L[min1])
{
min2 = min1;
min1 = i;
}
else if (L[i] < L[min2])
min2 = i;
}
// glue the two smallest board together.
int tmp = L[min1] + L[min2];
ans+=tmp;
if (min1 == N-1)
swap(&L[min1],&L[min2]);
L[min1] = tmp;
L[min2] = L[N-1];
N--;
}
printf("%lld\n",ans);
}
void swap(int *a1,int *a2)
{
int tmp = *a1;
*a1 = *a2;
*a2 = tmp;
} | [
"ssorryqaq@gmail.com"
] | ssorryqaq@gmail.com |
c25ba78e36071affc40395073035ead9f65f4b56 | 3ca67d69abd4e74b7145b340cdda65532f90053b | /BOJ/10816.숫자 카드 2/6047198844.cpp | 12a1fbb66323e54a99f89b012623b0c5b6a8ab52 | [] | no_license | DKU-STUDY/Algorithm | 19549516984b52a1c5cd73e1ed1e58f774d6d30e | 6f78efdbefd8eedab24e43d74c7dae7f95c2893b | refs/heads/master | 2023-02-18T06:48:39.309641 | 2023-02-09T07:16:14 | 2023-02-09T07:16:14 | 258,455,710 | 175 | 49 | null | 2023-02-09T07:16:16 | 2020-04-24T08:42:27 | Python | UTF-8 | C++ | false | false | 583 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int N;
cin >> N;
vector<int> arr(N);
for (int i = 0; i < N; i++)
cin >> arr[i];
sort(arr.begin(), arr.end());
int M;
cin >> M;
while (M--) {
int _;
cin >> _;
int idx = lower_bound(arr.begin(), arr.end(), _) - arr.begin();
int res = 0;
if (idx != arr.size()&&arr[idx]==_) {
int eIdx = upper_bound(arr.begin(), arr.end(), _) - arr.begin();
res = eIdx - idx;
}
cout << res << " ";
}
} | [
"2615240@gmail.com"
] | 2615240@gmail.com |
6d1914adbca804933f48b4e8a4fbff9d368b96bb | b80e2ac63e114eeeb2d6cdb07a63fe237ff2dd26 | /Stardust/Stardust/src/stardust/text/Text.cpp | 068c27c24136819b430b7d2441030aea921e6848 | [
"MIT"
] | permissive | LucidSigma/stardust-old | deccbce0b1a4d147dfc7e9a55447d97f84d5ebe3 | 8edef859025b8dc350b0419cbeafc4bc13c739d5 | refs/heads/master | 2023-02-09T23:32:39.890159 | 2021-01-04T04:29:05 | 2021-01-04T04:29:05 | 298,258,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,741 | cpp | #include "Text.h"
#include <cstdint>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "../rect/Rect.h"
namespace stardust
{
namespace text
{
[[nodiscard]] Texture RenderGlyph(const Renderer& renderer, const Font& font, const char glyph, const Colour& colour)
{
return RenderGlyph(renderer, font, static_cast<char16_t>(glyph), colour);
}
[[nodiscard]] Texture RenderGlyph(const Renderer& renderer, const Font& font, const char16_t glyph, const Colour& colour)
{
SDL_Surface* renderedTextSurface = TTF_RenderGlyph_Blended(font.GetRawHandle(), static_cast<std::uint16_t>(glyph), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderText(const Renderer& renderer, const Font& font, const std::string& text, const Colour& colour)
{
SDL_Surface* renderedTextSurface = TTF_RenderText_Blended(font.GetRawHandle(), text.c_str(), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderText(const Renderer& renderer, const Font& font, const std::u16string& text, const Colour& colour)
{
SDL_Surface* renderedTextSurface = TTF_RenderUNICODE_Blended(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextWrapped(const Renderer& renderer, const Font& font, const std::string& text, const Colour& colour, const unsigned int wrapLength)
{
SDL_Surface* renderedTextSurface = TTF_RenderText_Blended_Wrapped(font.GetRawHandle(), text.c_str(), colour, wrapLength);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextWrapped(const Renderer& renderer, const Font& font, const std::u16string& text, const Colour& colour, const unsigned int wrapLength)
{
SDL_Surface* renderedTextSurface = TTF_RenderUNICODE_Blended_Wrapped(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), colour, wrapLength);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderGlyphQuick(const Renderer& renderer, const Font& font, const char glyph, const Colour& colour)
{
return RenderGlyphQuick(renderer, font, static_cast<char16_t>(glyph), colour);
}
[[nodiscard]] Texture RenderGlyphQuick(const Renderer& renderer, const Font& font, const char16_t glyph, const Colour& colour)
{
SDL_Surface* renderedTextSurface = TTF_RenderGlyph_Solid(font.GetRawHandle(), static_cast<std::uint16_t>(glyph), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextQuick(const Renderer& renderer, const Font& font, const std::string& text, const Colour& colour)
{
SDL_Surface* renderedTextSurface = TTF_RenderText_Solid(font.GetRawHandle(), text.c_str(), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextQuick(const Renderer& renderer, const Font& font, const std::u16string& text, const Colour& colour)
{
SDL_Surface* renderedTextSurface = TTF_RenderUNICODE_Solid(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderShadedGlyph(const Renderer& renderer, const Font& font, const char glyph, const Colour& colour, const Colour& backgroundColour)
{
return RenderShadedGlyph(renderer, font, static_cast<char16_t>(glyph), colour, backgroundColour);
}
[[nodiscard]] Texture RenderShadedGlyph(const Renderer& renderer, const Font& font, const char16_t glyph, const Colour& colour, const Colour& backgroundColour)
{
SDL_Surface* renderedTextSurface = TTF_RenderGlyph_Shaded(font.GetRawHandle(), static_cast<std::uint16_t>(glyph), colour, backgroundColour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderShadedText(const Renderer& renderer, const Font& font, const std::string& text, const Colour& colour, const Colour& backgroundColour)
{
SDL_Surface* renderedTextSurface = TTF_RenderText_Shaded(font.GetRawHandle(), text.c_str(), colour, backgroundColour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderShadedText(const Renderer& renderer, const Font& font, const std::u16string& text, const Colour& colour, const Colour& backgroundColour)
{
SDL_Surface* renderedTextSurface = TTF_RenderUNICODE_Shaded(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), colour, backgroundColour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
renderedTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderGlyphWithOutline(const Renderer& renderer, const Font& font, const char glyph, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
return RenderGlyphWithOutline(renderer, font, static_cast<char16_t>(glyph), colour, outlineSize, outlineColour);
}
[[nodiscard]] Texture RenderGlyphWithOutline(const Renderer& renderer, const Font& font, const char16_t glyph, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderGlyph_Blended(font.GetRawHandle(), static_cast<std::uint16_t>(glyph), outlineColour);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderGlyph_Blended(font.GetRawHandle(), static_cast<std::uint16_t>(glyph), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextWithOutline(const Renderer& renderer, const Font& font, const std::string& text, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderText_Blended(font.GetRawHandle(), text.c_str(), outlineColour);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderText_Blended(font.GetRawHandle(), text.c_str(), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextWithOutline(const Renderer& renderer, const Font& font, const std::u16string& text, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderUNICODE_Blended(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), outlineColour);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderUNICODE_Blended(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextWrappedWithOutline(const Renderer& renderer, const Font& font, const std::string& text, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour, const unsigned int wrapLength)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderText_Blended_Wrapped(font.GetRawHandle(), text.c_str(), outlineColour, wrapLength);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderText_Blended_Wrapped(font.GetRawHandle(), text.c_str(), colour, wrapLength);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextWrappedWithOutline(const Renderer& renderer, const Font& font, const std::u16string& text, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour, const unsigned int wrapLength)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderUNICODE_Blended_Wrapped(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), outlineColour, wrapLength);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderUNICODE_Blended_Wrapped(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), colour, wrapLength);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderGlyphQuickWithOutline(const Renderer& renderer, const Font& font, const char glyph, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
return RenderGlyphQuickWithOutline(renderer, font, static_cast<char16_t>(glyph), colour, outlineSize, outlineColour);
}
[[nodiscard]] Texture RenderGlyphQuickWithOutline(const Renderer& renderer, const Font& font, const char16_t glyph, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderGlyph_Solid(font.GetRawHandle(), static_cast<std::uint16_t>(glyph), outlineColour);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderGlyph_Solid(font.GetRawHandle(), static_cast<std::uint16_t>(glyph), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextQuickWithOutline(const Renderer& renderer, const Font& font, const std::string& text, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderText_Solid(font.GetRawHandle(), text.c_str(), outlineColour);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderText_Solid(font.GetRawHandle(), text.c_str(), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
[[nodiscard]] Texture RenderTextQuickWithOutline(const Renderer& renderer, const Font& font, const std::u16string& text, const Colour& colour, const unsigned int outlineSize, const Colour& outlineColour)
{
font.SetOutlineThickness(outlineSize);
SDL_Surface* renderedTextSurface = TTF_RenderUNICODE_Solid(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), outlineColour);
font.RemoveOutline();
if (renderedTextSurface == nullptr)
{
return Texture();
}
SDL_Surface* innerTextSurface = TTF_RenderUNICODE_Solid(font.GetRawHandle(), reinterpret_cast<const std::uint16_t*>(text.data()), colour);
if (renderedTextSurface == nullptr)
{
return Texture();
}
rect::Rect blitArea = rect::Create(outlineSize, outlineSize, innerTextSurface->w, innerTextSurface->h);
if (SDL_BlitSurface(innerTextSurface, nullptr, renderedTextSurface, &blitArea) != 0)
{
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return Texture();
}
Texture textTexture = Texture(renderer, renderedTextSurface);
SDL_FreeSurface(renderedTextSurface);
SDL_FreeSurface(innerTextSurface);
renderedTextSurface = nullptr;
innerTextSurface = nullptr;
return textTexture;
}
}
} | [
"lucidsigma17@gmail.com"
] | lucidsigma17@gmail.com |
8172cc3ab19498d16e5fb25bc788464326332eac | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE124_Buffer_Underwrite/s03/CWE124_Buffer_Underwrite__new_wchar_t_memcpy_82_bad.cpp | 51dc7e2976c6dcb37ca62977e5d9ba4342361b3b | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,443 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__new_wchar_t_memcpy_82_bad.cpp
Label Definition File: CWE124_Buffer_Underwrite__new.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: memcpy
* BadSink : Copy string to data using memcpy
* Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE124_Buffer_Underwrite__new_wchar_t_memcpy_82.h"
namespace CWE124_Buffer_Underwrite__new_wchar_t_memcpy_82
{
void CWE124_Buffer_Underwrite__new_wchar_t_memcpy_82_bad::action(wchar_t * data)
{
{
wchar_t source[100];
wmemset(source, L'C', 100-1); /* fill with 'C's */
source[100-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
memcpy(data, source, 100*sizeof(wchar_t));
/* Ensure the destination buffer is null terminated */
data[100-1] = L'\0';
printWLine(data);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by new [] so can't safely call delete [] on it */
}
}
}
#endif /* OMITBAD */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
2c44e77376a59741cdb0e341b3e81b3adcb7d222 | 4808781e44b4170582197063916f2dde6825ed59 | /aws-cpp-sdk-glue/source/model/DevEndpoint.cpp | a6f5a7f9d259d3fdbb339f45729aa94147675736 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | Yuanfeng-Wang/aws-sdk-cpp | a4007cb05e0fa243808fbc596f44602d4f607f58 | 74d2a9daa24a19cd3fdd0883ecd2712a1cf027f5 | refs/heads/master | 2021-09-09T14:18:27.633177 | 2018-03-16T21:23:52 | 2018-03-16T21:23:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,068 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/glue/model/DevEndpoint.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Glue
{
namespace Model
{
DevEndpoint::DevEndpoint() :
m_endpointNameHasBeenSet(false),
m_roleArnHasBeenSet(false),
m_securityGroupIdsHasBeenSet(false),
m_subnetIdHasBeenSet(false),
m_yarnEndpointAddressHasBeenSet(false),
m_zeppelinRemoteSparkInterpreterPort(0),
m_zeppelinRemoteSparkInterpreterPortHasBeenSet(false),
m_publicAddressHasBeenSet(false),
m_statusHasBeenSet(false),
m_numberOfNodes(0),
m_numberOfNodesHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_extraPythonLibsS3PathHasBeenSet(false),
m_extraJarsS3PathHasBeenSet(false),
m_failureReasonHasBeenSet(false),
m_lastUpdateStatusHasBeenSet(false),
m_createdTimestampHasBeenSet(false),
m_lastModifiedTimestampHasBeenSet(false),
m_publicKeyHasBeenSet(false)
{
}
DevEndpoint::DevEndpoint(const JsonValue& jsonValue) :
m_endpointNameHasBeenSet(false),
m_roleArnHasBeenSet(false),
m_securityGroupIdsHasBeenSet(false),
m_subnetIdHasBeenSet(false),
m_yarnEndpointAddressHasBeenSet(false),
m_zeppelinRemoteSparkInterpreterPort(0),
m_zeppelinRemoteSparkInterpreterPortHasBeenSet(false),
m_publicAddressHasBeenSet(false),
m_statusHasBeenSet(false),
m_numberOfNodes(0),
m_numberOfNodesHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_extraPythonLibsS3PathHasBeenSet(false),
m_extraJarsS3PathHasBeenSet(false),
m_failureReasonHasBeenSet(false),
m_lastUpdateStatusHasBeenSet(false),
m_createdTimestampHasBeenSet(false),
m_lastModifiedTimestampHasBeenSet(false),
m_publicKeyHasBeenSet(false)
{
*this = jsonValue;
}
DevEndpoint& DevEndpoint::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("EndpointName"))
{
m_endpointName = jsonValue.GetString("EndpointName");
m_endpointNameHasBeenSet = true;
}
if(jsonValue.ValueExists("RoleArn"))
{
m_roleArn = jsonValue.GetString("RoleArn");
m_roleArnHasBeenSet = true;
}
if(jsonValue.ValueExists("SecurityGroupIds"))
{
Array<JsonValue> securityGroupIdsJsonList = jsonValue.GetArray("SecurityGroupIds");
for(unsigned securityGroupIdsIndex = 0; securityGroupIdsIndex < securityGroupIdsJsonList.GetLength(); ++securityGroupIdsIndex)
{
m_securityGroupIds.push_back(securityGroupIdsJsonList[securityGroupIdsIndex].AsString());
}
m_securityGroupIdsHasBeenSet = true;
}
if(jsonValue.ValueExists("SubnetId"))
{
m_subnetId = jsonValue.GetString("SubnetId");
m_subnetIdHasBeenSet = true;
}
if(jsonValue.ValueExists("YarnEndpointAddress"))
{
m_yarnEndpointAddress = jsonValue.GetString("YarnEndpointAddress");
m_yarnEndpointAddressHasBeenSet = true;
}
if(jsonValue.ValueExists("ZeppelinRemoteSparkInterpreterPort"))
{
m_zeppelinRemoteSparkInterpreterPort = jsonValue.GetInteger("ZeppelinRemoteSparkInterpreterPort");
m_zeppelinRemoteSparkInterpreterPortHasBeenSet = true;
}
if(jsonValue.ValueExists("PublicAddress"))
{
m_publicAddress = jsonValue.GetString("PublicAddress");
m_publicAddressHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = jsonValue.GetString("Status");
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("NumberOfNodes"))
{
m_numberOfNodes = jsonValue.GetInteger("NumberOfNodes");
m_numberOfNodesHasBeenSet = true;
}
if(jsonValue.ValueExists("AvailabilityZone"))
{
m_availabilityZone = jsonValue.GetString("AvailabilityZone");
m_availabilityZoneHasBeenSet = true;
}
if(jsonValue.ValueExists("VpcId"))
{
m_vpcId = jsonValue.GetString("VpcId");
m_vpcIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ExtraPythonLibsS3Path"))
{
m_extraPythonLibsS3Path = jsonValue.GetString("ExtraPythonLibsS3Path");
m_extraPythonLibsS3PathHasBeenSet = true;
}
if(jsonValue.ValueExists("ExtraJarsS3Path"))
{
m_extraJarsS3Path = jsonValue.GetString("ExtraJarsS3Path");
m_extraJarsS3PathHasBeenSet = true;
}
if(jsonValue.ValueExists("FailureReason"))
{
m_failureReason = jsonValue.GetString("FailureReason");
m_failureReasonHasBeenSet = true;
}
if(jsonValue.ValueExists("LastUpdateStatus"))
{
m_lastUpdateStatus = jsonValue.GetString("LastUpdateStatus");
m_lastUpdateStatusHasBeenSet = true;
}
if(jsonValue.ValueExists("CreatedTimestamp"))
{
m_createdTimestamp = jsonValue.GetDouble("CreatedTimestamp");
m_createdTimestampHasBeenSet = true;
}
if(jsonValue.ValueExists("LastModifiedTimestamp"))
{
m_lastModifiedTimestamp = jsonValue.GetDouble("LastModifiedTimestamp");
m_lastModifiedTimestampHasBeenSet = true;
}
if(jsonValue.ValueExists("PublicKey"))
{
m_publicKey = jsonValue.GetString("PublicKey");
m_publicKeyHasBeenSet = true;
}
return *this;
}
JsonValue DevEndpoint::Jsonize() const
{
JsonValue payload;
if(m_endpointNameHasBeenSet)
{
payload.WithString("EndpointName", m_endpointName);
}
if(m_roleArnHasBeenSet)
{
payload.WithString("RoleArn", m_roleArn);
}
if(m_securityGroupIdsHasBeenSet)
{
Array<JsonValue> securityGroupIdsJsonList(m_securityGroupIds.size());
for(unsigned securityGroupIdsIndex = 0; securityGroupIdsIndex < securityGroupIdsJsonList.GetLength(); ++securityGroupIdsIndex)
{
securityGroupIdsJsonList[securityGroupIdsIndex].AsString(m_securityGroupIds[securityGroupIdsIndex]);
}
payload.WithArray("SecurityGroupIds", std::move(securityGroupIdsJsonList));
}
if(m_subnetIdHasBeenSet)
{
payload.WithString("SubnetId", m_subnetId);
}
if(m_yarnEndpointAddressHasBeenSet)
{
payload.WithString("YarnEndpointAddress", m_yarnEndpointAddress);
}
if(m_zeppelinRemoteSparkInterpreterPortHasBeenSet)
{
payload.WithInteger("ZeppelinRemoteSparkInterpreterPort", m_zeppelinRemoteSparkInterpreterPort);
}
if(m_publicAddressHasBeenSet)
{
payload.WithString("PublicAddress", m_publicAddress);
}
if(m_statusHasBeenSet)
{
payload.WithString("Status", m_status);
}
if(m_numberOfNodesHasBeenSet)
{
payload.WithInteger("NumberOfNodes", m_numberOfNodes);
}
if(m_availabilityZoneHasBeenSet)
{
payload.WithString("AvailabilityZone", m_availabilityZone);
}
if(m_vpcIdHasBeenSet)
{
payload.WithString("VpcId", m_vpcId);
}
if(m_extraPythonLibsS3PathHasBeenSet)
{
payload.WithString("ExtraPythonLibsS3Path", m_extraPythonLibsS3Path);
}
if(m_extraJarsS3PathHasBeenSet)
{
payload.WithString("ExtraJarsS3Path", m_extraJarsS3Path);
}
if(m_failureReasonHasBeenSet)
{
payload.WithString("FailureReason", m_failureReason);
}
if(m_lastUpdateStatusHasBeenSet)
{
payload.WithString("LastUpdateStatus", m_lastUpdateStatus);
}
if(m_createdTimestampHasBeenSet)
{
payload.WithDouble("CreatedTimestamp", m_createdTimestamp.SecondsWithMSPrecision());
}
if(m_lastModifiedTimestampHasBeenSet)
{
payload.WithDouble("LastModifiedTimestamp", m_lastModifiedTimestamp.SecondsWithMSPrecision());
}
if(m_publicKeyHasBeenSet)
{
payload.WithString("PublicKey", m_publicKey);
}
return payload;
}
} // namespace Model
} // namespace Glue
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
ac5a9cb059d79671f1573a05e9ad2980195f1404 | 4ad2674fabe0eb0e90b5f2137771d48ffaad0478 | /Elona_KR_exe/Elona_KR/Elona_KR.cpp | 160b35863b1c01b2c829af0f1d5d05c7b06b3746 | [] | no_license | dkpark89/ElonaKR | f2af010cf2d4a08af5c85d1d12d65c16bc6f0120 | 6cb462c0cf634a717965ae8712816f8383e31206 | refs/heads/master | 2021-01-23T20:17:54.453164 | 2014-11-24T16:41:42 | 2014-11-24T16:41:42 | 26,052,696 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 2,378 | cpp | // Elona_KR.cpp : 응용 프로그램에 대한 클래스 동작을 정의합니다.
//
#include "stdafx.h"
#include "Elona_KR.h"
#include "Elona_KRDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CElona_KRApp
BEGIN_MESSAGE_MAP(CElona_KRApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CElona_KRApp 생성
CElona_KRApp::CElona_KRApp()
{
// TODO: 여기에 생성 코드를 추가합니다.
// InitInstance에 모든 중요한 초기화 작업을 배치합니다.
}
// 유일한 CElona_KRApp 개체입니다.
CElona_KRApp theApp;
// CElona_KRApp 초기화
BOOL CElona_KRApp::InitInstance()
{
//TODO: call AfxInitRichEdit2() to initialize richedit2 library.
// 응용 프로그램 매니페스트가 ComCtl32.dll 버전 6 이상을 사용하여 비주얼 스타일을
// 사용하도록 지정하는 경우, Windows XP 상에서 반드시 InitCommonControlsEx()가 필요합니다.
// InitCommonControlsEx()를 사용하지 않으면 창을 만들 수 없습니다.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 응용 프로그램에서 사용할 모든 공용 컨트롤 클래스를 포함하도록
// 이 항목을 설정하십시오.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// 표준 초기화
// 이들 기능을 사용하지 않고 최종 실행 파일의 크기를 줄이려면
// 아래에서 필요 없는 특정 초기화
// 루틴을 제거해야 합니다.
// 해당 설정이 저장된 레지스트리 키를 변경하십시오.
// TODO: 이 문자열을 회사 또는 조직의 이름과 같은
// 적절한 내용으로 수정해야 합니다.
SetRegistryKey(_T("로컬 응용 프로그램 마법사에서 생성된 응용 프로그램"));
CElona_KRDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 여기에 [확인]을 클릭하여 대화 상자가 없어질 때 처리할
// 코드를 배치합니다.
}
else if (nResponse == IDCANCEL)
{
// TODO: 여기에 [취소]를 클릭하여 대화 상자가 없어질 때 처리할
// 코드를 배치합니다.
}
// 대화 상자가 닫혔으므로 응용 프로그램의 메시지 펌프를 시작하지 않고 응용 프로그램을 끝낼 수 있도록 FALSE를
// 반환합니다.
return FALSE;
}
| [
"dkpark89@gmail.com"
] | dkpark89@gmail.com |
8b93f807988756ff11de7eb1fc2c3132e5b1167d | 901ca35ac6d1a9f22e71092805b5381b6537a75f | /docker-of.cc | 49918e49f12f4893510946788b2af51e9452e924 | [] | no_license | zhouyou-gu/scratch | b8487aaac8a3540f92c4645e6073c8209322e346 | b041f49ccdd674af391ce0125454f56c09833b3a | refs/heads/master | 2021-09-07T22:26:33.691613 | 2018-03-02T05:56:57 | 2018-03-02T05:56:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,988 | cc | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2017 University of Campinas (Unicamp)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Luciano Chaves <luciano@lrc.ic.unicamp.br>
*
* Two hosts connected to different OpenFlow switches.
* Both switches are managed by the same external controller application.
*
* External Controller
* |
* +-------------+
* | |
* +----------+ +----------+
* Host 0 === | Switch 0 | === | Switch 1 | === Host 1
* +----------+ +----------+
*/
#include <ns3/core-module.h>
#include <ns3/network-module.h>
#include <ns3/csma-module.h>
#include <ns3/internet-module.h>
#include <ns3/ofswitch13-module.h>
#include <ns3/internet-apps-module.h>
#include <ns3/tap-bridge-module.h>
using namespace ns3;
int
main (int argc, char *argv[])
{
uint16_t simTime = 10000;
bool verbose = false;
bool trace = true;
// Configure command line parameters
CommandLine cmd;
cmd.AddValue ("simTime", "Simulation time (seconds)", simTime);
cmd.AddValue ("verbose", "Enable verbose output", verbose);
cmd.AddValue ("trace", "Enable datapath stats and pcap traces", trace);
cmd.Parse (argc, argv);
if (verbose)
{
OFSwitch13Helper::EnableDatapathLogs ();
LogComponentEnable ("OFSwitch13Interface", LOG_LEVEL_ALL);
LogComponentEnable ("OFSwitch13Device", LOG_LEVEL_ALL);
LogComponentEnable ("OFSwitch13Port", LOG_LEVEL_ALL);
LogComponentEnable ("OFSwitch13Queue", LOG_LEVEL_ALL);
LogComponentEnable ("OFSwitch13Controller", LOG_LEVEL_ALL);
LogComponentEnable ("OFSwitch13LearningController", LOG_LEVEL_ALL);
LogComponentEnable ("OFSwitch13Helper", LOG_LEVEL_ALL);
LogComponentEnable ("OFSwitch13ExternalHelper", LOG_LEVEL_ALL);
}
// Enable checksum computations (required by OFSwitch13 module)
GlobalValue::Bind ("ChecksumEnabled", BooleanValue (true));
// Set simulator to real time mode
GlobalValue::Bind ("SimulatorImplementationType", StringValue ("ns3::RealtimeSimulatorImpl"));
// Create two host nodes
NodeContainer hosts;
hosts.Create (2);
// Create two switch nodes
NodeContainer switches;
switches.Create (2);
// Use the CsmaHelper to connect hosts and switches
CsmaHelper csmaHelper;
csmaHelper.SetChannelAttribute ("DataRate", DataRateValue (DataRate ("100Mbps")));
csmaHelper.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NodeContainer pair;
NetDeviceContainer pairDevs;
NetDeviceContainer hostDevices;
NetDeviceContainer switchPorts [2];
switchPorts [0] = NetDeviceContainer ();
switchPorts [1] = NetDeviceContainer ();
// Connect host 0 to first switch
pair = NodeContainer (hosts.Get (0), switches.Get (0));
pairDevs = csmaHelper.Install (pair);
hostDevices.Add (pairDevs.Get (0));
switchPorts [0].Add (pairDevs.Get (1));
// Connect host 1 to second switch
pair = NodeContainer (hosts.Get (1), switches.Get (1));
pairDevs = csmaHelper.Install (pair);
hostDevices.Add (pairDevs.Get (0));
switchPorts [1].Add (pairDevs.Get (1));
// Connect the switches
pair = NodeContainer (switches.Get (0), switches.Get (1));
pairDevs = csmaHelper.Install (pair);
switchPorts [0].Add (pairDevs.Get (0));
switchPorts [1].Add (pairDevs.Get (1));
// Create the controller node
Ptr<Node> controllerNode = CreateObject<Node> ();
// Configure the OpenFlow network domain using an external controller
Ptr<OFSwitch13ExternalHelper> of13Helper = CreateObject<OFSwitch13ExternalHelper> ();
Ptr<NetDevice> ctrlDev = of13Helper->InstallExternalController (controllerNode);
of13Helper->InstallSwitch (switches.Get (0), switchPorts [0]);
of13Helper->InstallSwitch (switches.Get (1), switchPorts [1]);
of13Helper->CreateOpenFlowChannels ();
// TapBridge the controller device to local machine
// The default configuration expects a controller on local port 6653
TapBridgeHelper tapBridge;
tapBridge.SetAttribute ("Mode", StringValue ("ConfigureLocal"));
tapBridge.SetAttribute ("DeviceName", StringValue ("ctrl"));
tapBridge.Install (controllerNode, ctrlDev);
// Install the TCP/IP stack into hosts nodes
InternetStackHelper internet;
internet.Install (hosts);
// Set IPv4 host addresses
Ipv4AddressHelper ipv4helpr;
Ipv4InterfaceContainer hostIpIfaces;
ipv4helpr.SetBase ("10.1.1.0", "255.255.255.0");
hostIpIfaces = ipv4helpr.Assign (hostDevices);
// Configure ping application between hosts
V4PingHelper pingHelper = V4PingHelper (hostIpIfaces.GetAddress (1));
pingHelper.SetAttribute ("Verbose", BooleanValue (true));
ApplicationContainer pingApps = pingHelper.Install (hosts.Get (0));
pingApps.Start (Seconds (100));
// Enable datapath stats and pcap traces at hosts, switch(es), and controller(s)
if (trace)
{
of13Helper->EnableOpenFlowPcap ("openflow");
of13Helper->EnableDatapathStats ("switch-stats");
csmaHelper.EnablePcap ("switch", switchPorts [0], true);
csmaHelper.EnablePcap ("switch", switchPorts [1], true);
csmaHelper.EnablePcap ("host", hostDevices);
}
// Run the simulation
Simulator::Stop (Seconds (simTime));
Simulator::Run ();
Simulator::Destroy ();
}
| [
"guzhouyou@gmail.com"
] | guzhouyou@gmail.com |
0bd3bfdc22d46c85227696c0132a4d5a70e866bb | 8899518abbd7c8d56a6ee9be6834ff60fccf378f | /Sorting Algorithms/Quick Sort/quick_sort.h | 082dfc353894a7bdf88327307597ad6902ae94fd | [
"MIT"
] | permissive | Mohammed-Shoaib/WhatsAlgo | 7cc23191ea3ef715b9cd057bd99284934d004be2 | d6131aaed7fdb2679da93f3eeebcb34073c7eb15 | refs/heads/master | 2023-04-17T22:21:09.708746 | 2021-05-02T22:28:34 | 2021-05-02T22:28:34 | 175,226,682 | 17 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 109 | h | #pragma once
#include <vector>
#include <algorithm>
void quick_sort(int low, int high, std::vector<int>& a); | [
"shoaib98libra@gmail.com"
] | shoaib98libra@gmail.com |
cbd142b5a5ceec8beba586bad0c1956024b19e2f | 7388ccfcf5e586cc62a2e837f92a0c744002b153 | /BERT/dllmain.cpp | 4dc4004640347192b038b8b91c7c5c622c9da056 | [] | no_license | hungryducks/Basic-Excel-R-Toolkit | a9607a1c0837ae8432516b75b1676e3135e732fd | 96d73d491ae6a52227c59c0373f29089e52b93b8 | refs/heads/master | 2021-01-18T12:46:02.013494 | 2016-05-19T16:10:40 | 2016-05-19T16:10:40 | 60,756,529 | 1 | 0 | null | 2016-06-09T07:17:09 | 2016-06-09T07:17:09 | null | UTF-8 | C++ | false | false | 1,141 | cpp | /*
* Basic Excel R Toolkit (BERT)
* Copyright (C) 2014-2016 Structured Data, LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "stdafx.h"
extern BOOL TLS_Action(DWORD DllMainCallReason);
HMODULE ghModule;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
ghModule = hModule;
return TLS_Action(ul_reason_for_call);
}
| [
"dwerner@riskamp.com"
] | dwerner@riskamp.com |
462ae2a417df563477a3745fd2ee346f96b3c5ed | a7d1b1158f5b8ffdfc7e2b6f1a24dfd234bcded6 | /C_expedtion/polymorphism/exception/IndexException.cpp | 127644a480116159f16b93efbf2306f30c772065 | [] | no_license | Ferrymania/Cplusplus_learning | 56f44c4dc47b66deea3319275a122fbda4e66930 | 99cd1451075b57aa125931e40e9f2d2aaa6d98eb | refs/heads/master | 2020-03-22T02:35:10.849423 | 2018-07-05T12:39:00 | 2018-07-05T12:39:00 | 139,380,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | #include "IndexException.h"
#include <iostream>
using namespace std;
void IndexException::printException()
{
cout<<"提示:下标越界"<<endl;
}
| [
"904655716@qq.com"
] | 904655716@qq.com |
64a394c8228b04439b97838c913c8d67ae1379fc | f56ca3f25490b74c81ba5403ffb99386dd12b97d | /libsdraudio/main.cpp | e86e9617b4995716aaf948b4597a4e274e25553e | [] | no_license | pc1cp/pappsdr | 136c4830096ccfc85a6dacce7d797600ddc667cf | 98f2c4bf16030825211901dc48b34dcc586fedee | refs/heads/master | 2021-01-10T05:26:56.473699 | 2012-06-14T20:04:35 | 2012-06-14T20:04:35 | 51,033,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | cpp | #include <iostream>
#include <fstream>
#include "complexsample.hpp"
#include "firfilter.hpp"
#include "agc.hpp"
int main( int argc, char** argv )
{
ComplexSample iSample;
ComplexSample oSample;
FirFilter* filter = new FirFilter( 12000, 2500, 129 );
AutomaticGainControl* agc = new AutomaticGainControl( 12000 );
std::fstream file("out.raw", std::ios::binary|std::ios::out );
float gain=1;
for( int n=0; n < 44100; ++n )
{
if( (n%2400)==0 )
{
gain = (float)rand()/(float)RAND_MAX;
}
iSample = ComplexSample( ((float)rand()/(float)RAND_MAX-0.5f)*2.0f,
((float)rand()/(float)RAND_MAX-0.5f)*2.0f );
iSample *= gain;
oSample = filter->update( iSample );
oSample = agc->update( oSample );
file.write( (char*)&oSample, sizeof( oSample ) );
}
return( 0 );
} | [
"smfendt@gmail.com"
] | smfendt@gmail.com |
74b74459f7873616cf1d6f43534ad726cf5ac921 | f9d5eab33c0ddf32ff2a497177874872dabf2950 | /ExternNetVarDumper/stdafx.h | b12cc3f8a1a3ebd401d36166465e99f69e237a33 | [] | no_license | testcc2c/source-basehack | d3f28c4ad90b6c06f8549067b88cc78e8afe1299 | d61a8b6d5ca8809fa679c35c55fb288f2f00e32c | refs/heads/master | 2021-06-01T07:06:36.930704 | 2016-08-13T04:33:33 | 2016-08-13T04:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | h | #ifndef stdafx_h__
#define stdafx_h__
//--Windows API
#include <windows.h>
#include <TlHelp32.h>
//--C++ Standard Library
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cstdlib>
//--Valve
#include "client_class.h"
#include "dt_common.h"
#include "dt_recv.h"
//--Util functions
#include "Util.h"
//--NetVar Dumper
#include "NetVars.h"
typedef ClientClass* (__thiscall* GetAllClasses_t)(PVOID pThis);
typedef void* (*CI)(const char *pName, int *pReturnCode);
#define procflags ( PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ )
#endif // stdafx_h__ | [
"michaelt.marzullo@gmail.com"
] | michaelt.marzullo@gmail.com |
134e2397f89e47b9ddf6ba4c93f630f5247e2ed2 | 613953a34ffd9614db2f91f18e5183513f57a8ac | /teensy/RoverBase.ino/RoverBase.ino.ino | 85818b898a39042e2acafd85c176e3b4c46edbbc | [] | no_license | philiprodriguez/Project-Rover | d651362a75a2f48c605cc276c305272cfbf2db28 | ccd9601ead709470a274c6333a83c6c5da48a38b | refs/heads/master | 2021-06-22T20:51:05.768385 | 2020-12-14T04:04:26 | 2020-12-14T04:04:26 | 161,207,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,870 | ino | /*
Philip Rodriguez
December 7, 2018
This is a simple software for the Teensy that is the basic controller for the robot. This software's job is to
take commands in over the Bluetooth Serial module on the Serial3 interface, and then "apply" those commands to
the physical hardware of the robot, whether it be the motors, lights, servos, etc... This should be a wait-free
and very simple code. Process incoming commands sequentially, without any delaying if at all possible.
Update May 29, 2019
Add ability to read battery level and send it back periodically to the Android device.
Update July 8, 2019
Add ability to control new robotic arm of 3 servos.
*/
#include <Servo.h>
int pinLED = 13;
int pinVoltageRead = A0;
int pinServoTilt = 16;
int pinLeftForward = 23;
int pinLeftBackward = 22;
int pinRightForward = 21;
int pinRightBackward = 20;
int pinServoArmBase = A3;
int pinServoArmOne = A4;
int pinServoArmTwo = A5;
Servo servoTilt;
Servo servoArmBase;
float servoArmBaseLastRadians = 0.0;
Servo servoArmOne;
float servoArmOneLastRadians = 0.0;
Servo servoArmTwo;
float servoArmTwoLastRadians = 0.0;
// Squish the range [0, maxRadians] radians into [544, 2400]
int convertRadianstoMicroseconds(float angle, float maxRadians) {
float percentage = angle/maxRadians;
int us = (int)(544.0+(1856.0*percentage));
// Clip to prevent overdriving the servo
us = max(544, us);
us = min(2400, us);
return us;
}
// Account for the zero shift amount so we can support some negative angles
// Limit range from -20 deg to 220 deg
void setServoArmBase(float thetaRadians) {
thetaRadians = min(thetaRadians, 3.8397);
thetaRadians = max(thetaRadians, -0.3491);
servoArmBaseLastRadians = thetaRadians;
servoArmBase.writeMicroseconds(convertRadianstoMicroseconds(thetaRadians+(0.5306), 4.3074));
}
void setServoArmOne(float thetaRadians) {
thetaRadians = min(thetaRadians, 2.2689); // 130 deg
thetaRadians = max(thetaRadians, -0.1309); // -7.5 deg
servoArmOneLastRadians = thetaRadians;
servoArmOne.writeMicroseconds(convertRadianstoMicroseconds(2.49582-(thetaRadians+0.1309), 4.3459));
}
void setServoArmTwo(float thetaRadians) {
thetaRadians = min(thetaRadians, 5.218); // 299 deg
thetaRadians = max(thetaRadians, 0.7854); // 45 deg
servoArmTwoLastRadians = thetaRadians;
servoArmTwo.writeMicroseconds(convertRadianstoMicroseconds(thetaRadians-0.7854, 4.4331));
}
void setup() {
pinMode(pinLED, OUTPUT);
// initialize the digital pin as an output.
pinMode(pinLeftForward, OUTPUT); // Left forward
pinMode(pinLeftBackward, OUTPUT); // Left backward
pinMode(pinRightForward, OUTPUT); // Right forward
pinMode(pinRightBackward, OUTPUT); // Right backward
// Read battery voltage on A0
pinMode(pinVoltageRead, INPUT);
// Set ALL motor pins (which are sharing the same timer) from their default of a loud 488Mhz to the silent 60Khz
analogWriteFrequency(pinLeftForward, 22000);
// Servo initialization
servoTilt.attach(pinServoTilt);
servoArmBase.attach(pinServoArmBase);
setServoArmBase(1.57079632);
servoArmOne.attach(pinServoArmOne);
setServoArmOne(2.2689);
servoArmTwo.attach(pinServoArmTwo);
setServoArmTwo(0.7853);
Serial.begin(9600);
Serial3.begin(9600);
Serial3.setTimeout(10000);
// Blink a few times to show life lol
for (int i = 0; i < 3; i++) {
digitalWrite(pinLED, HIGH);
delay(500);
digitalWrite(pinLED, LOW);
delay(500);
}
Serial.println(sizeof(float));
}
#define START_SEQUENCE_LENGTH 8
const int START_SEQUENCE[START_SEQUENCE_LENGTH] = {'a', '8', 'f', 'e', 'J', '2', '9', 'p'};
int nextSerial3Byte() {
int readVal = -1;
while ((readVal = Serial3.read()) == -1) {
// Do nothing!
}
return readVal;
}
float parseFloatFromBytes(byte * bytes) {
unsigned int temp = 0;
temp = temp | bytes[0];
temp = temp << 8;
temp = temp | bytes[1];
temp = temp << 8;
temp = temp | bytes[2];
temp = temp << 8;
temp = temp | bytes[3];
float result = *(float*)&temp;
return result;
}
void printIntBits(int b) {
for (int i = 0; i < 32; i++) {
if ((b&(1<<(31-i))) > 0) {
Serial.print("1");
} else {
Serial.print("0");
}
}
}
void loop() {
// Look for start sequence
Serial.println("Waiting for start sequence...");
for (int i = 0; i < START_SEQUENCE_LENGTH; i++) {
if (nextSerial3Byte() != START_SEQUENCE[i]) {
// Failure to read start sequence! Retry!
return;
}
}
Serial.println("Got start sequence!");
int opcode = nextSerial3Byte();
Serial.println("Opcode:");
Serial.println(opcode);
if (opcode == 'm') {
// Motor set
Serial.println("Opcode was for motor set...");
int leftForward = nextSerial3Byte();
int leftBackward = nextSerial3Byte();
int rightForward = nextSerial3Byte();
int rightBackward = nextSerial3Byte();
analogWrite(pinLeftForward, leftForward);
analogWrite(pinLeftBackward, leftBackward);
analogWrite(pinRightForward, rightForward);
analogWrite(pinRightBackward, rightBackward);
Serial.println("Motors set:");
Serial.println(leftForward);
Serial.println(leftBackward);
Serial.println(rightForward);
Serial.println(rightBackward);
} else if (opcode == 'l') {
// LED set
Serial.println("Opcode was for led set...");
int val = nextSerial3Byte();
if (val == 'h') {
digitalWrite(pinLED, HIGH);
} else if (val == 'l') {
digitalWrite(pinLED, LOW);
}
} else if (opcode == 's') {
// Servo set
Serial.println("Opcode was for servo set...");
int val = nextSerial3Byte();
if (val >= 5 && val <= 175) {
int curValue = servoTilt.read();
int delayAmt = 105;
while(curValue != val) {
if (val > curValue) {
curValue++;
}
else {
curValue--;
}
servoTilt.write(curValue);
delay(delayAmt);
if (delayAmt > 5) {
delayAmt-=5;
}
}
// Small back off to prevent stress
delay(200);
if (curValue > 90) {
servoTilt.write(curValue-4);
} else {
servoTilt.write(curValue+4);
}
}
} else if (opcode == 'v') {
// Voltage read
//Serial.println("Opcode was for voltage read...");
int voltageValue = analogRead(pinVoltageRead);
//Serial.println("Voltage value int is:");
//Serial.println(voltageValue);
byte buf[START_SEQUENCE_LENGTH+1+4];
int i;
for (i = 0; i < START_SEQUENCE_LENGTH; i++) {
buf[i] = START_SEQUENCE[i];
}
buf[i++] = 'v';
buf[i++] = (voltageValue >> 24) & 255;
buf[i++] = (voltageValue >> 16) & 255;
buf[i++] = (voltageValue >> 8) & 255;
buf[i++] = voltageValue & 255;
//Serial.print("Sending int bytes: ");
for (int j = 0; j < START_SEQUENCE_LENGTH+1+4; j++) {
//Serial.print(buf[j]);
//Serial.print(" ");
}
//Serial.println();
Serial3.write(buf, sizeof(buf));
} else if (opcode == 'a') {
// Arm set
Serial.println("Opcode was for arm set...");
byte bufBase[4];
for (int i = 0; i < 4; i++) {
bufBase[i] = nextSerial3Byte();
}
byte bufOne[4];
for (int i = 0; i < 4; i++) {
bufOne[i] = nextSerial3Byte();
}
byte bufTwo[4];
for (int i = 0; i < 4; i++) {
bufTwo[i] = nextSerial3Byte();
}
float baseRad = parseFloatFromBytes(bufBase);
float oneRad = parseFloatFromBytes(bufOne);
float twoRad = parseFloatFromBytes(bufTwo);
Serial.print("Base Radians: ");
Serial.print(baseRad);
Serial.print(", One Radians: ");
Serial.print(oneRad);
Serial.print(", Two Radians: ");
Serial.print(twoRad);
Serial.println();
setServoArmBase(baseRad);
setServoArmOne(oneRad);
setServoArmTwo(twoRad);
} else {
Serial.println("Illegal opcode!");
return;
}
}
| [
"philiprodriguez@knights.ucf.edu"
] | philiprodriguez@knights.ucf.edu |
d26c2b0e7512c602fe47416221cff9e2a6dcd1af | bce1d5beb9e6f254163d9a5daec62af09ca85d95 | /ALLIZWEL.cpp | 5cf07edaa33b0831d9f2414a5968380e682823c9 | [] | no_license | abhi-portrait/SPOJ | 7b4f9540453e480046912853407d214b8da8eabc | bd59367d4937080d6ae65ba686b9c93267b3deb1 | refs/heads/master | 2021-01-10T14:44:48.885933 | 2016-03-29T04:35:19 | 2016-03-29T04:35:19 | 54,945,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,000 | cpp | #include<bits/stdc++.h>
using namespace std;
char a[101][101];
int visited[101][101],flag=0,r,c;
int d_x[8]={0,-1,-1,-1,0,1,1,1};
int d_y[8]={-1,-1,0,1,1,1,0,-1};
char b[10]={'A','L','L','I','Z','Z','W','E','L','L'};
void dfs(int i,int j,int k)
{
if(k==9)
{
flag=1;
return;
}
int p;
for(p=0;p<8;p++)
{
if(i+d_x[p]>=0 && i+d_x[p]<r && j+d_y[p]>=0 && j+d_y[p]<c && a[i+d_x[p]][j+d_y[p]]==b[k+1] && visited[i+d_x[p]][j+d_y[p]]==0)
{
visited[i+d_x[p]][j+d_y[p]]=1;
dfs(i+d_x[p],j+d_y[p],k+1);
visited[i+d_x[p]][j+d_y[p]]=0;
}
}
visited[i][j]=0;
}
int main()
{
int t,i,j;
cin>>t;
while(t--)
{
flag=0;
cin>>r>>c;
for(i=0;i<r;i++)
cin>>a[i];
memset(visited,0,sizeof(visited));
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(a[i][j]=='A' && flag==0)
{visited[i][j]=1;dfs(i,j,0);}
else if(a[i][j]=='A' && flag==1)
break;
}
if(a[i][j]=='A' && flag==1)
break;
}
if(flag==1)
cout<<"YES"<<"\n\n";
else
cout<<"NO"<<"\n\n";
}
}
| [
"Abhishek Mishra"
] | Abhishek Mishra |
f1ebda988b6449d187178a42d35315bed0d4f299 | 09ddd2df75bce4df9e413d3c8fdfddb7c69032b4 | /src/X3D/RigidBody.cpp | 74b1035d95485efb121316998da2041e69ac1df8 | [] | no_license | sigurdle/FirstProject2 | be22e4824da8cd2cb5047762478050a04a4ac63b | dee78c62a1b95e55fcdf3bf2a9bc79c69705bf94 | refs/heads/master | 2021-01-16T18:45:41.042140 | 2020-08-18T16:57:13 | 2020-08-18T16:57:13 | 3,554,336 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 4,734 | cpp | #include "stdafx.h"
#include "X3D2.h"
#include "RigidBody.h"
#include "Shape.h"
#include "CollidableShape.h"
#include "GUI/physics.h"
#include "pxutils.h"
namespace System
{
namespace x3d
{
IMP_X3DFIELD0(RigidBody, SFBool, enabled, Enabled)
IMP_X3DFIELD0(RigidBody, SFVec3f, linearVelocity, LinearVelocity)
NodeType* RigidBody::GetNodeType()
{
static X3DFieldDefinition angularDampingFactor("angularDampingFactor", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_angularDampingFactor));
static X3DFieldDefinition geometry("geometry", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_geometry));
static X3DFieldDefinition mass("mass", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_mass));
static X3DFieldDefinition position("position", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_position));
static X3DFieldDefinition orientation("orientation", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_orientation));
static X3DFieldDefinition angularVelocity("angularVelocity", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_angularVelocity));
// static X3DFieldDefinition linearVelocity("linearVelocity", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_linearVelocity));
static X3DFieldDefinition fixed("fixed", SAIFieldAccess_inputOutput, offsetof(RigidBody, m_fixed));
static X3DFieldDefinition* fields[] =
{
&angularDampingFactor,
&geometry,
&mass,
&position,
&orientation,
&angularVelocity,
//&linearVelocity,
get_enabledFieldDef(),
get_linearVelocityFieldDef(),
&fixed,
};
static NodeType nodeType("RigidBody", typeid(thisClass), fields, _countof(fields), baseClass::GetNodeType());
return &nodeType;
}
NodeType* RigidBody::nodeType(GetNodeType());
RigidBody::RigidBody() : X3DNode(GetNodeType()),
m_mass(new SFFloat(this, 1.0f))
{
}
void RigidBody::OnFieldChanged(X3DField* field)
{
#if defined(PX_PHYSICS_NXPHYSICS_API)
if (field == m_position || field == m_orientation)
{
// TODO, cache
m_globalPoseValid = false;
if (m_actor)
{
physx::PxTransform pose(
_NxVec3(m_position->getValue()),
_NxQuat(m_orientation->getValue()));
m_actor->setGlobalPose(pose);
m_globalPoseValid = true;
}
}
else if (field == m_fixed)
{
if (m_actor)
{
// TODO
ASSERT(0);
}
}
#endif
X3DNode::OnFieldChanged(field);
}
void RigidBody::UpdatePosOrient()
{
#if defined(PX_PHYSICS_NXPHYSICS_API)
physx::PxTransform pose = m_actor->getGlobalPose();
// physx::PxVec3 pos = m_actor->getGlobalPosition();
// m_actor->getGlobalOrientationQuat().getAngleAxis(angle, axis);
float angleRadians;
physx::PxVec3 axis;
pose.q.toRadiansAndUnitAxis(angleRadians, axis);
setPosition(_Vec3f(pose.p));
setOrientation(Rotation(_Vec3f(axis), angleRadians));
// TODO, should not be necessary, the above is enough
MFNode* geometry = getGeometryField();
for (size_t i = 0; i < geometry->m_items.size(); ++i)
{
X3DNode* node = geometry->get1Value(i);
X3DNBodyCollidableNode* cnode = dynamic_cast<X3DNBodyCollidableNode*>(node);
cnode->setTranslation(getPosition());
cnode->setRotation(getOrientation());
}
// TODO, not here
m_scene->Invalidate();
#endif
}
void RigidBody::CreateActor(physx::PxScene* nxScene)
{
#if defined(PX_PHYSICS_NXPHYSICS_API)
physx::PxTransform pose(_NxVec3(getPosition()), _NxQuat(getOrientation()));
physx::PxRigidDynamic* actor = Gui::gPhysics->createRigidDynamic(pose);
ASSERT(m_actor);
MFNode* geometry = getGeometryField();
for (size_t i = 0; i < geometry->m_items.size(); ++i)
{
X3DNode* node = geometry->get1Value(i);
// X3DNBodyCollidableNode* cnode = dynamic_cast<X3DNBodyCollidableNode*>(node);
CollidableShape* cnode = dynamic_cast<CollidableShape*>(node);
Shape* shape = cnode->getShape();
shape->AddShapeDesc(actor);
}
float density = 10.0f;
physx::PxRigidBodyExt::updateMassAndInertia(*actor, density);
// There are two ways to implement fixed bodies in PhysX SDK, either as static or kinematic actors, I've chosen
// kinematic actors since they can be turned into dynamic actors
// if (!getFixed()) // Static actor
{
// actorDesc.body = &bodyDesc;
// bodyDesc.angularVelocity = ;
// bodyDesc.linearVelocity = ;
// bodyDesc.mass = getMass();
actor->setAngularVelocity(_NxVec3(getAngularVelocity()));
actor->setLinearVelocity(_NxVec3(getLinearVelocity()));
}
if (getFixed()) // Kinetic actor
{
actor->setRigidDynamicFlag(physx::PxRigidDynamicFlag::eKINEMATIC, true);
//bodyDesc.flags |= NX_BF_KINEMATIC;//NxActor::raiseBodyFlag(NX_BF_KINEMATIC)
// TODO
//actor->setKinematicTarget(position);
}
// actorDesc.density = 10.0f;
// actorDesc.globalPose.t = _NxVec3(getPosition());
// m_actor = nxScene->createActor(actorDesc);
#endif
}
} // x3d
} // System
| [
"sigurd.lerstad@gmail.com"
] | sigurd.lerstad@gmail.com |
96748d025167f711ca43b79d09acf93c296926e2 | fd57ede0ba18642a730cc862c9e9059ec463320b | /av/media/libstagefright/foundation/include/media/stagefright/foundation/hexdump.h | ef15b006840d4b1689d07d5a67e4b52f5be74715 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | kailaisi/android-29-framwork | a0c706fc104d62ea5951ca113f868021c6029cd2 | b7090eebdd77595e43b61294725b41310496ff04 | refs/heads/master | 2023-04-27T14:18:52.579620 | 2021-03-08T13:05:27 | 2021-03-08T13:05:27 | 254,380,637 | 1 | 1 | null | 2023-04-15T12:22:31 | 2020-04-09T13:35:49 | C++ | UTF-8 | C++ | false | false | 912 | h | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HEXDUMP_H_
#define HEXDUMP_H_
#include <sys/types.h>
namespace android {
struct AString;
void hexdump(
const void *_data, size_t size,
size_t indent = 0, AString *appendTo = NULL);
} // namespace android
#endif // HEXDUMP_H_
| [
"541018378@qq.com"
] | 541018378@qq.com |
5edd3fcf112322f654ce9d4e6b0ddf04d8231851 | 835a80ac73114c328ac229ed953c989d3351861d | /PE/src/p163.cpp | f2929d0a0692696d2d95a6dc8b02e9d615a84134 | [
"Zlib"
] | permissive | desaic/webgl | db18661f446bd35cc3236c98b30f914941f9379f | 2e0e78cb14967b7885bfa00824e4d5f409d7cc07 | refs/heads/master | 2023-08-14T15:31:57.451868 | 2023-08-10T17:49:48 | 2023-08-10T17:49:48 | 10,447,154 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,339 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
const int MAX_EDGE = 1000;
const int NUM_EDGE_TYPE = 6;
int edgeToInt(int edgeType, int edgeIdx) {
return edgeIdx * NUM_EDGE_TYPE + edgeType;
}
void intToEdge(int i, int & edgeType, int & edgeIdx) {
edgeType = i % NUM_EDGE_TYPE;
edgeIdx = i / NUM_EDGE_TYPE;
}
size_t trigToId(int e1, int e2, int e3) {
int trig[] = { e1, e2, e3 };
std::sort(trig, trig + 3);
size_t id = (trig[0] * MAX_EDGE + trig[1])*MAX_EDGE + trig[2];
return id;
}
void addAllPairs(const std::vector<int> & edges, std::map<int , set<int> > & adj,
std::set<size_t> & trips
) {
for (size_t i = 0; i < edges.size(); i++) {
for (size_t j = 0; j < edges.size(); j++) {
if (i == j) {
continue;
}
auto it = adj.find(edges[i]);
if (it == adj.end()) {
adj[edges[i]] = std::set<int>();
adj[edges[i]].insert(edges[j]);
}
else {
it->second.insert(edges[j]);
}
}
}
if (edges.size() < 3) {
return;
}
for (int i = 0; i < int(edges.size()) - 2; i++) {
for (int j = i+1; j<int(edges.size()) - 1; j++) {
for (int k = j + 1; k<int(edges.size()); k++) {
size_t id = trigToId(edges[i], edges[j], edges[k]);
trips.insert(id);
}
}
}
}
void p163() {
cout << 163<< "\n";
//iterate over hex centers
int N = 36;
//intersection map of edges
//edge id
// 0 / \ 1
// / \
// / 3 4\
// / \
// /____|5____\
// 2
//edge ordering: first up to lower, then left to right
map<int, set<int>> adj;
set<size_t> trips;
//last row has no new triangles.
for (int row = 0; row <= N; row++) {
for (int col = 0; col <= row; col++) {
//hex center
std::vector<int> edges;
if (col < N) {
edges.push_back(edgeToInt(0, col));
}
if (row-col < N) {
edges.push_back(edgeToInt(1, row - col));
}
if (row > 0) {
edges.push_back( edgeToInt(2, row - 1));
}
int eid = 2 * row - col - 1;
if (eid >= 0 && eid < 2 * N - 1) {
edges.push_back(edgeToInt(3, eid));
}
eid = row + col - 1;
if (eid >= 0 && eid < 2 * N - 1) {
edges.push_back(edgeToInt(4, eid));
}
eid = 2*col - row + N - 1;
if (eid >= 0 && eid < 2 * N - 1) {
edges.push_back(edgeToInt(5, eid));
}
addAllPairs(edges, adj, trips);
//5 neightbors of each hex center
if (col < row) {
//child edge set
std::vector<int> ce(2,0);
ce[0] = edgeToInt(2, row - 1);
ce[1] = edgeToInt(5, 2 * col - row + N);
addAllPairs(ce, adj, trips);
}
if (col < row && row < N) {
std::vector<int> ce(3, 0);
ce[0] = edgeToInt(3, 2 * row - col - 1);
ce[1] = edgeToInt(4, row + col);
ce[2] = edgeToInt(5, 2 * col - row + N);
addAllPairs(ce, adj, trips);
}
if (row < N) {
std::vector<int> ce(2, 0);
ce[0] = edgeToInt(1, row - col);
ce[1] = edgeToInt(4, row + col);
addAllPairs(ce, adj, trips);
}
if (row < N) {
std::vector<int> ce(3, 0);
ce[0] = edgeToInt(3, 2 * row - col);
ce[1] = edgeToInt(4, row + col);
ce[2] = edgeToInt(5, 2 * col - row + N - 1);
addAllPairs(ce, adj, trips);
}
if (row < N) {
std::vector<int> ce(2, 0);
ce[0] = edgeToInt(0, col);
ce[1] = edgeToInt(3, 2 * row - col);
addAllPairs(ce, adj, trips);
}
}
}
size_t trigCnt = 0;
size_t numEdges = adj.size();
for (auto e1 = adj.begin(); e1 != adj.end(); e1++) {
std::set<int> nbrs = e1->second;
std::vector<int> n;
for (auto e2: nbrs) {
if (e2 < e1->first) {
continue;
}
n.push_back(e2);
}
for (int i = 0; i < int(n.size() )- 1; i++) {
int e2 = n[i];
for (int j = i + 1; j < n.size(); j++) {
int e3 = n[j];
if (trips.find(trigToId(e1->first, e2, e3)) != trips.end()) {
continue;
}
if (adj[e2].find(e3) != adj[e2].end()) {
trigCnt++;
}
}
}
}
cout << "num edges " << numEdges << "\n";
cout << "num trigs" << trigCnt << "\n";
}
| [
"desai@inkbit3d.com"
] | desai@inkbit3d.com |
ff782b94b835eb1fbc5341e29aa0e41489bcf745 | c654452923735c7856882cc96edbcc0b0e6a1aa5 | /Datasets/ImportGeoLife.h | 8f805502c5f5ca0229593a5d7f529ce61a5bf80e | [] | no_license | omereis/BGU_Projects | 8a3dd5999b0588d46fd0e74a5862c7b1a81c8d52 | 06578a9dadcf853de7f5722e967e0037eb65a31d | refs/heads/master | 2021-04-29T17:35:12.443837 | 2018-02-15T19:39:54 | 2018-02-15T19:39:54 | 121,673,154 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,184 | h | //----------------------------------------------------------------------------
#ifndef ImportGeoLifeH
#define ImportGeoLifeH
//----------------------------------------------------------------------------
#include <vcl\ExtCtrls.hpp>
#include <vcl\Buttons.hpp>
#include <vcl\StdCtrls.hpp>
#include <vcl\Controls.hpp>
#include <vcl\Forms.hpp>
#include <vcl\Graphics.hpp>
#include <vcl\Classes.hpp>
#include <vcl\SysUtils.hpp>
#include <vcl\Windows.hpp>
#include <vcl\System.hpp>
#include <FileCtrl.hpp>
#include "DBMisc.h"
#include "DatasetInfo.h"
#include <AppEvnts.hpp>
//----------------------------------------------------------------------------
#include "DatasetObj.h"
#include "RouteInfo.h"
#include "cgauges.h"
#include "ShowProgress.h"
//----------------------------------------------------------------------------
class TdlgImportGeoLife : public TForm
{
__published:
TBitBtn *bitbtnOK;
TBitBtn *bitbtnCancel;
TDriveComboBox *DriveComboBox1;
TDirectoryListBox *DirectoryListBox1;
TBitBtn *bitbtnSelDir;
TEdit *edtRootDir;
TBitBtn *bitbtnFind;
TApplicationEvents *ApplicationEvents1;
TFileListBox *FileListBox1;
TListBox *lboxFiles;
TPanel *Panel1;
TButton *btnInsObjs;
TListBox *lboxObjs;
TListBox *lboxRoutes;
TLabel *Label1;
TLabel *Label2;
TButton *btnLoadObjects;
TButton *btnShowRoutes;
TPanel *Panel2;
TPanel *Panel3;
TPanel *Panel6;
TPanel *Panel7;
TTimer *timerUpdateGui;
void __fastcall DirectoryListBox1Change(TObject *Sender);
void __fastcall OnIdle(TObject *Sender, bool &Done);
void __fastcall bitbtnFindClick(TObject *Sender);
void __fastcall btnInsObjsClick(TObject *Sender);
void __fastcall lboxFilesDblClick(TObject *Sender);
void __fastcall btnLoadObjectsClick(TObject *Sender);
void __fastcall btnShowRoutesClick(TObject *Sender);
void __fastcall Panel2Click(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
void __fastcall timerUpdateGuiTimer(TObject *Sender);
private:
TADOConnection *m_db;
TADOQuery *m_query;
String m_strErr;
int m_nDatasetID;
TRoutes m_vRoutes;
int m_LastObj;
int m_nInsertCounter;
TDatasetObjects m_vObjs;
TfrmShowProgress *formShowProgress;
String m_strCurrentObj;
protected:
void __fastcall InitShowForm (int nFiles);
void __fastcall EndFormShow ();
int __fastcall ParseObjects (TDatasetObjects &vObjs);
void __fastcall ShowRoutes ();
void __fastcall InsertRoute (const TDatasetObj &ds_obj, const String &strFile);
void __fastcall InsertPoints (const String &strRoot, TStringList *lstr);
void __fastcall Download (TADOConnection *db, int nDatasetID);
void __fastcall LoadDatasetPath ();
void __fastcall SaveDatasetPath ();
public:
static String GeoConvert;
static String DatasetPath;
virtual __fastcall ~TdlgImportGeoLife();
virtual __fastcall TdlgImportGeoLife(TComponent* AOwner);
bool __fastcall Execute (TADOConnection *db, int nDatasetID);
void __fastcall UpdateGUI();
};
//----------------------------------------------------------------------------
extern PACKAGE TdlgImportGeoLife *dlgImportGeoLife;
//----------------------------------------------------------------------------
#endif
| [
"omereis@yahoo.com"
] | omereis@yahoo.com |
24ec234598a9ae18edcbb95534965e10cc5b1a81 | e1c2a102e85c37f0e99b931e3a70b5f2c0682a31 | /src/heranca/Caminhonete.h | 5c1a3e2da3714f183f3d2b7a2ba54c7e2d413216 | [
"MIT"
] | permissive | coleandro/programacao-avancada | cc370755b7f85bb44644e326fd36f30361d1a7ea | 0de06243432fb799b1dc6707b24f2b3f6f23f76d | refs/heads/master | 2020-05-04T13:37:51.327385 | 2019-04-16T23:57:04 | 2019-04-16T23:57:04 | 131,093,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | h | #ifndef _CAMINHONETE_H_
#define _CAMINHONETE_H_
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "Carro.h"
#include "Caminhao.h"
using namespace std;
class Caminhonete : public Carro, public Caminhao {
public:
// Construtores
Caminhonete();
Caminhonete(string placa, float peso, float vel_max, float preco, string modelo, string cor, float capacidade, float comprimento, float altura_max);
// Destrutor
~Caminhonete(){
}
// Metodos auxiliares
void imprime();
private:
};
#endif | [
"co.leandro@gmail.com"
] | co.leandro@gmail.com |
66f49eab8ff970341ba3250e6bd51ffeabfbab53 | 929e8fcf79315035e6d26675eabbc279b31e5a2e | /093_tests_binsrch/search.cpp | 5e2b36ab149920cbeb8fb4d88cfb365f68bff21b | [] | no_license | JiaranJerryZhou/ECE551 | e776c87df5c440915d028102b0c39c97777e77df | 11e31515759eaf6b7cb271b687cc459a828b9f5d | refs/heads/master | 2020-04-16T04:43:24.050362 | 2019-01-11T23:05:31 | 2019-01-11T23:05:31 | 165,278,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | cpp | #include <cmath>
#include <cstdio>
#include <iostream>
#include "function.h"
int binarySearchForZero(Function<int, int> * f, int low, int high) {
int mid = low + (high - low) / 2;
if (f->invoke(mid) == 0) {
return mid;
}
else if (f->invoke(mid) < 0) {
return binarySearchForZero(f, mid, high);
}
else {
return binarySearchForZero(f, low, mid - 1);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7e3103ed6321d182725340231267063758d68189 | 695046f95e57143c816785bdb2cb60562c8aba3e | /src/main.cpp | 4df35f89cdea285cc79f0c33c922fadc8be47abf | [] | no_license | hungrysushi/gb_emulator | 4db256025d366f4a043a96235c698f5caad24d88 | f23dec050429ef0d852d2d64da210ad059fd9ee3 | refs/heads/master | 2020-03-22T22:55:58.812044 | 2018-07-18T13:18:54 | 2018-07-18T13:18:54 | 140,779,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp |
#include <iostream>
#include <string>
#include "cpu.h"
#include "rom.h"
int main(int argc, char** argv)
{
if (argc < 2) {
std::cout << "Please enter a filename" << std::endl;
return 0;
}
std::string filename(argv[1]);
Rom rom(filename);
std::cout << rom.title_ << std::endl;
// header bytes
rom.PrintBytes(0x100, 0x14F);
// first few instructions
rom.PrintBytes(0x150, 0x200);
CPU cpu;
cpu.Run(rom.buffer_, rom.size_);
return 0;
}
| [
"ashw.chandr@gmail.com"
] | ashw.chandr@gmail.com |
d3c3bfc74a4c1c9c59357949f50952eb36bc80ee | 47a16a6fd9e3daf9208fcaee046bdaf716f760eb | /code/765.cpp | d2d2e04d6fc328893e50cbec24f9a40933a08686 | [
"MIT"
] | permissive | Nightwish-cn/my_leetcode | ba9bf05487b60ac1d1277fb4bf1741da4556f87a | 40f206e346f3f734fb28f52b9cde0e0041436973 | refs/heads/master | 2022-11-29T03:32:54.069824 | 2020-08-08T14:46:47 | 2020-08-08T14:46:47 | 287,178,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,564 | cpp | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeaf(TreeNode* root) {
return root->left == NULL && root->right == NULL;
}
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int minSwapsCouples(vector<int>& row) {
int to[31][2], ans = 0, n = row.size();
int f = 0;
memset(to, -1, sizeof(to));
for (int i = 0; i < n; i += 2){
int t1 = row[i] >> 1, t2 = row[i + 1] >> 1;
if (to[t1][0] < 0) to[t1][0] = t2;
else to[t1][1] = t2;
if (to[t2][0] < 0) to[t2][0] = t1;
else to[t2][1] = t1;
}
for (int i = (n >> 1) - 1; i >= 0; --i){
if (f & (1 << i)) continue;
int cnt = 0, t = i, fa = -1;
do{
f |= (1 << t);
int tt = (to[t][0] == fa ? to[t][1]: to[t][0]);
fa = t, t = tt, ++cnt;
}while (t != i);
ans += cnt - 1;
}
return ans;
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| [
"979115525@qq.com"
] | 979115525@qq.com |
a39705ba2283cb8a36b3977982e114e046d741f1 | 48165c78833beb50663afd653114f03cfb60c173 | /system/system_monitor/src/cpu_monitor/cpu_monitor_node.cpp | de32f1f0f6b87566b2cb4b4dda967580d1eaa9d2 | [
"Apache-2.0"
] | permissive | wep21/autoware.iv.universe | 611e5dafc7ea14fdb549f96d81581f4afe1e7aa6 | 8bcfbf7419552b5f6050e28c89c6488804652666 | refs/heads/master | 2023-04-03T11:37:28.114239 | 2020-09-25T06:32:13 | 2020-09-25T06:33:34 | 300,148,301 | 0 | 0 | Apache-2.0 | 2022-02-07T04:10:35 | 2020-10-01T04:54:28 | null | UTF-8 | C++ | false | false | 1,451 | cpp | /*
* Copyright 2020 Autoware Foundation. 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.
*/
/**
* @file cpu_monitor_node.cpp
* @brief CPU monitor node class
*/
#include <ros/ros.h>
#include <string>
#if defined _CPU_INTEL_
#include <system_monitor/cpu_monitor/intel_cpu_monitor.h>
#elif defined _CPU_ARM_
#include <system_monitor/cpu_monitor/arm_cpu_monitor.h>
#elif defined _CPU_RASPI_
#include <system_monitor/cpu_monitor/raspi_cpu_monitor.h>
#elif defined _CPU_TEGRA_
#include <system_monitor/cpu_monitor/tegra_cpu_monitor.h>
#else
#include <system_monitor/cpu_monitor/unknown_cpu_monitor.h>
#endif
int main(int argc, char ** argv)
{
ros::init(argc, argv, "cpu_monitor");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
std::shared_ptr<CPUMonitorBase> monitor;
monitor = std::make_shared<CPUMonitor>(nh, pnh);
monitor->getTempNames();
monitor->getFreqNames();
monitor->run();
return 0;
}
| [
"ryohsuke.mitsudome@tier4.jp"
] | ryohsuke.mitsudome@tier4.jp |
e69b088d3a56cb8db135cedac294373efc568f93 | 8794a823d52d5e58311c8f269c9e693bb078c974 | /Lab7/main.cpp | 33e1b2278785c1fb33c760eb69d5bf420fc92c38 | [] | no_license | TRZcodes/OOP1_Labs | 39f5b85121bba2bc327166d128c1acda15726bbc | 5b24cb95e9f9e63f33d66783aa3388375e291e2f | refs/heads/main | 2023-06-01T13:35:52.462952 | 2021-06-11T10:11:20 | 2021-06-11T10:11:20 | 375,978,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,505 | cpp | /*
Celem zadania jest napisanie hierarchii klas opisującej składniki systemu plików.
Składnikami tymi sa katalog (klasa Dir) i plik (klasa File), i może przydałaby się jeszcze jakaś klasa. Pliki mają nazwę i rozmiar (podawany w nawiasach), katalogi nazwę i tablicę podrzędnych składników systemu plików.
Prosze uniemożliwić dziedziczenie po klasie Dir i uzasadnić słownie w komentarzu.
UWAGA:
* Nazwy składników systemu plików proponuję przechowywać w std::string
* Implementacja klasy Dir może opierać się o std::vector (już wszyscy powinni go znać), ew. tablicę ograniczoną do 20 elementów). Tablica musi być tylko jedna wspólna dla plików i katalogów.
* Aby zapewnic wypisywanie z wcięciami, klasy te powinny posiadac metodę print z argumentem informujacym, ile spacji potrzeba wypisac przed nazwa (indentacja).
* Podczas kopiowania przydana bedzie polimorficzna metoda kopiujaca wywoływana przez copy.
*/
#include <iostream>
#include "Dir.h"
#include "File.h"
int main() {
std::cout << "------- Etap 1 -------\n";
Dir *top = new Dir(".");
Dir *home = new Dir("home");
*top += home; // dodajemy do kat top podkatalog
Dir *stud1 = new Dir("stud1");
*home += stud1;
Dir *stud2 = new Dir("stud2");
*home += stud2;
std::cout << const_cast<const Dir&>(*top) <<std::endl;
std::cout << "------- Etap 2 -------\n";
*stud1 += new File("img1.jpg",2020);
*stud1 += new File("img2.jpg");
Dir* work = new Dir("work");
*work += new File("main.h",150);
*work += new File("proj.h",175);
*stud1 += work;
std::cout << *home <<std::endl;
std::cout << "------- Etap 3 -------\n";
stud2->copy(stud1->getDir("work")); // trzeba koniecznie zrobic kopie
if (stud1->getDir("img1.jpg"))
std::cout << "**** TO NIE POWINNO SIE WYPISAC ****\n";
stud2->copy(stud1->get("img1.jpg"));
*work += new Dir("tmp");
Dir *tmp = static_cast<Dir*>(work->getDir("tmp"));
*tmp += new Dir("cpp");
std::cout << *(stud1->getDir("work"));
//usuwanie
*work -= "tmp";
*work -= "proj.h";
*work += new File("main.cpp"); // w kat: home/stud1/work pojawi sie nowy plik main.cpp, ktorego brak w kat home/stud2/work
std::cout << "\n------ Cale drzewo -------" << std::endl;
std::cout << *top;
// zadanie domowe albo w miarę wolnego czasu
// std::cout << *(home->get("main.h")); //main.h (150)
std::cout << "\n------- Czyszczenie -------" << std::endl;
delete top;
}
/* oczekiwany wynik
./main
------- Etap 1 -------
. (dir)
home (dir)
stud1 (dir)
stud2 (dir)
------- Etap 2 -------
home (dir)
stud1 (dir)
img1.jpg (2020)
img2.jpg (0)
work (dir)
main.h (150)
proj.h (175)
stud2 (dir)
------- Etap 3 -------
work (dir)
main.h (150)
proj.h (175)
tmp (dir)
cpp (dir)
Destruktor Dir: tmp
Destruktor Dir: cpp
---Destruktor File: proj.h
------ Cale drzewo -------
. (dir)
home (dir)
stud1 (dir)
img1.jpg (2020)
img2.jpg (0)
work (dir)
main.h (150)
main.cpp (175)
stud2 (dir)
work (dir)
main.h (150)
proj.h (175)
img1.jpg (2020)
------- Czyszczenie -------
Destruktor Dir: .
Destruktor Dir: home
Destruktor Dir: stud1
---Destruktor File: img1.jpg
---Destruktor File: img2.jpg
Destruktor Dir: work
---Destruktor File: main.h
---Destruktor File: main.cpp
Destruktor Dir: stud2
Destruktor Dir: work
---Destruktor File: main.h
---Destruktor File: proj.h
---Destruktor File: img1.jpg
*/ | [
"noreply@github.com"
] | noreply@github.com |
38ed6029438278a7a64e845d99432ca8f11d6aa0 | bb97e00bf288483393f039c017021be975776e67 | /src/fbw/src/model/Autothrust.cpp | c57d239416e2b0819229019e5b7e5c24f5d0c7a2 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | SSK123z/a32nx | cd7c7722b4737999473860491281632c4e84b698 | ff9425ae19d607662e1e8adb6732dd0509aacb9f | refs/heads/master | 2023-05-29T05:44:11.853083 | 2021-06-06T15:03:45 | 2021-06-06T15:03:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,380 | cpp | #include "Autothrust.h"
#include "Autothrust_private.h"
#include "look1_binlxpw.h"
#include "look2_binlcpw.h"
#include "look2_binlxpw.h"
const uint8_T Autothrust_IN_InAir = 1U;
const uint8_T Autothrust_IN_OnGround = 2U;
void AutothrustModelClass::Autothrust_TimeSinceCondition(real_T rtu_time, boolean_T rtu_condition, real_T *rty_y,
rtDW_TimeSinceCondition_Autothrust_T *localDW)
{
if (!localDW->eventTime_not_empty) {
localDW->eventTime = rtu_time;
localDW->eventTime_not_empty = true;
}
if ((!rtu_condition) || (localDW->eventTime == 0.0)) {
localDW->eventTime = rtu_time;
}
*rty_y = rtu_time - localDW->eventTime;
}
void AutothrustModelClass::Autothrust_ThrustMode1(real_T rtu_u, real_T *rty_y)
{
if (rtu_u < 0.0) {
*rty_y = 1.0;
} else if (rtu_u == 0.0) {
*rty_y = 2.0;
} else if ((rtu_u > 0.0) && (rtu_u < 25.0)) {
*rty_y = 3.0;
} else if ((rtu_u >= 25.0) && (rtu_u < 35.0)) {
*rty_y = 4.0;
} else if ((rtu_u >= 35.0) && (rtu_u < 45.0)) {
*rty_y = 5.0;
} else if (rtu_u == 45.0) {
*rty_y = 6.0;
} else {
*rty_y = 0.0;
}
}
void AutothrustModelClass::Autothrust_TLAComputation1(const athr_out *rtu_in, real_T rtu_TLA, real_T *rty_N1c, boolean_T
*rty_inReverse)
{
real_T N1_begin;
real_T N1_end;
real_T u0;
int32_T TLA_begin;
int32_T TLA_end;
u0 = rtu_TLA;
*rty_inReverse = (rtu_TLA < 0.0);
if (rtu_TLA >= 0.0) {
if (rtu_TLA <= 25.0) {
TLA_begin = 0;
N1_begin = rtu_in->input.thrust_limit_IDLE_percent;
TLA_end = 25;
N1_end = rtu_in->input.thrust_limit_CLB_percent;
} else if (rtu_TLA <= 35.0) {
TLA_begin = 25;
N1_begin = rtu_in->input.thrust_limit_CLB_percent;
TLA_end = 35;
if (rtu_in->data_computed.is_FLX_active) {
N1_end = rtu_in->input.thrust_limit_FLEX_percent;
} else {
N1_end = rtu_in->input.thrust_limit_MCT_percent;
}
} else {
TLA_begin = 35;
if (rtu_in->data_computed.is_FLX_active) {
N1_begin = rtu_in->input.thrust_limit_FLEX_percent;
} else {
N1_begin = rtu_in->input.thrust_limit_MCT_percent;
}
TLA_end = 45;
N1_end = rtu_in->input.thrust_limit_TOGA_percent;
}
} else {
u0 = std::abs(rtu_TLA);
if (u0 <= 6.0) {
u0 = 6.0;
}
TLA_begin = 6;
N1_begin = std::abs(rtu_in->input.thrust_limit_IDLE_percent);
TLA_end = 20;
N1_end = std::abs(rtu_in->input.thrust_limit_REV_percent);
}
*rty_N1c = (N1_end - N1_begin) / static_cast<real_T>(TLA_end - TLA_begin) * (u0 - static_cast<real_T>(TLA_begin)) +
N1_begin;
}
void AutothrustModelClass::Autothrust_RateLimiter(real_T rtu_u, real_T rtu_up, real_T rtu_lo, real_T rtu_Ts, real_T
rtu_init, real_T *rty_Y, rtDW_RateLimiter_Autothrust_T *localDW)
{
real_T u0;
real_T u1;
if (!localDW->pY_not_empty) {
localDW->pY = rtu_init;
localDW->pY_not_empty = true;
}
u0 = rtu_u - localDW->pY;
u1 = rtu_up * rtu_Ts;
if (u0 < u1) {
u1 = u0;
}
u0 = rtu_lo * rtu_Ts;
if (u1 > u0) {
u0 = u1;
}
localDW->pY += u0;
*rty_Y = localDW->pY;
}
void AutothrustModelClass::step()
{
athr_out rtb_BusAssignment_n;
real_T result_tmp[9];
real_T result[3];
real_T x[3];
real_T Phi_rad;
real_T Theta_rad;
real_T ca;
real_T rtb_Gain2;
real_T rtb_Gain3;
real_T rtb_Gain_f;
real_T rtb_Saturation;
real_T rtb_Sum_c;
real_T rtb_Sum_g;
real_T rtb_Switch1_k;
real_T rtb_Switch2_k;
real_T rtb_Switch_dx;
real_T rtb_Switch_f_idx_0;
real_T rtb_Switch_i_tmp;
real_T rtb_Switch_m;
real_T rtb_y_a;
real_T rtb_y_c;
int32_T i;
int32_T rtb_on_ground;
boolean_T ATHR_ENGAGED_tmp;
boolean_T ATHR_ENGAGED_tmp_0;
boolean_T ATHR_PB;
boolean_T ATHR_PB_tmp;
boolean_T condition_AP_FD_ATHR_Specific;
boolean_T condition_TOGA;
boolean_T flightDirectorOffTakeOff_tmp;
boolean_T rtb_Compare_e;
boolean_T rtb_NOT;
boolean_T rtb_NOT1_m;
boolean_T rtb_out;
boolean_T rtb_y_cs;
athr_status rtb_status;
rtb_Gain2 = Autothrust_P.Gain2_Gain * Autothrust_U.in.data.Theta_deg;
rtb_Gain3 = Autothrust_P.Gain3_Gain * Autothrust_U.in.data.Phi_deg;
Theta_rad = 0.017453292519943295 * rtb_Gain2;
Phi_rad = 0.017453292519943295 * rtb_Gain3;
rtb_Saturation = std::cos(Theta_rad);
Theta_rad = std::sin(Theta_rad);
rtb_Sum_c = std::sin(Phi_rad);
Phi_rad = std::cos(Phi_rad);
result_tmp[0] = rtb_Saturation;
result_tmp[3] = 0.0;
result_tmp[6] = -Theta_rad;
result_tmp[1] = rtb_Sum_c * Theta_rad;
result_tmp[4] = Phi_rad;
result_tmp[7] = rtb_Saturation * rtb_Sum_c;
result_tmp[2] = Phi_rad * Theta_rad;
result_tmp[5] = 0.0 - rtb_Sum_c;
result_tmp[8] = Phi_rad * rtb_Saturation;
for (i = 0; i < 3; i++) {
result[i] = result_tmp[i + 6] * Autothrust_U.in.data.bz_m_s2 + (result_tmp[i + 3] * Autothrust_U.in.data.by_m_s2 +
result_tmp[i] * Autothrust_U.in.data.bx_m_s2);
}
rtb_Saturation = Autothrust_P.Gain_Gain_p * Autothrust_U.in.data.gear_strut_compression_1 -
Autothrust_P.Constant1_Value_d;
if (rtb_Saturation > Autothrust_P.Saturation_UpperSat) {
rtb_Saturation = Autothrust_P.Saturation_UpperSat;
} else {
if (rtb_Saturation < Autothrust_P.Saturation_LowerSat) {
rtb_Saturation = Autothrust_P.Saturation_LowerSat;
}
}
Phi_rad = Autothrust_P.Gain1_Gain * Autothrust_U.in.data.gear_strut_compression_2 - Autothrust_P.Constant1_Value_d;
if (Phi_rad > Autothrust_P.Saturation1_UpperSat) {
Phi_rad = Autothrust_P.Saturation1_UpperSat;
} else {
if (Phi_rad < Autothrust_P.Saturation1_LowerSat) {
Phi_rad = Autothrust_P.Saturation1_LowerSat;
}
}
if (Autothrust_DWork.is_active_c5_Autothrust == 0U) {
Autothrust_DWork.is_active_c5_Autothrust = 1U;
Autothrust_DWork.is_c5_Autothrust = Autothrust_IN_OnGround;
rtb_on_ground = 1;
} else if (Autothrust_DWork.is_c5_Autothrust == 1) {
if ((rtb_Saturation > 0.05) || (Phi_rad > 0.05)) {
Autothrust_DWork.is_c5_Autothrust = Autothrust_IN_OnGround;
rtb_on_ground = 1;
} else {
rtb_on_ground = 0;
}
} else {
if ((rtb_Saturation == 0.0) && (Phi_rad == 0.0)) {
Autothrust_DWork.is_c5_Autothrust = Autothrust_IN_InAir;
rtb_on_ground = 0;
} else {
rtb_on_ground = 1;
}
}
rtb_Saturation = 15.0 - 0.0019812 * Autothrust_U.in.data.H_ft;
if (rtb_Saturation <= -56.5) {
rtb_Saturation = -56.5;
}
Phi_rad = (Autothrust_U.in.data.engine_N1_1_percent + Autothrust_U.in.data.commanded_engine_N1_1_percent) -
Autothrust_U.in.data.corrected_engine_N1_1_percent;
Theta_rad = (Autothrust_U.in.data.engine_N1_2_percent + Autothrust_U.in.data.commanded_engine_N1_2_percent) -
Autothrust_U.in.data.corrected_engine_N1_2_percent;
Autothrust_RateLimiter(look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_engine_1_active ||
Autothrust_U.in.input.is_anti_ice_engine_2_active), static_cast<real_T>
(Autothrust_U.in.input.is_anti_ice_wing_active), Autothrust_P.uDLookupTable_bp01Data,
Autothrust_P.uDLookupTable_bp02Data, Autothrust_P.uDLookupTable_tableData, Autothrust_P.uDLookupTable_maxIndex, 2U),
Autothrust_P.RateLimiterVariableTs_up, Autothrust_P.RateLimiterVariableTs_lo, Autothrust_U.in.time.dt,
Autothrust_P.RateLimiterVariableTs_InitialCondition, &rtb_Switch_m, &Autothrust_DWork.sf_RateLimiter_b);
rtb_Sum_c = Autothrust_U.in.input.thrust_limit_IDLE_percent + rtb_Switch_m;
rtb_Switch1_k = look2_binlcpw(Autothrust_U.in.data.TAT_degC, Autothrust_U.in.data.H_ft,
Autothrust_P.OATCornerPoint_bp01Data, Autothrust_P.OATCornerPoint_bp02Data, Autothrust_P.OATCornerPoint_tableData,
Autothrust_P.OATCornerPoint_maxIndex, 26U);
Autothrust_RateLimiter((look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_engine_1_active ||
Autothrust_U.in.input.is_anti_ice_engine_2_active), rtb_Switch1_k, Autothrust_P.AntiIceEngine_bp01Data,
Autothrust_P.AntiIceEngine_bp02Data, Autothrust_P.AntiIceEngine_tableData, Autothrust_P.AntiIceEngine_maxIndex, 2U)
+ look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_wing_active), rtb_Switch1_k,
Autothrust_P.AntiIceWing_bp01Data, Autothrust_P.AntiIceWing_bp02Data,
Autothrust_P.AntiIceWing_tableData, Autothrust_P.AntiIceWing_maxIndex, 2U)) + look2_binlxpw(
static_cast<real_T>(Autothrust_U.in.input.is_air_conditioning_1_active ||
Autothrust_U.in.input.is_air_conditioning_2_active), rtb_Switch1_k,
Autothrust_P.AirConditioning_bp01Data, Autothrust_P.AirConditioning_bp02Data, Autothrust_P.AirConditioning_tableData,
Autothrust_P.AirConditioning_maxIndex, 2U), Autothrust_P.RateLimiterVariableTs_up_c,
Autothrust_P.RateLimiterVariableTs_lo_g, Autothrust_U.in.time.dt,
Autothrust_P.RateLimiterVariableTs_InitialCondition_e, &rtb_Switch_m, &Autothrust_DWork.sf_RateLimiter);
rtb_Sum_g = look2_binlxpw(Autothrust_U.in.data.TAT_degC, Autothrust_U.in.data.H_ft, Autothrust_P.MaximumClimb_bp01Data,
Autothrust_P.MaximumClimb_bp02Data, Autothrust_P.MaximumClimb_tableData, Autothrust_P.MaximumClimb_maxIndex, 26U) +
rtb_Switch_m;
Autothrust_RateLimiter((look1_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_engine_1_active ||
Autothrust_U.in.input.is_anti_ice_engine_2_active), Autothrust_P.AntiIceEngine_bp01Data_d,
Autothrust_P.AntiIceEngine_tableData_l, 1U) + look1_binlxpw(static_cast<real_T>
(Autothrust_U.in.input.is_anti_ice_wing_active), Autothrust_P.AntiIceWing_bp01Data_n,
Autothrust_P.AntiIceWing_tableData_g, 1U)) + look1_binlxpw(static_cast<real_T>
(Autothrust_U.in.input.is_air_conditioning_1_active || Autothrust_U.in.input.is_air_conditioning_2_active),
Autothrust_P.AirConditioning_bp01Data_d, Autothrust_P.AirConditioning_tableData_p, 1U),
Autothrust_P.RateLimiterVariableTs_up_m, Autothrust_P.RateLimiterVariableTs_lo_n, Autothrust_U.in.time.dt,
Autothrust_P.RateLimiterVariableTs_InitialCondition_b, &rtb_Switch_m, &Autothrust_DWork.sf_RateLimiter_k);
if (Autothrust_U.in.input.flex_temperature_degC < rtb_Saturation + 55.0) {
rtb_Switch1_k = Autothrust_U.in.input.flex_temperature_degC;
} else {
rtb_Switch1_k = rtb_Saturation + 55.0;
}
if (rtb_Switch1_k <= rtb_Saturation + 29.0) {
rtb_Switch1_k = rtb_Saturation + 29.0;
}
if (rtb_Switch1_k <= Autothrust_U.in.data.OAT_degC) {
rtb_Switch1_k = Autothrust_U.in.data.OAT_degC;
}
rtb_y_c = look2_binlxpw(look2_binlxpw(Autothrust_U.in.data.H_ft, rtb_Switch1_k, Autothrust_P.Right_bp01Data,
Autothrust_P.Right_bp02Data, Autothrust_P.Right_tableData, Autothrust_P.Right_maxIndex, 10U),
Autothrust_U.in.data.TAT_degC, Autothrust_P.Left_bp01Data, Autothrust_P.Left_bp02Data, Autothrust_P.Left_tableData,
Autothrust_P.Left_maxIndex, 2U) + rtb_Switch_m;
if (rtb_y_c <= rtb_Sum_g) {
rtb_y_c = rtb_Sum_g;
}
rtb_Switch2_k = look2_binlcpw(Autothrust_U.in.data.TAT_degC, Autothrust_U.in.data.H_ft,
Autothrust_P.OATCornerPoint_bp01Data_a, Autothrust_P.OATCornerPoint_bp02Data_i,
Autothrust_P.OATCornerPoint_tableData_n, Autothrust_P.OATCornerPoint_maxIndex_i, 26U);
rtb_Switch_i_tmp = (Autothrust_U.in.input.is_air_conditioning_1_active ||
Autothrust_U.in.input.is_air_conditioning_2_active);
rtb_Switch_m = look2_binlxpw(rtb_Switch_i_tmp, rtb_Switch2_k, Autothrust_P.AirConditioning_bp01Data_l,
Autothrust_P.AirConditioning_bp02Data_c, Autothrust_P.AirConditioning_tableData_l,
Autothrust_P.AirConditioning_maxIndex_g, 2U);
Autothrust_RateLimiter((look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_engine_1_active ||
Autothrust_U.in.input.is_anti_ice_engine_2_active), rtb_Switch2_k, Autothrust_P.AntiIceEngine_bp01Data_l,
Autothrust_P.AntiIceEngine_bp02Data_e, Autothrust_P.AntiIceEngine_tableData_d, Autothrust_P.AntiIceEngine_maxIndex_e,
2U) + look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_wing_active), rtb_Switch2_k,
Autothrust_P.AntiIceWing_bp01Data_b, Autothrust_P.AntiIceWing_bp02Data_n,
Autothrust_P.AntiIceWing_tableData_a, Autothrust_P.AntiIceWing_maxIndex_d, 2U)) + rtb_Switch_m,
Autothrust_P.RateLimiterVariableTs_up_i, Autothrust_P.RateLimiterVariableTs_lo_ns, Autothrust_U.in.time.dt,
Autothrust_P.RateLimiterVariableTs_InitialCondition_bl, &rtb_Switch_m, &Autothrust_DWork.sf_RateLimiter_f);
rtb_y_a = look2_binlxpw(Autothrust_U.in.data.TAT_degC, Autothrust_U.in.data.H_ft,
Autothrust_P.MaximumContinuous_bp01Data, Autothrust_P.MaximumContinuous_bp02Data,
Autothrust_P.MaximumContinuous_tableData, Autothrust_P.MaximumContinuous_maxIndex, 26U) + rtb_Switch_m;
rtb_Switch_m = look2_binlcpw(Autothrust_U.in.data.TAT_degC, Autothrust_U.in.data.H_ft,
Autothrust_P.OATCornerPoint_bp01Data_j, Autothrust_P.OATCornerPoint_bp02Data_g,
Autothrust_P.OATCornerPoint_tableData_f, Autothrust_P.OATCornerPoint_maxIndex_m, 36U);
if (Autothrust_U.in.data.H_ft <= Autothrust_P.CompareToConstant_const) {
rtb_Switch_dx = look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_engine_1_active ||
Autothrust_U.in.input.is_anti_ice_engine_2_active), rtb_Switch_m, Autothrust_P.AntiIceEngine8000_bp01Data,
Autothrust_P.AntiIceEngine8000_bp02Data, Autothrust_P.AntiIceEngine8000_tableData,
Autothrust_P.AntiIceEngine8000_maxIndex, 2U);
rtb_Switch1_k = look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_wing_active), rtb_Switch_m,
Autothrust_P.AntiIceWing8000_bp01Data, Autothrust_P.AntiIceWing8000_bp02Data,
Autothrust_P.AntiIceWing8000_tableData, Autothrust_P.AntiIceWing8000_maxIndex, 2U);
rtb_Switch2_k = look2_binlxpw(rtb_Switch_i_tmp, rtb_Switch_m, Autothrust_P.AirConditioning8000_bp01Data,
Autothrust_P.AirConditioning8000_bp02Data, Autothrust_P.AirConditioning8000_tableData,
Autothrust_P.AirConditioning8000_maxIndex, 2U);
} else {
rtb_Switch_dx = look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_engine_1_active ||
Autothrust_U.in.input.is_anti_ice_engine_2_active), rtb_Switch_m, Autothrust_P.AntiIceEngine8000_bp01Data_m,
Autothrust_P.AntiIceEngine8000_bp02Data_i, Autothrust_P.AntiIceEngine8000_tableData_d,
Autothrust_P.AntiIceEngine8000_maxIndex_a, 2U);
rtb_Switch1_k = look2_binlxpw(static_cast<real_T>(Autothrust_U.in.input.is_anti_ice_wing_active), rtb_Switch_m,
Autothrust_P.AntiIceWing8000_bp01Data_d, Autothrust_P.AntiIceWing8000_bp02Data_e,
Autothrust_P.AntiIceWing8000_tableData_k, Autothrust_P.AntiIceWing8000_maxIndex_c, 2U);
rtb_Switch2_k = look2_binlxpw(rtb_Switch_i_tmp, rtb_Switch_m, Autothrust_P.AirConditioning8000_bp01Data_p,
Autothrust_P.AirConditioning8000_bp02Data_l, Autothrust_P.AirConditioning8000_tableData_f,
Autothrust_P.AirConditioning8000_maxIndex_o, 2U);
}
Autothrust_RateLimiter((rtb_Switch_dx + rtb_Switch1_k) + rtb_Switch2_k, Autothrust_P.RateLimiterVariableTs_up_in,
Autothrust_P.RateLimiterVariableTs_lo_a, Autothrust_U.in.time.dt,
Autothrust_P.RateLimiterVariableTs_InitialCondition_j, &rtb_Switch_dx, &Autothrust_DWork.sf_RateLimiter_p);
rtb_Switch_m = look2_binlxpw(Autothrust_U.in.data.TAT_degC, Autothrust_U.in.data.H_ft,
Autothrust_P.MaximumTakeOff_bp01Data, Autothrust_P.MaximumTakeOff_bp02Data, Autothrust_P.MaximumTakeOff_tableData,
Autothrust_P.MaximumTakeOff_maxIndex, 36U) + rtb_Switch_dx;
rtb_Switch1_k = rtb_Switch_m;
Autothrust_TimeSinceCondition(Autothrust_U.in.time.simulation_time, Autothrust_U.in.input.ATHR_disconnect,
&rtb_Switch_m, &Autothrust_DWork.sf_TimeSinceCondition_o);
Autothrust_DWork.Memory_PreviousInput = Autothrust_P.Logic_table[(((static_cast<uint32_T>(rtb_Switch_m >=
Autothrust_P.CompareToConstant_const_k) << 1) + false) << 1) + Autothrust_DWork.Memory_PreviousInput];
if (!Autothrust_DWork.eventTime_not_empty_g) {
Autothrust_DWork.eventTime_f = Autothrust_U.in.time.simulation_time;
Autothrust_DWork.eventTime_not_empty_g = true;
}
if ((Autothrust_U.in.input.ATHR_push != Autothrust_P.CompareToConstant1_const) || (Autothrust_DWork.eventTime_f == 0.0))
{
Autothrust_DWork.eventTime_f = Autothrust_U.in.time.simulation_time;
}
Autothrust_DWork.Memory_PreviousInput_m = Autothrust_P.Logic_table_m[(((Autothrust_U.in.time.simulation_time -
Autothrust_DWork.eventTime_f >= Autothrust_P.CompareToConstant2_const) + (static_cast<uint32_T>
(Autothrust_DWork.Delay_DSTATE_a) << 1)) << 1) + Autothrust_DWork.Memory_PreviousInput_m];
if (Autothrust_U.in.data.is_engine_operative_1 && Autothrust_U.in.data.is_engine_operative_2) {
rtb_out = ((Autothrust_U.in.input.TLA_1_deg >= 0.0) && (Autothrust_U.in.input.TLA_1_deg <= 25.0) &&
(Autothrust_U.in.input.TLA_2_deg >= 0.0) && (Autothrust_U.in.input.TLA_2_deg <= 25.0));
} else {
rtb_out = ((Autothrust_U.in.data.is_engine_operative_1 && (Autothrust_U.in.input.TLA_1_deg >= 0.0) &&
(Autothrust_U.in.input.TLA_1_deg <= 35.0)) || (Autothrust_U.in.data.is_engine_operative_2 &&
(Autothrust_U.in.input.TLA_2_deg >= 0.0) && (Autothrust_U.in.input.TLA_2_deg <= 35.0)));
}
rtb_Compare_e = ((Autothrust_U.in.input.flex_temperature_degC > Autothrust_U.in.data.TAT_degC) &&
(Autothrust_U.in.input.flex_temperature_degC != 0.0) && (Autothrust_U.in.input.flight_phase < 3.0));
Autothrust_DWork.latch = ((rtb_Compare_e && (rtb_on_ground != 0) && (Autothrust_U.in.input.TLA_1_deg == 35.0) &&
(Autothrust_U.in.input.TLA_2_deg == 35.0)) || Autothrust_DWork.latch);
Autothrust_DWork.latch = (((!Autothrust_DWork.latch) || (((Autothrust_U.in.input.TLA_1_deg != 25.0) ||
(Autothrust_U.in.input.TLA_2_deg != 25.0)) && ((Autothrust_U.in.input.TLA_1_deg != 45.0) ||
(Autothrust_U.in.input.TLA_2_deg != 45.0)))) && Autothrust_DWork.latch);
rtb_y_cs = ((rtb_Compare_e && (rtb_on_ground != 0)) || ((rtb_on_ground == 0) && Autothrust_DWork.latch));
Autothrust_DWork.Delay_DSTATE_a = (static_cast<int32_T>(Autothrust_U.in.input.ATHR_push) > static_cast<int32_T>
(Autothrust_P.CompareToConstant_const_j));
rtb_NOT1_m = (Autothrust_DWork.Delay_DSTATE_a && (!Autothrust_DWork.Memory_PreviousInput_m));
Autothrust_TimeSinceCondition(Autothrust_U.in.time.simulation_time, rtb_on_ground != 0, &rtb_Switch_m,
&Autothrust_DWork.sf_TimeSinceCondition1);
rtb_BusAssignment_n.time = Autothrust_U.in.time;
rtb_BusAssignment_n.data.nz_g = Autothrust_U.in.data.nz_g;
rtb_BusAssignment_n.data.Theta_deg = rtb_Gain2;
rtb_BusAssignment_n.data.Phi_deg = rtb_Gain3;
rtb_BusAssignment_n.data.V_ias_kn = Autothrust_U.in.data.V_ias_kn;
rtb_BusAssignment_n.data.V_tas_kn = Autothrust_U.in.data.V_tas_kn;
rtb_BusAssignment_n.data.V_mach = Autothrust_U.in.data.V_mach;
rtb_BusAssignment_n.data.V_gnd_kn = Autothrust_U.in.data.V_gnd_kn;
rtb_BusAssignment_n.data.alpha_deg = Autothrust_U.in.data.alpha_deg;
rtb_BusAssignment_n.data.H_ft = Autothrust_U.in.data.H_ft;
rtb_BusAssignment_n.data.H_ind_ft = Autothrust_U.in.data.H_ind_ft;
rtb_BusAssignment_n.data.H_radio_ft = Autothrust_U.in.data.H_radio_ft;
rtb_BusAssignment_n.data.H_dot_fpm = Autothrust_U.in.data.H_dot_fpm;
rtb_BusAssignment_n.data.ax_m_s2 = result[0];
rtb_BusAssignment_n.data.ay_m_s2 = result[1];
rtb_BusAssignment_n.data.az_m_s2 = result[2];
rtb_BusAssignment_n.data.bx_m_s2 = Autothrust_U.in.data.bx_m_s2;
rtb_BusAssignment_n.data.by_m_s2 = Autothrust_U.in.data.by_m_s2;
rtb_BusAssignment_n.data.bz_m_s2 = Autothrust_U.in.data.bz_m_s2;
rtb_BusAssignment_n.data.on_ground = (rtb_on_ground != 0);
rtb_BusAssignment_n.data.flap_handle_index = Autothrust_U.in.data.flap_handle_index;
rtb_BusAssignment_n.data.is_engine_operative_1 = Autothrust_U.in.data.is_engine_operative_1;
rtb_BusAssignment_n.data.is_engine_operative_2 = Autothrust_U.in.data.is_engine_operative_2;
rtb_BusAssignment_n.data.commanded_engine_N1_1_percent = Phi_rad;
rtb_BusAssignment_n.data.commanded_engine_N1_2_percent = Theta_rad;
rtb_BusAssignment_n.data.engine_N1_1_percent = Autothrust_U.in.data.engine_N1_1_percent;
rtb_BusAssignment_n.data.engine_N1_2_percent = Autothrust_U.in.data.engine_N1_2_percent;
rtb_BusAssignment_n.data.TAT_degC = Autothrust_U.in.data.TAT_degC;
rtb_BusAssignment_n.data.OAT_degC = Autothrust_U.in.data.OAT_degC;
rtb_BusAssignment_n.data.ISA_degC = rtb_Saturation;
rtb_BusAssignment_n.input.ATHR_push = Autothrust_U.in.input.ATHR_push;
rtb_BusAssignment_n.input.ATHR_disconnect = Autothrust_U.in.input.ATHR_disconnect;
rtb_BusAssignment_n.input.TLA_1_deg = Autothrust_U.in.input.TLA_1_deg;
rtb_BusAssignment_n.input.TLA_2_deg = Autothrust_U.in.input.TLA_2_deg;
rtb_BusAssignment_n.input.V_c_kn = Autothrust_U.in.input.V_c_kn;
rtb_BusAssignment_n.input.V_LS_kn = Autothrust_U.in.input.V_LS_kn;
rtb_BusAssignment_n.input.V_MAX_kn = Autothrust_U.in.input.V_MAX_kn;
rtb_BusAssignment_n.input.thrust_limit_REV_percent = Autothrust_U.in.input.thrust_limit_REV_percent;
rtb_BusAssignment_n.input.thrust_limit_IDLE_percent = rtb_Sum_c;
rtb_BusAssignment_n.input.thrust_limit_CLB_percent = rtb_Sum_g;
rtb_BusAssignment_n.input.thrust_limit_MCT_percent = rtb_y_a;
rtb_BusAssignment_n.input.thrust_limit_FLEX_percent = rtb_y_c;
rtb_BusAssignment_n.input.thrust_limit_TOGA_percent = rtb_Switch1_k;
rtb_BusAssignment_n.input.flex_temperature_degC = Autothrust_U.in.input.flex_temperature_degC;
rtb_BusAssignment_n.input.mode_requested = Autothrust_U.in.input.mode_requested;
rtb_BusAssignment_n.input.is_mach_mode_active = Autothrust_U.in.input.is_mach_mode_active;
rtb_BusAssignment_n.input.alpha_floor_condition = Autothrust_U.in.input.alpha_floor_condition;
rtb_BusAssignment_n.input.is_approach_mode_active = Autothrust_U.in.input.is_approach_mode_active;
rtb_BusAssignment_n.input.is_SRS_TO_mode_active = Autothrust_U.in.input.is_SRS_TO_mode_active;
rtb_BusAssignment_n.input.is_SRS_GA_mode_active = Autothrust_U.in.input.is_SRS_GA_mode_active;
rtb_BusAssignment_n.input.is_LAND_mode_active = Autothrust_U.in.input.is_LAND_mode_active;
rtb_BusAssignment_n.input.thrust_reduction_altitude = Autothrust_U.in.input.thrust_reduction_altitude;
rtb_BusAssignment_n.input.thrust_reduction_altitude_go_around =
Autothrust_U.in.input.thrust_reduction_altitude_go_around;
rtb_BusAssignment_n.input.flight_phase = Autothrust_U.in.input.flight_phase;
rtb_BusAssignment_n.input.is_alt_soft_mode_active = Autothrust_U.in.input.is_alt_soft_mode_active;
rtb_BusAssignment_n.input.is_anti_ice_wing_active = Autothrust_U.in.input.is_anti_ice_wing_active;
rtb_BusAssignment_n.input.is_anti_ice_engine_1_active = Autothrust_U.in.input.is_anti_ice_engine_1_active;
rtb_BusAssignment_n.input.is_anti_ice_engine_2_active = Autothrust_U.in.input.is_anti_ice_engine_2_active;
rtb_BusAssignment_n.input.is_air_conditioning_1_active = Autothrust_U.in.input.is_air_conditioning_1_active;
rtb_BusAssignment_n.input.is_air_conditioning_2_active = Autothrust_U.in.input.is_air_conditioning_2_active;
rtb_BusAssignment_n.input.FD_active = Autothrust_U.in.input.FD_active;
rtb_BusAssignment_n.output = Autothrust_P.athr_out_MATLABStruct.output;
if (Autothrust_U.in.data.is_engine_operative_1 && Autothrust_U.in.data.is_engine_operative_2) {
rtb_BusAssignment_n.data_computed.TLA_in_active_range = ((Autothrust_U.in.input.TLA_1_deg >= 0.0) &&
(Autothrust_U.in.input.TLA_1_deg <= 25.0) && (Autothrust_U.in.input.TLA_2_deg >= 0.0) &&
(Autothrust_U.in.input.TLA_2_deg <= 25.0));
} else {
rtb_BusAssignment_n.data_computed.TLA_in_active_range = ((Autothrust_U.in.data.is_engine_operative_1 &&
(Autothrust_U.in.input.TLA_1_deg >= 0.0) && (Autothrust_U.in.input.TLA_1_deg <= 35.0)) ||
(Autothrust_U.in.data.is_engine_operative_2 && (Autothrust_U.in.input.TLA_2_deg >= 0.0) &&
(Autothrust_U.in.input.TLA_2_deg <= 35.0)));
}
rtb_BusAssignment_n.data_computed.is_FLX_active = ((rtb_Compare_e && (rtb_on_ground != 0)) || ((rtb_on_ground == 0) &&
Autothrust_DWork.latch));
rtb_BusAssignment_n.data_computed.ATHR_push = rtb_NOT1_m;
rtb_BusAssignment_n.data_computed.ATHR_disabled = Autothrust_DWork.Memory_PreviousInput;
rtb_BusAssignment_n.data_computed.time_since_touchdown = rtb_Switch_m;
Autothrust_TLAComputation1(&rtb_BusAssignment_n, Autothrust_U.in.input.TLA_1_deg, &rtb_Switch_dx, &rtb_Compare_e);
Autothrust_TLAComputation1(&rtb_BusAssignment_n, Autothrust_U.in.input.TLA_2_deg, &rtb_Switch_m, &rtb_NOT1_m);
if (!Autothrust_DWork.prev_TLA_1_not_empty) {
Autothrust_DWork.prev_TLA_1 = Autothrust_U.in.input.TLA_1_deg;
Autothrust_DWork.prev_TLA_1_not_empty = true;
}
if (!Autothrust_DWork.prev_TLA_2_not_empty) {
Autothrust_DWork.prev_TLA_2 = Autothrust_U.in.input.TLA_2_deg;
Autothrust_DWork.prev_TLA_2_not_empty = true;
}
condition_AP_FD_ATHR_Specific = !Autothrust_DWork.Memory_PreviousInput;
ATHR_PB_tmp = !Autothrust_DWork.ATHR_ENGAGED;
ATHR_PB = ((rtb_on_ground == 0) && ATHR_PB_tmp && rtb_BusAssignment_n.data_computed.ATHR_push);
condition_TOGA = (((Autothrust_U.in.input.TLA_1_deg == 45.0) && (Autothrust_U.in.input.TLA_2_deg == 45.0)) ||
(rtb_y_cs && (Autothrust_U.in.input.TLA_1_deg >= 35.0) && (Autothrust_U.in.input.TLA_2_deg >= 35.0)));
flightDirectorOffTakeOff_tmp = !Autothrust_U.in.input.alpha_floor_condition;
Autothrust_DWork.flightDirectorOffTakeOff = (((!Autothrust_U.in.input.FD_active) && (rtb_on_ground != 0) &&
condition_TOGA && ((Autothrust_U.in.input.flight_phase <= 1.0) ||
(rtb_BusAssignment_n.data_computed.time_since_touchdown >= 30.0))) || ((!ATHR_PB) && (!rtb_out) &&
flightDirectorOffTakeOff_tmp && Autothrust_DWork.flightDirectorOffTakeOff));
ATHR_ENGAGED_tmp = ((Autothrust_DWork.prev_TLA_1 <= 0.0) || (Autothrust_U.in.input.TLA_1_deg != 0.0));
ATHR_ENGAGED_tmp_0 = ((Autothrust_DWork.prev_TLA_2 <= 0.0) || (Autothrust_U.in.input.TLA_2_deg != 0.0));
rtb_NOT = !Autothrust_U.in.input.ATHR_disconnect;
Autothrust_DWork.ATHR_ENGAGED = ((condition_AP_FD_ATHR_Specific && (!Autothrust_DWork.flightDirectorOffTakeOff) &&
(ATHR_PB || condition_TOGA || Autothrust_U.in.input.alpha_floor_condition)) || (condition_AP_FD_ATHR_Specific &&
((!rtb_BusAssignment_n.data_computed.ATHR_push) || ATHR_PB_tmp || Autothrust_U.in.input.is_LAND_mode_active) &&
rtb_NOT && ((ATHR_ENGAGED_tmp || ATHR_ENGAGED_tmp_0) && (ATHR_ENGAGED_tmp || (Autothrust_U.in.input.TLA_2_deg != 0.0))
&& (ATHR_ENGAGED_tmp_0 || (Autothrust_U.in.input.TLA_1_deg != 0.0))) && Autothrust_DWork.ATHR_ENGAGED));
condition_AP_FD_ATHR_Specific = (Autothrust_DWork.ATHR_ENGAGED && (rtb_out ||
Autothrust_U.in.input.alpha_floor_condition));
if (Autothrust_DWork.ATHR_ENGAGED && condition_AP_FD_ATHR_Specific) {
rtb_status = athr_status_ENGAGED_ACTIVE;
} else if (Autothrust_DWork.ATHR_ENGAGED && (!condition_AP_FD_ATHR_Specific)) {
rtb_status = athr_status_ENGAGED_ARMED;
} else {
rtb_status = athr_status_DISENGAGED;
}
Autothrust_DWork.prev_TLA_1 = Autothrust_U.in.input.TLA_1_deg;
Autothrust_DWork.prev_TLA_2 = Autothrust_U.in.input.TLA_2_deg;
if (Autothrust_U.in.input.TLA_1_deg > Autothrust_U.in.input.TLA_2_deg) {
rtb_Switch_i_tmp = Autothrust_U.in.input.TLA_1_deg;
} else {
rtb_Switch_i_tmp = Autothrust_U.in.input.TLA_2_deg;
}
Autothrust_DWork.pConditionAlphaFloor = (Autothrust_U.in.input.alpha_floor_condition || ((!(rtb_status ==
athr_status_DISENGAGED)) && Autothrust_DWork.pConditionAlphaFloor));
if (rtb_status == athr_status_DISENGAGED) {
Autothrust_DWork.pMode = athr_mode_NONE;
} else if (Autothrust_U.in.input.alpha_floor_condition) {
Autothrust_DWork.pMode = athr_mode_A_FLOOR;
} else if (flightDirectorOffTakeOff_tmp && Autothrust_DWork.pConditionAlphaFloor) {
Autothrust_DWork.pMode = athr_mode_TOGA_LK;
} else if ((rtb_status == athr_status_ENGAGED_ARMED) && ((Autothrust_U.in.input.TLA_1_deg == 45.0) ||
(Autothrust_U.in.input.TLA_2_deg == 45.0))) {
Autothrust_DWork.pMode = athr_mode_MAN_TOGA;
} else if ((rtb_status == athr_status_ENGAGED_ARMED) && rtb_y_cs && (rtb_Switch_i_tmp == 35.0)) {
Autothrust_DWork.pMode = athr_mode_MAN_FLEX;
} else if ((rtb_status == athr_status_ENGAGED_ARMED) && ((Autothrust_U.in.input.TLA_1_deg == 35.0) ||
(Autothrust_U.in.input.TLA_2_deg == 35.0))) {
Autothrust_DWork.pMode = athr_mode_MAN_MCT;
} else {
ATHR_PB_tmp = (Autothrust_U.in.data.is_engine_operative_1 && (!Autothrust_U.in.data.is_engine_operative_2));
flightDirectorOffTakeOff_tmp = (Autothrust_U.in.data.is_engine_operative_2 &&
(!Autothrust_U.in.data.is_engine_operative_1));
if ((rtb_status == athr_status_ENGAGED_ACTIVE) && (Autothrust_U.in.input.mode_requested == 3.0) && ((ATHR_PB_tmp &&
(Autothrust_U.in.input.TLA_1_deg == 35.0) && (Autothrust_U.in.input.TLA_2_deg <= 35.0)) ||
(flightDirectorOffTakeOff_tmp && (Autothrust_U.in.input.TLA_2_deg == 35.0) && (Autothrust_U.in.input.TLA_1_deg <=
35.0)))) {
Autothrust_DWork.pMode = athr_mode_THR_MCT;
} else if ((rtb_status == athr_status_ENGAGED_ACTIVE) && (Autothrust_U.in.input.mode_requested == 3.0) &&
Autothrust_U.in.data.is_engine_operative_1 && Autothrust_U.in.data.is_engine_operative_2 &&
(rtb_Switch_i_tmp == 25.0)) {
Autothrust_DWork.pMode = athr_mode_THR_CLB;
} else {
condition_AP_FD_ATHR_Specific = (Autothrust_U.in.data.is_engine_operative_1 &&
Autothrust_U.in.data.is_engine_operative_2);
if ((rtb_status == athr_status_ENGAGED_ACTIVE) && (Autothrust_U.in.input.mode_requested == 3.0) &&
((condition_AP_FD_ATHR_Specific && (Autothrust_U.in.input.TLA_1_deg < 25.0) &&
(Autothrust_U.in.input.TLA_2_deg < 25.0)) || (ATHR_PB_tmp && (Autothrust_U.in.input.TLA_1_deg < 35.0)) ||
(flightDirectorOffTakeOff_tmp && (Autothrust_U.in.input.TLA_2_deg < 35.0)))) {
Autothrust_DWork.pMode = athr_mode_THR_LVR;
} else if ((rtb_status == athr_status_ENGAGED_ARMED) && ((condition_AP_FD_ATHR_Specific && (rtb_Switch_i_tmp >
25.0) && (rtb_Switch_i_tmp < 35.0)) || ((rtb_Switch_i_tmp > 35.0) && (rtb_Switch_i_tmp < 45.0)))) {
Autothrust_DWork.pMode = athr_mode_MAN_THR;
} else if ((rtb_status == athr_status_ENGAGED_ACTIVE) && (Autothrust_U.in.input.mode_requested == 2.0)) {
Autothrust_DWork.pMode = athr_mode_THR_IDLE;
} else if ((rtb_status == athr_status_ENGAGED_ACTIVE) && (Autothrust_U.in.input.mode_requested == 1.0) &&
(!Autothrust_U.in.input.is_mach_mode_active)) {
Autothrust_DWork.pMode = athr_mode_SPEED;
} else {
if ((rtb_status == athr_status_ENGAGED_ACTIVE) && (Autothrust_U.in.input.mode_requested == 1.0) &&
Autothrust_U.in.input.is_mach_mode_active) {
Autothrust_DWork.pMode = athr_mode_MACH;
}
}
}
}
Autothrust_DWork.inhibitAboveThrustReductionAltitude = ((Autothrust_U.in.input.is_SRS_TO_mode_active &&
(!Autothrust_DWork.was_SRS_TO_active) && (Autothrust_U.in.data.H_ind_ft >
Autothrust_U.in.input.thrust_reduction_altitude)) || (Autothrust_U.in.input.is_SRS_GA_mode_active &&
(!Autothrust_DWork.was_SRS_GA_active) && (Autothrust_U.in.data.H_ind_ft >
Autothrust_U.in.input.thrust_reduction_altitude_go_around)) || ((Autothrust_U.in.input.is_SRS_TO_mode_active ||
Autothrust_U.in.input.is_SRS_GA_mode_active) && Autothrust_DWork.inhibitAboveThrustReductionAltitude));
flightDirectorOffTakeOff_tmp = !Autothrust_U.in.data.is_engine_operative_1;
condition_AP_FD_ATHR_Specific = !Autothrust_U.in.data.is_engine_operative_2;
ATHR_PB_tmp = (Autothrust_U.in.data.is_engine_operative_1 && Autothrust_U.in.data.is_engine_operative_2);
ATHR_PB = (Autothrust_U.in.data.is_engine_operative_1 && condition_AP_FD_ATHR_Specific);
condition_TOGA = (Autothrust_U.in.data.is_engine_operative_2 && flightDirectorOffTakeOff_tmp);
Autothrust_DWork.condition_THR_LK = (((rtb_status == athr_status_DISENGAGED) && (Autothrust_DWork.pStatus !=
athr_status_DISENGAGED) && rtb_NOT && ((ATHR_PB_tmp && (Autothrust_U.in.input.TLA_1_deg == 25.0) &&
(Autothrust_U.in.input.TLA_2_deg == 25.0)) || (ATHR_PB && (Autothrust_U.in.input.TLA_1_deg == 35.0) &&
(Autothrust_U.in.input.TLA_2_deg <= 35.0)) || (condition_TOGA && (Autothrust_U.in.input.TLA_2_deg == 35.0) &&
(Autothrust_U.in.input.TLA_1_deg <= 35.0)))) || (((!Autothrust_DWork.condition_THR_LK) || ((!(rtb_status !=
athr_status_DISENGAGED)) && ((Autothrust_U.in.input.TLA_1_deg == 25.0) || (Autothrust_U.in.input.TLA_2_deg == 25.0) ||
(Autothrust_U.in.input.TLA_1_deg == 35.0) || (Autothrust_U.in.input.TLA_2_deg == 35.0)))) &&
Autothrust_DWork.condition_THR_LK));
Autothrust_DWork.pStatus = rtb_status;
Autothrust_DWork.was_SRS_TO_active = Autothrust_U.in.input.is_SRS_TO_mode_active;
Autothrust_DWork.was_SRS_GA_active = Autothrust_U.in.input.is_SRS_GA_mode_active;
if ((rtb_on_ground == 0) || (flightDirectorOffTakeOff_tmp && condition_AP_FD_ATHR_Specific)) {
if ((Autothrust_DWork.pMode == athr_mode_A_FLOOR) || (Autothrust_DWork.pMode == athr_mode_TOGA_LK)) {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_TOGA;
Autothrust_Y.out.output.thrust_limit_percent = rtb_Switch1_k;
} else if (rtb_Switch_i_tmp > 35.0) {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_TOGA;
Autothrust_Y.out.output.thrust_limit_percent = rtb_Switch1_k;
} else if (rtb_Switch_i_tmp > 25.0) {
if (!rtb_y_cs) {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_MCT;
Autothrust_Y.out.output.thrust_limit_percent = rtb_y_a;
} else {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_FLEX;
Autothrust_Y.out.output.thrust_limit_percent = rtb_y_c;
}
} else if (rtb_Switch_i_tmp >= 0.0) {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_CLB;
Autothrust_Y.out.output.thrust_limit_percent = rtb_Sum_g;
} else if (rtb_Switch_i_tmp < 0.0) {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_REVERSE;
Autothrust_Y.out.output.thrust_limit_percent = Autothrust_U.in.input.thrust_limit_REV_percent;
} else {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_NONE;
Autothrust_Y.out.output.thrust_limit_percent = 0.0;
}
} else if (rtb_Switch_i_tmp >= 0.0) {
if ((!rtb_y_cs) || (rtb_Switch_i_tmp > 35.0)) {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_TOGA;
Autothrust_Y.out.output.thrust_limit_percent = rtb_Switch1_k;
} else {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_FLEX;
Autothrust_Y.out.output.thrust_limit_percent = rtb_y_c;
}
} else if (rtb_Switch_i_tmp < 0.0) {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_REVERSE;
Autothrust_Y.out.output.thrust_limit_percent = Autothrust_U.in.input.thrust_limit_REV_percent;
} else {
Autothrust_Y.out.output.thrust_limit_type = athr_thrust_limit_type_NONE;
Autothrust_Y.out.output.thrust_limit_percent = 0.0;
}
rtb_Switch_i_tmp = rtb_Switch_dx;
rtb_Switch2_k = rtb_Switch_m;
ATHR_ENGAGED_tmp = ((rtb_status == athr_status_ENGAGED_ACTIVE) && (((Autothrust_U.in.input.TLA_1_deg <= 35.0) &&
(Autothrust_U.in.input.TLA_2_deg <= 35.0)) || Autothrust_U.in.input.alpha_floor_condition));
ATHR_ENGAGED_tmp_0 = !ATHR_ENGAGED_tmp;
Autothrust_DWork.pThrustMemoActive = ((((Autothrust_U.in.input.ATHR_push && (rtb_status != athr_status_DISENGAGED)) ||
(ATHR_ENGAGED_tmp_0 && Autothrust_DWork.pUseAutoThrustControl && rtb_NOT)) && ((ATHR_PB_tmp &&
(Autothrust_U.in.input.TLA_1_deg == 25.0) && (Autothrust_U.in.input.TLA_2_deg == 25.0)) || (ATHR_PB &&
(Autothrust_U.in.input.TLA_1_deg == 35.0) && (Autothrust_U.in.input.TLA_2_deg <= 35.0)) || (condition_TOGA &&
(Autothrust_U.in.input.TLA_2_deg == 35.0) && (Autothrust_U.in.input.TLA_1_deg <= 35.0)))) || (ATHR_ENGAGED_tmp_0 &&
((Autothrust_U.in.input.TLA_1_deg == 25.0) || (Autothrust_U.in.input.TLA_1_deg == 35.0) ||
(Autothrust_U.in.input.TLA_2_deg == 25.0) || (Autothrust_U.in.input.TLA_2_deg == 35.0)) &&
Autothrust_DWork.pThrustMemoActive));
Autothrust_DWork.pUseAutoThrustControl = ATHR_ENGAGED_tmp;
rtb_NOT = ((!(rtb_status == Autothrust_P.CompareToConstant_const_d)) || ((Autothrust_DWork.pMode ==
Autothrust_P.CompareToConstant2_const_c) || (Autothrust_DWork.pMode == Autothrust_P.CompareToConstant3_const_k)));
if (Autothrust_U.in.data.is_engine_operative_1 && Autothrust_U.in.data.is_engine_operative_2) {
rtb_Switch_m = rtb_Sum_g;
} else {
rtb_Switch_m = rtb_y_a;
}
rtb_Switch_dx = Autothrust_P.Gain1_Gain_c * Autothrust_U.in.data.alpha_deg;
rtb_y_c = result[2] * std::sin(rtb_Switch_dx);
rtb_Switch_dx = std::cos(rtb_Switch_dx);
rtb_Switch_dx *= result[0];
x[0] = Autothrust_U.in.input.V_LS_kn;
x[1] = Autothrust_U.in.input.V_c_kn;
x[2] = Autothrust_U.in.input.V_MAX_kn;
if (Autothrust_U.in.input.V_LS_kn < Autothrust_U.in.input.V_c_kn) {
if (Autothrust_U.in.input.V_c_kn < Autothrust_U.in.input.V_MAX_kn) {
i = 1;
} else if (Autothrust_U.in.input.V_LS_kn < Autothrust_U.in.input.V_MAX_kn) {
i = 2;
} else {
i = 0;
}
} else if (Autothrust_U.in.input.V_LS_kn < Autothrust_U.in.input.V_MAX_kn) {
i = 0;
} else if (Autothrust_U.in.input.V_c_kn < Autothrust_U.in.input.V_MAX_kn) {
i = 2;
} else {
i = 1;
}
rtb_y_a = x[i] - Autothrust_U.in.data.V_ias_kn;
rtb_Switch_dx = (rtb_y_c + rtb_Switch_dx) * Autothrust_P.Gain_Gain_h * Autothrust_P.Gain_Gain_b * look1_binlxpw(
static_cast<real_T>(Autothrust_U.in.input.is_approach_mode_active),
Autothrust_P.ScheduledGain2_BreakpointsForDimension1, Autothrust_P.ScheduledGain2_Table, 1U) + rtb_y_a;
rtb_Gain_f = Autothrust_P.DiscreteDerivativeVariableTs_Gain * rtb_Switch_dx;
rtb_y_c = (rtb_Gain_f - Autothrust_DWork.Delay_DSTATE) / Autothrust_U.in.time.dt;
if ((!Autothrust_DWork.pY_not_empty) || (!Autothrust_DWork.pU_not_empty)) {
Autothrust_DWork.pU = rtb_y_c;
Autothrust_DWork.pU_not_empty = true;
Autothrust_DWork.pY = rtb_y_c;
Autothrust_DWork.pY_not_empty = true;
}
rtb_Switch_f_idx_0 = Autothrust_U.in.time.dt * Autothrust_P.LagFilter_C1;
ca = rtb_Switch_f_idx_0 / (rtb_Switch_f_idx_0 + 2.0);
Autothrust_DWork.pY = (2.0 - rtb_Switch_f_idx_0) / (rtb_Switch_f_idx_0 + 2.0) * Autothrust_DWork.pY + (rtb_y_c * ca +
Autothrust_DWork.pU * ca);
Autothrust_DWork.pU = rtb_y_c;
if (!Autothrust_DWork.eventTime_not_empty) {
Autothrust_DWork.eventTime = Autothrust_U.in.time.simulation_time;
Autothrust_DWork.eventTime_not_empty = true;
}
rtb_y_c = std::abs(rtb_y_a);
if (rtb_y_c > 5.0) {
Autothrust_DWork.eventTime = Autothrust_U.in.time.simulation_time;
} else {
if (Autothrust_DWork.eventTime == 0.0) {
Autothrust_DWork.eventTime = Autothrust_U.in.time.simulation_time;
}
}
if (Autothrust_U.in.input.mode_requested > Autothrust_P.Saturation_UpperSat_l) {
rtb_Switch_f_idx_0 = Autothrust_P.Saturation_UpperSat_l;
} else if (Autothrust_U.in.input.mode_requested < Autothrust_P.Saturation_LowerSat_i) {
rtb_Switch_f_idx_0 = Autothrust_P.Saturation_LowerSat_i;
} else {
rtb_Switch_f_idx_0 = Autothrust_U.in.input.mode_requested;
}
switch (static_cast<int32_T>(rtb_Switch_f_idx_0)) {
case 0:
rtb_Switch_dx = Autothrust_P.Constant1_Value;
break;
case 1:
if (10.0 < rtb_y_c) {
rtb_y_c = 10.0;
}
rtb_Switch_f_idx_0 = Autothrust_U.in.time.simulation_time - Autothrust_DWork.eventTime;
if (0.0 > rtb_Switch_f_idx_0) {
rtb_Switch_f_idx_0 = 0.0;
}
if (1.0 > rtb_y_c) {
rtb_y_c = 1.0;
}
if (15.0 < rtb_Switch_f_idx_0) {
rtb_Switch_f_idx_0 = 15.0;
}
rtb_Switch_dx = ((1.0 - (rtb_y_c - 1.0) * 0.1111111111111111) * 0.5 * (0.066666666666666666 * rtb_Switch_f_idx_0) *
rtb_y_a + (Autothrust_DWork.pY * look1_binlxpw(static_cast<real_T>
(Autothrust_U.in.input.is_approach_mode_active), Autothrust_P.ScheduledGain1_BreakpointsForDimension1,
Autothrust_P.ScheduledGain1_Table, 1U) + rtb_Switch_dx * look1_binlxpw(static_cast<real_T>
(Autothrust_U.in.input.is_approach_mode_active), Autothrust_P.ScheduledGain_BreakpointsForDimension1,
Autothrust_P.ScheduledGain_Table, 1U))) * look1_binlxpw(static_cast<real_T>
(Autothrust_U.in.input.is_alt_soft_mode_active), Autothrust_P.ScheduledGain4_BreakpointsForDimension1,
Autothrust_P.ScheduledGain4_Table, 1U);
break;
case 2:
if (Phi_rad > Theta_rad) {
rtb_y_c = Phi_rad;
} else {
rtb_y_c = Theta_rad;
}
rtb_Switch_dx = (rtb_Sum_c - rtb_y_c) * Autothrust_P.Gain_Gain;
break;
default:
if (Phi_rad > Theta_rad) {
rtb_y_c = Phi_rad;
} else {
rtb_y_c = Theta_rad;
}
rtb_Switch_dx = (rtb_Sum_g - rtb_y_c) * Autothrust_P.Gain_Gain_m;
break;
}
rtb_Switch_dx *= Autothrust_P.DiscreteTimeIntegratorVariableTsLimit_Gain;
rtb_Switch_dx *= Autothrust_U.in.time.dt;
if (rtb_NOT) {
Autothrust_DWork.icLoad = 1U;
}
if (Autothrust_DWork.icLoad != 0) {
if (Phi_rad > Theta_rad) {
rtb_y_c = Phi_rad;
} else {
rtb_y_c = Theta_rad;
}
Autothrust_DWork.Delay_DSTATE_k = rtb_y_c - rtb_Switch_dx;
}
Autothrust_DWork.Delay_DSTATE_k += rtb_Switch_dx;
if (Autothrust_DWork.Delay_DSTATE_k > rtb_Switch_m) {
Autothrust_DWork.Delay_DSTATE_k = rtb_Switch_m;
} else {
if (Autothrust_DWork.Delay_DSTATE_k < rtb_Sum_c) {
Autothrust_DWork.Delay_DSTATE_k = rtb_Sum_c;
}
}
if (rtb_NOT) {
Autothrust_DWork.icLoad_c = 1U;
}
if (Autothrust_DWork.icLoad_c != 0) {
Autothrust_DWork.Delay_DSTATE_j = Autothrust_DWork.Delay_DSTATE_k;
}
rtb_Switch_m = Autothrust_DWork.Delay_DSTATE_k - Autothrust_DWork.Delay_DSTATE_j;
rtb_y_c = Autothrust_P.Constant2_Value * Autothrust_U.in.time.dt;
if (rtb_Switch_m < rtb_y_c) {
rtb_y_c = rtb_Switch_m;
}
rtb_Switch_f_idx_0 = Autothrust_U.in.time.dt * Autothrust_P.Constant3_Value;
if (rtb_y_c > rtb_Switch_f_idx_0) {
rtb_Switch_f_idx_0 = rtb_y_c;
}
Autothrust_DWork.Delay_DSTATE_j += rtb_Switch_f_idx_0;
if (Autothrust_DWork.pUseAutoThrustControl) {
if ((Autothrust_DWork.pMode == Autothrust_P.CompareToConstant2_const_h) || (Autothrust_DWork.pMode ==
Autothrust_P.CompareToConstant3_const)) {
if (rtb_Switch1_k < rtb_Switch_i_tmp) {
rtb_Switch_f_idx_0 = rtb_Switch_i_tmp;
} else {
rtb_Switch_f_idx_0 = rtb_Switch1_k;
}
if (rtb_Switch1_k < rtb_Switch2_k) {
ca = rtb_Switch2_k;
} else {
ca = rtb_Switch1_k;
}
} else {
if (Autothrust_DWork.Delay_DSTATE_j > rtb_Switch_i_tmp) {
rtb_Switch_f_idx_0 = rtb_Switch_i_tmp;
} else if (Autothrust_DWork.Delay_DSTATE_j < rtb_Sum_c) {
rtb_Switch_f_idx_0 = rtb_Sum_c;
} else {
rtb_Switch_f_idx_0 = Autothrust_DWork.Delay_DSTATE_j;
}
if (Autothrust_DWork.Delay_DSTATE_j > rtb_Switch2_k) {
ca = rtb_Switch2_k;
} else if (Autothrust_DWork.Delay_DSTATE_j < rtb_Sum_c) {
ca = rtb_Sum_c;
} else {
ca = Autothrust_DWork.Delay_DSTATE_j;
}
}
} else if (Autothrust_DWork.pThrustMemoActive) {
rtb_Switch_f_idx_0 = Phi_rad;
ca = Theta_rad;
} else {
rtb_Switch_f_idx_0 = rtb_Switch_i_tmp;
ca = rtb_Switch2_k;
}
rtb_Switch_m = rtb_Switch_f_idx_0 - Phi_rad;
if (rtb_Compare_e) {
Autothrust_DWork.Delay_DSTATE_n = Autothrust_P.DiscreteTimeIntegratorVariableTs_InitialCondition;
}
Autothrust_DWork.Delay_DSTATE_n += Autothrust_P.Gain_Gain_d * rtb_Switch_m *
Autothrust_P.DiscreteTimeIntegratorVariableTs_Gain * Autothrust_U.in.time.dt;
if (Autothrust_DWork.Delay_DSTATE_n > Autothrust_P.DiscreteTimeIntegratorVariableTs_UpperLimit) {
Autothrust_DWork.Delay_DSTATE_n = Autothrust_P.DiscreteTimeIntegratorVariableTs_UpperLimit;
} else {
if (Autothrust_DWork.Delay_DSTATE_n < Autothrust_P.DiscreteTimeIntegratorVariableTs_LowerLimit) {
Autothrust_DWork.Delay_DSTATE_n = Autothrust_P.DiscreteTimeIntegratorVariableTs_LowerLimit;
}
}
if (!rtb_Compare_e) {
Autothrust_DWork.Delay_DSTATE_l = Autothrust_P.DiscreteTimeIntegratorVariableTs1_InitialCondition;
}
Autothrust_DWork.Delay_DSTATE_l += Autothrust_P.Gain1_Gain_h * rtb_Switch_m *
Autothrust_P.DiscreteTimeIntegratorVariableTs1_Gain * Autothrust_U.in.time.dt;
if (Autothrust_DWork.Delay_DSTATE_l > Autothrust_P.DiscreteTimeIntegratorVariableTs1_UpperLimit) {
Autothrust_DWork.Delay_DSTATE_l = Autothrust_P.DiscreteTimeIntegratorVariableTs1_UpperLimit;
} else {
if (Autothrust_DWork.Delay_DSTATE_l < Autothrust_P.DiscreteTimeIntegratorVariableTs1_LowerLimit) {
Autothrust_DWork.Delay_DSTATE_l = Autothrust_P.DiscreteTimeIntegratorVariableTs1_LowerLimit;
}
}
Autothrust_ThrustMode1(Autothrust_U.in.input.TLA_1_deg, &rtb_y_a);
rtb_Switch_dx = ca - Theta_rad;
if (rtb_NOT1_m) {
Autothrust_DWork.Delay_DSTATE_lz = Autothrust_P.DiscreteTimeIntegratorVariableTs_InitialCondition_n;
}
rtb_y_c = Autothrust_P.Gain_Gain_bf * rtb_Switch_dx * Autothrust_P.DiscreteTimeIntegratorVariableTs_Gain_k *
Autothrust_U.in.time.dt + Autothrust_DWork.Delay_DSTATE_lz;
if (rtb_y_c > Autothrust_P.DiscreteTimeIntegratorVariableTs_UpperLimit_p) {
Autothrust_DWork.Delay_DSTATE_lz = Autothrust_P.DiscreteTimeIntegratorVariableTs_UpperLimit_p;
} else if (rtb_y_c < Autothrust_P.DiscreteTimeIntegratorVariableTs_LowerLimit_e) {
Autothrust_DWork.Delay_DSTATE_lz = Autothrust_P.DiscreteTimeIntegratorVariableTs_LowerLimit_e;
} else {
Autothrust_DWork.Delay_DSTATE_lz = rtb_y_c;
}
if (!rtb_NOT1_m) {
Autothrust_DWork.Delay_DSTATE_h = Autothrust_P.DiscreteTimeIntegratorVariableTs1_InitialCondition_e;
}
Autothrust_DWork.Delay_DSTATE_h += Autothrust_P.Gain1_Gain_g * rtb_Switch_dx *
Autothrust_P.DiscreteTimeIntegratorVariableTs1_Gain_l * Autothrust_U.in.time.dt;
if (Autothrust_DWork.Delay_DSTATE_h > Autothrust_P.DiscreteTimeIntegratorVariableTs1_UpperLimit_o) {
Autothrust_DWork.Delay_DSTATE_h = Autothrust_P.DiscreteTimeIntegratorVariableTs1_UpperLimit_o;
} else {
if (Autothrust_DWork.Delay_DSTATE_h < Autothrust_P.DiscreteTimeIntegratorVariableTs1_LowerLimit_h) {
Autothrust_DWork.Delay_DSTATE_h = Autothrust_P.DiscreteTimeIntegratorVariableTs1_LowerLimit_h;
}
}
Autothrust_ThrustMode1(Autothrust_U.in.input.TLA_2_deg, &rtb_y_c);
Autothrust_Y.out.time = Autothrust_U.in.time;
Autothrust_Y.out.data.nz_g = Autothrust_U.in.data.nz_g;
Autothrust_Y.out.data.Theta_deg = rtb_Gain2;
Autothrust_Y.out.data.Phi_deg = rtb_Gain3;
Autothrust_Y.out.data.V_ias_kn = Autothrust_U.in.data.V_ias_kn;
Autothrust_Y.out.data.V_tas_kn = Autothrust_U.in.data.V_tas_kn;
Autothrust_Y.out.data.V_mach = Autothrust_U.in.data.V_mach;
Autothrust_Y.out.data.V_gnd_kn = Autothrust_U.in.data.V_gnd_kn;
Autothrust_Y.out.data.alpha_deg = Autothrust_U.in.data.alpha_deg;
Autothrust_Y.out.data.H_ft = Autothrust_U.in.data.H_ft;
Autothrust_Y.out.data.H_ind_ft = Autothrust_U.in.data.H_ind_ft;
Autothrust_Y.out.data.H_radio_ft = Autothrust_U.in.data.H_radio_ft;
Autothrust_Y.out.data.H_dot_fpm = Autothrust_U.in.data.H_dot_fpm;
Autothrust_Y.out.data.ax_m_s2 = result[0];
Autothrust_Y.out.data.ay_m_s2 = result[1];
Autothrust_Y.out.data.az_m_s2 = result[2];
Autothrust_Y.out.data.bx_m_s2 = Autothrust_U.in.data.bx_m_s2;
Autothrust_Y.out.data.by_m_s2 = Autothrust_U.in.data.by_m_s2;
Autothrust_Y.out.data.bz_m_s2 = Autothrust_U.in.data.bz_m_s2;
Autothrust_Y.out.data.on_ground = (rtb_on_ground != 0);
Autothrust_Y.out.data.flap_handle_index = Autothrust_U.in.data.flap_handle_index;
Autothrust_Y.out.data.is_engine_operative_1 = Autothrust_U.in.data.is_engine_operative_1;
Autothrust_Y.out.data.is_engine_operative_2 = Autothrust_U.in.data.is_engine_operative_2;
Autothrust_Y.out.data.commanded_engine_N1_1_percent = Phi_rad;
Autothrust_Y.out.data.commanded_engine_N1_2_percent = Theta_rad;
Autothrust_Y.out.data.engine_N1_1_percent = Autothrust_U.in.data.engine_N1_1_percent;
Autothrust_Y.out.data.engine_N1_2_percent = Autothrust_U.in.data.engine_N1_2_percent;
Autothrust_Y.out.data.TAT_degC = Autothrust_U.in.data.TAT_degC;
Autothrust_Y.out.data.OAT_degC = Autothrust_U.in.data.OAT_degC;
Autothrust_Y.out.data.ISA_degC = rtb_Saturation;
Autothrust_Y.out.data_computed.TLA_in_active_range = rtb_out;
Autothrust_Y.out.data_computed.is_FLX_active = rtb_y_cs;
Autothrust_Y.out.data_computed.ATHR_push = rtb_BusAssignment_n.data_computed.ATHR_push;
Autothrust_Y.out.data_computed.ATHR_disabled = Autothrust_DWork.Memory_PreviousInput;
Autothrust_Y.out.data_computed.time_since_touchdown = rtb_BusAssignment_n.data_computed.time_since_touchdown;
Autothrust_Y.out.input.ATHR_push = Autothrust_U.in.input.ATHR_push;
Autothrust_Y.out.input.ATHR_disconnect = Autothrust_U.in.input.ATHR_disconnect;
Autothrust_Y.out.input.TLA_1_deg = Autothrust_U.in.input.TLA_1_deg;
Autothrust_Y.out.input.TLA_2_deg = Autothrust_U.in.input.TLA_2_deg;
Autothrust_Y.out.input.V_c_kn = Autothrust_U.in.input.V_c_kn;
Autothrust_Y.out.input.V_LS_kn = Autothrust_U.in.input.V_LS_kn;
Autothrust_Y.out.input.V_MAX_kn = Autothrust_U.in.input.V_MAX_kn;
Autothrust_Y.out.input.thrust_limit_REV_percent = Autothrust_U.in.input.thrust_limit_REV_percent;
Autothrust_Y.out.input.thrust_limit_IDLE_percent = rtb_Sum_c;
Autothrust_Y.out.input.thrust_limit_CLB_percent = rtb_Sum_g;
Autothrust_Y.out.input.thrust_limit_MCT_percent = rtb_BusAssignment_n.input.thrust_limit_MCT_percent;
Autothrust_Y.out.input.thrust_limit_FLEX_percent = rtb_BusAssignment_n.input.thrust_limit_FLEX_percent;
Autothrust_Y.out.input.thrust_limit_TOGA_percent = rtb_Switch1_k;
Autothrust_Y.out.input.flex_temperature_degC = Autothrust_U.in.input.flex_temperature_degC;
Autothrust_Y.out.input.mode_requested = Autothrust_U.in.input.mode_requested;
Autothrust_Y.out.input.is_mach_mode_active = Autothrust_U.in.input.is_mach_mode_active;
Autothrust_Y.out.input.alpha_floor_condition = Autothrust_U.in.input.alpha_floor_condition;
Autothrust_Y.out.input.is_approach_mode_active = Autothrust_U.in.input.is_approach_mode_active;
Autothrust_Y.out.input.is_SRS_TO_mode_active = Autothrust_U.in.input.is_SRS_TO_mode_active;
Autothrust_Y.out.input.is_SRS_GA_mode_active = Autothrust_U.in.input.is_SRS_GA_mode_active;
Autothrust_Y.out.input.is_LAND_mode_active = Autothrust_U.in.input.is_LAND_mode_active;
Autothrust_Y.out.input.thrust_reduction_altitude = Autothrust_U.in.input.thrust_reduction_altitude;
Autothrust_Y.out.input.thrust_reduction_altitude_go_around = Autothrust_U.in.input.thrust_reduction_altitude_go_around;
Autothrust_Y.out.input.flight_phase = Autothrust_U.in.input.flight_phase;
Autothrust_Y.out.input.is_alt_soft_mode_active = Autothrust_U.in.input.is_alt_soft_mode_active;
Autothrust_Y.out.input.is_anti_ice_wing_active = Autothrust_U.in.input.is_anti_ice_wing_active;
Autothrust_Y.out.input.is_anti_ice_engine_1_active = Autothrust_U.in.input.is_anti_ice_engine_1_active;
Autothrust_Y.out.input.is_anti_ice_engine_2_active = Autothrust_U.in.input.is_anti_ice_engine_2_active;
Autothrust_Y.out.input.is_air_conditioning_1_active = Autothrust_U.in.input.is_air_conditioning_1_active;
Autothrust_Y.out.input.is_air_conditioning_2_active = Autothrust_U.in.input.is_air_conditioning_2_active;
Autothrust_Y.out.input.FD_active = Autothrust_U.in.input.FD_active;
if (!rtb_Compare_e) {
Autothrust_Y.out.output.sim_throttle_lever_1_pos = Autothrust_DWork.Delay_DSTATE_n;
} else {
Autothrust_Y.out.output.sim_throttle_lever_1_pos = Autothrust_DWork.Delay_DSTATE_l;
}
if (!rtb_NOT1_m) {
Autothrust_Y.out.output.sim_throttle_lever_2_pos = Autothrust_DWork.Delay_DSTATE_lz;
} else {
Autothrust_Y.out.output.sim_throttle_lever_2_pos = Autothrust_DWork.Delay_DSTATE_h;
}
Autothrust_Y.out.output.sim_thrust_mode_1 = rtb_y_a;
Autothrust_Y.out.output.sim_thrust_mode_2 = rtb_y_c;
Autothrust_Y.out.output.N1_TLA_1_percent = rtb_Switch_i_tmp;
Autothrust_Y.out.output.N1_TLA_2_percent = rtb_Switch2_k;
Autothrust_Y.out.output.is_in_reverse_1 = rtb_Compare_e;
Autothrust_Y.out.output.is_in_reverse_2 = rtb_NOT1_m;
Autothrust_Y.out.output.N1_c_1_percent = rtb_Switch_f_idx_0;
Autothrust_Y.out.output.N1_c_2_percent = ca;
Autothrust_Y.out.output.status = rtb_status;
Autothrust_Y.out.output.mode = Autothrust_DWork.pMode;
ATHR_PB_tmp = (((!Autothrust_U.in.input.is_SRS_TO_mode_active) || ((Autothrust_U.in.data.H_ind_ft >=
Autothrust_U.in.input.thrust_reduction_altitude) && (!Autothrust_DWork.inhibitAboveThrustReductionAltitude))) &&
((!Autothrust_U.in.input.is_SRS_GA_mode_active) || ((Autothrust_U.in.data.H_ind_ft >=
Autothrust_U.in.input.thrust_reduction_altitude_go_around) && (!Autothrust_DWork.inhibitAboveThrustReductionAltitude))));
if ((rtb_status != athr_status_DISENGAGED) && (Autothrust_DWork.pMode != athr_mode_A_FLOOR) && (Autothrust_DWork.pMode
!= athr_mode_TOGA_LK) && (rtb_on_ground == 0) && ATHR_PB_tmp && Autothrust_U.in.data.is_engine_operative_1 &&
Autothrust_U.in.data.is_engine_operative_2 && (((Autothrust_U.in.input.TLA_1_deg < 25.0) &&
(Autothrust_U.in.input.TLA_2_deg < 25.0)) || (Autothrust_U.in.input.TLA_1_deg > 25.0) ||
(Autothrust_U.in.input.TLA_2_deg > 25.0))) {
Autothrust_Y.out.output.mode_message = athr_mode_message_LVR_CLB;
} else if ((rtb_status != athr_status_DISENGAGED) && (Autothrust_DWork.pMode != athr_mode_A_FLOOR) &&
(Autothrust_DWork.pMode != athr_mode_TOGA_LK) && (rtb_on_ground == 0) && ATHR_PB_tmp &&
(flightDirectorOffTakeOff_tmp || condition_AP_FD_ATHR_Specific) && (Autothrust_U.in.input.TLA_1_deg != 35.0)
&& (Autothrust_U.in.input.TLA_2_deg != 35.0)) {
Autothrust_Y.out.output.mode_message = athr_mode_message_LVR_MCT;
} else if ((rtb_status == athr_status_ENGAGED_ACTIVE) && Autothrust_U.in.data.is_engine_operative_1 &&
Autothrust_U.in.data.is_engine_operative_2 && (((Autothrust_U.in.input.TLA_1_deg == 25.0) &&
(Autothrust_U.in.input.TLA_2_deg != 25.0)) || ((Autothrust_U.in.input.TLA_2_deg == 25.0) &&
(Autothrust_U.in.input.TLA_1_deg != 25.0)))) {
Autothrust_Y.out.output.mode_message = athr_mode_message_LVR_ASYM;
} else if (Autothrust_DWork.condition_THR_LK) {
Autothrust_Y.out.output.mode_message = athr_mode_message_THR_LK;
} else {
Autothrust_Y.out.output.mode_message = athr_mode_message_NONE;
}
Autothrust_DWork.Delay_DSTATE = rtb_Gain_f;
Autothrust_DWork.icLoad = 0U;
Autothrust_DWork.icLoad_c = 0U;
}
void AutothrustModelClass::initialize()
{
Autothrust_DWork.Memory_PreviousInput = Autothrust_P.SRFlipFlop_initial_condition;
Autothrust_DWork.Delay_DSTATE_a = Autothrust_P.Delay_InitialCondition;
Autothrust_DWork.Memory_PreviousInput_m = Autothrust_P.SRFlipFlop_initial_condition_g;
Autothrust_DWork.Delay_DSTATE = Autothrust_P.DiscreteDerivativeVariableTs_InitialCondition;
Autothrust_DWork.icLoad = 1U;
Autothrust_DWork.icLoad_c = 1U;
Autothrust_DWork.Delay_DSTATE_n = Autothrust_P.DiscreteTimeIntegratorVariableTs_InitialCondition;
Autothrust_DWork.Delay_DSTATE_l = Autothrust_P.DiscreteTimeIntegratorVariableTs1_InitialCondition;
Autothrust_DWork.Delay_DSTATE_lz = Autothrust_P.DiscreteTimeIntegratorVariableTs_InitialCondition_n;
Autothrust_DWork.Delay_DSTATE_h = Autothrust_P.DiscreteTimeIntegratorVariableTs1_InitialCondition_e;
Autothrust_DWork.pMode = athr_mode_NONE;
Autothrust_DWork.pStatus = athr_status_DISENGAGED;
}
void AutothrustModelClass::terminate()
{
}
AutothrustModelClass::AutothrustModelClass() :
Autothrust_DWork(),
Autothrust_U(),
Autothrust_Y()
{
}
AutothrustModelClass::~AutothrustModelClass()
{
}
| [
"noreply@github.com"
] | noreply@github.com |
fcaf35314c77d911cd3a730a292c08f732621e6b | a70717537de46baab92d52e817fb626c18c1f9d1 | /Sobol_Lab_2.1/BTree.h | c3e52b4338edaf86881730f8b4bf3fab8aceb8bb | [] | no_license | kasobol/Lab_2_sem_3 | e361661f19611938b0c8a593502182807db57a4b | 6c7521a5284ba7a98f9b6207109c1484f8947b80 | refs/heads/master | 2023-03-03T00:46:14.100215 | 2021-02-08T08:00:06 | 2021-02-08T08:00:06 | 337,000,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,764 | h | #pragma once
#include <exception>
#include "BPrint.h"
#include "Dictionary.h"
using namespace std;
template<class TKey, class TValue>
class BTree : public Dictionary<TKey, TValue>
{
private:
struct SuperNode;
struct Node;
struct List
{
List(SuperNode* data, List* next)
{
this->data = data;
this->next = next;
}
SuperNode* data;
List* next;
};
public:
struct Node
{
Node(TKey Key, TValue Value, SuperNode* LeftSuperNode, SuperNode* RightSuperNode)
{
this->Key = Key;
this->Value = Value;
this->LeftSuperNode = LeftSuperNode;
this->RightSuperNode = RightSuperNode;
}
TKey Key;
TValue Value;
SuperNode* LeftSuperNode;
SuperNode* RightSuperNode;
};
struct SuperNode
{
SuperNode(int full_size)
{
real_size = 0;
this->full_size = full_size;
Nodes = new Node*[full_size];
}
SuperNode(SuperNode* CopySuperNode, int start, int end)
{
real_size = end - start + 1;
full_size = CopySuperNode->full_size;
Nodes = new Node*[full_size];
for (int i = start, k = 0; i <= end; i++, k++)
{
Nodes[k] = CopySuperNode->Nodes[i];
}
}
void For_All_OutNodes_Change_Prev()
{
if (Nodes[0]->LeftSuperNode != nullptr)
{
Nodes[0]->LeftSuperNode->PrevSuperNode = this;
Nodes[0]->LeftSuperNode->prev_number_node = 0;
for (int i = 0; i < real_size; i++)
{
Nodes[i]->RightSuperNode->PrevSuperNode = this;
Nodes[i]->RightSuperNode->prev_number_node = i + 1;
}
}
}
void Displacement(int start, int end)
{
for (int i = end; i >= start; i--)
{
Nodes[i + 1] = Nodes[i];
}
}
int GetPlace(TKey key)
{
int start_binary_search = 0;
int end_binary_search = real_size - 1;
int tmp;
while (end_binary_search - start_binary_search != -1)
{
tmp = (start_binary_search + end_binary_search) / 2;
if (key < Nodes[tmp]->Key)
{
end_binary_search = tmp - 1;
}
else
{
start_binary_search = tmp + 1;
}
}
return start_binary_search;
}
void Add(Node* add_node)
{
int insert_place = GetPlace(add_node->Key);
Displacement(insert_place, real_size - 1);
Nodes[insert_place] = add_node;
real_size++;
}
void Add(Node* add_node, int insert_place)
{
if (real_size != 0)
{
if (insert_place == 0)
{
Nodes[0]->LeftSuperNode = add_node->RightSuperNode;
}
else if (insert_place == real_size)
{
Nodes[real_size - 1]->RightSuperNode = add_node->LeftSuperNode;
}
else
{
Nodes[insert_place - 1]->RightSuperNode = add_node->LeftSuperNode;
Nodes[insert_place]->LeftSuperNode = add_node->RightSuperNode;
}
}
Displacement(insert_place, real_size - 1);
Nodes[insert_place] = add_node;
real_size++;
if (add_node->LeftSuperNode != nullptr)
{
Nodes[insert_place]->LeftSuperNode->prev_number_node = insert_place;
for (int i = insert_place; i < real_size; i++)
{
Nodes[i]->RightSuperNode->prev_number_node = i + 1;
}
}
}
string ShowStr()
{
string str = "";
for (int i = 0; i <= real_size - 1; i++)
{
str += to_string(Nodes[i]->Key) + "|";
}
str += "#";
return str;
}
int full_size;
int real_size;
Node** Nodes;
SuperNode* PrevSuperNode;
int prev_number_node;
~SuperNode()
{
}
};
SuperNode* superhead;
int number_tree;
int length;
btree* tree;
public:
BTree(int number_tree)
{
this->number_tree = number_tree;
length = 0;
superhead = nullptr;
tree = new btree(number_tree);
}
BTree(int number_tree, string str)
{
this->number_tree = number_tree;
length = 0;
superhead = nullptr;
tree = new btree(number_tree);
TKey add_key;
for (int i = 0, j = 0; i < (int)str.length(); i++)
{
if (str[i] == '|')
{
TKey add_key_1;
string key = str.substr(j, i - j);
stringstream ss(key);
ss >> add_key_1;
add_key = add_key_1;
j = i + 1;
}
else if (str[i] == '#')
{
TValue add_value;
string value = str.substr(j, i - j);
stringstream ss(value);
ss >> add_value;
j = i + 1;
Add(add_key, add_value);
}
}
}
int GetCount() override
{
return length;
}
int GetCapacity()
{
return 999999999;
}
bool ContainsKey(TKey key) override
{
try
{
Get(key);
}
catch (exception)
{
return false;
}
return true;
}
void Print() override
{
tree->show();
}
TValue Get1(TKey key) override
{
auto k = Get(key);
return k->Value;
}
Node* Get(TKey key)
{
if (superhead == nullptr)
{
throw exception("The Dictionary is empty");
}
SuperNode* super_tmp = superhead;
Node* tmp;
int place_tmp;
do
{
place_tmp = super_tmp->GetPlace(key);
if (place_tmp == 0)
{
tmp = super_tmp->Nodes[place_tmp];
}
else
{
tmp = super_tmp->Nodes[place_tmp - 1];
}
if (tmp->Key == key)
{
return tmp;
}
if (place_tmp <= 2 && super_tmp->real_size == place_tmp)
{
super_tmp = super_tmp->Nodes[place_tmp - 1]->RightSuperNode;
}
else if (place_tmp <= 2)
{
super_tmp = super_tmp->Nodes[place_tmp]->LeftSuperNode;
}
else if (super_tmp->Nodes[place_tmp - 1]->Key == super_tmp->Nodes[place_tmp - 2]->Key)
{
super_tmp = super_tmp->Nodes[place_tmp - 1]->LeftSuperNode;
}
else
{
super_tmp = super_tmp->Nodes[place_tmp - 1]->RightSuperNode;
}
} while (super_tmp != nullptr);
throw exception("Key is not exist");
}
public:
void Add(TKey key, TValue value) override
{
if (check)
{
tree->insert(key);
}
Node* add_node = new Node(key, value, nullptr, nullptr);
if (superhead == nullptr)
{
superhead = new SuperNode(number_tree - 1);
superhead->Add(add_node);
superhead->PrevSuperNode = nullptr;
length++;
}
else
{
SuperNode* super_tmp = superhead;
int place_tmp;
while (super_tmp->Nodes[0]->LeftSuperNode != nullptr)
{
place_tmp = super_tmp->GetPlace(key);
if (place_tmp == super_tmp->real_size)
{
super_tmp = super_tmp->Nodes[place_tmp - 1]->RightSuperNode;
}
else
{
super_tmp = super_tmp->Nodes[place_tmp]->LeftSuperNode;
}
}
place_tmp = super_tmp->GetPlace(key);
if (super_tmp->real_size != super_tmp->full_size)
{
super_tmp->Add(add_node);
length++;
}
else
{
int mean;
Node* tmp;
Node* help_tmp = add_node;
SuperNode* left_super;
SuperNode* right_super;
while (true)
{
mean = super_tmp->full_size / 2;
if (place_tmp < mean)
{
tmp = super_tmp->Nodes[mean - 1];
left_super = new SuperNode(super_tmp, 0, mean - 2);
right_super = new SuperNode(super_tmp, mean, super_tmp->full_size - 1);
left_super->Add(help_tmp, place_tmp);
}
else if (place_tmp > mean)
{
tmp = super_tmp->Nodes[mean];
left_super = new SuperNode(super_tmp, 0, mean - 1);
right_super = new SuperNode(super_tmp, mean + 1, super_tmp->full_size - 1);
right_super->Add(help_tmp, place_tmp - mean - 1);
}
else
{
tmp = help_tmp;
left_super = new SuperNode(super_tmp, 0, mean - 1);
right_super = new SuperNode(super_tmp, mean, super_tmp->full_size - 1);
if (tmp->LeftSuperNode != nullptr)
{
tmp->LeftSuperNode->prev_number_node = mean;
tmp->RightSuperNode->prev_number_node = 0;
for (int i = 0; i < right_super->real_size; i++)
{
right_super->Nodes[i]->RightSuperNode->prev_number_node = i + 1;
}
left_super->Nodes[mean - 1]->RightSuperNode = tmp->LeftSuperNode;
right_super->Nodes[0]->LeftSuperNode = tmp->RightSuperNode;
}
}
help_tmp = tmp;
tmp->LeftSuperNode = left_super;
tmp->RightSuperNode = right_super;
left_super->For_All_OutNodes_Change_Prev();
right_super->For_All_OutNodes_Change_Prev();
if (super_tmp->PrevSuperNode == nullptr)
{
delete superhead;
superhead = new SuperNode(number_tree - 1);
superhead->Add(help_tmp);
superhead->PrevSuperNode = nullptr;
left_super->PrevSuperNode = superhead;
right_super->PrevSuperNode = superhead;
left_super->prev_number_node = 0;
right_super->prev_number_node = 1;
length++;
return;
}
left_super->PrevSuperNode = super_tmp->PrevSuperNode;
right_super->PrevSuperNode = super_tmp->PrevSuperNode;
place_tmp = super_tmp->prev_number_node;
auto help = super_tmp;
super_tmp = super_tmp->PrevSuperNode;
delete help;
if (super_tmp->real_size != super_tmp->full_size)
{
super_tmp->Add(help_tmp, place_tmp);
length++;
return;
}
}
}
}
}
bool check = true;
void Remove(TKey key) override
{
check = false;
Node* remove_node = Get(key);
List* head = new List(superhead, nullptr);
List* res_head = head;
auto end_tmp = head->data;
int leng = 1;
while (true)
{
if (head == nullptr)
{
break;
}
if (head->data->Nodes[0]->LeftSuperNode == nullptr)
{
head = head->next;
continue;
}
Add1(head, head->data->Nodes[0]->LeftSuperNode);
for (int i = 0; i <= head->data->real_size - 1; i++)
{
Add1(head, head->data->Nodes[i]->RightSuperNode);
leng++;
}
head = head->next;
}
Node** Nodes = new Node*[length - 1];
auto tmp = res_head;
int i = 0;
while (tmp != nullptr)
{
for (int j = 0; j < tmp->data->real_size; j++)
{
if (tmp->data->Nodes[j] != remove_node)
{
Nodes[i] = tmp->data->Nodes[j];
i++;
}
}
tmp = tmp->next;
}
superhead = nullptr;
leng = length;
length = 0;
for (int i = 0; i < leng - 1; i++)
{
Add(Nodes[i]->Key, Nodes[i]->Value);
}
tmp = res_head;
while (tmp->next != nullptr)
{
auto help = tmp->next;
delete tmp;
tmp = help;
}
for (int i = 0; i < leng - 1; i++)
{
delete Nodes[i];
}
check = false;
tree->del(key);
}
void Change(TKey key, TValue value) override
{
Node* node = Get(key);
node->Value = value;
}
string Show()
{
string str = "";
List* head = new List(superhead, nullptr);
List* res_head = head;
auto end_tmp = head->data;
while (true)
{
str += head->data->ShowStr();
if (head->data == end_tmp)
{
/*cout << str << endl;
str = "";*/
end_tmp = head->data->Nodes[head->data->real_size - 1]->RightSuperNode;
if (end_tmp == nullptr)
{
break;
}
}
Add1(head, head->data->Nodes[0]->LeftSuperNode);
for (int i = 0; i <= head->data->real_size - 1; i++)
{
Add1(head, head->data->Nodes[i]->RightSuperNode);
}
head = head->next;
}
return str;
}
void Add1(List* head, SuperNode* str)
{
List* tmp = head;
while (tmp->next != nullptr)
{
tmp = tmp->next;
}
tmp->next = new List(str, nullptr);
}
};
//template<class TKey, class TValue>
//class BTree
//{
//public:
// struct SuperNode;
// struct List
// {
// List(SuperNode* data, List* next)
// {
// this->data = data;
// this->next = next;
// }
// SuperNode* data;
// List* next;
// };
// struct Node
// {
// Node(TKey Key, TValue Value, SuperNode* ActualSuperNode, SuperNode* LeftSuperNode, SuperNode* RightSuperNode)
// {
// this->Key = Key;
// this->Value = Value;
// this->ActualSuperNode = ActualSuperNode;
// this->LeftSuperNode = LeftSuperNode;
// this->RightSuperNode = RightSuperNode;
// }
// TKey Key;
// TValue Value;
// SuperNode* ActualSuperNode;
// SuperNode* LeftSuperNode;
// SuperNode* RightSuperNode;
// };
// struct SuperNode
// {
// SuperNode(int full_size, SuperNode* PrevSuperNode, int prev_number_node)
// {
// this->full_size = full_size;
// real_size = 0;
// Nodes = new Node*[full_size];
// this->PrevSuperNode = PrevSuperNode;
// this->prev_number_node = prev_number_node;
// }
// SuperNode(SuperNode* copysupernode, int start, int end)
// {
// full_size = copysupernode->full_size;
// real_size = end - start + 1;
// Nodes = new Node*[full_size];
// if (copysupernode->Nodes[0]->LeftSuperNode == nullptr)
// {
// for (int i = 0, k = start; i < real_size; i++, k++)
// {
// Nodes[i] = copysupernode->Nodes[k];
// }
// }
// else
// {
// for (int i = 0, k = start; i < real_size; i++, k++)
// {
// Nodes[i] = copysupernode->Nodes[k];
// Nodes[i]->LeftSuperNode->PrevSuperNode = this;
// Nodes[i]->LeftSuperNode->prev_number_node = i;
// }
// Nodes[real_size - 1]->RightSuperNode->PrevSuperNode = this;
// Nodes[real_size - 1]->RightSuperNode->prev_number_node = real_size;
// }
// PrevSuperNode = copysupernode->PrevSuperNode;
// prev_number_node = copysupernode->prev_number_node;
// }
// SuperNode(SuperNode* copysupernode, int start, int end, Node* add_node, int place_insert)
// {
// full_size = copysupernode->full_size;
// real_size = end - start + 2;
// Nodes = new Node*[full_size];
//
// int i = 0;
// int k = start;
//
// if (copysupernode->Nodes[0]->LeftSuperNode == nullptr)
// {
// for (; i < place_insert; i++, k++)
// {
// Nodes[i] = copysupernode->Nodes[k];
// }
// Nodes[place_insert] = add_node;
// i++;
// for (; i < real_size; i++, k++)
// {
// Nodes[i] = copysupernode->Nodes[k];
// }
// }
// else
// {
// for (; i < place_insert; i++, k++)
// {
// Nodes[i] = copysupernode->Nodes[k];
// Nodes[i]->LeftSuperNode->PrevSuperNode = this;
// Nodes[i]->LeftSuperNode->prev_number_node = i;
// }
// Nodes[place_insert] = add_node;
// add_node->LeftSuperNode->PrevSuperNode = this;
// add_node->LeftSuperNode->prev_number_node = place_insert;
// add_node->RightSuperNode->PrevSuperNode = this;
// add_node->RightSuperNode->prev_number_node = place_insert + 1;
// i++;
// for (; i < real_size; i++, k++)
// {
// Nodes[i] = copysupernode->Nodes[k];
// Nodes[i]->LeftSuperNode->PrevSuperNode = this;
// Nodes[i]->LeftSuperNode->prev_number_node = i;
// }
// Nodes[i - 1]->RightSuperNode->PrevSuperNode = this;
// Nodes[i - 1]->RightSuperNode->prev_number_node = i;
// if (place_insert != 0)
// {
// Nodes[place_insert - 1]->RightSuperNode = add_node->LeftSuperNode;
// }
// if (place_insert != real_size - 1)
// {
// Nodes[place_insert + 1]->LeftSuperNode = add_node->RightSuperNode;
// }
// }
// PrevSuperNode = copysupernode->PrevSuperNode;
// prev_number_node = copysupernode->prev_number_node;
// }
//
// int GetPlace(TKey key)
// {
// int start_binary_search = 0;
// int end_binary_search = real_size - 1;
// int tmp;
// while (end_binary_search - start_binary_search != -1)
// {
// tmp = (start_binary_search + end_binary_search) / 2;
// if (key < Nodes[tmp]->Key)
// {
// end_binary_search = tmp - 1;
// }
// else
// {
// start_binary_search = tmp + 1;
// }
// }
// return start_binary_search;
// }
//
// void Add_Place(Node* add_node, int place_insert)
// {
// if (real_size != 0)
// {
// if (Nodes[0]->LeftSuperNode != nullptr)
// {
// for (int i = real_size; i > place_insert; i--)
// {
// Nodes[i] = Nodes[i - 1];
// Nodes[i]->LeftSuperNode->prev_number_node = i;
// }
// Nodes[place_insert] = add_node;
// add_node->LeftSuperNode->prev_number_node = place_insert;
// add_node->RightSuperNode->prev_number_node = place_insert + 1;
//
// add_node->LeftSuperNode->PrevSuperNode = this;
// add_node->RightSuperNode->PrevSuperNode = this;
//
// Nodes[real_size]->RightSuperNode->prev_number_node = real_size + 1;
// if (place_insert != 0)
// {
// Nodes[place_insert - 1]->RightSuperNode = add_node->LeftSuperNode;
// }
// if (place_insert != real_size)
// {
// Nodes[place_insert + 1]->LeftSuperNode = add_node->RightSuperNode;
// }
// }
// else
// {
// for (int i = real_size; i > place_insert; i--)
// {
// Nodes[i] = Nodes[i - 1];
// }
// Nodes[place_insert] = add_node;
// }
// }
// else
// {
// Nodes[place_insert] = add_node;
// }
// real_size++;
// }
//
// string ShowStr()
// {
// string str = "";
// for (int i = 0; i <= real_size - 1; i++)
// {
// str += to_string(Nodes[i]->Key) + "|";
// }
// str += "#";
// return str;
// }
//
// int full_size;
// int real_size;
// Node** Nodes;
// SuperNode* PrevSuperNode;
// int prev_number_node;
// };
//
// SuperNode* superhead;
// int number_tree;
// int length;
//
// btree* tree;
//
//public:
// BTree(int number_tree)
// {
// this->number_tree = number_tree;
// length = 0;
// superhead = nullptr;
// tree = new btree(number_tree);
// }
//
// int GetCount()
// {
// return length;
// }
//
// int GetCapacity()
// {
// return 999999999;
// }
//
// void Print()
// {
// tree->show();
// }
//
// void Add(TKey key, TValue value)
// {
// tree->insert(key);
//
// if (superhead == nullptr)
// {
// superhead = new SuperNode(number_tree - 1, nullptr, -1);
// Node* add_node = new Node(key, value, nullptr, nullptr, nullptr);
// superhead->Add_Place(add_node, superhead->GetPlace(key));
// }
// else
// {
// SuperNode* super_tmp = superhead;
// int place_tmp = super_tmp->GetPlace(key);
// while (super_tmp->Nodes[0]->LeftSuperNode != nullptr)
// {
// if (place_tmp != super_tmp->real_size)
// {
// super_tmp = super_tmp->Nodes[place_tmp]->LeftSuperNode;
// }
// else
// {
// super_tmp = super_tmp->Nodes[place_tmp - 1]->RightSuperNode;
// }
// place_tmp = super_tmp->GetPlace(key);
// }
// int mean;
// Node* tmp = new Node(key, value, super_tmp, nullptr, nullptr);
// SuperNode* left_super;
// SuperNode* right_super;
// SuperNode* help_super;
// while (super_tmp->real_size == super_tmp->full_size)
// {
// mean = super_tmp->full_size / 2;
// if (place_tmp < mean)
// {
// left_super = new SuperNode(super_tmp, 0, mean - 2, tmp, place_tmp);
// right_super = new SuperNode(super_tmp, mean, super_tmp->full_size - 1);
// tmp = super_tmp->Nodes[mean - 1];
// }
// else if (place_tmp > mean)
// {
// left_super = new SuperNode(super_tmp, 0, mean - 1);
// right_super = new SuperNode(super_tmp, mean + 1, super_tmp->full_size - 1, tmp, place_tmp - mean - 1);
// tmp = super_tmp->Nodes[mean];
// }
// else
// {
// left_super = new SuperNode(super_tmp, 0, mean - 1);
// right_super = new SuperNode(super_tmp, mean, super_tmp->full_size - 1);
// left_super->Nodes[left_super->real_size - 1]->RightSuperNode = tmp->LeftSuperNode;
// right_super->Nodes[0]->LeftSuperNode = tmp->RightSuperNode;
// }
// tmp->LeftSuperNode = left_super;
// tmp->RightSuperNode = right_super;
//
// help_super = super_tmp;
//
// if (super_tmp != superhead)
// {
// place_tmp = super_tmp->prev_number_node;
// super_tmp = super_tmp->PrevSuperNode;
// }
// else
// {
// SuperNode* new_superhead = new SuperNode(superhead->full_size, nullptr, -1);
// left_super->PrevSuperNode = new_superhead;
// right_super->PrevSuperNode = new_superhead;
// left_super->prev_number_node = 0;
// right_super->prev_number_node = 1;
// place_tmp = 0;
//
// super_tmp = new_superhead;
// superhead = new_superhead;
// }
// delete help_super;
// }
// super_tmp->Add_Place(tmp, place_tmp);
// }
// length++;
// }
// void Show()
// {
// string str = "";
// List* head = new List(superhead, nullptr);
// List* res_head = head;
// auto end_tmp = head->data;
// while (true)
// {
// str += head->data->ShowStr();
// if (head->data == end_tmp)
// {
// cout << str << endl;
// str = "";
// end_tmp = head->data->Nodes[head->data->real_size - 1]->RightSuperNode;
// if (end_tmp == nullptr)
// {
// break;
// }
// }
// Add1(head, head->data->Nodes[0]->LeftSuperNode);
// for (int i = 0; i <= head->data->real_size - 1; i++)
// {
// Add1(head, head->data->Nodes[i]->RightSuperNode);
// }
// head = head->next;
// }
// }
//};
//void Add1(BTree<int, int>::List* head, BTree<int, int>::SuperNode* str)
//{
// BTree<int, int>::List* tmp = head;
// while (tmp->next != nullptr)
// {
// tmp = tmp->next;
// }
// tmp->next = new BTree<int, int>::List(str, nullptr);
//}
| [
"kasobol@edu.hse.ru"
] | kasobol@edu.hse.ru |
25e40e3bb7ca9a98bcaf26f89fa5ba3078610d45 | f13fc535d6324dffb3ab63ec3b5ec94e0c646809 | /Code/Libraries/Workbench/src/Components/wbcompowner.h | be80fa7c3541b7413d127725907b884d9d1d460d | [
"Zlib"
] | permissive | rohit-n/Eldritch | df0f2acf553b253478a71f6fe9b26b209b995fc0 | b1d2a200eac9c8026e696bdac1f7d2ca629dd38c | refs/heads/master | 2021-01-12T22:19:23.762253 | 2015-04-03T01:06:43 | 2015-04-03T01:06:43 | 18,807,726 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | h | #ifndef WBCOMPOWNER_H
#define WBCOMPOWNER_H
#include "wbcomponent.h"
#include "wbentityref.h"
class WBCompOwner : public WBComponent
{
public:
WBCompOwner();
virtual ~WBCompOwner();
DEFINE_WBCOMP( Owner, WBComponent );
virtual int GetTickOrder() { return ETO_NoTick; }
virtual void HandleEvent( const WBEvent& Event );
virtual uint GetSerializationSize();
virtual void Save( const IDataStream& Stream );
virtual void Load( const IDataStream& Stream );
virtual void Report() const;
void SetOwner( WBEntity* const pNewOwner );
WBEntity* GetOwner() const;
static WBEntity* GetTopmostOwner( WBEntity* pEntity );
private:
WBEntityRef m_Owner;
};
#endif // WBCOMPOWNER_H | [
"xixonia@gmail.com"
] | xixonia@gmail.com |
0e93785f43db585e98a88249c342cd7df891142e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_patch_hunk_330.cpp | 9fbeea0b7a78bb9321c50777282887083ab8928e | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | cpp | "\n"
" You can specify any amount of URLs on the command line. They will be\n"
" fetched in a sequential manner in the specified order.\n"
"\n"
, stdout);
fputs(
-" Since curl 7.15.1 you can also specify step counter for the ranges, so\n"
-" that you can get every Nth number or letter:\n"
+" Since curl 7.15.1 you can also specify a step counter for the ranges,\n"
+" so that you can get every Nth number or letter:\n"
+"\n"
" http://www.numericals.com/file[1-100:10].txt\n"
" http://www.letters.com/file[a-z:2].txt\n"
"\n"
" If you specify URL without protocol:// prefix, curl will attempt to\n"
" guess what protocol you might want. It will then default to HTTP but\n"
" try other protocols based on often-used host name prefixes. For exam-\n"
| [
"993273596@qq.com"
] | 993273596@qq.com |
c00658236ffa5c74cb67674c3640649eef277995 | e63985bdea5081809ed50822fea45983562cc48a | /LabC++/assgn1.cpp | 726601738b6c3b5a54e014537482c70489e9ae6d | [] | no_license | arnbsen/CPPLab | 241d3c257d5ae529f3232205f87f40f0cb899285 | d59b68c0aab66bc8854fd5e45a86a94edc7b4efd | refs/heads/master | 2021-08-22T03:41:13.080819 | 2017-11-29T05:25:03 | 2017-11-29T05:25:03 | 112,244,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,114 | cpp | //
// assgn1.cpp
// LabC++
//
// Created by Arnab Sen on 02/10/17.
// Copyright © 2017 Arnab Sen. All rights reserved.
//
#include <stdio.h>
#include <iostream>
using namespace std;
class student{
string name,dept;
int roll_no;
public:
void set_data(){
cout<<"Enter the name"<<endl;
cin>>name;
cout<<"Enter the roll no"<<endl;
cin>>roll_no;
cout<<"Enter the dept"<<endl;
cin>>dept;
}
void display(){
cout<<"\nName: "<<name<<"\nRoll No: "<<roll_no<<"\nDept: "<<dept;
}
};
class modified_student: public student{
int marks, yop;
float cgpa;
public:
void set_data1(){
cout<<"Enter the marks"<<endl;
cin>>marks;
cout<<"Enter cgpa"<<endl;
cin>>cgpa;
cout<<"Enter year of passing"<<endl;
cin>>yop;
}
void display1(){
cout<<"\nMarks: "<<marks<<"\nCGPA: "<<cgpa<<"\nYear of Passing: "<<yop;
}
};
int main(){
student s1;
s1.set_data();
s1.display();
modified_student m1;
m1.set_data();
m1.set_data1();
m1.display();
m1.display1();
}
| [
"arnb.sen@hotmail.com"
] | arnb.sen@hotmail.com |
5ab0b8aab66d1bc829014b399ee3b1c5f4ba4b65 | eb49db20a5ab0e84dc72eb6694ac5a2bd6fc24b5 | /Modularizacion en C++ RPi/SEE_master/tcpclass.cpp | f8238a932e3b9019738fba789f69ce8810bbc801 | [] | no_license | kill4n/SistemasEmbebidos_17_1 | 07012b3610c8dfc152c4e4d92135cd1630bf0248 | 16f666f5339703d08fbf87209d52ac61379d0fa8 | refs/heads/master | 2021-01-11T10:50:19.767067 | 2017-05-27T16:34:21 | 2017-05-27T16:34:21 | 81,213,767 | 4 | 0 | null | 2017-05-22T22:32:17 | 2017-02-07T13:58:11 | C | UTF-8 | C++ | false | false | 1,192 | cpp | #include "tcpclass.h"
/* Developed and mantained by killan*/
/* Constructor
* parametros de entrada:
* seg -> Cada cuanto se repite el proceso en segundos
* *myLog -> Apuntador al Objeto que escribe el Log
*/
TCPClass::TCPClass(unsigned long seg, LogClass *myLog)
{
this->setObjectName("TCP");
interval = seg;
mLog = myLog;
mLog->writeLog(this, "Creacion modulo " + this->objectName());
}
//Destructor
TCPClass::~TCPClass()
{
mLog->writeLog(this, "Fin modulo " + this->objectName());
}
//Funcion que se ejecuta al iniciar el hilo
void TCPClass::run()
{
mLog->writeLog(this, "Inicio modulo " + this->objectName());
this->mStop = false;
for (int i = 0; i < 10; ++i) {
this->mutex.lock();
mLog->writeLog(this, this->objectName() +
" is Alive: " + QString::number(i));
if(this->mStop == true)
{
this->mutex.unlock();
break;
}
this->mutex.unlock();
sleep(interval);
//put your code here
}
mLog->writeLog(this, "Fin modulo " + this->objectName());
}
//Funcion para detener el proceso
void TCPClass::stop()
{
this->mStop = true;
}
| [
"crhistian.segura@gmail.com"
] | crhistian.segura@gmail.com |
62168f2eb896a248ef61875c508eb16da674c099 | 8d5ec68b918279bd47ab6b57fa2cce7567c4b3a6 | /Framework/Viewer/Orbit.h | e6414eb6e734dc821550b0f679a8e3ba37d5caa9 | [] | no_license | sork777/PortFolio | 7d6a77a595ca35f821486f620a0b1318d6e7511c | 152d9d8b3d38f490ffccb644691f5a052b677307 | refs/heads/master | 2022-12-30T17:10:58.267379 | 2020-01-11T05:32:26 | 2020-01-11T05:32:26 | 232,132,922 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 583 | h | #pragma once
class Orbit : public Camera
{
public:
Orbit(const float& rad,const float& minRad, const float& maxRad);
virtual ~Orbit();
//궤도를 돌 포지션
void GetObjPos(const Vector3& objPos) { this->objPos = objPos; }
void Update() override;
void Speed(float rot);
void SetRad(const float& rad, const float& minRad, const float& maxRad);
void ViewCameraArea();
void OrbitStaus();
private:
void OrbitUp();
void View() override;
private:
float rSpeed;
float phi;
float theta;
float minRad;
float maxRad;
float rad;
Vector3 objPos;
Vector3 oUp;
};
| [
"ladse123@gmail.com"
] | ladse123@gmail.com |
1b3b043f48ae24ee07132dadf5e34ffb6c5210ec | ec07a78ff899c8fd24e9a41e5305e41643756cdd | /abc164_b.cpp | 91d12bc2dd521557936697291585194dd4b8140e | [] | no_license | jasonhuh/AtCoder-Solutions | 90a72692f6b08126dbb869f70ca70829c2840863 | ff0abe29215a3fb5b3e2229583878e6c7b1b564d | refs/heads/master | 2022-12-22T16:42:28.190905 | 2020-10-05T13:39:52 | 2020-10-05T13:39:52 | 286,298,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 478 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
string solve() {
int h1, s1, h2, s2; cin >> h1 >> s1 >> h2 >> s2;
int player = 0;
while (true) {
if (player == 0) h2 -= s1;
else h1 -= s2;
if (h1 <= 0 || h2 <= 0) break;
player ^= 1;
}
return (h2 <= 0) ? "Yes" : "No";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout << solve() << endl;
}
| [
"jason.huh@aircreek.com"
] | jason.huh@aircreek.com |
113b3097fb74ab350847e5f9c7b5fc7fe0e63f68 | 44ab461147c679c6f654b5ca8643557e1033ffb9 | /MultiStationWorker.cpp | f9aca1d66f63bb390333ca59a18a020454f48c58 | [
"BSD-3-Clause"
] | permissive | snowmanman/structrock | 767e6f5544aae48e1d70e2c3cf56091f5e7ff40f | 754d8c481d22a48ea7eb4e055eb16c64c44055ab | refs/heads/master | 2021-07-31T01:03:37.715307 | 2020-07-16T07:32:03 | 2020-07-16T07:32:03 | 193,132,993 | 1 | 1 | BSD-3-Clause | 2019-06-21T16:56:32 | 2019-06-21T16:56:32 | null | UTF-8 | C++ | false | false | 10,054 | cpp | /*
* Software License Agreement (BSD License)
*
* Xin Wang
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* Author : Xin Wang
* Email : ericrussell@zju.edu.cn
*
*/
#include <string>
#include <sstream>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/registration/icp.h>
#include <pcl/registration/icp_nl.h>
#include <pcl/registration/transforms.h>
#include "geo_normal_3d.h"
#include "geo_normal_3d_omp.h"
#include "globaldef.h"
#include "MultiStationWorker.h"
#include "dataLibrary.h"
bool MultiStationWorker::is_para_satisfying(QString &message)
{
this->setParaSize(6);
if(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters.size()>=this->getParaSize())
{
std::istringstream line_stream(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[0]);
char command_split_str = '|';
std::vector<std::string> tokens;
for(std::string each; std::getline(line_stream, each, command_split_str); tokens.push_back(each));
for(int i=0; i<tokens.size(); i++)
{
tokens[i].erase(std::remove(tokens[i].begin(), tokens[i].end(),'\n'), tokens[i].end());
tokens[i].erase(std::remove(tokens[i].begin(), tokens[i].end(),'\r'), tokens[i].end());
tokens[i].erase(std::remove(tokens[i].begin(), tokens[i].end(),'\t'), tokens[i].end());
if(tokens[i].empty())
tokens.erase(tokens.begin()+i);
}
if(tokens.size()>0)
{
for(int i=0; i<tokens.size(); i++)
{
this->multiStationFilePath.push_back(tokens[i]);
}
double pre_align_ds_leaf, pre_align_StdDev, max_correspondence_distance, euclidean_fitness_epsilon;
int pre_align_normals_k;
std::stringstream ss_pre_align_ds_leaf(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[1]);
ss_pre_align_ds_leaf >> pre_align_ds_leaf;
this->setPreAlignDSLeaf(pre_align_ds_leaf);
std::stringstream ss_pre_align_StdDev(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[2]);
ss_pre_align_StdDev >> pre_align_StdDev;
this->setPreAlignStdDev(pre_align_StdDev);
std::stringstream ss_pre_align_normals_k(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[3]);
ss_pre_align_normals_k >> pre_align_normals_k;
this->setPreAlignNormalsK(pre_align_normals_k);
std::stringstream ss_max_correspondence_distance(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[4]);
ss_max_correspondence_distance >> max_correspondence_distance;
this->setMaxCorrDistance(max_correspondence_distance);
std::stringstream ss_euclidean_fitness_epsilon(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[5]);
ss_euclidean_fitness_epsilon >> euclidean_fitness_epsilon;
this->setEFEpsilon(euclidean_fitness_epsilon);
this->setParaIndex(this->getParaSize());
return true;
}
else
{
message = QString("multistation: None Valid MultiStation Point Cloud File Path Provided.");
return false;
}
}
else
{
message = QString("multistation: MultiStation Point Cloud File Paths Not Provided and/or Not Enough Parameters Given.");
return false;
}
}
void MultiStationWorker::prepare()
{
this->setUnmute();
this->setWriteLog();
this->check_mute_nolog();
}
void MultiStationWorker::doWork()
{
bool is_success(false);
dataLibrary::Status = STATUS_MULTISTATION;
this->timer_start();
//begin of processing
bool is_reading_success(true);
for(int i=0; i<this->multiStationFilePath.size(); i++)
{
sensor_msgs::PointCloud2::Ptr cloud_blob(new sensor_msgs::PointCloud2);
if(!pcl::io::loadPCDFile (this->multiStationFilePath[i], *cloud_blob))
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr temp_cloudxyzrgb(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::fromROSMsg (*cloud_blob, *temp_cloudxyzrgb);
this->multiStationPointClouds.push_back(temp_cloudxyzrgb);
}
else
{
std::string error_msg = "Error opening pcd file: " + this->multiStationFilePath[i];
emit showErrors(QString::fromUtf8(error_msg.c_str()));
is_reading_success = false;
break;
}
}
if(is_reading_success)
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr dsed_rgb_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr ro_rgb_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::Normal>::Ptr target_normals (new pcl::PointCloud<pcl::Normal>);
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr target_pointnormal (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
if(!dataLibrary::cloudxyzrgb->empty())
{
dataLibrary::cloudxyzrgb->clear();
}
*dataLibrary::cloudxyzrgb = *this->multiStationPointClouds[0];
pcl::VoxelGrid<pcl::PointXYZRGB> vg;
vg.setInputCloud (this->multiStationPointClouds[0]);
vg.setLeafSize (this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf());
vg.filter (*dsed_rgb_cloud);
pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;
sor.setInputCloud(dsed_rgb_cloud);
sor.setMeanK(50);
sor.setStddevMulThresh(this->getPreAlignStdDev());
sor.setNegative(false);
sor.filter(*ro_rgb_cloud);
GeoNormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal> ne_target;
ne_target.setInputCloud(ro_rgb_cloud);
pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree_target (new pcl::search::KdTree<pcl::PointXYZRGB>());
ne_target.setSearchMethod(tree_target);
ne_target.setKSearch(this->getPreAlignNormalsK());
ne_target.compute(*target_normals);
pcl::concatenateFields(*ro_rgb_cloud, *target_normals, *target_pointnormal);
for(int i=1; i<this->multiStationPointClouds.size(); i++)
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr dsed_rgb_cloud_i(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr ro_rgb_cloud_i(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::Normal>::Ptr src_normals (new pcl::PointCloud<pcl::Normal>);
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr src_pointnormal (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr transformed_pointnormal (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr transformed_rgb_cloud_i(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::VoxelGrid<pcl::PointXYZRGB> vg_i;
vg_i.setInputCloud (this->multiStationPointClouds[i]);
vg_i.setLeafSize (this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf());
vg_i.filter (*dsed_rgb_cloud_i);
pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor_i;
sor_i.setInputCloud(dsed_rgb_cloud_i);
sor_i.setMeanK(50);
sor_i.setStddevMulThresh(this->getPreAlignStdDev());
sor_i.setNegative(false);
sor_i.filter(*ro_rgb_cloud_i);
GeoNormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal> ne_i;
ne_i.setInputCloud(ro_rgb_cloud_i);
pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree_i (new pcl::search::KdTree<pcl::PointXYZRGB>());
ne_i.setSearchMethod(tree_i);
ne_i.setKSearch(this->getPreAlignNormalsK());
ne_i.compute(*src_normals);
pcl::concatenateFields(*ro_rgb_cloud_i, *src_normals, *src_pointnormal);
pcl::IterativeClosestPoint<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> icp;
icp.setInputCloud(src_pointnormal);
icp.setInputTarget(target_pointnormal);
icp.setMaxCorrespondenceDistance(this->getMaxCorrDistance());
icp.setEuclideanFitnessEpsilon(this->getEFEpsilon());
icp.align (*transformed_pointnormal);
//pcl::copyPointCloud(*transformed_pointnormal, *transformed_rgb_cloud_i);
pcl::transformPointCloud (*this->multiStationPointClouds[i], *transformed_rgb_cloud_i, icp.getFinalTransformation());
*dataLibrary::cloudxyzrgb += *transformed_rgb_cloud_i;
}
if(!dataLibrary::cloudxyz->empty())
{
dataLibrary::cloudxyz->clear();
}
pcl::copyPointCloud(*dataLibrary::cloudxyzrgb, *dataLibrary::cloudxyz);
is_success = true;
}
//end of processing
this->timer_stop();
if(this->getWriteLogMode()&&is_success)
{
std::string log_text = "MultiStation costs: ";
std::ostringstream strs;
strs << this->getTimer_sec();
log_text += (strs.str() +" seconds.");
dataLibrary::write_text_to_log_file(log_text);
}
if(!this->getMuteMode()&&is_success)
{
emit show(CLOUDXYZRGB);
}
dataLibrary::Status = STATUS_READY;
emit showReadyStatus();
if(this->getWorkFlowMode()&&is_success)
{
this->Sleep(1000);
emit GoWorkFlow();
}
} | [
"WXGHolmes@Gmail.com"
] | WXGHolmes@Gmail.com |
cf1315a7340449e850c655531d6959919b909a97 | a5ce66a982043377ef0811bf620f175ee377538a | /Shader.cpp | f5fe310004facd4141168647f9a3f93abe70109e | [] | no_license | FrozenIndie/ISEngine | 57d67c19d5974f4b39c36b420a6f98f7acf52713 | 4ea20cbb80cead198b3f445c4ed771143ba3dcc1 | refs/heads/master | 2020-03-19T16:34:29.856197 | 2018-06-09T12:17:18 | 2018-06-09T12:17:18 | 136,720,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | cpp | #include "Shader.h"
Shader::Shader(const char* a_VertexFilePath, const char* a_FragmentFilePath)
{
VertexFilePath = a_VertexFilePath;
FragmentFilePath = a_FragmentFilePath;
}
Shader::~Shader()
{
}
void Shader::Init()
{
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile, fShaderFile;
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
vShaderFile.open(VertexFilePath);
fShaderFile.open(FragmentFilePath);
std::stringstream vShaderStream, fShaderStream;
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
vShaderFile.close();
fShaderFile.close();
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
std::cout << e.what() << std::endl;
}
const char* vShaderCode = vertexCode.c_str();
const char* fShaderCpde = fragmentCode.c_str();
_ShaderID = glCreateProgram();
_VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(_VertexShaderID, 1, &vShaderCode, 0);
glCompileShader(_VertexShaderID);
int success;
char infoLog[512];
glGetShaderiv(_VertexShaderID, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(_VertexShaderID, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
};
_FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(_FragmentShaderID, 1, &fShaderCpde, 0);
glCompileShader(_FragmentShaderID);
glGetShaderiv(_FragmentShaderID, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(_FragmentShaderID, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
};
glAttachShader(_ShaderID, _VertexShaderID);
glAttachShader(_ShaderID, _FragmentShaderID);
glLinkProgram(_ShaderID);
}
void Shader::Use()
{
glUseProgram(_ShaderID);
}
| [
"mennaandm@hotmail.com"
] | mennaandm@hotmail.com |
7cf1cacad1930b31b3362e2d9c2b3abd262b87fb | 4f66c08dce6611be236ef2f1bc0fdf7086e768af | /ff_test_mem/main.cpp | 3b6dd2ccf924b5f4be075cef280b681765049481 | [] | no_license | xaruch/ffmpeg_tests | 8da57fac0aa0d55d4926024363447b307bf5d799 | e4970bdcf7ed768c92dcd60b0fc2c6bb71b63822 | refs/heads/master | 2021-01-13T02:02:33.973437 | 2014-10-27T12:50:06 | 2014-10-27T12:50:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | #include "include/main.h"
#include "include/ff_writer_engine.h"
#include "include/vars.h"
int main()
{
FfWriterEngine *Writer = new FfWriterEngine();
Log = new Logging("ff_test_mem.log", LOG_LEVEL);
MainLoop = g_main_loop_new(NULL, FALSE);
Writer->FirstStartRec();
g_timeout_add_seconds_full(1000, 1, TimeoutCallback, (gpointer) Writer, NULL);
Memory = Writer->GetMemoryConsumption();
g_main_loop_run(MainLoop);
delete Log;
delete Writer;
}
gboolean TimeoutCallback(gpointer data)
{
FfWriterEngine *PWriter = (FfWriterEngine *) data;
PWriter->TimerCounter++;
PWriter->AppendMemoryData();
if (PWriter->TimerCounter >= REC_TIMEOUT)
{
uint64_t mem = PWriter->GetMemoryConsumption();
sprintf(str, "DEBUG: Timeout callback. Memory: %lld. Delta: %lld\n", mem, mem - Memory);
AppendLog(str, "MAIN");
Memory = mem;
PWriter->TimerCounter = 0;
PWriter->Continue();
}
return true;
}
| [
"xuch@list.ru"
] | xuch@list.ru |
43f439182c16b6ec43fdc074a49d84644f86c629 | 32661cd29ed94213c567bcdc82887b1d85f0088f | /TwoPointers/reverse-words-in-a-string-iii.cpp | e0cb6d05d37c3924b328ce1f78367bff9bb6d1fb | [] | no_license | iamnidheesh/Leet-Code-Solutions | 5ae5116b279b0c4bbaccb6471189bd74cc263642 | d65d0c7395bea447244fa7e3950b1a8562c71abc | refs/heads/master | 2021-04-03T06:58:00.482698 | 2018-06-24T17:52:35 | 2018-06-24T17:52:35 | 124,734,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | cpp | class Solution {
public:
void rev(string &s,int l,int h) {
while(l < h) {
char temp = s[l];
s[l] = s[h];
s[h] = temp;
l++;
h--;
}
}
string reverseWords(string s) {
int l = 0;
for(int i = 0;i < s.size();i++) {
if(s[i] == ' ') {
rev(s,l,i-1);
l = i+1;
}
}
rev(s,l,s.size()-1);
return s;
}
}; | [
"nidheeshpandey@gmail.com"
] | nidheeshpandey@gmail.com |
52ed19aab9e2faa08539e66f1b2565a3aeca0e23 | 0b57b2563238c86e4cdbf937d0af4604a34fdf6a | /IrpsimEngine/options.cpp | 7937235944b004710418759dde3b94154e29a798 | [] | no_license | jnikolas-mwd/IRPSIM | c902917d7d438c599602b82bf623bdff15804130 | 482e142262e877ae71c2097312aee7598cdfc3eb | refs/heads/master | 2020-09-27T03:44:54.389795 | 2019-12-06T22:56:45 | 2019-12-06T22:56:45 | 226,421,536 | 0 | 0 | null | 2019-12-06T22:27:45 | 2019-12-06T22:27:44 | null | WINDOWS-1252 | C++ | false | false | 5,263 | cpp | // options.cpp : implementation file
//
// Copyright © 1998-2015 Casey McSpadden
// mailto:casey@crossriver.com
// http://www.crossriver.com/
//
// ==========================================================================
// DESCRIPTION:
// ==========================================================================
// CMOption implemets an option (string-value pair) used to control a
// simulation.
// CMOptions implements a collection of options
// ==========================================================================
//
// ==========================================================================
// HISTORY:
// ==========================================================================
// 1.00 09 March 2015 - Initial re-write and release.
// ==========================================================================
//
/////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "options.h"
#include "cmlib.h"
#include "token.h"
#include "notify.h"
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
//#include <fstream>
//static wofstream sdebug("debug_options.txt");
const wchar_t* allowedOptions[] = {
L"simbegin",
L"simend",
L"siminterval",
L"simulationname",
L"costprecision",
L"numtrials",
L"outputfolder",
L"precision",
L"randomseed",
L"tracebegin",
L"traceend",
L"tracemode",
L"tracestart",
L"yearend",
0
};
CMOption::CMOption(const CMString& n, const CMString& v, int app_id) : CMIrpObject(n, app_id)
{
BOOL bFound = FALSE;
const wchar_t* name = n.c_str();
for (unsigned i = 0; allowedOptions[i] != 0; i++)
{
if (!_wcsicmp(name, allowedOptions[i]))
{
bFound = TRUE;
break;
}
}
if (!bFound)
CMNotifier::Notify(CMNotifier::WARNING, L"Option " + n + L" is not recognized or is deprecated");
SetValue(v);
}
void CMOption::SetValue(const CMString& v)
{
value = stripends(v);
}
CMOptions::CMOptions() :
options(),
maxwidth(0)
{
//SetDefaults();
}
CMOptions::CMOptions(const CMOptions& opt) :
options(),
maxwidth(0)
{
for (unsigned i=0;i<opt.Count();i++) {
int len = opt.At(i)->GetName().length();
if (len>maxwidth) maxwidth=len;
options.Add(new CMOption(*opt.At(i)));
}
}
CMString CMOptions::GetOption(const CMString& name)
{
CMString ret;
CMString _name(name);
_name.to_lower();
CMOption* op = options.Find(_name);
if (op) ret = op->GetValue();
return ret;
}
const wchar_t* CMOptions::GetOptionString(const CMString& option)
{
CMString op = GetOption(option);
return op.c_str();
}
double CMOptions::GetOptionDouble(const CMString& option)
{
const wchar_t* str = GetOption(option).c_str();
return isnumber(str) ? _wtof(str) : 0;
}
short CMOptions::GetOptionInt(const CMString& option)
{
const wchar_t* str = GetOption(option).c_str();
return isnumber(str) ? _wtoi(str) : 0;
}
long CMOptions::GetOptionLong(const CMString& option)
{
const wchar_t* str = GetOption(option).c_str();
return isnumber(str) ? _wtol(str) : 0;
}
CMOption* CMOptions::SetOption(const CMString& line, int id)
{
CMTokenizer next(line);
CMString name = next(L" \t\r\n");
CMString value = next(L"\r\n");
return SetOption(name, value, id);
}
CMOption* CMOptions::SetOption(const CMString& name, const CMString& value, int id)
{
CMString nm = stripends(name);
nm.to_lower();
int len = nm.length();
if (len>maxwidth) maxwidth=len;
CMOption* op = options.Find(nm);
if (op) op->SetValueAndAppId(value, id);
else {
op = new CMOption(CMOption(nm, value, id));
options.Add(op);
}
return op;
}
CMOption* CMOptions::SetOption(const CMString& name, double option, int id)
{
wchar_t buffer[64];
swprintf_s(buffer, 64, L"%.12g",option);
return SetOption(name,buffer,id);
}
CMOptions& CMOptions::operator = (const CMOptions& op)
{
options.ResetAndDestroy(1);
for (unsigned i=0;i<op.Count();i++)
SetOption(*op.At(i));
return *this;
}
wostream& operator << (wostream& s, CMOptions& o)
{
s << setiosflags(ios::left) << L"#OPTIONS" << ENDL;
o.options.Sort();
s << setiosflags(ios::left);
for (unsigned i=0;i<o.Count();i++)
s << setw(o.maxwidth+2) << o.At(i)->GetName() << o.At(i)->GetValue() << ENDL;
return s << L"#END";
}
wistream& operator >> (wistream& s, CMOptions& o)
{
static wchar_t* header = L"#options";
static wchar_t* footer = L"#end";
o.options.Reset(1);
CMString line;
int begin = 0;
while (!s.eof()) {
line.read_line(s);
line = stripends(line);
if (line.is_null() || line[0] == L'*') {
continue;
}
if (line(0,wcslen(header)) == header) {
begin = 1;
continue;
}
else if (line(0,wcslen(footer)) == footer) {
if (!begin) { continue; }
else { break; }
}
else if (!begin) {
continue;
}
/*
while (line.length() && line[line.length()-1] == L'\\') {
line = line(0,line.length()-1);
CMString cont;
cont.read_line(s);
line += stripends(cont);
}
*/
CMOption* poption = o.SetOption(line, o.GetApplicationId());
if (poption) poption->SetApplicationIndex(o.GetApplicationIndex());
}
o.options.Sort();
return s;
}
| [
"casey@crossriver.com"
] | casey@crossriver.com |
8075bb42c300dc88e10b1c45120b7f23199c62fd | b5dc3bd1d2d71e388efe910549118b80f365022f | /SDL-Game-1/ModuleTextures.cpp | 71a92cfc477b241517d7349a0af5a7bc9fc9699e | [] | no_license | candiajo/SDL-Game-1 | 08fb266a41c6b9b11caf7fea77fbc2163c3486bf | 6923fe3b5614d4a4ee99ec5eefc914eb4b888bc9 | refs/heads/master | 2021-01-10T13:27:11.111606 | 2015-12-03T13:10:20 | 2015-12-03T13:10:20 | 47,021,777 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,510 | cpp | #include "Globals.h"
#include "Application.h"
#include "ModuleRender.h"
#include "ModuleTextures.h"
#include "SDL/include/SDL.h"
#include "SDL_image/include/SDL_image.h"
#pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" )
using namespace std;
ModuleTextures::ModuleTextures()
{}
// Destructor
ModuleTextures::~ModuleTextures()
{
IMG_Quit();
}
// Called before render is available
bool ModuleTextures::Init()
{
LOG("Init Image library");
bool ret = true;
// load support for the PNG image format
int flags = IMG_INIT_PNG;
int init = IMG_Init(flags);
if((init & flags) != flags)
{
LOG("Could not initialize Image lib. IMG_Init: %s", IMG_GetError());
ret = false;
}
return ret;
}
// Called before quitting
bool ModuleTextures::CleanUp()
{
LOG("Freeing textures and Image library");
//for (auto it = texturesMap.begin(); it != texturesMap.end(); ++it)
// SDL_DestroyTexture(it->second);
for (auto& it : texturesMap)
SDL_DestroyTexture(it.second);
texturesMap.clear();
return true;
}
// Load new texture from file path
//SDL_Texture* const ModuleTextures::Load(const char* path)
//{
// SDL_Texture* texture = NULL;
// SDL_Surface* surface = IMG_Load(path);
//
// if (surface == NULL)
// {
// LOG("Could not load surface with path: %s. IMG_Load: %s", path, IMG_GetError());
// }
// else
// {
// texture = SDL_CreateTextureFromSurface(App->renderer->renderer, surface);
//
// if (texture == NULL)
// {
// LOG("Unable to create texture from surface! SDL Error: %s\n", SDL_GetError());
// }
// else
// {
// textures.push_back(texture);
// }
//
// SDL_FreeSurface(surface);
// }
//
// return texture;
//}
// Load new texture from file path
SDL_Texture* const ModuleTextures::LoadMap(const char* name, const char* path)
{
SDL_Texture* texture = NULL;
SDL_Surface* surface = IMG_Load(path);
if (surface == NULL)
{
LOG("Could not load surface with path: %s. IMG_Load: %s", path, IMG_GetError());
}
else
{
texture = SDL_CreateTextureFromSurface(App->renderer->renderer, surface);
if (texture == NULL)
{
LOG("Unable to create texture from surface! SDL Error: %s\n", SDL_GetError());
}
else
{
texturesMap[name] = texture;
}
SDL_FreeSurface(surface);
}
return texture;
}
SDL_Texture* const ModuleTextures::GetTextureMap(const char* name)
{
auto i = texturesMap.find(name);
if (i == texturesMap.end())
{
return NULL; // the map doesn't contains that name
}
else
{
return i->second; // found, returning the texture
}
}
| [
"jordicanodiaz@gmail.com"
] | jordicanodiaz@gmail.com |
e75f73983b2abdc442c01ca29d02b6c337677e08 | 9fb35658e59a1555e2c45dc2a8f5378aeb685dd1 | /shengdaGamea.cpp | 4278fd0a671bfb811290cfa9027d3393c79121b8 | [] | no_license | SmallSir/ACM_Practice | 27d6e484d447764c9a645dc62e5142ec3347e2e0 | f743f4c3ddf231b82097cf22b068437fd36c996c | refs/heads/master | 2021-10-24T05:07:37.988330 | 2019-03-22T05:52:27 | 2019-03-22T05:52:27 | 110,557,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include<iostream>
#include<cstdio>
#include<stdio.h>
#include<cstring>
#include<cstdio>
#include<climits>
#include<cmath>
#include<vector>
#include <bitset>
#include<algorithm>
#include <queue>
#include<map>
#define inf 9999999;
using namespace std;
int a[105][105],b[105],n,m,i,j;
int main()
{
while(cin>>n>>m)
{
memset(b,0,sizeof(b));
memset(a,0,sizeof(a));
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
cin>>a[i][j];
if(a[i][j]==1)
{
b[j]++;
}
}
}
for(i=1;i<m;i++)
{
cout<<b[i]<<" ";
}
cout<<b[i]<<endl;
}
}
| [
"280690956@qq.com"
] | 280690956@qq.com |
a37ebdffb55b3b2190d49f8c5a03cd1a6e1cabaa | 43764cf2c1121e9168e5507799b1745da52e3975 | /9.7/Time.h | da594eba966c516734793d3cadfe3a384f73e9c1 | [] | no_license | SamirOmarov/C-Homeworks | 9c9cfb959129748f71313ef0cb12ee856ffa014b | e8b91b9352820a6e8e174c8d2ae78a6f2a8cf405 | refs/heads/master | 2020-04-06T20:59:42.227147 | 2018-11-16T00:50:53 | 2018-11-16T00:50:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | h | #pragma once
class Time {
private:
int hour;
int minute;
int second;
public:
Time(int, int, int);
// SET
void setTime(int, int, int);
void setHour(int);
void setMinute(int);
void setSecond(int);
// GET
int getHour();
int getMinute();
int getSecond();
void print();
}; | [
"samir.omarov@gmail.com"
] | samir.omarov@gmail.com |
488cb17efbca6be36bf1c1b836cd0b67433b915f | b236c9b5738dee4318ca11fb8218343ed3deb9c9 | /Engine/main.cpp | c4a346153aa158d476f3e06c66ab4eaf34dca2f3 | [] | no_license | lordnorthern/New-Engine | 092f85b71b5c509d6f61932a19a2158193fa1903 | ab6dba11dd5f953720e42b7c9753714cf72c2bfb | refs/heads/master | 2021-01-18T02:12:14.298362 | 2015-10-19T17:44:46 | 2015-10-19T17:44:46 | 44,012,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | #define _CRTDBG_MAPALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include "globaldef.h"
#include <windows.h>
#include "Engine.h"
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
Engine * myEngine = new Engine(hInstance);
myEngine->window_width = 1280;
myEngine->window_height = 800;
if (!myEngine->initialize_engine())
{
delete myEngine;
return 0;
}
delete myEngine;
_CrtDumpMemoryLeaks();
return 0;
}
| [
"wasiktir@outlook.com"
] | wasiktir@outlook.com |
59d294c982488a130bd4580122832837fe40d0ce | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/policy/core/browser/url_allowlist_policy_handler_unittest.cc | 6ebde2250284243aeae5bfab56427b6c6c0960f1 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 6,820 | cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/policy/core/browser/url_allowlist_policy_handler.h"
#include <memory>
#include <utility>
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "components/policy/core/browser/policy_error_map.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_value_map.h"
#include "components/strings/grit/components_strings.h"
#include "components/url_matcher/url_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
namespace policy {
namespace {
const char kTestAllowlistValue[] = "kTestAllowlistValue";
} // namespace
class URLAllowlistPolicyHandlerTest : public testing::Test {
public:
void SetUp() override {
handler_ = std::make_unique<URLAllowlistPolicyHandler>(key::kURLAllowlist);
}
protected:
void SetPolicy(const std::string& key, base::Value value) {
policies_.Set(key, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
POLICY_SOURCE_CLOUD, std::move(value), nullptr);
}
bool CheckPolicy(const std::string& key, base::Value value) {
SetPolicy(key, std::move(value));
return handler_->CheckPolicySettings(policies_, &errors_);
}
void ApplyPolicies() { handler_->ApplyPolicySettings(policies_, &prefs_); }
bool ValidatePolicy(const std::string& policy) {
return handler_->ValidatePolicy(policy);
}
base::Value GetURLAllowlistPolicyValueWithEntries(size_t len) {
base::Value::List allowlist;
for (size_t i = 0; i < len; ++i)
allowlist.Append(kTestAllowlistValue);
return base::Value(std::move(allowlist));
}
std::unique_ptr<URLAllowlistPolicyHandler> handler_;
PolicyErrorMap errors_;
PolicyMap policies_;
PrefValueMap prefs_;
};
TEST_F(URLAllowlistPolicyHandlerTest, CheckPolicySettings_WrongType) {
// The policy expects a list. Give it a boolean.
EXPECT_TRUE(CheckPolicy(key::kURLAllowlist, base::Value(false)));
EXPECT_EQ(1U, errors_.size());
const std::string expected = key::kURLAllowlist;
const std::string actual = errors_.begin()->first;
EXPECT_EQ(expected, actual);
}
TEST_F(URLAllowlistPolicyHandlerTest, ApplyPolicySettings_NothingSpecified) {
ApplyPolicies();
EXPECT_FALSE(prefs_.GetValue(policy_prefs::kUrlAllowlist, nullptr));
}
TEST_F(URLAllowlistPolicyHandlerTest, ApplyPolicySettings_WrongType) {
// The policy expects a list. Give it a boolean.
SetPolicy(key::kURLAllowlist, base::Value(false));
ApplyPolicies();
EXPECT_FALSE(prefs_.GetValue(policy_prefs::kUrlAllowlist, nullptr));
}
TEST_F(URLAllowlistPolicyHandlerTest, ApplyPolicySettings_Empty) {
SetPolicy(key::kURLAllowlist, base::Value(base::Value::Type::LIST));
ApplyPolicies();
base::Value* out;
EXPECT_TRUE(prefs_.GetValue(policy_prefs::kUrlAllowlist, &out));
ASSERT_TRUE(out->is_list());
EXPECT_EQ(0U, out->GetList().size());
}
TEST_F(URLAllowlistPolicyHandlerTest, ApplyPolicySettings_WrongElementType) {
// The policy expects string-valued elements. Give it booleans.
base::Value::List in;
in.Append(false);
SetPolicy(key::kURLAllowlist, base::Value(std::move(in)));
ApplyPolicies();
// The element should be skipped.
base::Value* out;
EXPECT_TRUE(prefs_.GetValue(policy_prefs::kUrlAllowlist, &out));
ASSERT_TRUE(out->is_list());
EXPECT_EQ(0U, out->GetList().size());
}
TEST_F(URLAllowlistPolicyHandlerTest, ApplyPolicySettings_Successful) {
base::Value::List in_url_allowlist;
in_url_allowlist.Append(kTestAllowlistValue);
SetPolicy(key::kURLAllowlist, base::Value(std::move(in_url_allowlist)));
ApplyPolicies();
base::Value* out;
EXPECT_TRUE(prefs_.GetValue(policy_prefs::kUrlAllowlist, &out));
ASSERT_TRUE(out->is_list());
ASSERT_EQ(1U, out->GetList().size());
const std::string* out_string = out->GetList()[0].GetIfString();
ASSERT_TRUE(out_string);
EXPECT_EQ(kTestAllowlistValue, *out_string);
}
TEST_F(URLAllowlistPolicyHandlerTest,
ApplyPolicySettings_CheckPolicySettingsMaxFiltersLimitOK) {
size_t max_filters_per_policy = policy::kMaxUrlFiltersPerPolicy;
base::Value urls =
GetURLAllowlistPolicyValueWithEntries(max_filters_per_policy);
EXPECT_TRUE(CheckPolicy(key::kURLAllowlist, std::move(urls)));
EXPECT_EQ(0U, errors_.size());
ApplyPolicies();
base::Value* out;
EXPECT_TRUE(prefs_.GetValue(policy_prefs::kUrlAllowlist, &out));
ASSERT_TRUE(out->is_list());
EXPECT_EQ(max_filters_per_policy, out->GetList().size());
}
// Test that the warning message, mapped to
// |IDS_POLICY_URL_ALLOW_BLOCK_LIST_MAX_FILTERS_LIMIT_WARNING|, is added to
// |errors_| when URLAllowlist entries exceed the max filters per policy limit.
TEST_F(URLAllowlistPolicyHandlerTest,
ApplyPolicySettings_CheckPolicySettingsMaxFiltersLimitExceeded) {
size_t max_filters_per_policy = policy::kMaxUrlFiltersPerPolicy;
base::Value urls =
GetURLAllowlistPolicyValueWithEntries(max_filters_per_policy + 1);
EXPECT_TRUE(CheckPolicy(key::kURLAllowlist, std::move(urls)));
EXPECT_EQ(1U, errors_.size());
ApplyPolicies();
auto error_str = errors_.GetErrorMessages(key::kURLAllowlist);
auto expected_str = l10n_util::GetStringFUTF16(
IDS_POLICY_URL_ALLOW_BLOCK_LIST_MAX_FILTERS_LIMIT_WARNING,
base::NumberToString16(max_filters_per_policy));
EXPECT_TRUE(error_str.find(expected_str) != std::wstring::npos);
base::Value* out;
EXPECT_TRUE(prefs_.GetValue(policy_prefs::kUrlAllowlist, &out));
ASSERT_TRUE(out->is_list());
EXPECT_EQ(max_filters_per_policy + 1, out->GetList().size());
}
TEST_F(URLAllowlistPolicyHandlerTest, ValidatePolicy) {
EXPECT_TRUE(ValidatePolicy("http://*"));
EXPECT_TRUE(ValidatePolicy("http:*"));
EXPECT_TRUE(ValidatePolicy("ws://example.org/component.js"));
EXPECT_FALSE(ValidatePolicy("wsgi:///rancom,org/"));
EXPECT_TRUE(ValidatePolicy("127.0.0.1:1"));
EXPECT_TRUE(ValidatePolicy("127.0.0.1:65535"));
EXPECT_FALSE(ValidatePolicy("127.0.0.1:65536"));
EXPECT_TRUE(ValidatePolicy("*"));
EXPECT_FALSE(ValidatePolicy("*.developers.com"));
}
// When the invalid sequence with '*' in the host is added to the allowlist, the
// policy can still be applied, but an error is added to the error map to
// indicate an invalid URL.
TEST_F(URLAllowlistPolicyHandlerTest, CheckPolicyURLHostWithAsterik) {
base::Value::List allowed_urls;
allowed_urls.Append("*.developers.com");
EXPECT_TRUE(
CheckPolicy(key::kURLAllowlist, base::Value(std::move(allowed_urls))));
EXPECT_EQ(1U, errors_.size());
}
} // namespace policy
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
172c73d4fa2ccaa4c40d22f1a6dfc18ad05186f4 | 440f814f122cfec91152f7889f1f72e2865686ce | /src/game_server/server/extension/auction/auction_actor_pool.h | 89651f6b49d900762851fa3ea50ad87759f614f4 | [] | no_license | hackerlank/buzz-server | af329efc839634d19686be2fbeb700b6562493b9 | f76de1d9718b31c95c0627fd728aba89c641eb1c | refs/heads/master | 2020-06-12T11:56:06.469620 | 2015-12-05T08:03:25 | 2015-12-05T08:03:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | h | #ifndef __GAME__SERVER__AUCTION__AUCTION__ACTOR__POOL__H
#define __GAME__SERVER__AUCTION__AUCTION__ACTOR__POOL__H
#include "global/pool_template.h"
#include "global/singleton_factory.h"
#include "game_server/server/extension/auction/auction_actor.h"
namespace game {
namespace server {
namespace auction {
class AuctionActorPool : public global::SingletonFactory<AuctionActorPool> {
friend class global::SingletonFactory<AuctionActorPool>;
public:
bool Initialize(size_t initial_number, size_t extend_number);
void Finalize();
AuctionActor *Allocate();
void Deallocate(AuctionActor *actor);
private:
AuctionActorPool() {}
~AuctionActorPool() {}
global::PoolTemplate<AuctionActor> actors_;
};
} // namespace auction
} // namespace server
} // namespace game
#endif // __GAME__SERVER__AUCTION__AUCTION__ACTOR__POOL__H
| [
"251729465@qq.com"
] | 251729465@qq.com |
daa36c878d58bcc0aecaf5aaea5932cc05a1858b | 4e255627848ce4322ffd4b03c3c6fdba7a132ba7 | /Anime4KCore/include/CNN.h | e4d3fbbb5c434f87ad39ecb1f2275ac710b194b2 | [
"MIT"
] | permissive | zengxiao29/Anime4KCPP | 046d092ca3a2986b4c5a71a2c7d616f93370ecb1 | e187ed7bd42365c8bbeb6185537ce6b42713e32e | refs/heads/master | 2022-12-29T06:17:47.434598 | 2020-10-13T18:05:20 | 2020-10-13T18:05:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | h | #pragma once
#include "ACNet.h"
#include "ACNetHDN.h"
namespace Anime4KCPP
{
class CNNCreator;
}
//CNN Processor Factory
class Anime4KCPP::CNNCreator
{
public:
static CNNProcessor* create(const CNNType& type);
static void release(CNNProcessor*& processor) noexcept;
};
| [
"TianLin2112@outlook.com"
] | TianLin2112@outlook.com |
1f6cbc11c17f8d49b9bc9ab68d22bc6c5a20466b | 636394fc4967123179dd2dc935f437e735c6d38a | /export/windows/obj/include/openfl/geom/Transform.h | ac75a715329f84d1dae935c0f25bb57f31307b95 | [
"MIT"
] | permissive | arturspon/zombie-killer | 865e6ef3bdb47408f9bfea9016f61bf19b2559c7 | 07848c5006916e9079537a3d703ffe3740afaa5a | refs/heads/master | 2021-07-18T16:44:26.556092 | 2019-05-04T13:56:08 | 2019-05-04T13:56:08 | 181,805,463 | 0 | 1 | MIT | 2021-07-16T23:18:46 | 2019-04-17T02:50:10 | C++ | UTF-8 | C++ | false | true | 3,144 | h | // Generated by Haxe 4.0.0-rc.2+77068e10c
#ifndef INCLUDED_openfl_geom_Transform
#define INCLUDED_openfl_geom_Transform
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS2(openfl,display,DisplayObject)
HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable)
HX_DECLARE_CLASS2(openfl,events,EventDispatcher)
HX_DECLARE_CLASS2(openfl,events,IEventDispatcher)
HX_DECLARE_CLASS2(openfl,geom,ColorTransform)
HX_DECLARE_CLASS2(openfl,geom,Matrix)
HX_DECLARE_CLASS2(openfl,geom,Matrix3D)
HX_DECLARE_CLASS2(openfl,geom,Rectangle)
HX_DECLARE_CLASS2(openfl,geom,Transform)
namespace openfl{
namespace geom{
class HXCPP_CLASS_ATTRIBUTES Transform_obj : public hx::Object
{
public:
typedef hx::Object super;
typedef Transform_obj OBJ_;
Transform_obj();
public:
enum { _hx_ClassId = 0x48ea4500 };
void __construct( ::openfl::display::DisplayObject displayObject);
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="openfl.geom.Transform")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,true,"openfl.geom.Transform"); }
static hx::ObjectPtr< Transform_obj > __new( ::openfl::display::DisplayObject displayObject);
static hx::ObjectPtr< Transform_obj > __alloc(hx::Ctx *_hx_ctx, ::openfl::display::DisplayObject displayObject);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~Transform_obj();
HX_DO_RTTI_ALL;
hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp);
hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp);
void __GetFields(Array< ::String> &outFields);
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("Transform",4c,0d,66,e7); }
::openfl::geom::ColorTransform concatenatedColorTransform;
::openfl::geom::Rectangle pixelBounds;
::openfl::geom::ColorTransform _hx___colorTransform;
::openfl::display::DisplayObject _hx___displayObject;
bool _hx___hasMatrix;
bool _hx___hasMatrix3D;
::openfl::geom::ColorTransform get_colorTransform();
::Dynamic get_colorTransform_dyn();
::openfl::geom::ColorTransform set_colorTransform( ::openfl::geom::ColorTransform value);
::Dynamic set_colorTransform_dyn();
::openfl::geom::Matrix get_concatenatedMatrix();
::Dynamic get_concatenatedMatrix_dyn();
::openfl::geom::Matrix get_matrix();
::Dynamic get_matrix_dyn();
::openfl::geom::Matrix set_matrix( ::openfl::geom::Matrix value);
::Dynamic set_matrix_dyn();
::openfl::geom::Matrix3D get_matrix3D();
::Dynamic get_matrix3D_dyn();
::openfl::geom::Matrix3D set_matrix3D( ::openfl::geom::Matrix3D value);
::Dynamic set_matrix3D_dyn();
void _hx___setTransform(Float a,Float b,Float c,Float d,Float tx,Float ty);
::Dynamic _hx___setTransform_dyn();
};
} // end namespace openfl
} // end namespace geom
#endif /* INCLUDED_openfl_geom_Transform */
| [
"artursponchi@gmail.com"
] | artursponchi@gmail.com |
52de6e450a1507167cdac4145bca730749f8e1f4 | 5a565ee6dfe2a17a47f6767e8e5f64a202e0c367 | /src/Core/Material/Texture.h | c309bb8d8ed3373bf5247d03b5559ee552072869 | [] | no_license | CHKingSun/KEngine | 85eba9f0949bee8c26993d8c4b61f784bc8ecb97 | 927d4556b9220ff223e538baaebcf338777b8735 | refs/heads/master | 2020-03-14T15:19:31.843045 | 2018-06-07T18:41:06 | 2018-06-07T18:41:06 | 131,673,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,884 | h | //
// Created by KingSun on 2018/05/11
//
#ifndef KENGINE_TEXTURE_H
#define KENGINE_TEXTURE_H
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <memory>
#include <GL/glew.h>
#include <stb_image.h>
#include <iostream>
#include "../../Render/Buffer/UniformBlock.h"
#include "../../KHeader.h"
#include "../../Render/Shader.h"
namespace KEngine {
namespace KMaterial {
enum TextureType {
AMBIENT = 1, DIFFUSE, SPECULAR,
COLOR, DEPTH, STENCIL, DEPTH_AND_STENCIL
};
struct TextureCount {
TextureCount(Kuint id): tex_id(id), count(1) {}
Kuint tex_id;
Ksize count;
};
class Texture {
friend class KBuffer::FrameBuffer;
private:
Kuint id;
mutable Kuint activeId;
std::string path;
TextureType type;
static Kint max_num; // = 0;
static std::unordered_map<std::string, TextureCount> texPaths;
const static KRenderer::Shader* shader;
const static std::string TEXTURES; // = "textures";
const static std::string TEX_HEAD; // = "u_textures[";
const static std::string TEX_TEXTURE; // = "].tex";
const static std::string TEX_TYPE; // = "].type";
const static std::string TEX_ENABLE; // = "].enable";
public:
Texture(const std::string &path, TextureType type = AMBIENT):
path(path), type(type) {
if (max_num == 0) glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_num);
id = getTextureId(path);
}
Texture(TextureType type = COLOR, Ksize width = 1024, Ksize height = 1024):
type(type), path() {
if (max_num == 0) glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_num);
id = getTextureId(type, width, height);
}
~Texture() {
//if (glIsTexture(id)) glDeleteTextures(1, &id);
//remember that you share your textures with other objects,
//so some day when you get wrong with texture, maybe here.
//Oh yeah I got no texture hours later.
//texPaths.erase(path);
if (!path.empty()) {
auto fit = texPaths.find(path);
if (fit != texPaths.end()) {
fit->second.count -= 1;
if (fit->second.count == 0) {
if (glIsTexture(id)) glDeleteTextures(1, &id);
texPaths.erase(fit);
}
}
return;
}
if (glIsTexture(id)) glDeleteTextures(1, &id);
}
static Kuint getTextureId(const std::string &path) {
auto fit = texPaths.find(path);
if (fit != texPaths.end()) {
fit->second.count += 1;
return fit->second.tex_id;
}
GLuint tex_id;
glGenTextures(1, &tex_id);
//OpenGL 4.5 glCreateTextures(target, size, *textures);
int width, height, component;
GLubyte *data = stbi_load(path.data(), &width, &height, &component, 0);
if (data != nullptr) {
GLenum format;
switch (component) {
case 1:
format = GL_RED;
break;
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
default:
format = GL_RGB;
}
glBindTexture(GL_TEXTURE_2D, tex_id);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 6);
//OpenGL 4.5 glGenerateTextureMipmap(texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else {
std::cerr << "Load texture file: " << path << " failed!" << std::endl;
glDeleteTextures(1, &tex_id);
}
texPaths.emplace(path, tex_id);
return tex_id;
}
static Kuint getTextureId(TextureType type = COLOR, Ksize width = 1024, Ksize height = 1024) {
Kuint tex_id;
glGenTextures(1, &tex_id);
glBindTexture(GL_TEXTURE_2D, tex_id);
GLenum format = GL_RGBA;
switch (type)
{
case KEngine::KMaterial::DEPTH:
format = GL_DEPTH_COMPONENT;
break;
case KEngine::KMaterial::STENCIL:
format = GL_STENCIL_INDEX;
break;
case KEngine::KMaterial::DEPTH_AND_STENCIL:
format = GL_DEPTH_STENCIL;
break;
default:
break;
}
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
return tex_id;
}
static Kuint getCubeTextureId(TextureType type = COLOR, Ksize width = 1024, Ksize height = 1024) {
Kuint tex_id;
glGenTextures(1, &tex_id);
glBindTexture(GL_TEXTURE_CUBE_MAP, tex_id);
GLenum format = GL_RGBA;
switch (type)
{
case KEngine::KMaterial::DEPTH:
format = GL_DEPTH_COMPONENT;
break;
case KEngine::KMaterial::STENCIL:
format = GL_STENCIL_INDEX;
break;
case KEngine::KMaterial::DEPTH_AND_STENCIL:
format = GL_DEPTH_STENCIL;
break;
default:
break;
}
for (Kuint i = 0; i < 6; ++i) {
//PX, NX, PY, NY, PZ, NZ
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, width, height, 0, format, GL_FLOAT, nullptr);
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
return tex_id;
}
static void bindUniform(const KRenderer::Shader* shader) {
Texture::shader = shader;
}
void bind(Kuint activeId = 0XFFFFFFFF)const {
if (activeId < max_num) this->activeId = activeId;
if (shader == nullptr) return;
glActiveTexture(GL_TEXTURE0 + this->activeId);
glBindTexture(GL_TEXTURE_2D, id);
const std::string index = std::to_string(this->activeId);
shader->bindUniform1i(TEX_HEAD + index + TEX_TEXTURE, this->activeId);
shader->bindUniform1i(TEX_HEAD + index + TEX_TYPE, type);
shader->bindUniform1i(TEX_HEAD + index + TEX_ENABLE, 1);
}
void active(Kboolean enable = true) {
shader->bindUniform1i(TEX_HEAD + std::to_string(activeId) + TEX_ENABLE, enable);
}
};
Kint Texture::max_num = 0;
std::unordered_map<std::string, TextureCount> Texture::texPaths = std::unordered_map<std::string, TextureCount>();
const KRenderer::Shader* Texture::shader(nullptr);
const std::string Texture::TEXTURES("textures");
const std::string Texture::TEX_HEAD("u_textures[");
const std::string Texture::TEX_TEXTURE("].tex");
const std::string Texture::TEX_TYPE("].type");
const std::string Texture::TEX_ENABLE("].enable");
}
}
#endif //KENGINE_TEXTURE_H
| [
"chkingsun@gmail.com"
] | chkingsun@gmail.com |
3b6ca05f65b707938f2006b607e5449b889a5360 | 5521a03064928d63cc199e8034e4ea76264f76da | /fboss/agent/state/Transceiver.cpp | ee74247135aaf3604e334fac70159a057c2f3efc | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | facebook/fboss | df190fd304e0bf5bfe4b00af29f36b55fa00efad | 81e02db57903b4369200eec7ef22d882da93c311 | refs/heads/main | 2023-09-01T18:21:22.565059 | 2023-09-01T15:53:39 | 2023-09-01T15:53:39 | 31,927,407 | 925 | 353 | NOASSERTION | 2023-09-14T05:44:49 | 2015-03-09T23:04:15 | C++ | UTF-8 | C++ | false | false | 2,509 | cpp | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/state/Transceiver.h"
#include "fboss/agent/FbossError.h"
#include "fboss/agent/state/NodeBase-defs.h"
#include <thrift/lib/cpp/util/EnumUtils.h>
namespace facebook::fboss {
namespace {
constexpr auto kTransceiverID = "id";
constexpr auto kCableLength = "cableLength";
constexpr auto kMediaInterface = "mediaInterface";
constexpr auto kManagementInterface = "managementInterface";
} // namespace
TransceiverSpec::TransceiverSpec(TransceiverID id) {
set<switch_state_tags::id>(id);
}
std::shared_ptr<TransceiverSpec> TransceiverSpec::createPresentTransceiver(
const TransceiverInfo& tcvrInfo) {
std::shared_ptr<TransceiverSpec> newTransceiver;
if (*tcvrInfo.tcvrState()->present()) {
newTransceiver = std::make_shared<TransceiverSpec>(
TransceiverID(*tcvrInfo.tcvrState()->port()));
if (tcvrInfo.tcvrState()->cable() &&
tcvrInfo.tcvrState()->cable()->length()) {
newTransceiver->setCableLength(*tcvrInfo.tcvrState()->cable()->length());
}
if (auto settings = tcvrInfo.tcvrState()->settings();
settings && settings->mediaInterface()) {
if (settings->mediaInterface()->size() == 0) {
XLOG(WARNING) << "Missing media interface, skip setting it.";
} else {
const auto& interface = (*settings->mediaInterface())[0];
newTransceiver->setMediaInterface(*interface.code());
}
}
if (auto interface =
tcvrInfo.tcvrState()->transceiverManagementInterface()) {
newTransceiver->setManagementInterface(*interface);
}
}
return newTransceiver;
}
cfg::PlatformPortConfigOverrideFactor
TransceiverSpec::toPlatformPortConfigOverrideFactor() const {
cfg::PlatformPortConfigOverrideFactor factor;
if (auto cableLength = getCableLength()) {
factor.cableLengths() = {*cableLength};
}
if (auto mediaInterface = getMediaInterface()) {
factor.mediaInterfaceCode() = *mediaInterface;
}
if (auto managerInterface = getManagementInterface()) {
factor.transceiverManagementInterface() = *managerInterface;
}
return factor;
}
template class ThriftStructNode<TransceiverSpec, state::TransceiverSpecFields>;
} // namespace facebook::fboss
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
567a764746f2b19b7176fbe0f07555f988668f41 | bb7645bab64acc5bc93429a6cdf43e1638237980 | /Official Windows Platform Sample/Windows 8 app samples/[C++]-Windows 8 app samples/C++/Windows 8 app samples/Network status background sample (Windows 8)/C++/NetworkStatusApp/Constants.h | 9dbbdd56883a7f9dd4e461e576979de6faf5dcc4 | [
"MIT"
] | permissive | Violet26/msdn-code-gallery-microsoft | 3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312 | df0f5129fa839a6de8f0f7f7397a8b290c60ffbb | refs/heads/master | 2020-12-02T02:00:48.716941 | 2020-01-05T22:39:02 | 2020-01-05T22:39:02 | 230,851,047 | 1 | 0 | MIT | 2019-12-30T05:06:00 | 2019-12-30T05:05:59 | null | UTF-8 | C++ | false | false | 1,813 | h | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#pragma once
#include <collection.h>
using namespace Platform;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::Storage;
#define SampleBackgroundTaskEntryPoint "NetworkStatusTask.BackgroundTask"
#define SampleBackgroundTaskWithConditionName "SampleBackgroundTaskWithCondition"
namespace SDKSample
{
public value struct Scenario
{
Platform::String^ Title;
Platform::String^ ClassName;
};
partial ref class MainPage
{
public:
static property Platform::String^ FEATURE_NAME
{
Platform::String^ get()
{
return ref new Platform::String(L"Network Status");
}
}
static property Platform::Array<Scenario>^ scenarios
{
Platform::Array<Scenario>^ get()
{
return scenariosInner;
}
}
private:
static Platform::Array<Scenario>^ scenariosInner;
};
class BackgroundTaskSample
{
public:
static BackgroundTaskRegistration^ RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition);
static void UnregisterBackgroundTasks(String^ name);
static void UpdateBackgroundTaskStatus(Platform::String^ name, bool registered);
static bool SampleBackgroundTaskWithConditionRegistered;
};
}
| [
"v-tiafe@microsoft.com"
] | v-tiafe@microsoft.com |
6fc09598fedca19f4d8594b33f83c20d2a16e03e | c611cfc951ec1fcc9f79660022bd73d6f037730f | /Computer Graphics Program/cohensutherland.cpp | 0dafa354ceaa3d5b6774a76eb41874906bb57f19 | [
"MIT"
] | permissive | shainisoni1696/Computer-Graphics-Lab-Programs | 6c5534be04799dec2dbf4319d137ca0bd3f23b4a | 621c6741a898f6360ec0a2127bf25ce10706e7c9 | refs/heads/master | 2020-05-05T08:49:07.471808 | 2019-04-06T19:47:22 | 2019-04-06T19:47:22 | 179,879,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,229 | cpp | #include<bits/stdc++.h>
#include<graphics.h>
using namespace std;
#define left 1
#define right 2
#define bottom 4
#define top 8
int getcode(int rec[],double x1, double y1)
{
int code=0;
if(x1 < rec[0])
code|=left;
if(x1 > rec[2])
code|=right;
if(y1 < rec[1])
code|=top;
if(y1 > rec[3])
code|=bottom;
return code;
}
void cohens(int rec[],double x1,double y1, double x2, double y2)
{
int code1=getcode(rec,x1,y1);
int code2=getcode(rec,x2,y2);
bool accept=false;
while(true)
{
if(code1==0 && code2==0)
{
accept=true;
break;
}
else
{
if(code1 & code2)
break;
else
{
int code_out;
double x,y;
if(code1!=0)
code_out=code1;
else
code_out=code2;
if(code_out & top) //rec[1]=y_min
{
x=x1 + (x2-x1)*(rec[1]-y1)/(y2-y1);
y=rec[1];
}
else if(code_out & bottom) //rec[3]=y_max
{
x=x1 + (x2-x1)*(rec[3]-y1)/(y2-y1);
y=rec[3];
}
else if(code_out & left)
{
x=rec[0];
y=y1+(y2-y1)*(rec[0]-x1)/(x2-x1);
}
else if(code_out & right)
{
x=rec[2];
y=y1+(y2-y1)*(rec[2]-x1)/(x2-x1);
}
if(code_out == code1)
{
x1=x;
y1=y;
code1=getcode(rec,x1,y1);
}
else
{
x2=x;
y2=y;
code2=getcode(rec,x2,y2);
}
} //end else
}
}//end of while
if(accept)
{
line(x1,y1,x2,y2);
}
delay(300);
}
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
int rec[]={200,200,400,350};
rectangle(200,200,400,350);
line(100,250,100,340);
line(250,300,270,400);
line(240,240,240,315);
line(300,100,450,300);
delay(600);
cleardevice();
rectangle(200,200,400,350);
cohens(rec,100,250,100,340);
cohens(rec,250,300,270,400);
cohens(rec,240,240,240,315);
cohens(rec,300,100,450,300);
delay(500);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
cd7a7f825d81ca8609c1fb31384545451e54f164 | 69dd4bd4268e1c361d8b8d95f56b5b3f5264cc96 | /GPU Pro1/03_Rendering Techniques/05_VolumeDecals/VolumeDecals/Framework3/Direct3D/Direct3DRenderer.cpp | 3cd8aeb5fbf36db8d1b2ca71508c697f7917cf82 | [
"MIT"
] | permissive | AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen | 65c16710d1abb9207fd7e1116290336a64ddfc86 | f442622273c6c18da36b61906ec9acff3366a790 | refs/heads/master | 2022-12-15T00:40:42.931271 | 2020-09-07T16:48:25 | 2020-09-07T16:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,929 | cpp |
/* * * * * * * * * * * * * Author's note * * * * * * * * * * * *\
* _ _ _ _ _ _ _ _ _ _ _ _ *
* |_| |_| |_| |_| |_|_ _|_| |_| |_| _|_|_|_|_| *
* |_|_ _ _|_| |_| |_| |_|_|_|_|_| |_| |_| |_|_ _ _ *
* |_|_|_|_|_| |_| |_| |_| |_| |_| |_| |_| |_|_|_|_ *
* |_| |_| |_|_ _ _|_| |_| |_| |_|_ _ _|_| _ _ _ _|_| *
* |_| |_| |_|_|_| |_| |_| |_|_|_| |_|_|_|_| *
* *
* http://www.humus.name *
* *
* This file is a part of the work done by Humus. You are free to *
* use the code in any way you like, modified, unmodified or copied *
* into your own work. However, I expect you to respect these points: *
* - If you use this file and its contents unmodified, or use a major *
* part of this file, please credit the author and leave this note. *
* - For use in anything commercial, please request my approval. *
* - Share your work and ideas too as much as you can. *
* *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Direct3DRenderer.h"
#include "../Util/String.h"
struct Texture {
LPDIRECT3DBASETEXTURE9 texture;
LPDIRECT3DSURFACE9 *surfaces;
int width, height;
uint flags;
DWORD usage;
FORMAT format;
bool mipMapped;
// TextureFilter filter;
// float lod;
};
struct Constant {
char *name;
int vsReg;
int psReg;
};
int constantComp(const void *s0, const void *s1){
return strcmp(((Constant *) s0)->name, ((Constant *) s1)->name);
}
struct Sampler {
char *name;
uint index;
};
int samplerComp(const void *s0, const void *s1){
return strcmp(((Sampler *) s0)->name, ((Sampler *) s1)->name);
}
struct Shader {
LPDIRECT3DVERTEXSHADER9 vertexShader;
LPDIRECT3DPIXELSHADER9 pixelShader;
ID3DXConstantTable *vsConstants;
ID3DXConstantTable *psConstants;
Constant *constants;
Sampler *samplers;
uint nConstants;
uint nSamplers;
};
struct VertexFormat {
LPDIRECT3DVERTEXDECLARATION9 vertexDecl;
uint vertexSize[MAX_VERTEXSTREAM];
};
struct VertexBuffer {
LPDIRECT3DVERTEXBUFFER9 vertexBuffer;
long size;
DWORD usage;
};
struct IndexBuffer {
LPDIRECT3DINDEXBUFFER9 indexBuffer;
uint nIndices;
uint indexSize;
DWORD usage;
};
struct SamplerState {
D3DTEXTUREFILTERTYPE minFilter;
D3DTEXTUREFILTERTYPE magFilter;
D3DTEXTUREFILTERTYPE mipFilter;
D3DTEXTUREADDRESS wrapS;
D3DTEXTUREADDRESS wrapT;
D3DTEXTUREADDRESS wrapR;
DWORD maxAniso;
float lod;
D3DCOLOR borderColor;
};
struct BlendState {
int srcFactorRGB;
int dstFactorRGB;
int blendModeRGB;
int srcFactorAlpha;
int dstFactorAlpha;
int blendModeAlpha;
int mask;
bool blendEnable;
};
struct DepthState {
int depthFunc;
bool depthTest;
bool depthWrite;
};
struct RasterizerState {
int cullMode;
int fillMode;
bool multiSample;
bool scissor;
};
// Blending constants
const int ZERO = D3DBLEND_ZERO;
const int ONE = D3DBLEND_ONE;
const int SRC_COLOR = D3DBLEND_SRCCOLOR;
const int ONE_MINUS_SRC_COLOR = D3DBLEND_INVSRCCOLOR;
const int DST_COLOR = D3DBLEND_DESTCOLOR;
const int ONE_MINUS_DST_COLOR = D3DBLEND_INVDESTCOLOR;
const int SRC_ALPHA = D3DBLEND_SRCALPHA;
const int ONE_MINUS_SRC_ALPHA = D3DBLEND_INVSRCALPHA;
const int DST_ALPHA = D3DBLEND_DESTALPHA;
const int ONE_MINUS_DST_ALPHA = D3DBLEND_INVDESTALPHA;
const int SRC_ALPHA_SATURATE = D3DBLEND_SRCALPHASAT;
const int BM_ADD = D3DBLENDOP_ADD;
const int BM_SUBTRACT = D3DBLENDOP_SUBTRACT;
const int BM_REVERSE_SUBTRACT = D3DBLENDOP_REVSUBTRACT;
const int BM_MIN = D3DBLENDOP_MIN;
const int BM_MAX = D3DBLENDOP_MAX;
// Depth-test constants
const int NEVER = D3DCMP_NEVER;
const int LESS = D3DCMP_LESS;
const int EQUAL = D3DCMP_EQUAL;
const int LEQUAL = D3DCMP_LESSEQUAL;
const int GREATER = D3DCMP_GREATER;
const int NOTEQUAL = D3DCMP_NOTEQUAL;
const int GEQUAL = D3DCMP_GREATEREQUAL;
const int ALWAYS = D3DCMP_ALWAYS;
// Stencil-test constants
const int KEEP = D3DSTENCILOP_KEEP;
const int SET_ZERO = D3DSTENCILOP_ZERO;
const int REPLACE = D3DSTENCILOP_REPLACE;
const int INVERT = D3DSTENCILOP_INVERT;
const int INCR = D3DSTENCILOP_INCR;
const int DECR = D3DSTENCILOP_DECR;
const int INCR_SAT = D3DSTENCILOP_INCRSAT;
const int DECR_SAT = D3DSTENCILOP_DECRSAT;
// Culling constants
const int CULL_NONE = D3DCULL_NONE;
const int CULL_BACK = D3DCULL_CCW;
const int CULL_FRONT = D3DCULL_CW;
// Fillmode constants
const int SOLID = D3DFILL_SOLID;
const int WIREFRAME = D3DFILL_WIREFRAME;
static D3DFORMAT formats[] = {
D3DFMT_UNKNOWN,
// Unsigned formats
D3DFMT_L8,
D3DFMT_A8L8,
D3DFMT_X8R8G8B8,
D3DFMT_A8R8G8B8,
D3DFMT_L16,
D3DFMT_G16R16,
D3DFMT_UNKNOWN, // RGB16 not directly supported
D3DFMT_A16B16G16R16,
// Signed formats
D3DFMT_UNKNOWN,
D3DFMT_V8U8,
D3DFMT_UNKNOWN,
D3DFMT_Q8W8V8U8,
D3DFMT_UNKNOWN,
D3DFMT_V16U16,
D3DFMT_UNKNOWN,
D3DFMT_Q16W16V16U16,
// Float formats
D3DFMT_R16F,
D3DFMT_G16R16F,
D3DFMT_UNKNOWN, // RGB16F not directly supported
D3DFMT_A16B16G16R16F,
D3DFMT_R32F,
D3DFMT_G32R32F,
D3DFMT_UNKNOWN, // RGB32F not directly supported
D3DFMT_A32B32G32R32F,
// Signed integer formats
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
// Unsigned integer formats
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
D3DFMT_UNKNOWN,
// Packed formats
D3DFMT_UNKNOWN, // RGBE8 not directly supported
D3DFMT_UNKNOWN, // RGB9E5 not supported
D3DFMT_UNKNOWN, // RG11B10F not supported
D3DFMT_R5G6B5,
D3DFMT_A4R4G4B4,
D3DFMT_A2B10G10R10,
// Depth formats
D3DFMT_D16,
D3DFMT_D24X8,
D3DFMT_D24S8,
D3DFMT_D32F_LOCKABLE,
// Compressed formats
D3DFMT_DXT1,
D3DFMT_DXT3,
D3DFMT_DXT5,
(D3DFORMAT) '1ITA', // 3Dc 1 channel
(D3DFORMAT) '2ITA', // 3Dc 2 channels
};
Direct3DRenderer::Direct3DRenderer(const LPDIRECT3DDEVICE9 d3ddev, const D3DCAPS9 &d3dcaps) : Renderer(){
dev = d3ddev;
createFrameBufferSurfaces();
if (d3dcaps.PixelShaderVersion >= D3DPS_VERSION(1,0)){
nImageUnits = 4;
if (d3dcaps.PixelShaderVersion >= D3DPS_VERSION(1,4)) nImageUnits = 6;
if (d3dcaps.PixelShaderVersion >= D3DPS_VERSION(2,0)) nImageUnits = 16;
} else {
nImageUnits = d3dcaps.MaxSimultaneousTextures;
}
maxAnisotropic = d3dcaps.MaxAnisotropy;
nMRTs = d3dcaps.NumSimultaneousRTs;
if (nMRTs > MAX_MRTS) nMRTs = MAX_MRTS;
plainShader = SHADER_NONE;
plainVF = VF_NONE;
texShader = SHADER_NONE;
texVF = VF_NONE;
eventQuery = NULL;
setD3Ddefaults();
resetToDefaults();
}
Direct3DRenderer::~Direct3DRenderer(){
if (eventQuery) eventQuery->Release();
releaseFrameBufferSurfaces();
// Delete shaders
for (uint i = 0; i < shaders.getCount(); i++){
if (shaders[i].vertexShader) shaders[i].vertexShader->Release();
if (shaders[i].pixelShader) shaders[i].pixelShader->Release();
if (shaders[i].vsConstants) shaders[i].vsConstants->Release();
if (shaders[i].psConstants) shaders[i].psConstants->Release();
for (uint j = 0; j < shaders[i].nSamplers; j++){
delete shaders[i].samplers[j].name;
}
for (uint j = 0; j < shaders[i].nConstants; j++){
delete shaders[i].constants[j].name;
}
delete shaders[i].samplers;
delete shaders[i].constants;
}
// Delete vertex formats
for (uint i = 0; i < vertexFormats.getCount(); i++){
if (vertexFormats[i].vertexDecl) vertexFormats[i].vertexDecl->Release();
}
// Delete vertex buffers
for (uint i = 0; i < vertexBuffers.getCount(); i++){
if (vertexBuffers[i].vertexBuffer) vertexBuffers[i].vertexBuffer->Release();
}
// Delete index buffers
for (uint i = 0; i < indexBuffers.getCount(); i++){
if (indexBuffers[i].indexBuffer) indexBuffers[i].indexBuffer->Release();
}
// Delete textures
for (uint i = 0; i < textures.getCount(); i++){
removeTexture(i);
}
}
bool Direct3DRenderer::createFrameBufferSurfaces(){
if (dev->GetRenderTarget(0, &fbColor) != D3D_OK) return false;
dev->GetDepthStencilSurface(&fbDepth);
return true;
}
bool Direct3DRenderer::releaseFrameBufferSurfaces(){
if (fbColor) fbColor->Release();
if (fbDepth) fbDepth->Release();
return true;
}
void Direct3DRenderer::resetToDefaults(){
Renderer::resetToDefaults();
for (uint i = 0; i < MAX_TEXTUREUNIT; i++){
currentTextures[i] = TEXTURE_NONE;
}
for (uint i = 0; i < MAX_SAMPLERSTATE; i++){
currentSamplerStates[i] = SS_NONE;
}
currentSrcFactorRGB = currentSrcFactorAlpha = ONE;
currentDstFactorRGB = currentDstFactorAlpha = ZERO;
currentBlendModeRGB = currentBlendModeAlpha = BM_ADD;
currentMask = ALL;
currentBlendEnable = false;
currentDepthFunc = LESS;
currentDepthTestEnable = true;
currentDepthWriteEnable = true;
currentCullMode = CULL_NONE;
currentFillMode = SOLID;
currentMultiSampleEnable = true;
currentScissorEnable = false;
currentDepthRT = FB_DEPTH;
memset(vsRegs, 0, sizeof(vsRegs));
memset(psRegs, 0, sizeof(psRegs));
minVSDirty = 256;
maxVSDirty = -1;
minPSDirty = 224;
maxPSDirty = -1;
}
void Direct3DRenderer::reset(const uint flags){
Renderer::reset(flags);
if (flags & RESET_TEX){
for (uint i = 0; i < MAX_TEXTUREUNIT; i++){
selectedTextures[i] = TEXTURE_NONE;
}
}
if (flags & RESET_SS){
for (uint i = 0; i < MAX_SAMPLERSTATE; i++){
selectedSamplerStates[i] = SS_NONE;
}
}
}
void Direct3DRenderer::setD3Ddefaults(){
// Set some of my preferred defaults
dev->SetRenderState(D3DRS_LIGHTING, FALSE);
dev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
dev->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
dev->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
if (maxAnisotropic > 1){
for (uint i = 0; i < nImageUnits; i++){
dev->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, maxAnisotropic);
}
}
}
bool createRenderTarget(LPDIRECT3DDEVICE9 dev, Texture &tex){
if (isDepthFormat(tex.format)){
if (tex.surfaces == NULL) tex.surfaces = new LPDIRECT3DSURFACE9;
if (dev->CreateDepthStencilSurface(tex.width, tex.height, formats[tex.format], D3DMULTISAMPLE_NONE, 0, FALSE, tex.surfaces, NULL) != D3D_OK){
delete tex.surfaces;
ErrorMsg("Couldn't create depth surface");
return false;
}
} else {
if (tex.flags & CUBEMAP){
if (dev->CreateCubeTexture(tex.width, tex.mipMapped? 0 : 1, tex.usage, formats[tex.format], D3DPOOL_DEFAULT, (LPDIRECT3DCUBETEXTURE9 *) &tex.texture, NULL) != D3D_OK){
ErrorMsg("Couldn't create render target");
return false;
}
if (tex.surfaces == NULL) tex.surfaces = new LPDIRECT3DSURFACE9[6];
for (uint i = 0; i < 6; i++){
((LPDIRECT3DCUBETEXTURE9) tex.texture)->GetCubeMapSurface((D3DCUBEMAP_FACES) i, 0, &tex.surfaces[i]);
}
} else {
if (dev->CreateTexture(tex.width, tex.height, tex.mipMapped? 0 : 1, tex.usage, formats[tex.format], D3DPOOL_DEFAULT, (LPDIRECT3DTEXTURE9 *) &tex.texture, NULL) != D3D_OK){
ErrorMsg("Couldn't create render target");
return false;
}
if (tex.surfaces == NULL) tex.surfaces = new LPDIRECT3DSURFACE9;
((LPDIRECT3DTEXTURE9) tex.texture)->GetSurfaceLevel(0, tex.surfaces);
}
}
return true;
}
bool Direct3DRenderer::resetDevice(D3DPRESENT_PARAMETERS &d3dpp){
for (uint i = 0; i < textures.getCount(); i++){
if (textures[i].surfaces){
int n = (textures[i].flags & CUBEMAP)? 6 : 1;
if (textures[i].texture) textures[i].texture->Release();
for (int k = 0; k < n; k++){
textures[i].surfaces[k]->Release();
}
}
}
if (!releaseFrameBufferSurfaces()) return false;
if (dev->Reset(&d3dpp) != D3D_OK){
ErrorMsg("Device reset failed");
return false;
}
if (!createFrameBufferSurfaces()) return false;
resetToDefaults();
setD3Ddefaults();
for (uint i = 0; i < textures.getCount(); i++){
if (textures[i].surfaces){
createRenderTarget(dev, textures[i]);
}
}
return true;
}
// Returns the closest power of two
int getPow2(const int x){
int i = 1;
while (i < x) i += i;
if (4 * x < 3 * i) i >>= 1;
return i;
}
TextureID Direct3DRenderer::addTexture(Image &img, const SamplerStateID samplerState, uint flags){
Texture tex;
memset(&tex, 0, sizeof(tex));
tex.mipMapped = (img.getMipMapCount() > 1);
FORMAT format = img.getFormat();
if (img.isCube()){
if (dev->CreateCubeTexture(img.getWidth(), img.getMipMapCount(), 0, formats[format], D3DPOOL_MANAGED, (LPDIRECT3DCUBETEXTURE9 *) &tex.texture, NULL) != D3D_OK){
ErrorMsg("Couldn't create cubemap");
return false;
}
} else if (img.is3D()){
if (dev->CreateVolumeTexture(img.getWidth(), img.getHeight(), img.getDepth(), img.getMipMapCount(), 0, formats[format], D3DPOOL_MANAGED, (LPDIRECT3DVOLUMETEXTURE9 *) &tex.texture, NULL) != D3D_OK){
ErrorMsg("Couldn't create volumetric texture");
return false;
}
} else {
D3DFORMAT form = formats[format];
if (dev->CreateTexture(img.getWidth(), img.getHeight(), img.getMipMapCount(), 0, formats[format], D3DPOOL_MANAGED, (LPDIRECT3DTEXTURE9 *) &tex.texture, NULL) != D3D_OK){
ErrorMsg("Couldn't create texture");
return false;
}
}
if (format == FORMAT_RGB8) img.convert(FORMAT_RGBA8);
if (format == FORMAT_RGB8 || format == FORMAT_RGBA8) img.swap(0, 2);
unsigned char *src;
int mipMapLevel = 0;
while ((src = img.getPixels(mipMapLevel)) != NULL){
int size = img.getMipMappedSize(mipMapLevel, 1);
if (img.is3D()){
D3DLOCKED_BOX box;
if (((LPDIRECT3DVOLUMETEXTURE9) tex.texture)->LockBox(mipMapLevel, &box, NULL, 0) == D3D_OK){
memcpy(box.pBits, src, size);
((LPDIRECT3DVOLUMETEXTURE9) tex.texture)->UnlockBox(mipMapLevel);
}
} else if (img.isCube()){
size /= 6;
D3DLOCKED_RECT rect;
for (int i = 0; i < 6; i++){
if (((LPDIRECT3DCUBETEXTURE9) tex.texture)->LockRect((D3DCUBEMAP_FACES) i, mipMapLevel, &rect, NULL, 0) == D3D_OK){
memcpy(rect.pBits, src, size);
((LPDIRECT3DCUBETEXTURE9) tex.texture)->UnlockRect((D3DCUBEMAP_FACES) i, mipMapLevel);
}
src += size;
}
} else {
D3DLOCKED_RECT rect;
if (((LPDIRECT3DTEXTURE9) tex.texture)->LockRect(mipMapLevel, &rect, NULL, 0) == D3D_OK){
memcpy(rect.pBits, src, size);
((LPDIRECT3DTEXTURE9) tex.texture)->UnlockRect(mipMapLevel);
}
}
mipMapLevel++;
}
// setupFilter(tex, filter, flags);
// tex.lod = lod;
return textures.add(tex);
}
TextureID Direct3DRenderer::addRenderTarget(const int width, const int height, const int depth, const int mipMapCount, const int arraySize, const FORMAT format, const int msaaSamples, const SamplerStateID samplerState, uint flags){
if (depth > 1 || arraySize > 1) return TEXTURE_NONE;
// For now ...
if (msaaSamples > 1 || mipMapCount > 1) return TEXTURE_NONE;
Texture tex;
memset(&tex, 0, sizeof(tex));
tex.width = width;
tex.height = height;
tex.format = format;
tex.usage = D3DUSAGE_RENDERTARGET;
tex.flags = flags;
tex.mipMapped = false;
if (flags & R2VB) tex.usage |= D3DUSAGE_DMAP;
if (createRenderTarget(dev, tex)){
// setupFilter(tex, filter, flags);
return textures.add(tex);
} else {
return TEXTURE_NONE;
}
}
TextureID Direct3DRenderer::addRenderDepth(const int width, const int height, const int arraySize, const FORMAT format, const int msaaSamples, const SamplerStateID samplerState, uint flags){
// For now ...
if (msaaSamples > 1) return TEXTURE_NONE;
Texture tex;
memset(&tex, 0, sizeof(tex));
tex.format = format;
tex.width = width;
tex.height = height;
if (createRenderTarget(dev, tex)){
return textures.add(tex);
} else {
return TEXTURE_NONE;
}
}
bool Direct3DRenderer::resizeRenderTarget(const TextureID renderTarget, const int width, const int height, const int depth, const int mipMapCount, const int arraySize){
if (depth > 1 || arraySize > 1 || mipMapCount > 1) return false;
if (textures[renderTarget].surfaces){
int n = (textures[renderTarget].flags & CUBEMAP)? 6 : 1;
if (textures[renderTarget].texture) textures[renderTarget].texture->Release();
for (int k = 0; k < n; k++){
textures[renderTarget].surfaces[k]->Release();
}
}
textures[renderTarget].width = width;
textures[renderTarget].height = height;
return createRenderTarget(dev, textures[renderTarget]);
}
bool Direct3DRenderer::generateMipMaps(const TextureID renderTarget){
// TODO: Implement
return false;
}
void Direct3DRenderer::removeTexture(const TextureID texture){
if (textures[texture].surfaces){
int n = (textures[texture].flags & CUBEMAP)? 6 : 1;
for (int k = 0; k < n; k++){
textures[texture].surfaces[k]->Release();
}
delete textures[texture].surfaces;
textures[texture].surfaces = NULL;
}
if (textures[texture].texture){
textures[texture].texture->Release();
textures[texture].texture = NULL;
}
}
ShaderID Direct3DRenderer::addShader(const char *vsText, const char *gsText, const char *fsText, const int vsLine, const int gsLine, const int fsLine,
const char *header, const char *extra, const char *fileName, const char **attributeNames, const int nAttributes, const uint flags){
if (vsText == NULL && fsText == NULL) return SHADER_NONE;
LPD3DXBUFFER shaderBuf = NULL;
LPD3DXBUFFER errorsBuf = NULL;
Shader shader;
shader.vertexShader = NULL;
shader.pixelShader = NULL;
shader.vsConstants = NULL;
shader.psConstants = NULL;
if (vsText != NULL){
String shaderString;
if (extra != NULL) shaderString += extra;
if (header != NULL) shaderString += header;
shaderString.sprintf("#line %d\n", vsLine + 1);
shaderString += vsText;
const char *profile = D3DXGetVertexShaderProfile(dev);
if (D3DXCompileShader(shaderString, shaderString.getLength(), NULL, NULL, "main", profile, D3DXSHADER_DEBUG | D3DXSHADER_PACKMATRIX_ROWMAJOR, &shaderBuf, &errorsBuf, &shader.vsConstants) == D3D_OK){
dev->CreateVertexShader((DWORD *) shaderBuf->GetBufferPointer(), &shader.vertexShader);
#ifdef DEBUG
LPD3DXBUFFER disasm;
D3DXDisassembleShader((DWORD *) shaderBuf->GetBufferPointer(), FALSE, NULL, &disasm);
char *str = (char *) disasm->GetBufferPointer();
while (*str){
while (*str == '\n' || *str == '\r') *str++;
char *endStr = str;
while (*endStr && *endStr != '\n' && *endStr != '\r') *endStr++;
if (*str != '#'){
*endStr = '\0';
outputDebugString(str);
}
str = endStr + 1;
}
if (disasm != NULL) disasm->Release();
#endif
} else {
ErrorMsg((const char *) errorsBuf->GetBufferPointer());
}
if (shaderBuf != NULL) shaderBuf->Release();
if (errorsBuf != NULL) errorsBuf->Release();
if (shader.vertexShader == NULL) return SHADER_NONE;
}
if (fsText != NULL){
String shaderString;
if (extra != NULL) shaderString += extra;
if (header != NULL) shaderString += header;
shaderString.sprintf("#line %d\n", fsLine + 1);
shaderString += fsText;
const char *profile = D3DXGetPixelShaderProfile(dev);
if (D3DXCompileShader(shaderString, shaderString.getLength(), NULL, NULL, "main", profile, D3DXSHADER_DEBUG | D3DXSHADER_PACKMATRIX_ROWMAJOR, &shaderBuf, &errorsBuf, &shader.psConstants) == D3D_OK){
dev->CreatePixelShader((DWORD *) shaderBuf->GetBufferPointer(), &shader.pixelShader);
#ifdef DEBUG
LPD3DXBUFFER disasm;
D3DXDisassembleShader((DWORD *) shaderBuf->GetBufferPointer(), FALSE, NULL, &disasm);
char *str = (char *) disasm->GetBufferPointer();
while (*str){
while (*str == '\n' || *str == '\r') *str++;
char *endStr = str;
while (*endStr && *endStr != '\n' && *endStr != '\r') *endStr++;
if (*str != '#'){
*endStr = '\0';
outputDebugString(str);
}
str = endStr + 1;
}
if (disasm != NULL) disasm->Release();
#endif
} else {
ErrorMsg((const char *) errorsBuf->GetBufferPointer());
}
if (shaderBuf != NULL) shaderBuf->Release();
if (errorsBuf != NULL) errorsBuf->Release();
if (shader.pixelShader == NULL) return SHADER_NONE;
}
D3DXCONSTANTTABLE_DESC vsDesc, psDesc;
shader.vsConstants->GetDesc(&vsDesc);
shader.psConstants->GetDesc(&psDesc);
uint count = vsDesc.Constants + psDesc.Constants;
Sampler *samplers = (Sampler *) malloc(count * sizeof(Sampler));
Constant *constants = (Constant *) malloc(count * sizeof(Constant));
uint nSamplers = 0;
uint nConstants = 0;
D3DXCONSTANT_DESC cDesc;
for (uint i = 0; i < vsDesc.Constants; i++){
UINT count = 1;
shader.vsConstants->GetConstantDesc(shader.vsConstants->GetConstant(NULL, i), &cDesc, &count);
size_t length = strlen(cDesc.Name);
if (cDesc.Type >= D3DXPT_SAMPLER && cDesc.Type <= D3DXPT_SAMPLERCUBE){
// TODO: Vertex samplers not yet supported ...
} else {
constants[nConstants].name = new char[length + 1];
strcpy(constants[nConstants].name, cDesc.Name);
constants[nConstants].vsReg = cDesc.RegisterIndex;
constants[nConstants].psReg = -1;
//constants[nConstants].nElements = cDesc.RegisterCount;
nConstants++;
}
}
uint nVSConsts = nConstants;
for (uint i = 0; i < psDesc.Constants; i++){
UINT count = 1;
shader.psConstants->GetConstantDesc(shader.psConstants->GetConstant(NULL, i), &cDesc, &count);
size_t length = strlen(cDesc.Name);
if (cDesc.Type >= D3DXPT_SAMPLER && cDesc.Type <= D3DXPT_SAMPLERCUBE){
samplers[nSamplers].name = new char[length + 1];
samplers[nSamplers].index = cDesc.RegisterIndex;
strcpy(samplers[nSamplers].name, cDesc.Name);
nSamplers++;
} else {
int merge = -1;
for (uint i = 0; i < nVSConsts; i++){
if (strcmp(constants[i].name, cDesc.Name) == 0){
merge = i;
break;
}
}
if (merge < 0){
constants[nConstants].name = new char[length + 1];
strcpy(constants[nConstants].name, cDesc.Name);
constants[nConstants].vsReg = -1;
constants[nConstants].psReg = cDesc.RegisterIndex;
//constants[nConstants].nElements = cDesc.RegisterCount;
} else {
constants[merge].psReg = cDesc.RegisterIndex;
}
nConstants++;
}
}
// Shorten arrays to actual count
samplers = (Sampler *) realloc(samplers, nSamplers * sizeof(Sampler));
constants = (Constant *) realloc(constants, nConstants * sizeof(Constant));
qsort(samplers, nSamplers, sizeof(Sampler), samplerComp);
qsort(constants, nConstants, sizeof(Constant), constantComp);
shader.constants = constants;
shader.samplers = samplers;
shader.nConstants = nConstants;
shader.nSamplers = nSamplers;
return shaders.add(shader);
}
VertexFormatID Direct3DRenderer::addVertexFormat(const FormatDesc *formatDesc, const uint nAttribs, const ShaderID shader){
static const D3DDECLTYPE types[][4] = {
D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT4,
D3DDECLTYPE_UNUSED, D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_UNUSED, D3DDECLTYPE_FLOAT16_4,
D3DDECLTYPE_UNUSED, D3DDECLTYPE_UNUSED, D3DDECLTYPE_UNUSED, D3DDECLTYPE_UBYTE4N,
};
static const D3DDECLUSAGE usages[] = {
(D3DDECLUSAGE) (-1),
D3DDECLUSAGE_POSITION,
D3DDECLUSAGE_TEXCOORD,
D3DDECLUSAGE_NORMAL,
D3DDECLUSAGE_TANGENT,
D3DDECLUSAGE_BINORMAL,
};
int index[6];
memset(index, 0, sizeof(index));
VertexFormat vf;
memset(vf.vertexSize, 0, sizeof(vf.vertexSize));
D3DVERTEXELEMENT9 *vElem = new D3DVERTEXELEMENT9[nAttribs + 1];
// Fill the vertex element array
for (uint i = 0; i < nAttribs; i++){
int stream = formatDesc[i].stream;
int size = formatDesc[i].size;
vElem[i].Stream = stream;
vElem[i].Offset = vf.vertexSize[stream];
vElem[i].Type = types[formatDesc[i].format][size - 1];
vElem[i].Method = D3DDECLMETHOD_DEFAULT;
vElem[i].Usage = usages[formatDesc[i].type];
vElem[i].UsageIndex = index[formatDesc[i].type]++;
vf.vertexSize[stream] += size * getFormatSize(formatDesc[i].format);
}
// Terminating element
memset(vElem + nAttribs, 0, sizeof(D3DVERTEXELEMENT9));
vElem[nAttribs].Stream = 0xFF;
vElem[nAttribs].Type = D3DDECLTYPE_UNUSED;
HRESULT hr = dev->CreateVertexDeclaration(vElem, &vf.vertexDecl);
delete vElem;
if (hr != D3D_OK){
ErrorMsg("Couldn't create vertex declaration");
return VF_NONE;
}
return vertexFormats.add(vf);
}
DWORD usages[] = {
0,
D3DUSAGE_DYNAMIC,
D3DUSAGE_DYNAMIC,
};
VertexBufferID Direct3DRenderer::addVertexBuffer(const long size, const BufferAccess bufferAccess, const void *data){
VertexBuffer vb;
vb.size = size;
vb.usage = usages[bufferAccess];
bool dynamic = (vb.usage & D3DUSAGE_DYNAMIC) != 0;
if (dev->CreateVertexBuffer(size, vb.usage, 0, dynamic? D3DPOOL_DEFAULT : D3DPOOL_MANAGED, &vb.vertexBuffer, NULL) != D3D_OK){
ErrorMsg("Couldn't create vertex buffer");
return VB_NONE;
}
if (data != NULL){
void *dest;
if (vb.vertexBuffer->Lock(0, size, &dest, dynamic? D3DLOCK_DISCARD : 0) == D3D_OK){
memcpy(dest, data, size);
vb.vertexBuffer->Unlock();
}
}
return vertexBuffers.add(vb);
}
IndexBufferID Direct3DRenderer::addIndexBuffer(const uint nIndices, const uint indexSize, const BufferAccess bufferAccess, const void *data){
IndexBuffer ib;
ib.nIndices = nIndices;
ib.indexSize = indexSize;
ib.usage = usages[bufferAccess];
bool dynamic = (ib.usage & D3DUSAGE_DYNAMIC) != 0;
uint size = nIndices * indexSize;
if (dev->CreateIndexBuffer(size, ib.usage, indexSize == 2? D3DFMT_INDEX16 : D3DFMT_INDEX32, dynamic? D3DPOOL_DEFAULT : D3DPOOL_MANAGED, &ib.indexBuffer, NULL) != D3D_OK){
ErrorMsg("Couldn't create index buffer");
return IB_NONE;
}
// Upload the provided index data if any
if (data != NULL){
void *dest;
if (ib.indexBuffer->Lock(0, size, &dest, dynamic? D3DLOCK_DISCARD : 0) == D3D_OK){
memcpy(dest, data, size);
ib.indexBuffer->Unlock();
} else {
ErrorMsg("Couldn't lock index buffer");
}
}
return indexBuffers.add(ib);
}
SamplerStateID Direct3DRenderer::addSamplerState(const Filter filter, const AddressMode s, const AddressMode t, const AddressMode r, const float lod, const uint maxAniso, const int compareFunc, const float *border_color){
SamplerState samplerState;
samplerState.minFilter = hasAniso(filter)? D3DTEXF_ANISOTROPIC : (filter != NEAREST)? D3DTEXF_LINEAR : D3DTEXF_POINT;
samplerState.magFilter = hasAniso(filter)? D3DTEXF_ANISOTROPIC : (filter != NEAREST)? D3DTEXF_LINEAR : D3DTEXF_POINT;
samplerState.mipFilter = (filter == TRILINEAR || filter == TRILINEAR_ANISO)? D3DTEXF_LINEAR : hasMipmaps(filter)? D3DTEXF_POINT : D3DTEXF_NONE;
samplerState.wrapS = (s == WRAP)? D3DTADDRESS_WRAP : (s == CLAMP)? D3DTADDRESS_CLAMP : D3DTADDRESS_BORDER;
samplerState.wrapT = (t == WRAP)? D3DTADDRESS_WRAP : (t == CLAMP)? D3DTADDRESS_CLAMP : D3DTADDRESS_BORDER;
samplerState.wrapR = (r == WRAP)? D3DTADDRESS_WRAP : (r == CLAMP)? D3DTADDRESS_CLAMP : D3DTADDRESS_BORDER;
samplerState.maxAniso = min((uint) maxAnisotropic, maxAniso);
samplerState.lod = lod;
if (border_color)
{
samplerState.borderColor = D3DCOLOR_ARGB(
uint32(border_color[3] * 255.0f + 0.5f),
uint32(border_color[0] * 255.0f + 0.5f),
uint32(border_color[1] * 255.0f + 0.5f),
uint32(border_color[2] * 255.0f + 0.5f));
}
else
{
samplerState.borderColor = 0;
}
return samplerStates.add(samplerState);
}
BlendStateID Direct3DRenderer::addBlendState(const int srcFactorRGB, const int destFactorRGB, const int srcFactorAlpha, const int destFactorAlpha, const int blendModeRGB, const int blendModeAlpha, const int mask, const bool alphaToCoverage){
BlendState blendState;
blendState.srcFactorRGB = srcFactorRGB;
blendState.dstFactorRGB = destFactorRGB;
blendState.blendModeRGB = blendModeRGB;
blendState.srcFactorAlpha = srcFactorAlpha;
blendState.dstFactorAlpha = destFactorAlpha;
blendState.blendModeAlpha = blendModeAlpha;
blendState.mask = mask;
blendState.blendEnable = (srcFactorRGB != ONE || destFactorRGB != ZERO || srcFactorAlpha != ONE || destFactorAlpha != ZERO);
return blendStates.add(blendState);
}
DepthStateID Direct3DRenderer::addDepthState(const bool depthTest, const bool depthWrite, const int depthFunc,
const bool stencilTest, const uint8 stencilMask, const int stencilFunc,
const int stencilFail, const int depthFail, const int stencilPass){
// TODO: Add stencil support...
DepthState depthState;
depthState.depthTest = depthTest;
depthState.depthWrite = depthWrite;
depthState.depthFunc = depthFunc;
return depthStates.add(depthState);
}
RasterizerStateID Direct3DRenderer::addRasterizerState(const int cullMode, const int fillMode, const bool multiSample, const bool scissor){
RasterizerState rasterizerState;
rasterizerState.cullMode = cullMode;
rasterizerState.fillMode = fillMode;
rasterizerState.multiSample = multiSample;
rasterizerState.scissor = scissor;
return rasterizerStates.add(rasterizerState);
}
int Direct3DRenderer::getSamplerUnit(const ShaderID shader, const char *samplerName) const {
Sampler *samplers = shaders[shader].samplers;
int minSampler = 0;
int maxSampler = shaders[shader].nSamplers - 1;
// Do a quick lookup in the sorted table with a binary search
while (minSampler <= maxSampler){
int currSampler = (minSampler + maxSampler) >> 1;
int res = strcmp(samplerName, samplers[currSampler].name);
if (res == 0){
return samplers[currSampler].index;
} else if (res > 0){
minSampler = currSampler + 1;
} else {
maxSampler = currSampler - 1;
}
}
return -1;
}
void Direct3DRenderer::setTexture(const char *textureName, const TextureID texture){
int unit = getSamplerUnit(selectedShader, textureName);
if (unit >= 0){
selectedTextures[unit] = texture;
}
}
void Direct3DRenderer::setTexture(const char *textureName, const TextureID texture, const SamplerStateID samplerState){
int unit = getSamplerUnit(selectedShader, textureName);
if (unit >= 0){
selectedTextures[unit] = texture;
selectedSamplerStates[unit] = samplerState;
}
}
void Direct3DRenderer::setTextureSlice(const char *textureName, const TextureID texture, const int slice){
ASSERT(0);
}
void Direct3DRenderer::applyTextures(){
for (uint i = 0; i < MAX_TEXTUREUNIT; i++){
TextureID texture = selectedTextures[i];
if (texture != currentTextures[i]){
if (texture == TEXTURE_NONE){
dev->SetTexture(i, NULL);
} else {
dev->SetTexture(i, textures[texture].texture);
}
currentTextures[i] = texture;
}
}
}
void Direct3DRenderer::setSamplerState(const char *samplerName, const SamplerStateID samplerState){
int unit = getSamplerUnit(selectedShader, samplerName);
if (unit >= 0){
selectedSamplerStates[unit] = samplerState;
}
}
void Direct3DRenderer::applySamplerStates(){
for (uint i = 0; i < MAX_SAMPLERSTATE; i++){
SamplerStateID samplerState = selectedSamplerStates[i];
if (samplerState != currentSamplerStates[i]){
SamplerState ss, css;
if (samplerState == SS_NONE){
ss.magFilter = D3DTEXF_POINT;
ss.minFilter = D3DTEXF_POINT;
ss.mipFilter = D3DTEXF_NONE;
ss.wrapS = D3DTADDRESS_WRAP;
ss.wrapT = D3DTADDRESS_WRAP;
ss.wrapR = D3DTADDRESS_WRAP;
ss.maxAniso = 1;
} else {
ss = samplerStates[samplerState];
}
if (currentSamplerStates[i] == SS_NONE){
css.magFilter = D3DTEXF_POINT;
css.minFilter = D3DTEXF_POINT;
css.mipFilter = D3DTEXF_NONE;
css.wrapS = D3DTADDRESS_WRAP;
css.wrapT = D3DTADDRESS_WRAP;
css.wrapR = D3DTADDRESS_WRAP;
css.maxAniso = 1;
} else {
css = samplerStates[currentSamplerStates[i]];
}
if (ss.minFilter != css.minFilter) dev->SetSamplerState(i, D3DSAMP_MINFILTER, ss.minFilter);
if (ss.magFilter != css.magFilter) dev->SetSamplerState(i, D3DSAMP_MAGFILTER, ss.magFilter);
if (ss.mipFilter != css.mipFilter) dev->SetSamplerState(i, D3DSAMP_MIPFILTER, ss.mipFilter);
if (ss.wrapS != css.wrapS) dev->SetSamplerState(i, D3DSAMP_ADDRESSU, ss.wrapS);
if (ss.wrapT != css.wrapT) dev->SetSamplerState(i, D3DSAMP_ADDRESSV, ss.wrapT);
if (ss.wrapR != css.wrapR) dev->SetSamplerState(i, D3DSAMP_ADDRESSW, ss.wrapR);
if (ss.maxAniso != css.maxAniso) dev->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, ss.maxAniso);
if (ss.lod != css.lod) dev->SetSamplerState(i, D3DSAMP_MIPMAPLODBIAS, *(DWORD *) &ss.lod);
if (ss.borderColor != css.borderColor) dev->SetSamplerState(i, D3DSAMP_BORDERCOLOR, ss.borderColor);
currentSamplerStates[i] = samplerState;
}
}
}
void Direct3DRenderer::setShaderConstantRaw(const char *name, const void *data, const int size){
int minConstant = 0;
int maxConstant = shaders[selectedShader].nConstants - 1;
Constant *constants = shaders[selectedShader].constants;
// Do a quick lookup in the sorted table with a binary search
while (minConstant <= maxConstant){
int currConstant = (minConstant + maxConstant) >> 1;
int res = strcmp(name, constants[currConstant].name);
if (res == 0){
Constant *c = constants + currConstant;
if (c->vsReg >= 0){
if (memcmp(vsRegs + c->vsReg, data, size)){
memcpy(vsRegs + c->vsReg, data, size);
int r0 = c->vsReg;
int r1 = c->vsReg + ((size + 15) >> 4);
if (r0 < minVSDirty) minVSDirty = r0;
if (r1 > maxVSDirty) maxVSDirty = r1;
}
}
if (c->psReg >= 0){
if (memcmp(psRegs + c->psReg, data, size)){
memcpy(psRegs + c->psReg, data, size);
int r0 = c->psReg;
int r1 = c->psReg + ((size + 15) >> 4);
if (r0 < minPSDirty) minPSDirty = r0;
if (r1 > maxPSDirty) maxPSDirty = r1;
}
}
return;
} else if (res > 0){
minConstant = currConstant + 1;
} else {
maxConstant = currConstant - 1;
}
}
#ifdef _DEBUG
char str[256];
sprintf(str, "Invalid constant \"%s\"", name);
outputDebugString(str);
#endif
}
void Direct3DRenderer::applyConstants(){
// if (currentShader != SHADER_NONE){
if (minVSDirty < maxVSDirty){
dev->SetVertexShaderConstantF(minVSDirty, (const float *) (vsRegs + minVSDirty), maxVSDirty - minVSDirty);
minVSDirty = 256;
maxVSDirty = -1;
}
if (minPSDirty < maxPSDirty){
dev->SetPixelShaderConstantF(minPSDirty, (const float *) (psRegs + minPSDirty), maxPSDirty - minPSDirty);
minPSDirty = 224;
maxPSDirty = -1;
}
// }
}
void Direct3DRenderer::changeRenderTargets(const TextureID *colorRTs, const uint nRenderTargets, const TextureID depthRT, const int depthSlice, const int *slices){
for (uint i = 0; i < nRenderTargets; i++){
TextureID rt = colorRTs[i];
int face = (slices != NULL)? slices[i] : 0;
if (rt != currentColorRT[i] || face != currentColorRTSlice[i]){
if (face == NO_SLICE){
dev->SetRenderTarget(i, textures[rt].surfaces[0]);
} else {
dev->SetRenderTarget(i, textures[rt].surfaces[face]);
}
currentColorRT[i] = rt;
currentColorRTSlice[i] = face;
}
}
for (uint i = nRenderTargets; i < nMRTs; i++){
if (currentColorRT[i] != TEXTURE_NONE){
dev->SetRenderTarget(i, NULL);
currentColorRT[i] = TEXTURE_NONE;
}
}
if (depthRT != currentDepthRT){
if (depthRT == TEXTURE_NONE){
dev->SetDepthStencilSurface(NULL);
} else if (depthRT == FB_DEPTH){
dev->SetDepthStencilSurface(fbDepth);
} else {
dev->SetDepthStencilSurface(textures[depthRT].surfaces[0]);
}
currentDepthRT = depthRT;
}
}
void Direct3DRenderer::changeToMainFramebuffer(){
if (currentColorRT[0] != TEXTURE_NONE){
dev->SetRenderTarget(0, fbColor);
currentColorRT[0] = TEXTURE_NONE;
}
for (uint i = 1; i < nMRTs; i++){
if (currentColorRT[i] != TEXTURE_NONE){
dev->SetRenderTarget(i, NULL);
currentColorRT[i] = TEXTURE_NONE;
}
}
if (currentDepthRT != FB_DEPTH){
dev->SetDepthStencilSurface(fbDepth);
currentDepthRT = FB_DEPTH;
}
}
void Direct3DRenderer::changeShader(const ShaderID shader){
if (shader != currentShader){
if (shader == SHADER_NONE){
dev->SetVertexShader(NULL);
dev->SetPixelShader(NULL);
} else {
dev->SetVertexShader(shaders[shader].vertexShader);
dev->SetPixelShader(shaders[shader].pixelShader);
}
currentShader = shader;
}
}
void Direct3DRenderer::changeVertexFormat(const VertexFormatID vertexFormat){
if (vertexFormat != currentVertexFormat){
if (vertexFormat != VF_NONE){
dev->SetVertexDeclaration(vertexFormats[vertexFormat].vertexDecl);
if (currentVertexFormat != VF_NONE){
for (int i = 0; i < MAX_VERTEXSTREAM; i++){
if (vertexFormats[vertexFormat].vertexSize[i] != vertexFormats[currentVertexFormat].vertexSize[i]){
currentVertexBuffers[i] = VB_INVALID;
}
}
}
}
currentVertexFormat = vertexFormat;
}
}
void Direct3DRenderer::changeVertexBuffer(const int stream, const VertexBufferID vertexBuffer, const intptr offset){
if (vertexBuffer != currentVertexBuffers[stream] || offset != currentOffsets[stream]){
if (vertexBuffer == VB_NONE){
dev->SetStreamSource(stream, NULL, 0, 0);
} else {
dev->SetStreamSource(stream, vertexBuffers[vertexBuffer].vertexBuffer, (UINT) offset, vertexFormats[currentVertexFormat].vertexSize[stream]);
}
currentVertexBuffers[stream] = vertexBuffer;
currentOffsets[stream] = offset;
}
}
void Direct3DRenderer::changeIndexBuffer(const IndexBufferID indexBuffer){
if (indexBuffer != currentIndexBuffer){
if (indexBuffer == IB_NONE){
dev->SetIndices(NULL);
} else {
dev->SetIndices(indexBuffers[indexBuffer].indexBuffer);
}
currentIndexBuffer = indexBuffer;
}
}
void Direct3DRenderer::changeBlendState(const BlendStateID blendState, const uint sampleMask){
if (blendState != currentBlendState){
if (blendState == BS_NONE || !blendStates[blendState].blendEnable){
if (currentBlendEnable){
dev->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
currentBlendEnable = false;
}
} else {
if (blendStates[blendState].blendEnable){
if (!currentBlendEnable){
dev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
currentBlendEnable = true;
}
if (blendStates[blendState].srcFactorRGB != currentSrcFactorRGB){
dev->SetRenderState(D3DRS_SRCBLEND, currentSrcFactorRGB = blendStates[blendState].srcFactorRGB);
}
if (blendStates[blendState].dstFactorRGB != currentDstFactorRGB){
dev->SetRenderState(D3DRS_DESTBLEND, currentDstFactorRGB = blendStates[blendState].dstFactorRGB);
}
if (blendStates[blendState].blendModeRGB != currentBlendModeRGB){
dev->SetRenderState(D3DRS_BLENDOP, currentBlendModeRGB = blendStates[blendState].blendModeRGB);
}
if (blendStates[blendState].srcFactorAlpha != currentSrcFactorAlpha){
dev->SetRenderState(D3DRS_SRCBLENDALPHA, currentSrcFactorAlpha = blendStates[blendState].srcFactorRGB);
}
if (blendStates[blendState].dstFactorAlpha != currentDstFactorAlpha){
dev->SetRenderState(D3DRS_DESTBLENDALPHA, currentDstFactorAlpha = blendStates[blendState].dstFactorRGB);
}
if (blendStates[blendState].blendModeAlpha != currentBlendModeAlpha){
dev->SetRenderState(D3DRS_BLENDOPALPHA, currentBlendModeAlpha = blendStates[blendState].blendModeRGB);
}
}
}
int mask = ALL;
if (blendState != BS_NONE){
mask = blendStates[blendState].mask;
}
if (mask != currentMask){
dev->SetRenderState(D3DRS_COLORWRITEENABLE, currentMask = mask);
}
currentBlendState = blendState;
}
if (sampleMask != currentSampleMask){
dev->SetRenderState(D3DRS_MULTISAMPLEMASK, sampleMask);
currentSampleMask = sampleMask;
}
}
void Direct3DRenderer::changeDepthState(const DepthStateID depthState, const uint stencilRef){
if (depthState != currentDepthState){
if (depthState == DS_NONE){
if (!currentDepthTestEnable){
dev->SetRenderState(D3DRS_ZENABLE, TRUE);
currentDepthTestEnable = true;
}
if (!currentDepthWriteEnable){
dev->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
currentDepthWriteEnable = true;
}
if (currentDepthFunc != LESS){
dev->SetRenderState(D3DRS_ZFUNC, currentDepthFunc = LESS);
}
} else {
if (depthStates[depthState].depthTest){
if (!currentDepthTestEnable){
dev->SetRenderState(D3DRS_ZENABLE, TRUE);
currentDepthTestEnable = true;
}
if (depthStates[depthState].depthWrite != currentDepthWriteEnable){
dev->SetRenderState(D3DRS_ZWRITEENABLE, (currentDepthWriteEnable = depthStates[depthState].depthWrite)? TRUE : FALSE);
}
if (depthStates[depthState].depthFunc != currentDepthFunc){
dev->SetRenderState(D3DRS_ZFUNC, currentDepthFunc = depthStates[depthState].depthFunc);
}
} else {
if (currentDepthTestEnable){
dev->SetRenderState(D3DRS_ZENABLE, FALSE);
currentDepthTestEnable = false;
}
}
}
currentDepthState = depthState;
}
if (stencilRef != currentStencilRef){
dev->SetRenderState(D3DRS_STENCILREF, stencilRef);
currentStencilRef = stencilRef;
}
}
void Direct3DRenderer::changeRasterizerState(const RasterizerStateID rasterizerState){
if (rasterizerState != currentRasterizerState){
RasterizerState state;
if (rasterizerState == RS_NONE){
state.cullMode = CULL_NONE;
state.fillMode = SOLID;
state.multiSample = true;
state.scissor = false;
} else {
state = rasterizerStates[rasterizerState];
}
if (state.cullMode != currentCullMode){
dev->SetRenderState(D3DRS_CULLMODE, currentCullMode = state.cullMode);
}
if (state.fillMode != currentFillMode){
dev->SetRenderState(D3DRS_FILLMODE, currentFillMode = state.fillMode);
}
if (state.multiSample != currentMultiSampleEnable){
dev->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, currentMultiSampleEnable = state.multiSample);
}
if (state.scissor != currentScissorEnable){
dev->SetRenderState(D3DRS_SCISSORTESTENABLE, currentScissorEnable = state.scissor);
}
currentRasterizerState = rasterizerState;
}
}
/*
void Direct3DRenderer::changeShaderConstant1i(const char *name, const int constant){
ASSERT(0);
}
void Direct3DRenderer::changeShaderConstant1f(const char *name, const float constant){
changeShaderConstant4f(name, vec4(constant, constant, constant, constant));
}
void Direct3DRenderer::changeShaderConstant2f(const char *name, const vec2 &constant){
changeShaderConstant4f(name, vec4(constant, 0, 1));
}
void Direct3DRenderer::changeShaderConstant3f(const char *name, const vec3 &constant){
changeShaderConstant4f(name, vec4(constant, 1));
}
void Direct3DRenderer::changeShaderConstant4f(const char *name, const vec4 &constant){
ASSERT(currentShader != SHADER_NONE);
D3DXHANDLE handle;
if (shaders[currentShader].vertexShader != NULL){
if (shaders[currentShader].vsConstants != NULL){
if (handle = shaders[currentShader].vsConstants->GetConstantByName(NULL, name)){
shaders[currentShader].vsConstants->SetVector(dev, handle, (D3DXVECTOR4 *) &constant);
}
}
}
if (shaders[currentShader].pixelShader != NULL){
if (shaders[currentShader].psConstants != NULL){
if (handle = shaders[currentShader].psConstants->GetConstantByName(NULL, name)){
shaders[currentShader].psConstants->SetVector(dev, handle, (D3DXVECTOR4 *) &constant);
}
}
}
}
void Direct3DRenderer::changeShaderConstant3x3f(const char *name, const mat3 &constant){
ASSERT(currentShader != SHADER_NONE);
D3DXHANDLE handle;
if (shaders[currentShader].vertexShader != NULL){
if (shaders[currentShader].vsConstants != NULL){
if (handle = shaders[currentShader].vsConstants->GetConstantByName(NULL, name)){
shaders[currentShader].vsConstants->SetFloatArray(dev, handle, constant, 9);
}
}
}
if (shaders[currentShader].pixelShader != NULL){
if (shaders[currentShader].psConstants != NULL){
if (handle = shaders[currentShader].psConstants->GetConstantByName(NULL, name)){
shaders[currentShader].psConstants->SetFloatArray(dev, handle, constant, 9);
}
}
}
}
void Direct3DRenderer::changeShaderConstant4x4f(const char *name, const mat4 &constant){
ASSERT(currentShader != SHADER_NONE);
D3DXHANDLE handle;
if (shaders[currentShader].vertexShader != NULL){
if (shaders[currentShader].vsConstants != NULL){
if (handle = shaders[currentShader].vsConstants->GetConstantByName(NULL, name)){
shaders[currentShader].vsConstants->SetMatrix(dev, handle, (D3DXMATRIX *) &constant);
}
}
}
if (shaders[currentShader].pixelShader != NULL){
if (shaders[currentShader].psConstants != NULL){
if (handle = shaders[currentShader].psConstants->GetConstantByName(NULL, name)){
shaders[currentShader].psConstants->SetMatrix(dev, handle, (D3DXMATRIX *) &constant);
}
}
}
}
void Direct3DRenderer::changeShaderConstantArray1f(const char *name, const float *constant, const uint count){
ASSERT(currentShader != SHADER_NONE);
D3DXHANDLE handle;
if (shaders[currentShader].vertexShader != NULL){
if (shaders[currentShader].vsConstants != NULL){
if (handle = shaders[currentShader].vsConstants->GetConstantByName(NULL, name)){
shaders[currentShader].vsConstants->SetFloatArray(dev, handle, constant, count);
}
}
}
if (shaders[currentShader].pixelShader != NULL){
if (shaders[currentShader].psConstants != NULL){
if (handle = shaders[currentShader].psConstants->GetConstantByName(NULL, name)){
shaders[currentShader].psConstants->SetFloatArray(dev, handle, constant, count);
}
}
}
}
void Direct3DRenderer::changeShaderConstantArray2f(const char *name, const vec2 *constant, const uint count){
ASSERT(0);
}
void Direct3DRenderer::changeShaderConstantArray3f(const char *name, const vec3 *constant, const uint count){
ASSERT(0);
}
void Direct3DRenderer::changeShaderConstantArray4f(const char *name, const vec4 *constant, const uint count){
ASSERT(currentShader != SHADER_NONE);
D3DXHANDLE handle;
if (shaders[currentShader].vertexShader != NULL){
if (shaders[currentShader].vsConstants != NULL){
if (handle = shaders[currentShader].vsConstants->GetConstantByName(NULL, name)){
shaders[currentShader].vsConstants->SetVectorArray(dev, handle, (D3DXVECTOR4 *) constant, count);
}
}
}
if (shaders[currentShader].pixelShader != NULL){
if (shaders[currentShader].psConstants != NULL){
if (handle = shaders[currentShader].psConstants->GetConstantByName(NULL, name)){
shaders[currentShader].psConstants->SetVectorArray(dev, handle, (D3DXVECTOR4 *) constant, count);
}
}
}
}
*/
void Direct3DRenderer::clear(const bool clearColor, const bool clearDepth, const bool clearStencil, const float *color, const float depth, const uint stencil){
DWORD clearCol = 0, flags = 0;
if (clearColor){
flags |= D3DCLEAR_TARGET;
if (color) clearCol = toBGRA(*(float4 *) color);
}
if (clearDepth) flags |= D3DCLEAR_ZBUFFER;
if (clearStencil) flags |= D3DCLEAR_STENCIL;
dev->Clear(0, NULL, flags, clearCol, depth, stencil);
}
const D3DPRIMITIVETYPE d3dPrim[] = {
D3DPT_TRIANGLELIST,
D3DPT_TRIANGLEFAN,
D3DPT_TRIANGLESTRIP,
(D3DPRIMITIVETYPE) 0, // Quads not supported
D3DPT_LINELIST,
D3DPT_LINESTRIP,
(D3DPRIMITIVETYPE) 0, // Line loops not supported
D3DPT_POINTLIST,
};
int getPrimitiveCount(const Primitives primitives, const int count){
switch (primitives){
case PRIM_TRIANGLES:
return count / 3;
case PRIM_TRIANGLE_FAN:
case PRIM_TRIANGLE_STRIP:
return count - 2;
case PRIM_LINES:
return count / 2;
case PRIM_LINE_STRIP:
return count - 1;
case PRIM_POINTS:
return count;
};
return 0;
}
void Direct3DRenderer::drawArrays(const Primitives primitives, const int firstVertex, const int nVertices){
dev->DrawPrimitive(d3dPrim[primitives], firstVertex, nVertices);
}
void Direct3DRenderer::drawElements(const Primitives primitives, const int firstIndex, const int nIndices, const int firstVertex, const int nVertices){
int indexSize = indexBuffers[currentIndexBuffer].indexSize;
dev->DrawIndexedPrimitive(d3dPrim[primitives], 0, firstVertex, nVertices, firstIndex, getPrimitiveCount(primitives, nIndices));
}
void Direct3DRenderer::setup2DMode(const float left, const float right, const float top, const float bottom){
scaleBias2D.x = 2.0f / (right - left);
scaleBias2D.y = 2.0f / (top - bottom);
scaleBias2D.z = -1.0f;
scaleBias2D.w = 1.0f;
}
const char *plainVS =
"float4 scaleBias;"
"float4 main(float4 position: POSITION): POSITION {"
" position.xy = position.xy * scaleBias.xy + scaleBias.zw;"
" return position;"
"}";
const char *plainPS =
"float4 color;"
"float4 main(): COLOR {"
" return color;"
"}";
const char *texVS =
"struct VsIn {"
" float4 position: POSITION;"
" float2 texCoord: TEXCOORD;"
"};"
"float4 scaleBias;"
"VsIn main(VsIn In){"
" In.position.xy = In.position.xy * scaleBias.xy + scaleBias.zw;"
" return In;"
"}";
const char *texPS =
"sampler2D Base: register(s0);"
"float4 color;"
"float4 main(float2 texCoord: TEXCOORD): COLOR {"
" return tex2D(Base, texCoord) * color;"
"}";
void Direct3DRenderer::drawPlain(const Primitives primitives, vec2 *vertices, const uint nVertices, const BlendStateID blendState, const DepthStateID depthState, const vec4 *color){
if (plainShader == SHADER_NONE){
plainShader = addShader(plainVS, NULL, plainPS, 0, 0, 0);
FormatDesc format[] = { 0, TYPE_VERTEX, FORMAT_FLOAT, 2 };
plainVF = addVertexFormat(format, elementsOf(format), plainShader);
}
float4 col = float4(1, 1, 1, 1);
if (color) col = *color;
reset();
setShader(plainShader);
setShaderConstant4f("scaleBias", scaleBias2D);
setShaderConstant4f("color", col);
setBlendState(blendState);
setDepthState(depthState);
setVertexFormat(plainVF);
apply();
dev->DrawPrimitiveUP(d3dPrim[primitives], getPrimitiveCount(primitives, nVertices), vertices, sizeof(vec2));
}
void Direct3DRenderer::drawTextured(const Primitives primitives, TexVertex *vertices, const uint nVertices, const TextureID texture, const SamplerStateID samplerState, const BlendStateID blendState, const DepthStateID depthState, const vec4 *color){
if (texShader == SHADER_NONE){
texShader = addShader(texVS, NULL, texPS, 0, 0, 0);
FormatDesc format[] = {
0, TYPE_VERTEX, FORMAT_FLOAT, 2,
0, TYPE_TEXCOORD, FORMAT_FLOAT, 2,
};
texVF = addVertexFormat(format, elementsOf(format), texShader);
}
float4 col = float4(1, 1, 1, 1);
if (color) col = *color;
reset();
setShader(texShader);
setShaderConstant4f("scaleBias", scaleBias2D);
setShaderConstant4f("color", col);
setTexture("Base", texture, samplerState);
setBlendState(blendState);
setDepthState(depthState);
setVertexFormat(texVF);
apply();
dev->DrawPrimitiveUP(d3dPrim[primitives], getPrimitiveCount(primitives, nVertices), vertices, sizeof(TexVertex));
}
LPDIRECT3DBASETEXTURE9 Direct3DRenderer::getD3DTexture(const TextureID texture) const {
return textures[texture].texture;
}
void Direct3DRenderer::flush(){
if (eventQuery == NULL){
dev->CreateQuery(D3DQUERYTYPE_EVENT, &eventQuery);
}
eventQuery->Issue(D3DISSUE_END);
eventQuery->GetData(NULL, 0, D3DGETDATA_FLUSH);
}
void Direct3DRenderer::finish(){
if (eventQuery == NULL){
dev->CreateQuery(D3DQUERYTYPE_EVENT, &eventQuery);
}
eventQuery->Issue(D3DISSUE_END);
while (eventQuery->GetData(NULL, 0, D3DGETDATA_FLUSH) == S_FALSE){
// Spin-wait
}
}
| [
"IRONKAGE@gmail.com"
] | IRONKAGE@gmail.com |
79558c86839ec174ad9fcf70f7910f8a15bb1c7b | dfa44ced327f991a5d0fc093a5910ff06c58c9da | /tekhne/include/VScreen.h | 445106565aa12fcbc62cc1e2327ff8c5ada49cbe | [
"MIT"
] | permissive | HaikuArchives/Tekhne | d15740db2359789afc987e6d4a9d8b1d93f78378 | faeb3c8ebf13dd0986463f9442aaad1d98fcec31 | refs/heads/master | 2021-01-02T22:57:47.085831 | 2007-12-30T00:05:36 | 2007-12-30T00:05:36 | 23,687,039 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,085 | h | /***************************************************************************
* VScreen.h
*
* Copyright (c) 2006 Geoffrey Clements
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
****************************************************************************/
#ifndef _VSCREEN_H
#define _VSCREEN_H
#include "VErrors.h"
#include "VList.h"
#include "VLocker.h"
#include "InterfaceDefs.h"
namespace tekhne {
typedef struct {
int32_t id;
} screen_id;
extern screen_id V_MAIN_SCREEN_ID;
class VWindow;
class VBitmap;
typedef struct {
uint32_t pixel_clock;
uint16_t h_display;
uint16_t h_sync_start;
uint16_t h_sync_end;
uint16_t h_total;
uint16_t v_display;
uint16_t v_sync_start;
uint16_t v_sync_end;
uint16_t v_total;
uint32_t flags;
} display_timing;
// display timing flags
const int32_t V_BLANK_PEDESTAL = 1;
const int32_t V_TIMING_INTERLACED = 2;
const int32_t V_POSITIVE_HSYNC = 4;
const int32_t V_POSITIVE_VSYNC = 8;
const int32_t V_SYNC_ON_GREEN = 16;
typedef struct {
display_timing timing;
uint32_t space;
uint16_t virtual_width;
uint16_t virtual_height;
uint16_t h_display_start;
uint16_t v_display_start;
uint32_t flags;
} display_mode;
// display mode flags
const int32_t V_SCROLL = 1;
const int32_t V_8_BIT_DAC = 2;
const int32_t V_HARDWARE_CURSOR = 4;
const int32_t V_PARALLEL_ACCESS = 8;
const int32_t V_DPMS = 16;
const int32_t V_IO_FB_NA = 32;
const int32_t VDPMS_ON = 0;
const int32_t V_DPMS_STAND_BY = 1;
const int32_t V_DPMS_SUSPEND = 2;
const int32_t V_DPMS_OFF = 4;
class VScreen {
private:
public:
VScreen(VWindow *window);
VScreen(screen_id id = V_MAIN_SCREEN_ID);
~VScreen();
const color_map *ColorMap(void);
inline uint8_t IndexForColor(rgb_color color);
uint8_t IndexForColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255);
rgb_color ColorForIndex(const uint8_t index);
uint8_t InvertIndex(uint8_t index);
color_space ColorSpace(void);
VRect Frame(void);
// need defs for these fields
// status_t GetDeviceInfo(accelerant_device_info *info);
// status_t GetTimingConstraints(display_timing_constraints *dtc);
status_t GetModeList(display_mode **mode_list, uint32_t *count);
status_t SetMode(display_mode *mode, bool makeDefault = false);
status_t GetMode(display_mode *mode);
status_t GetPixelClockLimits(display_mode *mode, uint32_t *low, uint32_t *high);
screen_id ID(void);
bool IsValid(void);
status_t ProposeMode(display_mode *candidate, const display_mode *low, const display_mode *high);
status_t ReadBitmap(VBitmap *buffer, bool draw_cursor = true, VRect *bounds = NULL);
status_t GetBitmap(VBitmap **buffer, bool draw_cursor = true, VRect *bounds = NULL);
void SetDesktopColor(rgb_color color, bool makeDefault = true);
rgb_color DesktopColor(void);
status_t SetDPMS(uint32_t dpmsState);
uint32_t DPMSState(void);
uint32_t DPMSCapabilities(void);
status_t SetToNext(void) { return V_ERROR; }
status_t WaitForRetrace(void);
status_t WaitForRetrace(bigtime_t timeout);
};
} // namespace tekhne
#endif /* _VSCREEN_H */
| [
"baldmountain@gmail.com"
] | baldmountain@gmail.com |
c46530f3e0d0c4cd43faa730252380debaac4e57 | 957fc487933007b8123d1b975e6221c861b12b99 | /lce-test/util/synchronizing_sets/bit_vector_rank.hpp | ed0a830de826621e57c2a3446083706751fb489f | [
"BSD-2-Clause"
] | permissive | herlez/lce-test | 8b63990f4fd3e5a8715b8b2a1f3a004ba6eaced1 | b52e00a2918b0ef9e3cdbaae731fabad89ec6754 | refs/heads/master | 2023-05-13T16:48:31.285748 | 2022-08-16T09:05:01 | 2022-08-16T09:05:01 | 183,403,442 | 5 | 3 | BSD-2-Clause | 2023-05-07T21:26:22 | 2019-04-25T09:37:58 | C++ | UTF-8 | C++ | false | false | 5,669 | hpp | /*******************************************************************************
* bit_vector_rank.hpp
*
* Copyright (C) 2019 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
/* Based on
* @inproceedings{Zhou2013RankSelect,
* author = {Dong Zhou and David G. Andersen and Michael Kaminsky},
* title = {Space-Efficient, High-Performance Rank and Select Structures
* on Uncompressed Bit Sequences},
* booktitle = {12th International Symposium on Experimental Algorithms
* ({SEA})},
* series = {LNCS},
* volume = {7933},
* pages = {151--163},
* publisher = {Springer},
* year = {2013},
* }
*/
// Code from the TLX, as this is used in the original implementation
#pragma once
#include "bit_vector.hpp"
#include <vector>
#include <array>
#include <cstdint>
#include <iostream>
#if defined(__GNUC__) || defined(__clang__)
#define TLX_LIKELY(c) __builtin_expect((c), 1)
#define TLX_UNLIKELY(c) __builtin_expect((c), 0)
#else
#define TLX_LIKELY(c) c
#define TLX_UNLIKELY(c) c
#endif
#if defined(__GNUC__) || defined(__clang__)
#define TLX_ATTRIBUTE_PACKED __attribute__ ((packed))
#else
#define TLX_ATTRIBUTE_PACKED
#endif
template <size_t Words>
uint64_t popcount(uint64_t const * const buffer) {
uint64_t popcount = 0;
for (size_t i = 0; i < Words; ++i) {
popcount += __builtin_popcountll(buffer[i]);
}
return popcount;
}
struct l12_entry {
l12_entry(uint32_t const _l1, std::array<uint16_t, 3> const _l2)
: l1(_l1), l2_values(0ULL |((uint32_t(0b1111111111) & _l2[2]) << 20) |
((uint32_t(0b1111111111) & _l2[1]) << 10) |
(uint32_t(0b1111111111) & _l2[0])) { }
inline uint16_t operator[](size_t const idx) const {
return (l2_values >> (10 * idx)) & uint16_t(0b1111111111);
}
uint32_t l1;
uint32_t l2_values;
} TLX_ATTRIBUTE_PACKED; // struct l12_entry
class bit_vector_rank {
public:
static constexpr size_t l2_bit_size = 512;
static constexpr size_t l1_bit_size = 4 * l2_bit_size;
static constexpr size_t l0_bit_size =
static_cast<uint32_t>(std::numeric_limits<int32_t>::max()) + 1;
static constexpr size_t l2_word_size = l2_bit_size / (sizeof(uint64_t) * 8);
static constexpr size_t l1_word_size = l1_bit_size / (sizeof(uint64_t) * 8);
static constexpr size_t l0_word_size = l0_bit_size / (sizeof(uint64_t) * 8);
public:
bit_vector_rank(bit_vector const& bv)
: data_size_(bv.size_), data_(bv.data_),
l0_size_((data_size_ / l0_word_size) + 1),
l0_(static_cast<uint64_t*>(operator new(l0_size_*sizeof(uint64_t)))),
l12_size_((data_size_ / l1_word_size) + 1),
l12_(static_cast<l12_entry*>(operator new(l12_size_*sizeof(l12_entry)))) {
l0_[0] = 0;
size_t l0_pos = 1;
size_t l12_pos = 0;
uint32_t l1_entry = 0UL;
uint64_t const * data = data_;
uint64_t const * const data_end = data_ + data_size_;
// For each full L12-Block
std::array<uint16_t, 3> l2_entries = { 0, 0, 0 };
while (data + 32 <= data_end) {
uint32_t new_l1_entry = l1_entry;
for (size_t i = 0; i < 3; ++i) {
l2_entries[i] = popcount<8>(data);
data += 8;
new_l1_entry += l2_entries[i];
}
l12_[l12_pos++] = l12_entry(l1_entry, l2_entries);
new_l1_entry += popcount<8>(data);
data += 8;
l1_entry = new_l1_entry;
if (TLX_UNLIKELY(l12_pos % (l0_word_size / l1_word_size) == 0)) {
l0_[l0_pos] += (l0_[l0_pos - 1] + l1_entry);
++l0_pos;
l1_entry = 0;
}
}
// For the last not full L12-Block
size_t l2_pos = 0;
while (data + 8 <= data_end) {
l2_entries[l2_pos++] = popcount<8>(data);
data += 8;
}
l12_[l12_pos++] = l12_entry(l1_entry, l2_entries);
if (TLX_UNLIKELY(l12_pos % (l0_word_size / l1_word_size) == 0)) {
l0_[l0_pos] += (l0_[l0_pos - 1] + l1_entry);
++l0_pos;
l1_entry = 0;
}
}
~bit_vector_rank() {
delete[] l0_;
delete[] l12_;
}
size_t rank0(size_t const index) const {
return (index + 1) - rank1(index);
}
size_t rank1(size_t const index) const {
size_t result = 0;
size_t remaining_bits = index + 1;
size_t const l0_pos = remaining_bits / l0_bit_size;
remaining_bits -= l0_pos * l0_bit_size;
result += l0_[l0_pos];
size_t const l1_pos = remaining_bits / l1_bit_size;
remaining_bits -= l1_pos * l1_bit_size;
l12_entry const l12 = l12_[l1_pos + (l0_pos * (l0_word_size /
l1_word_size))];
result += l12.l1;
size_t const l2_pos = remaining_bits / l2_bit_size;
remaining_bits -= l2_pos * l2_bit_size;
for (size_t i = 0; i < l2_pos; ++i) {
result += l12[i];
}
size_t offset = (l1_pos * l1_word_size) + (l2_pos * l2_word_size);
while (remaining_bits >= 64) {
result += popcount<1>(data_ + offset++);
remaining_bits -= 64;
}
if (remaining_bits > 0) {
uint64_t const remaining = data_[offset] << (64 - remaining_bits);
result += popcount<1>(&remaining);
}
return result;
}
private:
// Access to the bit vector
size_t const data_size_;
uint64_t const * const data_;
// Members for the structure
size_t const l0_size_;
uint64_t * const l0_;
size_t const l12_size_;
l12_entry * const l12_;
}; // class bit_vector_rank
/******************************************************************************/
| [
"alexander.herlez@tu-dortmund.de"
] | alexander.herlez@tu-dortmund.de |
3810a89ed2d7d25b91596fee7b0057d28582e1c8 | 1a01fb3e990cd969664585a59a0b18da47ffc8f9 | /include/random.h | cb4aed0f0c7c04e88cc833db4937d744b00aef6a | [] | no_license | AllocBlock/Noise-Graph-Generator | abba78a8b59fbb1bf533e1b73bdd571c78679e6b | 5581ebf83b0d5c670037eed2ea68f2580c8e77a3 | refs/heads/master | 2022-04-28T00:12:07.775854 | 2020-04-20T13:05:17 | 2020-04-20T13:05:17 | 255,638,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | h | /**************************************************************************
* Author: AllocBlock
* Create At: 2020-04-16
* Update At: 2020-04-18
* Description: Generate random number
**************************************************************************/
typedef unsigned char byte;
class Random {
private:
int seed;
public:
Random() {
seed = (int)time(0);
srand(seed);
}
Random(int seed) {
this->seed = seed;
srand(seed);
}
void setSeed(int newSeed) {
seed = newSeed;
srand(seed);
}
byte randByte() {
return (byte)(rand() % 255);
}
float randFloat() {
return (float)rand() / RAND_MAX;
}
int randInt(int range) {
return rand() % range;
}
}; | [
"690051933@qq.com"
] | 690051933@qq.com |
73835646a5027cb2a1651f84733f474d45550c4c | 5cdc481e6f74abc93dbfa421998779c5c3984e2a | /Codeforces/352/A.cc | 8ea7d682721db60fc5a3e563e791f86acc770e8b | [] | no_license | joaquingx/Competitive-Programming-Problems | 4f0676bc3fb43d88f6427e106c6d9c81698993ce | c6baddbb6f1bdb1719c19cf08d3594bb37ba3147 | refs/heads/master | 2021-01-15T08:36:45.392896 | 2016-11-21T17:29:15 | 2016-11-21T17:29:15 | 54,804,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | cc | #include <bits/stdc++.h>
using namespace std;
int main()
{
string rpta;
int n ; cin >> n;
for(int i = 1 ; ; ++i)
{
// cout << to_string(i) << "\n";
rpta += to_string(i);
if(rpta.size() > 1001)
break;
}
// cout << rpta;
cout << rpta[n-1] << "\n";
return 0;
}
| [
"joaquingc123@gmail.com"
] | joaquingc123@gmail.com |
00de94d85adf2e3954f3f1e87fe819cd7e75db71 | 21553f6afd6b81ae8403549467230cdc378f32c9 | /arm/cortex/Freescale/MKM34ZA5/include/arch/reg/portc.hpp | 0bded85af4a9e529daba1e8512a0f2db33a64687 | [] | no_license | digint/openmptl-reg-arm-cortex | 3246b68dcb60d4f7c95a46423563cab68cb02b5e | 88e105766edc9299348ccc8d2ff7a9c34cddacd3 | refs/heads/master | 2021-07-18T19:56:42.569685 | 2017-10-26T11:11:35 | 2017-10-26T11:11:35 | 108,407,162 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | hpp | /*
* OpenMPTL - C++ Microprocessor Template Library
*
* This program is a derivative representation of a CMSIS System View
* Description (SVD) file, and is subject to the corresponding license
* (see "Freescale CMSIS-SVD License Agreement.pdf" in the parent directory).
*
* 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.
*/
////////////////////////////////////////////////////////////////////////
//
// Import from CMSIS-SVD: "Freescale/MKM34ZA5.svd"
//
// vendor: Freescale Semiconductor, Inc.
// vendorID: Freescale
// name: MKM34ZA5
// series: Kinetis_M
// version: 1.6
// description: MKM34ZA5 Freescale Microcontroller
// --------------------------------------------------------------------
//
// C++ Header file, containing architecture specific register
// declarations for use in OpenMPTL. It has been converted directly
// from a CMSIS-SVD file.
//
// https://digint.ch/openmptl
// https://github.com/posborne/cmsis-svd
//
#ifndef ARCH_REG_PORTC_HPP_INCLUDED
#define ARCH_REG_PORTC_HPP_INCLUDED
#warning "using untested register declarations"
#include <register.hpp>
namespace mptl {
/**
* Pin Control and Interrupts
*/
struct PORTC
{
static constexpr reg_addr_t base_addr = 0x40048000;
/**
* Pin Control Register n
*/
struct PCR%s
: public reg< uint32_t, base_addr + 0, rw, 0 >
{
using type = reg< uint32_t, base_addr + 0, rw, 0 >;
using PS = regbits< type, 0, 1 >; /**< Pull Select */
using PE = regbits< type, 1, 1 >; /**< Pull Enable */
using SRE = regbits< type, 2, 1 >; /**< Slew Rate Enable */
using MUX = regbits< type, 8, 3 >; /**< Pin Mux Control */
using LK = regbits< type, 15, 1 >; /**< Lock Register */
using IRQC = regbits< type, 16, 4 >; /**< Interrupt Configuration */
using ISF = regbits< type, 24, 1 >; /**< Interrupt Status Flag */
};
/**
* Global Pin Control Low Register
*/
struct GPCLR
: public reg< uint32_t, base_addr + 0x80, wo, 0 >
{
using type = reg< uint32_t, base_addr + 0x80, wo, 0 >;
using GPWD = regbits< type, 0, 16 >; /**< Global Pin Write Data */
using GPWE = regbits< type, 16, 16 >; /**< Global Pin Write Enable */
};
/**
* Global Pin Control High Register
*/
struct GPCHR
: public reg< uint32_t, base_addr + 0x84, wo, 0 >
{
using type = reg< uint32_t, base_addr + 0x84, wo, 0 >;
using GPWD = regbits< type, 0, 16 >; /**< Global Pin Write Data */
using GPWE = regbits< type, 16, 16 >; /**< Global Pin Write Enable */
};
/**
* Interrupt Status Flag Register
*/
struct ISFR
: public reg< uint32_t, base_addr + 0xa0, rw, 0 >
{
using type = reg< uint32_t, base_addr + 0xa0, rw, 0 >;
using ISF = regbits< type, 0, 32 >; /**< Interrupt Status Flag */
};
};
} // namespace mptl
#endif // ARCH_REG_PORTC_HPP_INCLUDED
| [
"axel@tty0.ch"
] | axel@tty0.ch |
820f2178381bf03031e2c63d5d857859377e23ec | 556bc516271dfe48b13850d51a6f65dce425adc4 | /Subeen problem/17th-Problem/morecin.cpp | 2970e16c251e52e72a81485dc9099f37ffcea5bd | [] | no_license | nur-alam/Problem-Solving | 4fae30499b5dd802854b7efa0b702b3f173fa236 | b0db93d597142590010b60bfa2054409a6ca6754 | refs/heads/master | 2021-01-13T11:10:06.766089 | 2019-01-16T12:01:52 | 2019-01-16T12:01:52 | 77,365,261 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | cpp | #include<iostream>
using namespace std;
int main(){
int i,j,k;
cin>>i>>j>>k;
cout<<i<<"\n"<<j<<endl<<k;
return 0;
}
| [
"nuralam862@gmail.com"
] | nuralam862@gmail.com |
a8700af449408a2aa9178d7e9f873d88249126a8 | d700e2fc362963ddb6ae519176ad28e0086ac890 | /Day9/Q5.cpp | 54c7b4d3d9cd89fe949c63225e4cdceed81313b6 | [] | no_license | shivangibisht/DSA-Assignments | ffea047c1efdf40b5c98fdf8198f210105ff75be | 3ec3ae876c31e7135ba0fbecb9c0a270f10333f5 | refs/heads/main | 2023-06-19T10:19:38.156344 | 2021-07-15T04:11:05 | 2021-07-15T04:11:05 | 385,482,242 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | class Solution {
public:
bool isValid(string str) { stack<char> s;
for(int i =0;i<str.size();i++)
{
if(str[i]=='(' || str[i]=='{' || str[i]=='[')
s.push(str[i]);
else if(str[i]==')' && !s.empty() && s.top()=='(')
s.pop();
else if(str[i]=='}' && !s.empty() && s.top()=='{')
s.pop();
else if(str[i]==']' && !s.empty() && s.top()=='[')
s.pop();
else
return false;
}
if(s.empty())
return true;
return false;}
};
| [
"noreply@github.com"
] | noreply@github.com |
4decb93d628010037ff0200de64fe69570511484 | bb72b975267b12fb678248ce565f3fd9bd6153ee | /testquick/cocos/2d/CCClippingRegionNode.h | dbe24055da5dbfe887962642e736561af273b60c | [] | no_license | fiskercui/testlanguage | cfbcc84ffaa31a535a7f898d6c7b42dcbf2dc71b | b15746d9fa387172b749e54a90e8c6251750f192 | refs/heads/master | 2021-05-30T13:26:11.792822 | 2016-01-13T02:03:26 | 2016-01-13T02:03:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,450 | h | /*
* cocos2d for iPhone: http://www.cocos2d-iphone.org
* cocos2d-x: http://www.cocos2d-x.org
*
* Copyright (c) 2012 Pierre-David Bélanger
* Copyright (c) 2012 cocos2d-x.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#ifndef __MISCNODE_CCCLIPPING_REGION_NODE_H__
#define __MISCNODE_CCCLIPPING_REGION_NODE_H__
#include "2d/CCNode.h"
#include "renderer/CCCustomCommand.h"
#include "CCGL.h"
NS_CC_BEGIN
class CC_DLL ClippingRegionNode : public Node
{
public:
static ClippingRegionNode* create(const Rect& clippingRegion);
static ClippingRegionNode* create(void);
const Rect getClippingRegion(void) {
return m_clippingRegion;
}
void setClippingRegion(const Rect& clippingRegion);
bool isClippingEnabled(void) {
return m_clippingEnabled;
}
void setClippingEnabled(bool enabled) {
m_clippingEnabled = enabled;
}
//virtual void draw(Renderer* renderer, const Mat4 &transform, uint32_t flags) override;
virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
protected:
ClippingRegionNode(void)
: m_clippingEnabled(true)
{
}
void onBeforeVisitScissor();
void onAfterVisitScissor();
Rect m_clippingRegion;
bool m_clippingEnabled;
CustomCommand _beforeVisitCmdScissor;
CustomCommand _afterVisitCmdScissor;
};
NS_CC_END
#endif
| [
"fisker.cui@gmail.com"
] | fisker.cui@gmail.com |
a4c614cda6b2ebc0c74bfc6968d693825f0cbb3e | 498e03501639226d77eb51d5643dccba8259111c | /CodeChef Solutions/PRACTICE/START01 19713962.cpp | 095ec06c71498f05e936839bd6a2cec1dcf97cbc | [] | no_license | bhaskarsen98/DS-Algo-practice | 72cf0f9770d9fb4679dfb3dcf3de6c833ce2ec6a | 6de3a51f792c0751cd154129a2a02d178c40515d | refs/heads/master | 2023-05-14T11:17:00.297803 | 2021-06-07T21:26:35 | 2021-06-07T21:26:35 | 317,600,777 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 101 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
cout<<n;
return 0;
} | [
"bhaskarsen1998@gmail.com"
] | bhaskarsen1998@gmail.com |
8712258f9b731f5733a4d446f2d844e62c28d8fa | 2c58db28ec2e26f8f3fb198251c717d219835477 | /Loadouts/Blufor/usmc20_m27iar_marpatw.hpp | e9c3b020b19f9f96df44072f16380d168606d34f | [] | no_license | BourbonWarfare/bwmf | 947c31933b51c3022a81baa936854dd4a2744ece | cef3d381ac6bf19383f4be309b66a882f19201fa | refs/heads/master | 2023-08-19T04:19:16.778559 | 2023-08-18T04:33:52 | 2023-08-18T04:33:52 | 23,380,002 | 19 | 22 | null | 2023-08-18T04:33:54 | 2014-08-27T06:55:05 | C++ | UTF-8 | C++ | false | false | 13,332 | hpp | author = "AChesheireCat";
description = "United States Marine Corps c.2020";
#include "undef.hpp" // Reset defines
// ------------------- PASTE BELOW THIS LINE
// Camo set
#define CAMO_UNIFORM "CUP_U_B_USMC_FROG1_WMARPAT","CUP_U_B_USMC_FROG2_WMARPAT","CUP_U_B_USMC_FROG3_WMARPAT","CUP_U_B_USMC_FROG3_WMARPAT"
#define CAMO_VEST "CUP_V_B_Eagle_SPC_Patrol"
#define CAMO_BACKPACK "B_AssaultPack_cbr"
#define CARRYALL "B_Carryall_cbr"
#define CAMO_HEADGEAR "CUP_H_OpsCore_Tan"
#define CAMO_HEADGEAR_SPECIAL "CUP_H_FR_BoonieMARPAT"
// Pilot Camo set
#define CAMO_UNIFORM_PILOT "CUP_U_B_USMC_PilotOverall"
#define CAMO_VEST_PILOT "CUP_V_B_Eagle_SPC_Empty"
#define CAMO_BACKPACK_PILOT "B_Battle_Belt_XL_F"
#define CAMO_HEADGEAR_PILOT "H_PilotHelmetHeli_B"
// Vic Crew Camo set
#define CAMO_UNIFORM_VICC "CUP_U_B_USMC_MCCUU_gloves"
#define CAMO_VEST_VICC "CUP_V_B_Eagle_SPC_Crew"
#define CAMO_BACKPACK_VICC "B_Battle_Belt_XL_F"
#define CAMO_HEADGEAR_VICC "cwr3_b_headgear_cvc"
// Rifle
#define RIFLE "CUP_arifle_HK_M27","CUP_arifle_HK_M27_VFG"
#define RIFLE_MAG "CUP_30Rnd_556x45_Emag:7","CUP_30Rnd_556x45_Emag_Tracer_Red:3"
#define RIFLE_ATTACHMENTS "hlc_muzzle_556nato_rotexiiic_tan", "cup_acc_anpeq_15_tan_top", "cup_optic_acog"
#define AAR_ATTACHMENTS RIFLE_ATTACHMENTS
#define ALT_OPTICS "cup_optic_sb_11_4x20_pm","cup_optic_acog_ta31_kf","cup_optic_elcan_specterdr_coyote","cup_optic_g33_hws_blk","cup_optic_aimm_microt1_blk","cup_optic_vortexrazor_uh1_black","optic_holosight_blk_f","cup_optic_eotech553_black","cup_optic_microt1"
// GL Rifle
#define GLRIFLE "CUP_arifle_HK_M27_AG36"
#define GLRIFLE_MAG RIFLE_MAG
#define GLRIFLE_MAG_SMOKE "1Rnd_Smoke_Grenade_shell:2","1Rnd_SmokeRed_Grenade_shell:2"
#define GLRIFLE_MAG_HE "CUP_1Rnd_HEDP_M203:5"
#define GLRIFLE_MAG_FLARE "UGL_FlareYellow_F:4"
#define GLRIFLE_MAG_HUNTIR "ACE_HuntIR_M203:3"
// Carbine
#define CARBINE "CUP_arifle_M4A1_black"
#define CARBINE_MAG RIFLE_MAG
// AR
#define AR "CUP_arifle_HK_M27_VFG"
#define AR_MAG "CUP_60Rnd_556x45_SureFire_Tracer_Red:10"
#define AR_ATTACHMENTS "hlc_muzzle_556nato_rotexiiic_tan", "cup_acc_anpeq_15_tan_top", "cup_optic_acog", "CUP_bipod_Harris_1A2_L_BLK"
// AT
#define AT "launch_MRAWS_green_F"
#define AT_MAG "MRAWS_HEAT55_F:2","MRAWS_HE_F:1"
// MMG
#define MMG "CUP_lmg_M240_B"
#define MMG_MAG "CUP_100Rnd_TE4_LRT4_Red_Tracer_762x51_Belt_M:5"
// MAT
#define MAT "CUP_launch_Mk153Mod0_blk"
#define MAT_MAG "CUP_SMAW_HEAA_M:2","CUP_SMAW_HEDP_M:1","CUP_SMAW_Spotting:5"
#define MAT_OPTIC "CUP_acc_ANPEQ_15", "CUP_optic_SMAW_Scope"
// HMG
#define HMG "ace_csw_staticM2ShieldCarry"
#define HMG_TRI_HI "ace_csw_m3CarryTripod"
#define HMG_TRI_LO "ace_csw_m3CarryTripod"
#define HMG_MAG "ace_csw_100Rnd_127x99_mag:3"
// HAT
#define HAT "CUP_launch_Javelin"
#define HAT_TRI_HI
#define HAT_TRI_LO
#define HAT_MAG "CUP_Javelin_M:2"
// SAM
#define SAM "CUP_launch_FIM92Stinger_Loaded"
#define SAM_MAG "CUP_Stinger_M:1"
// Sniper
#define SNIPER "CUP_srifle_M2010_wdl"
#define SNIPER_MAG "CUP_5Rnd_762x67_M2010_M:20"
#define SNIPER_ATTACHMENTS "muzzle_snds_B", "ACE_acc_pointer_green", "CUP_optic_LeupoldM3LR", "CUP_bipod_Harris_1A2_L_BLK"
// Spotter
#define SPOTTER "CUP_arifle_HK_M27"
#define SPOTTER_MAG "ACE_30Rnd_556x45_Stanag_Mk262_mag:10"
#define SPOTTER_ATTACHMENTS "CUP_muzzle_snds_M16_coyote", "cup_acc_anpeq_15", "CUP_optic_LeupoldM3LR", "CUP_bipod_Harris_1A2_L_BLK"
// SMG
#define SMG "CUP_smg_MP5A5_Rail"
#define SMG_MAG "CUP_30Rnd_9x19_MP5:5"
// Pistol
#define PISTOL "CUP_hgun_M17_Coyote"
#define PISTOL_MAG "CUP_21Rnd_9x19_M17_Coyote:3"
#define PISTOL_ATTACHMENTS "hlc_acc_tlr1"
// Grenades
#define LEADER_GRENADES BASE_FRAG,LEADER_SMOKES,SIDE_CHEM_LIGHT
// Gear
#define TOOLS BASE_TOOLS,"ACE_EntrenchingTool"
#define LEADER_TOOLS BASE_LEADER_TOOLS,SIDE_KEY
#define LINKED BASE_LINKED,"ACE_NVG_Gen4_Black"
#define LEADER_LINKED BASE_LEADER_LINKED
// -------------------- PASTE ABOVE THIS LINE
//Custom Defines
#define CAMO_VEST_AR "CUP_V_B_Eagle_SPC_AR"
#define CAMO_VEST_FTL "CUP_V_B_Eagle_SPC_GL"
#define CAMO_VEST_SL "CUP_V_B_Eagle_SPC_TL"
#define CAMO_VEST_MEDIC "CUP_V_B_Eagle_SPC_Corpsman"
#define CAMO_BACKPACK_LAT "B_Kitbag_cbr"
#define CAMO_BACKPACK_AR "B_Kitbag_cbr"
#define CAMO_BACKPACK_FTL "B_Kitbag_cbr"
#define CAMO_BACKPACK_MEDIC "B_Kitbag_cbr"
#define MMG_ATTACHMENTS "cup_optic_acog_ta648_308_rds_black","cup_acc_anpeq_15"
class Car {
TransportWeapons[] = {CARBINE,"CUP_launch_M136:2"};
TransportMagazines[] = {RIFLE_MAG,RIFLE_MAG,CARBINE_MAG,AR_MAG,AR_MAG,GLRIFLE_MAG_HE,GLRIFLE_MAG_HE,GLRIFLE_MAG_SMOKE,BASE_GRENADES,"SatchelCharge_Remote_Mag:1"};
TransportItems[] = {MEDIC_MEDICAL,MEDIC_MEDICAL,BASE_MEDICAL,BASE_MEDICAL,"ACE_M26_Clacker:1"};
};
class Tank {
TransportWeapons[] = {CARBINE,"CUP_launch_M136:2"};
TransportMagazines[] = {RIFLE_MAG,RIFLE_MAG,CARBINE_MAG,AR_MAG,AR_MAG,GLRIFLE_MAG_HE,GLRIFLE_MAG_HE,GLRIFLE_MAG_SMOKE,BASE_GRENADES,"SatchelCharge_Remote_Mag:1"};
TransportItems[] = {MEDIC_MEDICAL,MEDIC_MEDICAL,BASE_MEDICAL,BASE_MEDICAL,"ACE_M26_Clacker:1"};
};
class Helicopter {
TransportMagazines[] = {RIFLE_MAG,RIFLE_MAG,CARBINE_MAG,AR_MAG,AR_MAG,GLRIFLE_MAG_HE,"SatchelCharge_Remote_Mag:1"};
TransportItems[] = {MEDIC_MEDICAL,MEDIC_MEDICAL,BASE_MEDICAL,BASE_MEDICAL,"ACE_M26_Clacker:1"};
};
class Plane {};
class Ship_F {};
class rifleman {// rifleman
uniform[] = {CAMO_UNIFORM};
vest[] = {CAMO_VEST};
headgear[] = {CAMO_HEADGEAR};
backpack[] = {CAMO_BACKPACK};
backpackItems[] = {BASE_MEDICAL};
weapons[] = {RIFLE};
magazines[] = {RIFLE_MAG,BASE_GRENADES};
items[] = {TOOLS,"CUP_H_FR_BoonieMARPAT"};
linkedItems[] = {LINKED};
attachments[] = {RIFLE_ATTACHMENTS};
opticChoices[] = {ALT_OPTICS};
};
class Fic_Soldier_Carbine: rifleman {// carbine-man
weapons[] = {CARBINE};
magazines[] = {CARBINE_MAG,BASE_GRENADES};
};
class ftl: rifleman {// FTL
vest[] = {CAMO_VEST_FTL};
backpack[] = {CAMO_BACKPACK_FTL};
weapons[] = {GLRIFLE};
magazines[] = {GLRIFLE_MAG,GLRIFLE_MAG_HE,GLRIFLE_MAG_SMOKE,LEADER_GRENADES};
items[] += {LEADER_TOOLS};
linkedItems[] += {LEADER_LINKED,BINOS};
};
class sl: ftl {// SL
vest[] = {CAMO_VEST_SL};
handguns[] = {PISTOL};
secondaryAttachments[] = {PISTOL_ATTACHMENTS};
magazines[] += {PISTOL_MAG,GLRIFLE_MAG_HUNTIR};
linkedItems[] = {LINKED,LEADER_LINKED,RANGE_FINDER,SIDE_UAV_TERMINAL};
items[] += {RADIO_MR,"ACE_HuntIR_monitor"};
};
class coy: sl {// CO and DC
backpack[] = {CARRYALL};
items[] += {RADIO_LR};
};
class uav: rifleman {
backpack[] = {SIDE_UAV_BACKPACK};
linkedItems[] += {SIDE_UAV_TERMINAL};
};
class ar: rifleman {// AR
vest[] = {CAMO_VEST_AR};
backpack[] = {CAMO_BACKPACK_AR};
weapons[] = {AR};
magazines[] = {AR_MAG,PISTOL_MAG,BASE_GRENADES};
handguns[] = {PISTOL};
attachments[] = {AR_ATTACHMENTS};
secondaryAttachments[] = {PISTOL_ATTACHMENTS};
};
class aar: rifleman {// AAR
backpackItems[] += {AR_MAG};
linkedItems[] += {BINOS};
};
class lat: rifleman {// RAT
backpack[] = {CAMO_BACKPACK_LAT};
magazines[] += {AT_MAG};
launchers[] = {AT};
};
class sm: Fic_Soldier_Carbine {// Medic
vest[] = {CAMO_VEST_MEDIC};
magazines[] = {CARBINE_MAG,MEDIC_GRENADES};
backpack[] = {CAMO_BACKPACK_MEDIC};
backpackItems[] = {MEDIC_MEDICAL};
};
class Fic_Spotter: rifleman {
linkedItems[] += {RANGE_FINDER};
};
class mmgg: ar {// MMG
weapons[] = {MMG};
magazines[] = {MMG_MAG,PISTOL_MAG,BASE_GRENADES};
attachments[] = {MMG_ATTACHMENTS};
vest[] = {"CUP_V_B_Eagle_SPC_MG"};
backpack[] = {CARRYALL};
};
class mmgag: Fic_Spotter {// MMG Spotter/Ammo Bearer
backpack[] = {CARRYALL};
backpackItems[] += {MMG_MAG};
};
class matg: Fic_Soldier_Carbine {// MAT Gunner
backpack[] = {CARRYALL};
backpackItems[] = {};
magazines[] += {MAT_MAG};
items[] += {BASE_MEDICAL};
launchers[] = {MAT};
secondaryAttachments[] = {MAT_OPTIC};
};
class matag: Fic_Spotter {// MAT Spotter/Ammo Bearer
backpack[] = {CARRYALL};
backpackItems[] = {};
magazines[] += {MAT_MAG};
items[] += {BASE_MEDICAL};
};
class msamg: Fic_Soldier_Carbine {// SAM Gunner
SAM_GEAR(CARRYALL, SAM_MAG)
launchers[] = {SAM};
};
class msamag: Fic_Spotter {// SAM Spotter/Ammo Bearer
SAM_GEAR(CARRYALL, SAM_MAG)
launchers[] = {SAM};
};
class mtrg: Fic_Soldier_Carbine {// Mortar Gunner
launchers[] = {"potato_vz99_carryWeapon"};
MORTAR_GEAR(CARRYALL)
magazines[] += {"potato_vz99_HE_multi:6","potato_vz99_flare:2"};
};
class mtrag: Fic_Spotter {// Assistant Mortar
launchers[] = {"ace_csw_carryMortarBaseplate"};
MORTAR_GEAR(CARRYALL)
magazines[] += {"potato_vz99_HE_multi:2","potato_vz99_smokeWhite:4","potato_vz99_flare:2"};
};
class spotter: Fic_Spotter {// Spotter
weapons[] = {SPOTTER};
magazines[] = {SPOTTER_MAG,BASE_GRENADES};
items[] += {RADIO_MR,"ACE_ATragMX","ACE_Kestrel4500","ACE_SpottingScope"};
linkedItems[] += {LEADER_LINKED};
attachments[] = {SPOTTER_ATTACHMENTS};
};
class sniper: spotter {// Sniper
weapons[] = {SNIPER};
magazines[] = {SNIPER_MAG,BASE_GRENADES};
items[] = {TOOLS,"ACE_RangeCard","ACE_Tripod","CUP_H_FR_BoonieMARPAT"};
linkedItems[] = {LINKED};
attachments[] = {SNIPER_ATTACHMENTS};
};
class pilot {// Pilot
uniform[] = {CAMO_UNIFORM_PILOT};
backpack[] = {CAMO_BACKPACK_PILOT};
vest[] = {CAMO_VEST_PILOT};
headgear[] = {CAMO_HEADGEAR_PILOT};
weapons[] = {SMG};
magazines[] = {SMG_MAG,CREW_GRENADES};
backpackItems[] = {SIDE_KEY,RADIO_LR};
items[] = {BASE_MEDICAL,TOOLS,LEADER_TOOLS,RADIO_MR};
linkedItems[] = {LINKED,LEADER_LINKED};
};
class vicc: Fic_Soldier_Carbine {// Crew
uniform[] = {CAMO_UNIFORM_VICC};
vest[] = {CAMO_VEST_VICC};
headgear[] = {CAMO_HEADGEAR_VICC};
backpack[] = {CAMO_BACKPACK_VICC};
weapons[] = {CARBINE};
magazines[] = {CARBINE_MAG,CREW_GRENADES};
backpackItems[] = {SIDE_KEY,RADIO_LR};
linkedItems[] = {LINKED,LEADER_LINKED,BINOS};
items[] += {BASE_MEDICAL};
};
class vicd: vicc {// Repair Specialist
backpackItems[] = {"Toolkit",RADIO_MR,SIDE_KEY};
linkedItems[] = {LINKED,LEADER_LINKED};
};
class Fic_eng: vicd {
items[] += {BASE_ENG};
backpackItems[] = {};
};
class demo: Fic_eng {// Explosive Specialist
magazines[] += {BASE_EXP};
};
class mine: Fic_eng {// Mine Specialist
magazines[] += {BASE_MINE};
handguns[] = {MINE_DETECTOR};
};
class demol: Fic_eng {// Demolitions Leader
magazines[] += {BASE_EXP};
backpackItems[] = {RADIO_MR,"Toolkit"};
};
class eng: Fic_eng {// Logistics Engineer
backpackItems[] = {"Toolkit","ACE_EntrenchingTool","ACE_Fortify","ACE_wirecutter"};
};
class fac: coy {// FAC
magazines[] = {GLRIFLE_MAG,SIDE_FAC_GRENADES,"Laserbatteries",PISTOL_MAG};
linkedItems[] = {LINKED,LEADER_LINKED,"CUP_LRTV"};
};
class rifleman_02: rifleman {// Rifleman 2
vest[] = {"CUP_V_B_Eagle_SPC_GL"};
backpack[] = {CAMO_BACKPACK};
weapons[] = {GLRIFLE};
magazines[] = {GLRIFLE_MAG,GLRIFLE_MAG_HE,BASE_GRENADES};
};
class rifleman_03: rifleman {// Rifleman 2
backpack[] = {CAMO_BACKPACK};
launchers[] = {"CUP_launch_M136"};
};
class artl: sl {// Artillery Leader
backpack[] = {CARRYALL};
backpackItems[] += {BASE_ARTILLERY,RADIO_LR};
};
class artg: rifleman {// Artillery Gunner
backpackItems[] += {BASE_ARTILLERY};
};
class plm: sm {//Platoon Medic
backpack[] = {CARRYALL};
backpackItems[] = {PL_MEDIC_MEDICAL};
};
class cm: plm {// Company Medic
};
class xo: coy {// XO
};
class plt: coy {// Platoon Leader
};
class sgt: plt {// Platoon Sergeant
};
class vicl: vicc {// Vehicle Commander
items[] += {RADIO_MR};
backpackItems[] = {SIDE_KEY,RADIO_LR};
};
class mmgl: sl {// MMG Lead
backpack[] = {CARRYALL};
magazines[] += {MMG_MAG};
};
class matl: sl {// MAT Lead
backpack[] = {CARRYALL};
magazines[] += {MAT_MAG};
};
class hmgl: sl {// HMG Lead
weapons[] = {RIFLE};
magazines[] = {RIFLE_MAG,LEADER_GRENADES,PISTOL_MAG,HMG_MAG};
backpack[] = {CARRYALL};
launchers[] = {HMG_TRI_LO};
items[] += {BASE_BALLISTICS};
};
class hmgg: rifleman {// HMG Gunner
backpack[] = {CARRYALL};
magazines[] += {HMG_MAG};
launchers[] = {HMG};
};
class hmgag: rifleman {// HMG Spotter
backpack[] = {CARRYALL};
magazines[] += {HMG_MAG};
launchers[] = {HMG_TRI_HI};
items[] += {BASE_BALLISTICS};
};
class hatl: sl {// HAT Lead
weapons[] = {RIFLE};
backpackItems[] = {};
magazines[] = {RIFLE_MAG,LEADER_GRENADES,PISTOL_MAG,HAT_MAG};
backpack[] = {CARRYALL};
launchers[] = {HAT_TRI_LO};
items[] += {BASE_MEDICAL};
};
class hatg: rifleman {// HAT Gunner
backpack[] = {CARRYALL};
magazines[] += {HAT_MAG};
launchers[] = {HAT};
};
class hatag: rifleman {// HAT Spotter
backpack[] = {CARRYALL};
magazines[] += {HAT_MAG};
launchers[] = {HAT_TRI_HI};
};
class msaml: sl {// MSAM Lead
launchers[] = {SAM};
backpack[] = {CARRYALL};
magazines[] += {SAM_MAG};
};
class mtrl: sl {// Mortar Lead
items[] += {BASE_ARTILLERY};
};
class helicrew: pilot {// Aircrew
backpackItems[] = {"Toolkit",SIDE_KEY};
};
class cc: helicrew {// Crew Chief
backpackItems[] += {RADIO_MR};
};
class engl: eng {// Logistics Leader
weapons[] = {GLRIFLE};
magazines[] = {GLRIFLE_MAG,GLRIFLE_MAG_HE,GLRIFLE_MAG_SMOKE,LEADER_GRENADES};
items[] += {LEADER_TOOLS};
linkedItems[] += {LEADER_LINKED,BINOS};
backpackItems[] += {RADIO_MR};
};
class fallback: rifleman {}; // This means any faction member who doesn't match something will use this loadout
| [
"noreply@github.com"
] | noreply@github.com |
e8e9555605a74528f71faa7a2e091e87d8505672 | 466ac1c25d3a74ec68a2cc2cec90644f6e8be5c1 | /solutions/AccurateLee.cpp | 12fe2befa5a73011287531f00cc409f1c7714448 | [] | no_license | hiroshi-maybe/codeforces | e7384979b1788a3d5ed6662527273f5dc22b8220 | f83eaca933cbe68bec0947bab33bcbbbbf4f50ae | refs/heads/master | 2023-04-06T03:18:50.178940 | 2023-03-27T06:54:02 | 2023-03-27T06:54:02 | 131,480,025 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,837 | cpp | #include <bits/stdc++.h>
using namespace std;
// type alias
typedef long long LL;
typedef pair<int,int> II;
typedef tuple<int,int,int> III;
typedef vector<int> VI;
typedef vector<string> VS;
typedef unordered_map<int,int> MAPII;
typedef unordered_set<int> SETI;
template<class T> using VV=vector<vector<T>>;
// minmax
template<class T> inline T SMIN(T& a, const T b) { return a=(a>b)?b:a; }
template<class T> inline T SMAX(T& a, const T b) { return a=(a<b)?b:a; }
// repetition
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) for(int i=0;i<=(n);++i)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) for(int i=0;i<(n);++i)
#define FORR(x,arr) for(auto& x:arr)
#define SZ(a) int((a).size())
// collection
#define ALL(c) (c).begin(),(c).end()
// DP
#define MINUS(dp) memset(dp, -1, sizeof(dp))
#define ZERO(dp) memset(dp, 0, sizeof(dp))
// stdout
#define println(args...) fprintf(stdout, ##args),putchar('\n');
// debug cerr
template<class Iter> void __kumaerrc(Iter begin, Iter end) { for(; begin!=end; ++begin) { cerr<<*begin<<','; } cerr<<endl; }
void __kumaerr(istream_iterator<string> it) { (void)it; cerr<<endl; }
template<typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cerr<<*it<<"="<<a<<", ",__kumaerr(++it, args...); }
template<typename S, typename T> std::ostream& operator<<(std::ostream& _os, const std::pair<S,T>& _p) { return _os<<"{"<<_p.first<<','<<_p.second<<"}"; }
#define __KUMATRACE__ true
#ifdef __KUMATRACE__
#define dump(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); __kumaerr(_it, args); }
#define dumpc(ar) { cerr<<#ar<<": "; FORR(x,(ar)) { cerr << x << ','; } cerr << endl; }
#define dumpC(beg,end) { cerr<<"~"<<#end<<": "; __kumaerrc(beg,end); }
#else
#define dump(args...)
#define dumpc(ar)
#define dumpC(beg,end)
#endif
// $ cp-batch AccurateLee | diff AccurateLee.out -
// $ g++ -std=c++14 -Wall -O2 -D_GLIBCXX_DEBUG -fsanitize=address AccurateLee.cpp && ./a.out
/*
6/23/2020
7:20-7:34 AC
https://codeforces.com/blog/entry/79235
*/
//const int MAX_N=1e6+1;
string S;
int N;
void solve() {
string pre="",suf="";
REP(i,N) {
if(S[i]=='0') pre.push_back(S[i]);
else break;
}
string s=S.substr(SZ(pre));
for(int i=SZ(s)-1; i>=0; --i) {
if(s[i]=='1') suf.push_back(s[i]);
else break;
}
reverse(ALL(suf));
string ss=s.substr(0,SZ(s)-SZ(suf));
//dump(pre,ss,suf);
string res;
if(SZ(ss)) {
assert(count(ALL(ss),'1')>0);
assert(count(ALL(ss),'0')>0);
res=pre+"0"+suf;
} else {
res=pre+suf;
}
cout<<res<<endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout<<setprecision(12)<<fixed;
int t; cin>>t;
while(t--) {
cin>>N>>S;
solve();
}
return 0;
}
| [
"hiroshi.maybe@gmail.com"
] | hiroshi.maybe@gmail.com |
c83adecef02accaaab9ae56e82d1fb22ffa89a3e | 20182a48594874f1a909472b2949989a9e4599d6 | /AutonomicGUI/SimCooccupancy.cpp | d77b8d33af489e39feacafebe84787d97759f676 | [] | no_license | radtek/HAA | 952e3d5946723bc496d02227a067fcc9f257d51e | 85fede7e5456a13e9c5e5fc0531e339631c4cfba | refs/heads/master | 2021-02-17T21:44:19.444821 | 2017-05-29T16:25:14 | 2017-05-29T16:25:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,341 | cpp | // SimCooccupancy.cpp
//
#include "stdafx.h"
#include "math.h"
#include "SimAgent.h"
#include "SimCooccupancy.h"
#include <boost/math/special_functions/erf.hpp>
#define pfStateX( pr, i ) pr->pfState[i*3]
#define pfStateY( pr, i ) pr->pfState[i*3+1]
#define pfStateR( pr, i ) pr->pfState[i*3+2]
//*****************************************************************************
// SimCooccupancy
//-----------------------------------------------------------------------------
// Constructor
SimCooccupancy::SimCooccupancy( Simulation *sim, Visualize *vis, RandomGenerator *randGen ) : SimAgentBase( sim, vis, randGen ) {
this->nextReadingId = 0;
this->mapDataSize = 0;
this->mapData = NULL;
}
//-----------------------------------------------------------------------------
// Destructor
SimCooccupancy::~SimCooccupancy() {
if ( this->started ) {
this->stop();
}
}
//-----------------------------------------------------------------------------
// Configure
int SimCooccupancy::configure() {
if ( Log.getLogMode() == LOG_MODE_OFF ) {
// Init logging
char logName[256];
char timeBuf[64];
time_t t_t;
struct tm stm;
time( &t_t );
localtime_s( &stm, &t_t );
strftime( timeBuf, 64, "%y.%m.%d [%H.%M.%S]", &stm );
sprintf_s( logName, "log SimCooccupancy %s.txt", timeBuf );
Log.setLogMode( LOG_MODE_FILE, logName );
Log.setLogLevel( LOG_LEVEL_VERBOSE );
Log.log( 0, "SimCooccupancy" );
}
return SimAgentBase::configure();
}
//-----------------------------------------------------------------------------
// Start
int SimCooccupancy::start() {
if ( !this->configured )
return 1; // not configured
if ( SimAgentBase::start() )
return 1;
this->started = false;
this->mapUpdate = NewImage( 64, 64 );
this->sharedArraySize = 0;
this->obsDensity = NULL;
this->started = true;
return 0;
}
int SimCooccupancy::setMap( UUID *id ) {
this->mapId = *id;
// get map resolution
sim->ddbPOGGetInfo( id, &this->ds );
this->ds.rewind();
this->ds.unpackInt32(); // thread
if ( this->ds.unpackChar() == DDBR_OK ) {
this->ds.unpackFloat32(); // tilesize
this->mapResolution = this->ds.unpackFloat32();
this->ds.unpackInt32(); // stride
} else {
UuidCreateNil( &this->mapId );
return 1;
}
return 0;
}
//-----------------------------------------------------------------------------
// Stop
int SimCooccupancy::stop() {
// clean up buffers
if ( this->mapDataSize )
free( this->mapData );
FreeImage( this->mapUpdate );
if ( this->sharedArraySize ) {
free( this->obsDensity );
this->sharedArraySize = 0;
}
return SimAgentBase::stop();
}
//-----------------------------------------------------------------------------
// Processing
int SimCooccupancy::addReading( UUID *avatar, _timeb *tb ) {
// make sure we have the radius
mapRadius::iterator iterR = this->avatarRadius.find( *avatar );
if ( iterR == this->avatarRadius.end() ) {
// get radius
// TEMP for now just assume a radius of 0.15 m
this->avatarRadius[*avatar] = 0.15f;
/*sim->ddbSensorGetInfo( sensor, DDBSENSORINFO_AVATAR | DDBSENSORINFO_POSE, &this->ds );
this->ds.rewind();
this->ds.unpackInt32(); // discard thread
if ( this->ds.unpackChar() == DDBR_OK ) {
this->ds.unpackInt32(); // discard infoFlags
this->ds.unpackUUID( &avatar );
this->sensorAvatar[*sensor] = avatar;
this->ds.unpackInt32(); // discard poseSize
pose = *(SonarPose *)this->ds.unpackData( sizeof(SonarPose) );
this->sensorPose[*sensor] = pose;
} else {
return 1;
} */
}
// get PF
PROCESS_READING *pr = &this->readings[this->nextReadingId];
pr->id = this->nextReadingId;
this->nextReadingId++;
pr->avatar = *avatar;
pr->time = *tb;
pr->pfState = NULL;
pr->pfWeight = NULL;
pr->retries = 0;
this->cbRequestPFInfo( &pr->id );
return 0;
}
int SimCooccupancy::processReading( PROCESS_READING *pr ) {
int mapDivisions = (int)floor(1/this->mapResolution);
int border;
int p;
int r, c;
float stateX, stateY;
float PFbound[4];
float mapUpdateLoc[2]; // location of the mapUpdate origin
int mapUpdateSize[2]; // width,height (cols,rows)
float minObsDensity;
float radius; // avatar radius
// generate particle filter and map updates
// update PFbound
// TODO ignore particles with very little weight?
PFbound[0] = pfStateX(pr,0);
PFbound[1] = pfStateY(pr,0);
PFbound[2] = 0;
PFbound[3] = 0;
for ( p=1; p<pr->pfNum; p++ ) {
if ( PFbound[0] > pfStateX(pr,p) ) {
PFbound[2] = PFbound[0] + PFbound[2] - pfStateX(pr,p);
PFbound[0] = pfStateX(pr,p);
} else if ( PFbound[0] + PFbound[2] < pfStateX(pr,p) ) {
PFbound[2] = pfStateX(pr,p) - PFbound[0];
}
if ( PFbound[1] > pfStateY(pr,p) ) {
PFbound[3] = PFbound[1] + PFbound[3] - pfStateY(pr,p);
PFbound[1] = pfStateY(pr,p);
} else if ( PFbound[1] + PFbound[3] < pfStateY(pr,p) ) {
PFbound[3] = pfStateY(pr,p) - PFbound[1];
}
}
PFbound[2] = ceil((PFbound[0]+PFbound[2])*mapDivisions)/mapDivisions;
PFbound[0] = floor(PFbound[0]*mapDivisions)/mapDivisions;
PFbound[2] -= PFbound[0];
PFbound[3] = ceil((PFbound[1]+PFbound[3])*mapDivisions)/mapDivisions;
PFbound[1] = floor(PFbound[1]*mapDivisions)/mapDivisions;
PFbound[3] -= PFbound[1];
radius = this->avatarRadius[pr->avatar];
// prepare map update
border = (int)ceil(mapDivisions*radius);
mapUpdateLoc[0] = PFbound[0] - border/(float)mapDivisions;
mapUpdateLoc[1] = PFbound[1] - border/(float)mapDivisions;
mapUpdateSize[0] = (int)(PFbound[2]*mapDivisions)+border*2;
mapUpdateSize[1] = (int)(PFbound[3]*mapDivisions)+border*2;
if ( mapUpdate->bufSize < (int)sizeof(float)*(mapUpdateSize[0] * mapUpdateSize[1]) ) {
// allocate more space for the map update
ReallocImage( mapUpdate, mapUpdateSize[1], mapUpdateSize[0] );
} else {
mapUpdate->rows = mapUpdateSize[1];
mapUpdate->cols = mapUpdateSize[0];
mapUpdate->stride = mapUpdate->rows;
}
for ( r=0; r<mapUpdate->rows; r++ ) {
for ( c=0; c<mapUpdate->cols; c++ ) {
Px(mapUpdate,r,c) = 0.5f;
}
}
float mapX = mapUpdateLoc[0];
float mapY = mapUpdateLoc[1];
// get map
sim->ddbPOGGetRegion( &this->mapId, mapUpdateLoc[0], mapUpdateLoc[1], mapUpdateSize[0]*this->mapResolution, mapUpdateSize[1]*this->mapResolution, &this->ds );
this->ds.rewind();
this->ds.unpackInt32(); // thread
if ( this->ds.unpackChar() == DDBR_OK ) { // succeeded
float x, y, w, h;
int cw, ch;
x = this->ds.unpackFloat32();
y = this->ds.unpackFloat32();
w = this->ds.unpackFloat32();
h = this->ds.unpackFloat32();
this->mapResolution = this->ds.unpackFloat32();
cw = (int)floor( w / this->mapResolution );
ch = (int)floor( h / this->mapResolution );
// make sure mapData is big enough
if ( cw*ch*4 > this->mapDataSize ) {
if ( this->mapData )
free( this->mapData );
this->mapData = (float *)malloc(cw*ch*4);
if ( !this->mapData ) {
this->mapDataSize = 0;
this->finishReading( pr, 0 );
return 1;
}
this->mapDataSize = cw*ch*4;
}
memcpy( this->mapData, this->ds.unpackData( cw*ch*4 ), cw*ch*4 );
this->mapHeight = ch;
} else {
this->finishReading( pr, 0 );
return 0;
}
// make sure arrays are big enough
if ( this->sharedArraySize < pr->pfNum ) {
if ( this->sharedArraySize ) {
free( this->obsDensity );
}
this->sharedArraySize = pr->pfNum;
this->obsDensity = (float *)malloc( sizeof(float)*this->sharedArraySize );
if ( !this->obsDensity ) {
this->sharedArraySize = 0;
return 1; // malloc failed
}
}
float sigma = radius/3;
float invSqrt2SigSq = 1 / sqrt(2*sigma*sigma);
float CcdfA, CcdfB;
float RcdfA, RcdfB;
float vacancy;
// for each particle
minObsDensity = 0;
for ( p=0; p<pr->pfNum; p++ ) {
stateX = pfStateX(pr,p);
stateY = pfStateY(pr,p);
// iterate through cells, calculate vacancy and compare against map compare against map
obsDensity[p] = 0;
CcdfB = 0.5f * ( 1 + boost::math::erf( (mapX - stateX) * invSqrt2SigSq ));
for ( c=0; c<mapUpdate->cols; c++ ) {
CcdfA = CcdfB;
CcdfB = 0.5f * ( 1 + boost::math::erf( (mapX + (c+1)*mapResolution - stateX) * invSqrt2SigSq ));
RcdfB = 0.5f * ( 1 + boost::math::erf( (mapY - stateY) * invSqrt2SigSq ));
for ( r=0; r<mapUpdate->rows; r++ ) {
RcdfA = RcdfB;
RcdfB = 0.5f * ( 1 + boost::math::erf( (mapY + (r+1)*mapResolution - stateY) * invSqrt2SigSq ));
vacancy = (CcdfB - CcdfA)/mapResolution * (RcdfB - RcdfA)/mapResolution;
Px(mapUpdate,r,c) += pr->pfWeight[p] * vacancy * 0.49f * SimCooccupancy_MAP_UPDATE_STRENGTH;
// total penalty
if ( this->mapData[r+c*this->mapHeight] < 0.5f ) {
obsDensity[p] -= vacancy * (0.5f - this->mapData[r+c*this->mapHeight]);
}
}
}
minObsDensity = min( minObsDensity, obsDensity[p] );
}
// compute observation density
if ( minObsDensity < 0 ) {
for ( p=0; p<pr->pfNum; p++ ) { // shift observation densities positive and add ambient
obsDensity[p] += -minObsDensity + SimCooccupancy_OBS_DENSITY_AMBIENT;
}
// submit particle filter update
sim->ddbApplyPFCorrection( &pr->avatar, &pr->time, obsDensity );
}
// submit map update
sim->ddbApplyPOGUpdate( &this->mapId, mapUpdateLoc[0], mapUpdateLoc[1], mapUpdateSize[0]*this->mapResolution, mapUpdateSize[1]*this->mapResolution, this->mapUpdate->data );
// finish reading
this->finishReading( pr, 1 );
return 0;
}
int SimCooccupancy::finishReading( PROCESS_READING *pr, bool success ) {
if ( pr->pfState )
free( pr->pfState );
if ( pr->pfWeight )
free( pr->pfWeight );
this->readings.erase( pr->id );
return 0;
}
//-----------------------------------------------------------------------------
// Callbacks
bool SimCooccupancy::cbRequestPFInfo( void *vpReadingId ) {
int readingId = *(int *)vpReadingId;
PROCESS_READING *pr;
int infoFlags;
char response;
pr = &this->readings[readingId];
sim->ddbPFGetInfo( &pr->avatar, DDBPFINFO_NUM_PARTICLES | DDBPFINFO_STATE_SIZE | DDBPFINFO_STATE | DDBPFINFO_WEIGHT, &pr->time, &this->ds );
this->ds.rewind();
this->ds.unpackInt32(); // thread
response = this->ds.unpackChar();
if ( response == DDBR_OK ) { // succeeded
// handle info
infoFlags = this->ds.unpackInt32();
if ( infoFlags != (DDBPFINFO_NUM_PARTICLES | DDBPFINFO_STATE_SIZE | DDBPFINFO_STATE | DDBPFINFO_WEIGHT) ) {
this->finishReading( pr, 0 );
return 0; // what happened?
}
pr->pfNum = this->ds.unpackInt32();
pr->pfStateSize = this->ds.unpackInt32();
pr->pfState = (float *)malloc( pr->pfNum*pr->pfStateSize*sizeof(float) );
if ( pr->pfState == NULL ) {
this->finishReading( pr, 0 );
return 0;
}
pr->pfWeight = (float *)malloc( pr->pfNum*sizeof(float) );
if ( pr->pfWeight == NULL ) {
this->finishReading( pr, 0 );
return 0;
}
memcpy( pr->pfState, this->ds.unpackData( pr->pfNum*pr->pfStateSize*sizeof(float) ), pr->pfNum*pr->pfStateSize*sizeof(float) );
memcpy( pr->pfWeight, this->ds.unpackData( pr->pfNum*sizeof(float) ), pr->pfNum*sizeof(float) );
this->processReading( pr );
} else if ( response == DDBR_TOOLATE ) {
// wait 250 ms and try again
pr->retries++;
if ( pr->retries < 10 )
this->addTimeout( SimCooccupancy_REPEAT_RPFINFO_PERIOD, NEW_MEMBER_CB(SimCooccupancy, cbRequestPFInfo), &readingId, sizeof(int) );
else
this->finishReading( pr, 0 );
} else {
this->finishReading( pr, 0 );
}
return 0;
} | [
"stevendaniluk8@gmail.com"
] | stevendaniluk8@gmail.com |
001e48ff51a79185f8e63d13884edbbe2542a0b7 | 65f9576021285bc1f9e52cc21e2d49547ba77376 | /LINUX/android/vendor/qcom/proprietary/mm-video-utils/vtest-omx/app/src/vtest_App.cpp | e1b382fa79f62a1de26f007712aca8e0e5cd8b2f | [] | no_license | AVCHD/qcs605_root_qcom | 183d7a16e2f9fddc9df94df9532cbce661fbf6eb | 44af08aa9a60c6ca724c8d7abf04af54d4136ccb | refs/heads/main | 2023-03-18T21:54:11.234776 | 2021-02-26T11:03:59 | 2021-02-26T11:03:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,056 | cpp | /*-------------------------------------------------------------------
Copyright (c) 2013-2014, 2016 Qualcomm Technologies, Inc.
All Rights Reserved.
Confidential and Proprietary - Qualcomm Technologies, Inc.
Copyright (c) 2010 The Linux Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND
NON-INFRINGEMENT 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 <stdlib.h>
#include "vtest_Script.h"
#include "vtest_Debug.h"
#include "vtest_ComDef.h"
#include "vtest_XmlComdef.h"
#include "vtest_XmlParser.h"
#include "vtest_ITestCase.h"
#include "vtest_TestCaseFactory.h"
vtest::VideoStaticProperties sGlobalStaticVideoProp;
OMX_ERRORTYPE RunTest(vtest::VideoStaticProperties* pGlobalVideoProp, vtest::VideoSessionInfo* pSessionInfo) {
OMX_ERRORTYPE result = OMX_ErrorNone;
static OMX_S32 testNum = 0;
testNum++;
vtest::ITestCase *pTest =
vtest::TestCaseFactory::AllocTest(pSessionInfo->SessionType);
if (pTest == NULL) {
VTEST_MSG_CONSOLE("Unable to alloc test: %s", pSessionInfo->SessionType);
return OMX_ErrorInsufficientResources;
}
VTEST_SIMPLE_MSG_CONSOLE("\n\n");
VTEST_MSG_CONSOLE("Running OMX test %s", pSessionInfo->SessionType);
result = pTest->Start(testNum,pGlobalVideoProp, pSessionInfo);
if (result != OMX_ErrorNone) {
VTEST_MSG_CONSOLE("Error starting test");
} else {
result = pTest->Finish();
if (result != OMX_ErrorNone) {
VTEST_MSG_CONSOLE("Test failed\n");
if(pGlobalVideoProp->fResult) {
fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, FAIL\n", OMX_VTEST_VERSION, pSessionInfo->TestId);
} else {
VTEST_MSG_HIGH("Result file not found");
}
} else {
VTEST_MSG_CONSOLE("Test passed\n");
if(!strcmp(pSessionInfo->SessionType,"DECODE")) {
if(pGlobalVideoProp->fResult) {
fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, PASS\n", OMX_VTEST_VERSION, pSessionInfo->TestId);
} else {
VTEST_MSG_HIGH("Result file not found");
}
} else if(!strcmp(pSessionInfo->SessionType,"ENCODE")) {
if(pGlobalVideoProp->fResult) {
fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, EPV Pending \n", OMX_VTEST_VERSION, pSessionInfo->TestId);
} else {
VTEST_MSG_HIGH("Result file not found");
}
} else {
if(pGlobalVideoProp->fResult) {
fprintf(pGlobalVideoProp->fResult, "\nVTEST-OMX %s, %s, UNSUPPORTED TEST CASE \n", OMX_VTEST_VERSION, pSessionInfo->TestId);
} else {
VTEST_MSG_HIGH("Result file not found");
}
}
}
}
vtest::TestCaseFactory::DestroyTest(pTest);
return result;
}
int main(int argc, char *argv[]) {
OMX_ERRORTYPE result = OMX_ErrorNone;
vtest::XmlParser *pXmlParser = NULL;
vtest::VideoSessionInfo sSessionInfo[MAX_NUM_SESSIONS];
vtest::VideoSessionInfo *pSessionInfo = NULL;
vtest::VideoSessionInfo *pBaseSessionInfo = NULL;
char resultFile[MAX_STR_LEN];
char masterXmlLocation[MAX_STR_LEN];
OMX_Init();
if (argc != 3) {
VTEST_MSG_CONSOLE("Usage: %s <MasterConfg.xml path> <input.xml>\n", argv[0]);
return OMX_ErrorBadParameter;
}
pXmlParser = new vtest::XmlParser;
if(!pXmlParser) {
VTEST_MSG_CONSOLE("Error while allocating memory for pXmlParser\n");
result = OMX_ErrorUndefined;
goto DEINIT;
}
//Master XML Parsing
if (OMX_ErrorNone != pXmlParser->ResolveMasterXmlPath(argv[1], masterXmlLocation)) {
VTEST_MSG_CONSOLE("Error: Input %s is neither a valid path nor a valid filename\n", argv[1]);
return OMX_ErrorUndefined;
}
if (OMX_ErrorNone != pXmlParser->ProcessMasterConfig(&sGlobalStaticVideoProp)) {
VTEST_MSG_CONSOLE("Error while processing MasterXml\n");
return OMX_ErrorUndefined;
}
//Also open the Results.Csv file
SNPRINTF(resultFile, MAX_STR_LEN, "%s/Results.csv", masterXmlLocation);
sGlobalStaticVideoProp.fResult = fopen(resultFile, "a+");
if (!sGlobalStaticVideoProp.fResult) {
VTEST_MSG_CONSOLE("Results.Csv file opening failed");
return OMX_ErrorUndefined;
}
//Session XML Parsing and Running
memset((char*)&sSessionInfo[0], 0, MAX_NUM_SESSIONS * sizeof(vtest::VideoSessionInfo));
if (OMX_ErrorNone != pXmlParser->ParseSessionXml((OMX_STRING)argv[2], &sGlobalStaticVideoProp, &sSessionInfo[0])) {
VTEST_MSG_CONSOLE("Error while processing SessionXml and starting test\n");
return OMX_ErrorUndefined;
}
pSessionInfo = pBaseSessionInfo = &sSessionInfo[0];
while (pSessionInfo->bActiveSession == OMX_TRUE) {
if (OMX_ErrorNone != RunTest(&sGlobalStaticVideoProp,pSessionInfo)) {
VTEST_MSG_CONSOLE("Failed Processing Session: %s\n", pSessionInfo->SessionType);
}
pSessionInfo++;
if(pSessionInfo >= (pBaseSessionInfo + MAX_NUM_SESSIONS )) {
VTEST_MSG_CONSOLE("Exceeded the number of sessions\n");
break;
}
}
if (sGlobalStaticVideoProp.fResult) {
fclose(sGlobalStaticVideoProp.fResult);
sGlobalStaticVideoProp.fResult = NULL;
}
if(pXmlParser) {
delete pXmlParser;
pXmlParser = NULL;
}
DEINIT:
OMX_Deinit();
return result;
}
| [
"jagadeshkumar.s@pathpartnertech.com"
] | jagadeshkumar.s@pathpartnertech.com |
d10e4f3096e036db3d7f3018a7147b0e8db58427 | c9f588e5b79340bbec96307d7739e6c8c5acd552 | /User/ui/draw_filamentchange.cpp | ad255958a46615d835fb6878daacb3935f66a39e | [] | no_license | mpalpha/elf-corexy-stock-firmware | 174ca6144c724f1877b50495fd96c52d769dbd59 | 20f0c906d8f7c0cbc3d5c9452318e1669994e505 | refs/heads/master | 2022-07-10T11:49:56.777411 | 2020-05-15T17:44:50 | 2020-05-15T17:44:50 | 264,258,581 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 15,153 | cpp | #include "gui.h"
#include "button.h"
#include "draw_filamentchange.h"
#include "draw_ui.h"
//#include "printer.h"
#include "text.h"
//#include "gcode.h"
#include "draw_pre_heat.h"
//#include "mks_tft_fifo.h"
//#include "mks_tft_com.h"
#include "draw_printing.h"
#include "marlin.h"
#include "temperature.h"
#include "mks_reprint.h"
#include "draw_pause_ui.h"
extern float feedrate_mm_s;
//extern TFT_FIFO gcodeCmdTxFIFO; //gcode 指令发送队列
//extern TFT_FIFO gcodeCmdRxFIFO; //gcode 指令接收队列
extern int X_ADD,X_INTERVAL;
GUI_HWIN hFilamentChangeWnd;
static TEXT_Handle textExtruTemp, textExtruMsg;
static BUTTON_STRUCT buttonFilamentChangeIn, buttonFilamentChangeOut, buttonSprayType,buttonFilamentChangepreheat,buttonFilamentChangeStop, buttonRet;
extern volatile uint8_t get_temp_flag;
extern uint8_t Get_Temperature_Flg;
extern unsigned char positionSaveFlag;
uint8_t filamentchange_Process = 0;
extern uint8_t link_mutex_detect_time;
void disp_filament_sprayer_type();
void disp_filament_sprayer_temp();
uint8_t Filament_in_flg;
uint8_t Filament_out_flg;
uint8_t filament_loading_complete;
uint8_t filament_heating_flg;
uint8_t filament_loading_flg;
uint8_t filament_load_cmd_flg;
uint8_t filament_load_timing_flg;
uint16_t filament_load_timing_cnt;
uint8_t filament_load_heat_flg;
uint8_t filament_unload_heat_flg;
static uint8_t filament_in_out_flg;
extern uint8_t pause_flag;
extern void filament_sprayer_temp();
static void cbFilamentChangeWin(WM_MESSAGE * pMsg) {
char buf[50] = {0};
switch (pMsg->MsgId)
{
case WM_PAINT:
//GUI_SetColor(gCfgItems.state_background_color);
//GUI_SetColor(gCfgItems.state_background_color);
//GUI_DrawRect(LCD_WIDTH/4+X_ADD, 0, LCD_WIDTH *3 / 4-X_INTERVAL, imgHeight /2 -15);
//GUI_SetColor(gCfgItems.state_background_color);
//GUI_FillRect(LCD_WIDTH/4+X_ADD, 0, LCD_WIDTH *3 / 4-X_INTERVAL, imgHeight /2 -15);
break;
case WM_TOUCH:
break;
case WM_TOUCH_CHILD:
break;
case WM_NOTIFY_PARENT:
if(pMsg->Data.v == WM_NOTIFICATION_RELEASED)
{
if(pMsg->hWinSrc == buttonRet.btnHandle)
{
#if tan_mask
//if(last_disp_state != PAUSE_UI)
//{
//Get_Temperature_Flg = 0;
//}
#if 0
if((printerStaus== pr_pause)&&(pause_flag != 1))
{
pause_flag = 0;
//I2C_EE_Init(400000);
MX_I2C1_Init(400000);
start_print_time();
printerStaus = pr_working;
}
#endif
if(filament_in_out_flg == 1)
{
if((gCfgItems.sprayerNum == 2)&&(printerStaus != pr_idle))
{
gCfgItems.curSprayerChoose = gCfgItems.curSprayerChoose_bak;
}
sprintf(buf,"M104 T%d S%.f\n",gCfgItems.curSprayerChoose,gCfgItems.desireSprayerTempBak_1[gCfgItems.curSprayerChoose]);
pushFIFO(&gcodeCmdTxFIFO,(unsigned char *)buf);
}
#endif
if((mksCfg.extruders == 2)
&&(mksReprint.mks_printer_state!=MKS_IDLE)
&&(mksReprint.mks_printer_state!=MKS_REPRINTED))
{
if(gCfgItems.curSprayerChoose_bak == 1)
{
enqueue_and_echo_command("T1");
}
else
{
enqueue_and_echo_command("T0");
}
feedrate_mm_s = gCfgItems.moveSpeed_bak ;
}
thermalManager.target_temperature[gCfgItems.curSprayerChoose]= gCfgItems.desireSprayerTempBak;
filament_in_out_flg = 0;
last_disp_state = FILAMENTCHANGE_UI;
Clear_FilamentChange();
#if defined(TFT35)
draw_return_ui();
#else
if(mksReprint.mks_printer_state== MKS_IDLE)
draw_return_ui();
else
{
draw_pause();
}
#endif
}
else if(pMsg->hWinSrc == buttonFilamentChangeIn.btnHandle)
{
temperature_change_frequency = 1;
filament_load_heat_flg=1;
if((abs(thermalManager.target_temperature[gCfgItems.curSprayerChoose]-thermalManager.current_temperature[gCfgItems.curSprayerChoose])<=1)
||(gCfgItems.filament_load_limit_temper<=thermalManager.current_temperature[gCfgItems.curSprayerChoose]))
{
last_disp_state = FILAMENTCHANGE_UI;
Clear_FilamentChange();
draw_dialog(DIALOG_TYPE_FILAMENT_HEAT_LOAD_COMPLETED);
}
else
{
last_disp_state = FILAMENTCHANGE_UI;
Clear_FilamentChange();
draw_dialog(DIALOG_TYPE_FILAMENT_LOAD_HEAT);
if(thermalManager.target_temperature[gCfgItems.curSprayerChoose]<gCfgItems.filament_load_limit_temper)
{
memset(buf,0,sizeof(buf));
sprintf(buf,"M104 T%d S%d\n",gCfgItems.curSprayerChoose,gCfgItems.filament_load_limit_temper);
enqueue_and_echo_commands_P(PSTR(buf));
}
filament_sprayer_temp();
}
}
else if(pMsg->hWinSrc == buttonFilamentChangeOut.btnHandle)
{
temperature_change_frequency=1;
filament_unload_heat_flg=1;
if((thermalManager.target_temperature[gCfgItems.curSprayerChoose] > 0)
&&((abs((int)((int)thermalManager.target_temperature[gCfgItems.curSprayerChoose] - gCfgItems.filament_unload_limit_temper))<=1)
||((int)thermalManager.target_temperature[gCfgItems.curSprayerChoose] > gCfgItems.filament_unload_limit_temper)))
{
last_disp_state = FILAMENTCHANGE_UI;
Clear_FilamentChange();
draw_dialog(DIALOG_TYPE_FILAMENT_UNLOAD_COMPLETED);
}
else
{
last_disp_state = FILAMENTCHANGE_UI;
Clear_FilamentChange();
draw_dialog(DIALOG_TYPE_FILAMENT_UNLOAD_HEAT);
if(thermalManager.target_temperature[gCfgItems.curSprayerChoose]<gCfgItems.filament_load_limit_temper)
{
memset(buf,0,sizeof(buf));
sprintf(buf,"M104 T%d S%d\n",gCfgItems.curSprayerChoose,gCfgItems.filament_load_limit_temper);
enqueue_and_echo_commands_P(PSTR(buf));
}
filament_sprayer_temp();
//gCfgItems.desireSprayerTemp[gCfgItems.curSprayerChoose] = gCfgItems.filament_unload_limit_temper;
//Extruder::setTemperatureForExtruder(gCfgItems.filament_unload_limit_temper,gCfgItems.curSprayerChoose);
}
}
else if(pMsg->hWinSrc == buttonSprayType.btnHandle)
{
if(mksCfg.extruders == 2)
{
if(gCfgItems.curSprayerChoose == 0)
{
gCfgItems.curSprayerChoose = 1;
//enqueue_and_echo_commands_P("T1");
}
else
{
gCfgItems.curSprayerChoose = 0;
//enqueue_and_echo_commands_P("T0");
}
}
else
{
gCfgItems.curSprayerChoose = 0;
}
disp_filament_sprayer_temp();
disp_filament_sprayer_type();
}
}
break;
default:
WM_DefaultProc(pMsg);
}
}
void draw_FilamentChange()
{
int8_t buf[100] = {0};
//link_mutex_detect_time = 5;
//Get_Temperature_Flg = 1;
//get_temp_flag = 1;
if(disp_state_stack._disp_state[disp_state_stack._disp_index] != FILAMENTCHANGE_UI)
{
disp_state_stack._disp_index++;
disp_state_stack._disp_state[disp_state_stack._disp_index] = FILAMENTCHANGE_UI;
}
disp_state = FILAMENTCHANGE_UI;
GUI_SetBkColor(gCfgItems.background_color);
GUI_SetColor(gCfgItems.title_color);
GUI_Clear();
#if 0
if(gCfgItems.language == LANG_COMPLEX_CHINESE)
{
GUI_SetFont(&GUI_FontHZ16);
}
else if(gCfgItems.language == LANG_SIMPLE_CHINESE)
{
GUI_SetFont(&FONT_TITLE);
}
else
{
GUI_SetFont(&GUI_FontHZ_fontHz18);
}
#endif
GUI_DispStringAt(creat_title_text(), TITLE_XPOS, TITLE_YPOS);
hFilamentChangeWnd = WM_CreateWindow(0, titleHeight, LCD_WIDTH, imgHeight, WM_CF_SHOW, cbFilamentChangeWin, 0);
buttonFilamentChangeIn.btnHandle = BUTTON_CreateEx(INTERVAL_V,0,BTN_X_PIXEL, BTN_Y_PIXEL, hFilamentChangeWnd, BUTTON_CF_SHOW, 0, alloc_win_id());
buttonFilamentChangeOut.btnHandle = BUTTON_CreateEx(BTN_X_PIXEL*3+INTERVAL_V*4,0,BTN_X_PIXEL, BTN_Y_PIXEL, hFilamentChangeWnd, BUTTON_CF_SHOW, 0, alloc_win_id());
buttonSprayType.btnHandle = BUTTON_CreateEx(INTERVAL_V,BTN_Y_PIXEL+INTERVAL_H,BTN_X_PIXEL, BTN_Y_PIXEL, hFilamentChangeWnd, BUTTON_CF_SHOW, 0, alloc_win_id());
buttonRet.btnHandle = BUTTON_CreateEx(BTN_X_PIXEL*3+INTERVAL_V*4, BTN_Y_PIXEL+INTERVAL_H,BTN_X_PIXEL,BTN_Y_PIXEL, hFilamentChangeWnd, BUTTON_CF_SHOW, 0, alloc_win_id());
BUTTON_SetBmpFileName(buttonFilamentChangeIn.btnHandle, "bmp_in.bin",1);
BUTTON_SetBmpFileName(buttonFilamentChangeOut.btnHandle, "bmp_out.bin",1);
BUTTON_SetBmpFileName(buttonRet.btnHandle, "bmp_return.bin",1);
BUTTON_SetBitmapEx(buttonFilamentChangeIn.btnHandle, 0, &bmp_struct, BMP_PIC_X, BMP_PIC_Y);
BUTTON_SetBitmapEx(buttonFilamentChangeOut.btnHandle, 0, &bmp_struct, BMP_PIC_X, BMP_PIC_Y);
BUTTON_SetBitmapEx(buttonRet.btnHandle, 0, &bmp_struct, BMP_PIC_X, BMP_PIC_Y);
BUTTON_SetBkColor(buttonFilamentChangeIn.btnHandle, BUTTON_CI_PRESSED, gCfgItems.btn_color);
BUTTON_SetBkColor(buttonFilamentChangeIn.btnHandle, BUTTON_CI_UNPRESSED, gCfgItems.btn_color);
BUTTON_SetTextColor(buttonFilamentChangeIn.btnHandle, BUTTON_CI_PRESSED, gCfgItems.btn_textcolor);
BUTTON_SetTextColor(buttonFilamentChangeIn.btnHandle, BUTTON_CI_UNPRESSED, gCfgItems.btn_textcolor);
BUTTON_SetBkColor(buttonFilamentChangeOut.btnHandle, BUTTON_CI_PRESSED, gCfgItems.btn_color);
BUTTON_SetBkColor(buttonFilamentChangeOut.btnHandle, BUTTON_CI_UNPRESSED, gCfgItems.btn_color);
BUTTON_SetTextColor(buttonFilamentChangeOut.btnHandle, BUTTON_CI_PRESSED, gCfgItems.btn_textcolor);
BUTTON_SetTextColor(buttonFilamentChangeOut.btnHandle, BUTTON_CI_UNPRESSED, gCfgItems.btn_textcolor);
BUTTON_SetBkColor(buttonRet.btnHandle, BUTTON_CI_PRESSED, gCfgItems.back_btn_color);
BUTTON_SetBkColor(buttonRet.btnHandle,BUTTON_CI_UNPRESSED, gCfgItems.back_btn_color);
BUTTON_SetTextColor(buttonRet.btnHandle, BUTTON_CI_PRESSED, gCfgItems.back_btn_textcolor);
BUTTON_SetTextColor(buttonRet.btnHandle,BUTTON_CI_UNPRESSED, gCfgItems.back_btn_textcolor);
BUTTON_SetBkColor(buttonSprayType.btnHandle, BUTTON_CI_PRESSED, gCfgItems.btn_state_color);
BUTTON_SetBkColor(buttonSprayType.btnHandle,BUTTON_CI_UNPRESSED, gCfgItems.btn_state_color);
BUTTON_SetTextColor(buttonSprayType.btnHandle, BUTTON_CI_PRESSED, gCfgItems.btn_state_textcolor);
BUTTON_SetTextColor(buttonSprayType.btnHandle,BUTTON_CI_UNPRESSED, gCfgItems.btn_state_textcolor);
textExtruTemp = TEXT_CreateEx(BTN_X_PIXEL+INTERVAL_V*2,(BTN_Y_PIXEL-90)/2,BTN_X_PIXEL*2+INTERVAL_V,60, hFilamentChangeWnd, WM_CF_SHOW, TEXT_CF_HCENTER|TEXT_CF_VCENTER,GUI_ID_TEXT2, " ");
//textExtruMsg = TEXT_CreateEx(BTN_X_PIXEL+INTERVAL_V*2,(BTN_Y_PIXEL-30)/2+30, BTN_X_PIXEL*2+INTERVAL_V,30, hFilamentChangeWnd, WM_CF_SHOW, TEXT_CF_HCENTER|TEXT_CF_VCENTER,GUI_ID_TEXT1, " ");
if(gCfgItems.multiple_language != 0)
{
BUTTON_SetText(buttonFilamentChangeIn.btnHandle,filament_menu.in);
BUTTON_SetText(buttonFilamentChangeOut.btnHandle,filament_menu.out);
BUTTON_SetText(buttonRet.btnHandle,common_menu.text_back);
}
//TEXT_SetTextAlign(textExtruMsg, GUI_TA_BOTTOM | GUI_TA_HCENTER);
//TEXT_SetTextAlign(textExtruTemp, GUI_TA_TOP| GUI_TA_HCENTER);
disp_filament_sprayer_temp();
gCfgItems.curSprayerChoose = active_extruder;
disp_filament_sprayer_type();
//TEXT_SetTextColor(textExtruMsg, gCfgItems.state_text_color);
//TEXT_SetBkColor(textExtruMsg, gCfgItems.state_background_color);
//sprintf((char*)buf,filament_menu.ready_replace);
//TEXT_SetText(textExtruMsg, (const char *)buf);
}
void disp_filament_sprayer_temp()
{
int8_t buf[30] = {0};
int8_t buf1[20] = {0};
TEXT_SetTextColor(textExtruTemp, gCfgItems.state_text_color);
TEXT_SetBkColor(textExtruTemp, gCfgItems.state_background_color);
//TEXT_SetTextAlign(textExtruTemp, GUI_TA_VERTICAL| GUI_TA_HCENTER);
sprintf((char*)buf,"E%d: ",gCfgItems.curSprayerChoose+1);
sprintf((char*)buf1, filament_menu.stat_temp, (int)thermalManager.current_temperature[gCfgItems.curSprayerChoose],(int)thermalManager.target_temperature[gCfgItems.curSprayerChoose]);
strcat((char*)buf,(char*)buf1);
TEXT_SetText(textExtruTemp, (const char *)buf);
}
void disp_filament_sprayer_type()
{
if(gCfgItems.curSprayerChoose == 0)
{
#if VERSION_WITH_PIC
BUTTON_SetBmpFileName(buttonSprayType.btnHandle, "bmp_extru1.bin",1);
BUTTON_SetBitmapEx(buttonSprayType.btnHandle, 0, &bmp_struct, BMP_PIC_X, BMP_PIC_Y);
#endif
}
else
{
#if VERSION_WITH_PIC
BUTTON_SetBmpFileName(buttonSprayType.btnHandle, "bmp_extru2.bin",1);
BUTTON_SetBitmapEx(buttonSprayType.btnHandle, 0, &bmp_struct, BMP_PIC_X, BMP_PIC_Y);
#endif
}
if(gCfgItems.multiple_language != 0)
{
if(gCfgItems.curSprayerChoose == 0)
{
BUTTON_SetText(buttonSprayType.btnHandle,filament_menu.ext1);
}
else if(gCfgItems.curSprayerChoose == 1)
{
BUTTON_SetText(buttonSprayType.btnHandle,filament_menu.ext2);
}
}
}
#if 0
void FilamentChange_handle()
{
char buf[15] = {0};
switch(filamentchange_Process)
{
case 1:
if(gcodeCmdTxFIFO.count <= 12)
{
//pushFIFO(&gcodeCmdTxFIFO, RELATIVE_COORD_COMMAN);
if(gCfgItems.sprayerNum == 2)
{
sprintf(buf,"T%d\n",gCfgItems.curSprayerChoose);
pushFIFO(&gcodeCmdTxFIFO, (unsigned char *)buf);
memset(buf,0,sizeof(buf));
sprintf(buf, "G1 E%d F%d\n", gCfgItems.filamentchange_step, gCfgItems.filamentchange_speed);
pushFIFO(&gcodeCmdTxFIFO, (unsigned char *)buf);
}
else
{
MOVE_E_COMMAN(buf, gCfgItems.filamentchange_step, gCfgItems.filamentchange_speed);
pushFIFO(&gcodeCmdTxFIFO, (unsigned char *)buf);
}
//pushFIFO(&gcodeCmdTxFIFO, ABSOLUTE_COORD_COMMAN);
}
break;
case 2:
if(gcodeCmdTxFIFO.count <= 12)
{
//pushFIFO(&gcodeCmdTxFIFO, RELATIVE_COORD_COMMAN);
if(gCfgItems.sprayerNum == 2)
{
sprintf(buf,"T%d\n",gCfgItems.curSprayerChoose);
pushFIFO(&gcodeCmdTxFIFO, (unsigned char *)buf);
memset(buf,0,sizeof(buf));
sprintf(buf, "G1 E%d F%d\n", 0-gCfgItems.filamentchange_step, gCfgItems.filamentchange_speed);
pushFIFO(&gcodeCmdTxFIFO, (unsigned char *)buf);
}
else
{
MOVE_E_COMMAN(buf, 0-gCfgItems.filamentchange_step, gCfgItems.filamentchange_speed);
pushFIFO(&gcodeCmdTxFIFO, (unsigned char *)buf);
}
//pushFIFO(&gcodeCmdTxFIFO, ABSOLUTE_COORD_COMMAN);
}
break;
case 3:
initFIFO(&gcodeCmdTxFIFO);
filamentchange_Process = 0;
pushFIFO(&gcodeCmdTxFIFO, (unsigned char *)ABSOLUTE_COORD_COMMAN);//确保后续以绝对坐标执行
//移动后马上保存数据
if(last_disp_state == PRINT_MORE_UI)
positionSaveFlag = 1;
break;
default:break;
}
}
#endif
void Clear_FilamentChange()
{
GUI_SetBkColor(gCfgItems.background_color);
if(WM_IsWindow(hFilamentChangeWnd))
{
WM_DeleteWindow(hFilamentChangeWnd);
GUI_Exec();
}
//GUI_Clear();
}
| [
"jlusk@securustechnologies.com"
] | jlusk@securustechnologies.com |
0e563311a143a0f596c6e5a94065f81bfe544cd7 | 440bc87298fef759de173cfa734f13cd71f03c12 | /Source/ProjectJ/Client/Monster/StageTwo/HammerBoss/BruteAnimInstance.h | 5e485d3fea9dc6a7d3bf3575e0dffb2b86d73b36 | [] | no_license | ProjectGladiator/ProjectGladiator | 9bb954b01d4e21e5111b518db36fdcf4b3a42617 | 0708250d3e994ffef95527e49b6b5632b9435421 | refs/heads/master | 2021-06-09T03:33:57.499603 | 2019-11-08T11:33:24 | 2019-11-08T11:33:24 | 144,824,947 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Client/Monster/MonsterAnimInstance.h"
#include "Client/State/MonsterState/MonsterState.h"
#include "BruteAnimInstance.generated.h"
/**
*
*/
UCLASS()
class PROJECTJ_API UBruteAnimInstance : public UMonsterAnimInstance
{
GENERATED_BODY()
public:
UBruteAnimInstance();
UFUNCTION()
virtual void NativeUpdateAnimation(float DeltaSecnds)override;
private:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = State, Meta = (AllowPrivateAccess = true))
EBruteState CurrentState;
UPROPERTY(VisibleAnywhere, BlueprintType, Category = State, Meta = (AllowPrivateAccess = true))
EBruteAttackState CurrentAttackState;
UFUNCTION()
void AnimNotify_NomalAttackHit(UAnimNotify* Notify);
UFUNCTION()
void AnimNotify_KickAttackHit(UAnimNotify* Notify);
UFUNCTION()
void AnimNotify_JumpAttackHit(UAnimNotify* Notify);
UFUNCTION()
void AnimNotify_Death(UAnimNotify* Notify);
};
| [
"dodrv@naver.com"
] | dodrv@naver.com |
f8d4d6e9e435d7de5e457b1822eedcad61d5c022 | 5781992b8eb5f8e8f6ce7ccf8069b60138b6f4d7 | /old_src/highj.cpp | 9e75153c204fb3ce0d45ab4dcf41ee72911ad9d5 | [] | no_license | liyonghelpme/dota-replay-manager | fd7c041cc48bac9fd726af4771a03fe8ec1a4ae6 | 21b965a8a63e077df275379d1f5055d77d98e580 | refs/heads/master | 2021-01-10T08:11:31.169556 | 2014-12-24T21:35:29 | 2014-12-24T21:35:29 | 36,912,875 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 86 | cpp | #include "stdafx.h"
#include "dotaload.h"
void parse_high_j (MPQFILE file)
{
}
| [
"d07.RiV@gmail.com"
] | d07.RiV@gmail.com |
71487ab8bb3ebff336d9ca09d92031f0f5429691 | 7e9b3ec7ee63fce3da32d45cb163bc505d89fda7 | /src/Account.h | 81a485ae5eec36afeb9e9b515e8183f71def1404 | [] | no_license | lilione/Merkle-Patricia-Tree | d3a925d64dd0c54b6e332aa61e83d30a02085261 | 929630b25da446b0b6da7e6c6032f847a864fe62 | refs/heads/master | 2021-08-22T09:53:03.280449 | 2017-11-29T23:04:17 | 2017-11-29T23:04:17 | 101,330,307 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | h | //
// Created by lilione on 2017/9/13.
//
#ifndef MERKLE_PARTRICIA_TREE_ACCOUNT_H
#define MERKLE_PARTRICIA_TREE_ACCOUNT_H
#include "Bytes.h"
#include "uint256_t.h"
#include "../libethash/ethash.h"
class Account {
public:
uint64_t nonce;
uint256_t balance;
ethash_h256_t rootHash;
ethash_h256_t codeHash;
Account(uint64_t nonce, uint256_t balance, ethash_h256_t rootHash, ethash_h256_t codeHash):
nonce(nonce), balance(balance), rootHash(rootHash), codeHash(codeHash) {}
};
#endif //MERKLE_PARTRICIA_TREE_ACCOUNT_H
| [
"lilioneviola@gmail.com"
] | lilioneviola@gmail.com |
0b0d0cf5c9ab8d37701d28f507762724e35bce21 | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Spoj/P4574_CYCLERUN.cpp | 9b52c6f01a9a8a4b4fbd3c3e77886e7e50837643 | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,097 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define abs(x) ((x) > 0 ? (x) : -(x))
typedef long long LL;
#define maxn 1005
list<int> path;
int n;
bool g[maxn][maxn];
vector<vector<int> > ans;
void record() {
if (path.size() <= 2) return;
vector<int> t;
bool flag = false;
for (list<int>::iterator it = path.begin(); it != path.end(); it++) {
if (*it == 1) flag = true;
if (flag) t.PB(*it);
}
for (list<int>::iterator it = path.begin(); it != path.end(); it++) {
t.PB(*it);
if (*it == 1) break;
}
ans.PB(t);
}
void output() {
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++)
printf("%d%c", ans[i][j], j == ans[i].size() - 1 ? '\n' : ' ');
}
}
bool hamilton(int start) {
path.clear();
ans.clear();
path.PB(start);
list<int>::iterator cur, pre;
for (int i = 1; i <= n; i++) {
if (i == start) continue;
cur = path.begin();
if (g[i][*cur]) {
path.push_front(i);
record();
continue;
}
cur = path.end(); cur--;
if (g[*cur][i]) {
path.PB(i);
record();
continue;
}
pre = cur = path.begin();
cur++;
for (; cur != path.end(); cur++, pre++) {
if (g[*pre][i] && g[i][*cur]) {
path.insert(cur, i);
break;
}
}
record();
pre = path.begin(); cur = path.end(); cur--;
if (!g[*cur][*pre]) return false;
}
pre = path.begin(); cur = path.end(); cur--;
if (g[*cur][*pre]) return true;
return false;
}
char input[maxn];
int main() {
while (~scanf("%d", &n)) {
for (int i = 1; i <= n; i++) {
scanf("%s", input + 1);
for (int j = 1; j <= n; j++) {
g[i][j] = input[j] == '1';
}
}
bool flag = false;
for (int i = 1; i <= n; i++) {
if (hamilton(i)) {
flag = true;
break;
}
}
if (!flag) puts("impossible");
else output();
}
return 0;
} | [
"zjsxzy@gmail.com"
] | zjsxzy@gmail.com |
8e773e8d5e074edea50de124c1dcca14e929bd97 | 6abb3cd4c91c5c99eebbdd3da7ba9bf06c2f7565 | /Effects/11_dynamic_square.h | bc0d5e1454ce87da8643e204cc8405e8cd345423 | [] | no_license | npo6ka/LedTable_emulator | cace2a161c94f698d956c248ca2869f6a26df001 | b66b3d99043410aeff04290371683d974f6af53f | refs/heads/master | 2021-12-12T22:26:39.202647 | 2021-12-01T12:46:32 | 2021-12-01T12:46:32 | 142,282,706 | 0 | 2 | null | 2019-12-30T08:18:01 | 2018-07-25T10:07:40 | C++ | UTF-8 | C++ | false | false | 1,085 | h | #pragma once
#include "effect.h"
class DynamicSquare : public Effect
{
uint8_t fade_step = 192;
uint8_t radius = WIDTH > HEIGHT ? (HEIGHT): (WIDTH);
//uint32_t color = 0x0000ff;
uint8_t hsv = 0;
uint8_t cur_ring = 0;
public:
DynamicSquare() {}
void on_init() {
set_fps(12);
}
void draw_rectangle(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, CRGB color) {
drawLine(x1, y1, x1, y2, color);
drawLine(x1, y1, x2, y1, color);
drawLine(x1, y2, x2, y2, color);
drawLine(x2, y1, x2, y2, color);
}
void on_update() {
fader(fade_step);
if (cur_ring <= radius / 2) {
draw_rectangle(cur_ring, cur_ring, HEIGHT - cur_ring - 1, WIDTH - cur_ring - 1, CHSV(hsv, 255, 255));
} else {
draw_rectangle(radius - cur_ring + 1, radius - cur_ring + 1, HEIGHT - (radius - cur_ring + 1) - 1, WIDTH - (radius - cur_ring + 1) - 1, CHSV(hsv, 255, 255));
}
cur_ring = (cur_ring + 1) % (radius);
hsv = (hsv + 1) % 256;
//delay(25);
}
};
| [
"ivanov.92@mail.ru"
] | ivanov.92@mail.ru |
2035cd9cae12667a1a4cf64efd8d973bcfacfaf2 | 2e241ccf2c7439e4638aa8ca8710c4191d09bd83 | /re/NFAConvertHelper.cpp | f26b3e5ff099dc9210e87fe14ac9374be22c5e52 | [] | no_license | pl-0/compiler | fd65d98dd0576ea54f3197937beef1717c9db0ea | 1856deda0a2c0ec71eb712225024dc8a95836348 | refs/heads/master | 2020-04-14T20:09:28.685739 | 2019-01-10T09:50:57 | 2019-01-10T09:50:57 | 164,083,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,290 | cpp | #include <stack>
#include <unordered_set>
#include "NFAConvertHelper.h"
#include "UtilMethods.h"
using std::stack;
using std::unordered_set;
DFAState getClosure(const NFAState* nfaState)
{
stack<const NFAState*> stateStack;
stateStack.push(nfaState);
NFAStatesSet nfaStatesSet;
nfaStatesSet.insert(nfaState);
bool accept = nfaState->isAccept();
while (!stateStack.empty()) {
auto currentState = stateStack.top();
stateStack.pop();
const auto& outEdges = currentState->getOutEdges();
for (NFAEdge* edge : outEdges) {
if (edge->isEmpty()) {
auto targetState = edge->getTargetState();
// u not in e-closure(T)
if (nfaStatesSet.find(targetState) == nfaStatesSet.end()) {
//dfaState.addNFAState(edge->getTargetState());
nfaStatesSet.insert(targetState);
stateStack.push(targetState);
accept = targetState->isAccept() || accept;
}
}
}
}
return DFAState(std::move(nfaStatesSet), accept);
}
DFAState getClosure(const NFAStatesSet & statesSet)
{
NFAStatesSet closure;
bool accept = false;
for (const NFAState* nfaState : statesSet) {
DFAState dfaState(getClosure(nfaState));
unionWith(closure, dfaState.getNFAStatesSet());
accept = dfaState.isAccept() || accept;
}
return DFAState(std::move(closure), accept);
}
NFAStatesSet move(const DFAState & dfaState, char ch)
{
NFAStatesSet res;
const auto& nfaStatesSet = dfaState.getNFAStatesSet();
for (const NFAState* nfaState : nfaStatesSet) {
const auto& outEdges = nfaState->getOutEdges();
for (NFAEdge* edge : outEdges) {
if (edge->getSymbol() == ch) {
res.insert(edge->getTargetState());
}
}
}
return res;
}
//
//DFAModel NFAToDFAConverter::convert(const NFAModel & nfaModel)
//{
// // for one character, two state
//
// //state 0 is an empty state. All invalid inputs go to state 0
// DFAState state0;
//
// //state 1 is closure(nfaState[0])
// DFAState state1(getClosure(nfaModel.getEntryEdge()->getTargetState()));
// state1.setIndex(1);
//}
| [
"2256912385@qq.com"
] | 2256912385@qq.com |
8092ee524fb0c5960f779b5fddb2ca644c7f0ad1 | 1d743e83b5860e2a0a42a608d1a7f854db64427b | /include/nngpp/tcp/listener.h | cdec63a230d8b923e807a6bf766825bebaaa3f22 | [
"MIT"
] | permissive | shadowwalker2718/nngpp | 4c281f820dc8c6292d16dc6cdf19f0b810babff5 | fb3f9f70bbb113bfc2c35ec4cf93bd8e429e57e2 | refs/heads/master | 2020-04-15T12:21:14.634799 | 2019-01-06T22:08:29 | 2019-01-06T22:08:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | h | #ifndef NNGPP_TCP_LISTENER_H
#define NNGPP_TCP_LISTENER_H
#include "listener_view.h"
namespace nng { namespace tcp {
struct listener : listener_view {
listener() = default;
explicit listener( nng_tcp_listener* d ) noexcept : listener_view(d) {}
listener( const listener& rhs ) = delete;
listener( listener&& rhs ) noexcept : listener_view(rhs.d) {
rhs.d = nullptr;
}
listener& operator=( const listener& rhs ) = delete;
listener& operator=( listener&& rhs ) noexcept {
if( this != &rhs ) {
if( d != nullptr ) nng_tcp_listener_free(d);
d = rhs.d;
rhs.d = nullptr;
}
return *this;
}
~listener() {
if( d != nullptr ) nng_tcp_listener_free(d);
}
nng_tcp_listener* release() noexcept {
auto out = d;
d = nullptr;
return out;
}
};
inline listener make_listener() {
nng_tcp_listener* d;
int r = nng_tcp_listener_alloc( &d );
if( r != 0 ) {
throw exception(r,"nng_tcp_listener_alloc");
}
return listener(d);
}
}}
#endif
| [
"chriswelshman@gmail.com"
] | chriswelshman@gmail.com |
e5489ac9126f2ccea8a098701ee27994aa1f5624 | cc40d6b758088e9ba56641e91c35e1ea85b64e07 | /third_party/spirv-tools/source/val/instruction.cpp | 7284eb6dda31e6cefbb700da41aa6dfabcd7af05 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | chinmaygarde/filament | 1091b664f1ba4cc9b63c31c73f63ec8b449acd22 | 030ba324e0db96dfd31c0c1e016ae44001d92b00 | refs/heads/master | 2020-03-26T00:25:48.310901 | 2018-08-13T22:26:23 | 2018-08-13T22:26:23 | 144,320,013 | 1 | 0 | Apache-2.0 | 2018-08-10T18:29:11 | 2018-08-10T18:29:11 | null | UTF-8 | C++ | false | false | 1,919 | cpp | // Copyright (c) 2015-2016 The Khronos Group 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 "val/instruction.h"
#include <utility>
namespace spvtools {
namespace val {
#define OPERATOR(OP) \
bool operator OP(const Instruction& lhs, const Instruction& rhs) { \
return lhs.id() OP rhs.id(); \
} \
bool operator OP(const Instruction& lhs, uint32_t rhs) { \
return lhs.id() OP rhs; \
}
OPERATOR(<)
OPERATOR(==)
#undef OPERATOR
Instruction::Instruction(const spv_parsed_instruction_t* inst,
Function* defining_function,
BasicBlock* defining_block)
: words_(inst->words, inst->words + inst->num_words),
operands_(inst->operands, inst->operands + inst->num_operands),
inst_({words_.data(), inst->num_words, inst->opcode, inst->ext_inst_type,
inst->type_id, inst->result_id, operands_.data(),
inst->num_operands}),
line_num_(0),
function_(defining_function),
block_(defining_block),
uses_() {}
void Instruction::RegisterUse(const Instruction* inst, uint32_t index) {
uses_.push_back(std::make_pair(inst, index));
}
} // namespace val
} // namespace spvtools
| [
"romainguy@google.com"
] | romainguy@google.com |
5b6e5c6c411ba470c15fc845deeff33e51c0c59d | 1c12f602d8a7c1fdff34187d6d4a23e51e2ad2a4 | /sfftobmp3/tags/REL_3_1_4/win32/boost/boost/type_traits/detail/size_t_trait_undef.hpp | 4f5d2bfb24511fb920a5c6102f409e2995a0f3e0 | [
"BSL-1.0"
] | permissive | Sonderstorch/sfftools | 574649a6b6ba9c404e106f1ca94ae30c8dcafb7e | 53c8ba4fa2efd47e67b8ed986782b8694ee98e15 | refs/heads/master | 2020-03-27T08:06:53.094374 | 2016-06-16T18:11:24 | 2016-06-16T18:11:24 | 61,313,973 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | hpp |
// NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION
// Copyright Aleksey Gurtovoy 2002-2004
//
// 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)
// $Source: /cvsroot/sfftools/sfftobmp3/win32/boost/boost/type_traits/detail/size_t_trait_undef.hpp,v $
// $Date: 2009/08/23 12:39:24 $
// $Revision: 1.1 $
#undef BOOST_TT_AUX_SIZE_T_TRAIT_DEF1
#undef BOOST_TT_AUX_SIZE_T_TRAIT_SPEC1
#undef BOOST_TT_AUX_SIZE_T_TRAIT_PARTIAL_SPEC1_1
| [
"Sonderstorch@users.noreply.github.com"
] | Sonderstorch@users.noreply.github.com |
70707af5c769f334547c39aef244848b40b07ed7 | 0f84b56717a0dc95466f0042d29e80e58d2bdb69 | /SDD_ex/StockingStore/StockingStore/StockingStore.cpp | 431392a4319979daace2a2f2ceb9b95bc149eda8 | [] | no_license | cnicolae94/student_work | ea3e26d8b81081d59428c7bb0f1cc2b38878b916 | 2ffcd404bf5b1a1e4641ee8ff0644d97a7cb0998 | refs/heads/main | 2023-05-12T09:01:36.018985 | 2021-05-31T13:35:10 | 2021-05-31T13:35:10 | 355,815,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,346 | cpp | #include <iostream>
using namespace std;
struct produs
{
int cod;
char* nume;
float pret;
float cantitate;
};
struct nodls
{
produs inf;
nodls* next, * prev; //punem pointer la nume aparent
};
nodls* inserare(nodls* cap, nodls** coada, produs p)
{
nodls* nou = new nodls;
nou->inf.cod = p.cod;
nou->inf.nume = new char[strlen(p.nume) + 1];
strcpy_s(nou->inf.nume, strlen(p.nume) + 1, p.nume);
nou->inf.pret = p.pret;
nou->inf.cantitate = p.cantitate;
nou->next = NULL;
nou->prev = NULL;
if (cap == NULL)
{
cap = nou;
*coada = nou;
}
else
{
nodls* temp = cap;
while (temp->next != NULL)
temp = temp->next;
temp->next = nou;
nou->prev = temp;
*coada = nou;
}
return cap; // returnam doar capul.
}
void traversare(nodls* cap, nodls** coada)
{
nodls* temp = cap;
while (temp != NULL)
{
cout << "Produs: " << temp->inf.nume << " cod: " << temp->inf.cod << " pret: " << temp->inf.pret << " cantitate: " << temp->inf.cantitate << endl;
temp = temp->next;
}
}
void traversareInversa(nodls* cap, nodls** coada)
{
nodls* temp = *coada;
while (temp != NULL)
{
cout << "Produs: " << temp->inf.nume << " cod: " << temp->inf.cod << " pret: " << temp->inf.pret << " cantitate: " << temp->inf.cantitate << endl;
temp = temp->prev;
}
}
void dezalocare(nodls* cap, nodls** coada) //primeste capul si coada ca parametru, dar algoritmul ramane la fel
{
nodls* temp = cap;
while (temp != NULL)
{
nodls* temp2 = temp->next; //temp next va fi stocat in temp 2 si capul in temp simplu.
delete[] temp->inf.nume;
delete[] temp;
temp = temp2;
}
}
void main()
{
/*produs p1;
p1.nume = (char*)"Cosmetice";
p1.cod = 55;
p1.cantitate = 10;
p1.pret = 7.55;
cap = inserare(cap, &coada, p1);
traversare(cap, &coada);*/
produs p;
nodls* cap = NULL;
nodls* coada = NULL;
char buffer[20];
int n;
cout << "Introdu numarul de produse:" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "Cod: " << endl;
cin >> p.cod;
cout << "Nume: " << endl;
cin >> buffer;
p.nume = new char[strlen(buffer) + 1];
strcpy_s(p.nume,strlen(buffer)+1, buffer);
cout << "Cantitate: " << endl;
cin >> p.cantitate;
cout << "Pret: " << endl;
cin >> p.pret;
cap = inserare(cap, &coada, p);
}
traversare(cap, &coada);
traversareInversa(cap, &coada);
dezalocare(cap, &coada);
} | [
"62987170+cnicolae94@users.noreply.github.com"
] | 62987170+cnicolae94@users.noreply.github.com |
2a2829649c682281e7331059d9bd2ac95bcf813a | 07ef1b95490b14aed1925c526e9ca8075f51d397 | /include/TinySocket/LinkError.h | 04e6473703944a84442130d4553bec98403617e7 | [
"MIT"
] | permissive | baisai/LightInkLLM | 16123a338f3d890e16410bc16bdd49da49c32c77 | 7f984bf5f3afa3ccfc2c04e8d41948cf3a9bb4b2 | refs/heads/master | 2021-06-04T03:54:37.674684 | 2020-01-04T08:04:45 | 2020-01-04T08:04:45 | 110,995,336 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,540 | h |
/* Copyright ChenDong(Wilbur), email <baisaichen@live.com>. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef LIGHTINK_TINYSOCKET_LINKERROR_H_
#define LIGHTINK_TINYSOCKET_LINKERROR_H_
namespace LightInk
{
enum LinkError
{
LE_Success = 0, //Success
LE_Error = -1, //Not Get Error Info
LE_InvalidSocket = -2, //Invalid Socket Handle
LE_InvalidAddress = -3, //Invalid Address
LE_InvalidPort = -4, //Invalid Port
LE_ConnectionRefused = -5, //Connect Refused
LE_Timedout = -6, //Timed Out
LE_Wouldblock = -7, //Operation Would Block If Socket Was Blocking
LE_Notconnected = -8, //The Link Was Disconnected
LE_Einprogress = -9, //The Link Not Completed Immediately
LE_Interrupted = -10, //Call Interrupted By Signal
LE_ConnectionAborted = -11, //The Link Aborted
LE_ProtocolError = -12, //Invalid Link Protocol
LE_FirewallError = -13, //Firewall Rules Forbid Link
LE_InvalidSocketBuffer = -14, //The Buffer Invalid
LE_ConnectionReset = -15, //Connection Was Closed By The Remote Host
LE_AddressInUse = -16, //Address Already Use
LE_InvalidPointer = -17, //Pointer Type Invalid
LE_BufferLess = -18, //Buffer Less
LE_Unknown = -19, //Unknown Error
};
LIGHTINK_DECL LinkError get_last_error();
LIGHTINK_DECL const char * get_error_string(LinkError err);
}
#define LINK_ERROR_MAP(XX) \
XX(LightInk::LE_Success, "Success") \
XX(LightInk::LE_Error, "Not Get Error Info") \
XX(LightInk::LE_InvalidSocket, "Invalid Socket Handle") \
XX(LightInk::LE_InvalidAddress, "Invalid Address") \
XX(LightInk::LE_InvalidPort, "Invalid Port") \
XX(LightInk::LE_ConnectionRefused, "Connect Refused") \
XX(LightInk::LE_Timedout, "Timed Out") \
XX(LightInk::LE_Wouldblock, "Operation Would Block If Socket Was Blocking") \
XX(LightInk::LE_Notconnected, "The Link Was Disconnected") \
XX(LightInk::LE_Einprogress, "The Link Not Completed Immediately") \
XX(LightInk::LE_Interrupted, "Call Interrupted By Signal") \
XX(LightInk::LE_ConnectionAborted, "The Link Aborted") \
XX(LightInk::LE_ProtocolError, "Invalid Link Protocol") \
XX(LightInk::LE_FirewallError, "Firewall Rules Forbid Link") \
XX(LightInk::LE_InvalidSocketBuffer, "The Buffer Invalid") \
XX(LightInk::LE_ConnectionReset, "Connection Was Closed By The Remote Host") \
XX(LightInk::LE_AddressInUse, "Address Already Use") \
XX(LightInk::LE_InvalidPointer, "Pointer Type Invalid") \
XX(LightInk::LE_BufferLess, "Buffer Less") \
XX(LightInk::LE_Unknown, "Unknown Error")
#endif | [
"baisaichen@live.com"
] | baisaichen@live.com |
ccf7b350f606620a45f9a2ca850fa2f3a061be22 | cae581d56a31a313c0c60a8171f0d8ebe2f4665d | /src/Utilities/AlignedWriter.h | 0825af6c55459610780e9296aa3b206c3a4e7045 | [] | no_license | Joshhua5/Protheus | 3c5ac1a3a7a0f6ea81649bc5f328fc0446972b24 | b46384371dee863fc288e4ffb2dd1c479c3a20d5 | refs/heads/master | 2021-05-04T10:16:28.174610 | 2018-11-09T21:52:55 | 2018-11-09T21:52:55 | 52,888,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | h | #pragma once
#include "BufferIO.h"
namespace Pro {
namespace Util {
/*! AlignedWriter adds writing functionality to a preexisting AlignedWriter
AlignedWriter works in the sizeOf from the AlignedWriter instead of bytes.
*/
class AlignedWriter :
BufferIO {
public:
AlignedWriter(AlignedBuffer* buffer) {
aligned_buffer_ = buffer;
head_ = 0;
}
~AlignedWriter() {
head_ = 0;
aligned_buffer_ = nullptr;
}
/*! Writes a single value into the Pro::Util::AlignedBuffer and iterates the head*/
template<typename T>
inline void Write(const T& value){
*aligned_buffer_->At(head_++) = value;
}
/*! Writes a single value into the Pro::Util::AlignedBuffer and iterates the head*/
template<typename T>
inline void Write(const T&& value) {
*aligned_buffer_->At(head_++) = std::move(value);
}
/*! Writes an array into the Pro::Util::AlignedBuffer.
The Array must be at least of size count.
*/
template<typename T>
inline void WriteElements(T* elements, unsigned count) {
for (unsigned x = 0; x < count; ++x)
*aligned_buffer_->At(head_++) = elements[x];
}
};
}
} | [
"Joshhua123@gmail.com"
] | Joshhua123@gmail.com |
1c8349d22343474eb98be064996bf750e5f4273f | bea7ed83dd0b8e3e5cf291f252e1f99b3ad4c0ec | /listTut.cpp | 68e4d76b3e8afdf12cf89755a0daa5f990e74f2a | [] | no_license | manas2297/tutorial | ee1fa151f2ee30e680f48e6dd88d8262606170be | 496b2415fe428fb3887b1db5cd017314ef9001ee | refs/heads/master | 2020-04-14T13:21:33.756070 | 2019-01-23T17:55:38 | 2019-01-23T17:55:38 | 163,866,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | cpp | //this file shows some basic functions and implementations of list in stl c++
#include <iostream>
#include <list>
#include <iterator>
using namespace std;
//func for print list elements
void showList(list <int> g){
list <int> :: iterator it;
for(it= g.begin();it!=g.end();it++)
cout<<"\t"<< *it;
cout<<endl;
}
int main(int argc, char const *argv[]) {
/* code */
list <int> list1,list2;
for(int i=0;i<10;i++){
list1.push_back(i*2);
list2.push_back(i*3);
}
cout<< "\n list 1 is : ";
showList(list1);
cout<<"\n List 2 is : ";
showList(list2);
cout<<"\n list1.front(): ";
cout<<list1.front();
cout<<"\n list1.back(): ";
cout<<list1.back();
return 0;
}
| [
"yadavmanas22@gmail.com"
] | yadavmanas22@gmail.com |
376e3f995b38645fbf7b96a1fc65a10ca94f5d6e | 083100943aa21e05d2eb0ad745349331dd35239a | /aws-cpp-sdk-email/include/aws/email/model/TlsPolicy.h | fe16685eb11cbb6ed1fb6504dab77a43a6e460ca | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bmildner/aws-sdk-cpp | d853faf39ab001b2878de57aa7ba132579d1dcd2 | 983be395fdff4ec944b3bcfcd6ead6b4510b2991 | refs/heads/master | 2021-01-15T16:52:31.496867 | 2015-09-10T06:57:18 | 2015-09-10T06:57:18 | 41,954,994 | 1 | 0 | null | 2015-09-05T08:57:22 | 2015-09-05T08:57:22 | null | UTF-8 | C++ | false | false | 1,041 | h | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/email/SES_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace SES
{
namespace Model
{
enum class TlsPolicy
{
NOT_SET,
Require,
Optional
};
namespace TlsPolicyMapper
{
AWS_SES_API TlsPolicy GetTlsPolicyForName(const Aws::String& name);
AWS_SES_API Aws::String GetNameForTlsPolicy(TlsPolicy value);
} // namespace TlsPolicyMapper
} // namespace Model
} // namespace SES
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
ccc582ccc39c28191a8a62ed991c85bdda50a19f | 2af943fbfff74744b29e4a899a6e62e19dc63256 | /UNCShapeAnalysisLONIpipeline/genParam/par++/vertex.hh | 9846160606664e15ad43f34aaf6cc9dd96481976 | [] | no_license | lheckemann/namic-sandbox | c308ec3ebb80021020f98cf06ee4c3e62f125ad9 | 0c7307061f58c9d915ae678b7a453876466d8bf8 | refs/heads/master | 2021-08-24T12:40:01.331229 | 2014-02-07T21:59:29 | 2014-02-07T21:59:29 | 113,701,721 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 195 | hh | #include <stdio.h>
// should be replaced by <iostream.h>
struct Vertex {int x, y, z, count, neighb[14];};
struct Net {int nvert, nface, *face; Vertex *vert;};
int read_net(FILE*, Net*);
| [
"andy@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8"
] | andy@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8 |
cea47dbf38c9821b5e7196d11e6a24e48dfe07ea | fecd3b12f6a5e3107ffc4e1e941824ca79996201 | /lib/imgui_remote_webby.h | dbc4ea882da159ca3eb5ae4c0c5dfccd0a7b4108 | [] | no_license | balachandranc/Cinder-RemoteImGui | 28179cf26b33f16040c15fc69e49796b8b403b93 | e931ba0817627ebbe53429a689b4e980ddef6b47 | refs/heads/master | 2021-07-15T23:42:57.761650 | 2017-10-17T17:53:32 | 2017-10-17T17:53:32 | 107,258,421 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,705 | h | //-----------------------------------------------------------------------------
// Remote ImGui https://github.com/JordiRos/remoteimgui
// Uses
// ImGui https://github.com/ocornut/imgui 1.3
// Webby https://github.com/deplinenoise/webby
// LZ4 https://code.google.com/p/lz4/
//-----------------------------------------------------------------------------
#include "webby/webby.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#ifdef _WIN32
#include <winsock2.h>
#endif
#ifdef __APPLE__
#include <unistd.h>
#endif
struct IWebSocketServer;
IWebSocketServer *s_WebSocketServer;
static void onLog (const char* text);
static int onDispatch (struct WebbyConnection *connection);
static int onConnect (struct WebbyConnection *connection);
static void onConnected (struct WebbyConnection *connection);
static void onDisconnected(struct WebbyConnection *connection);
static int onFrame (struct WebbyConnection *connection, const struct WebbyWsFrame *frame);
struct IWebSocketServer
{
enum OpCode // based on websocket connection opcodes
{
Continuation = 0,
Text = 1,
Binary = 2,
Disconnect = 8,
Ping = 9,
Pong = 10,
};
void *Memory;
int MemorySize;
struct WebbyServer *Server;
struct WebbyServerConfig ServerConfig;
struct WebbyConnection *Client;
int Init(const char *local_address, int local_port)
{
s_WebSocketServer = this;
#if defined(_WIN32)
{
WORD wsa_version = MAKEWORD(2,2);
WSADATA wsa_data;
if (0 != WSAStartup(wsa_version, &wsa_data))
return -1;
}
#endif
memset(&ServerConfig, 0, sizeof ServerConfig);
ServerConfig.bind_address = local_address;
ServerConfig.listening_port = local_port;
ServerConfig.flags = WEBBY_SERVER_WEBSOCKETS;
ServerConfig.connection_max = 1;
ServerConfig.request_buffer_size = 2048;
ServerConfig.io_buffer_size = 8192;
ServerConfig.dispatch = &onDispatch;
ServerConfig.log = &onLog;
ServerConfig.ws_connect = &onConnect;
ServerConfig.ws_connected = &onConnected;
ServerConfig.ws_closed = &onDisconnected;
ServerConfig.ws_frame = &onFrame;
MemorySize = WebbyServerMemoryNeeded(&ServerConfig);
Memory = malloc(MemorySize);
Server = WebbyServerInit(&ServerConfig, Memory, MemorySize);
Client = NULL;
if (!Server)
return -2;
return 0;
}
void Update()
{
if (Server)
WebbyServerUpdate(Server);
}
void Shutdown()
{
if (Server)
{
WebbyServerShutdown(Server);
free(Memory);
}
#if defined(_WIN32)
WSACleanup();
#endif
}
void WsOnConnected(struct WebbyConnection *connection)
{
Client = connection;
}
void WsOnDisconnected(struct WebbyConnection *connection)
{
Client = NULL;
OnMessage(Disconnect, NULL, 0);
}
int WsOnFrame(struct WebbyConnection *connection, const struct WebbyWsFrame *frame)
{
// printf("WebSocket frame incoming\n");
// printf(" Frame OpCode: %d\n", frame->opcode);
// printf(" Final frame?: %s\n", (frame->flags & WEBBY_WSF_FIN) ? "yes" : "no");
// printf(" Masked? : %s\n", (frame->flags & WEBBY_WSF_MASKED) ? "yes" : "no");
// printf(" Data Length : %d\n", (int) frame->payload_length);
std::vector<unsigned char> buffer(frame->payload_length+1);
WebbyRead(connection, &buffer[0], frame->payload_length);
buffer[frame->payload_length] = 0;
// if(!strstr((char*)&buffer[0],"ImMouseMove"))
// printf(" Data : %s\n", &buffer[0]);
OnMessage((OpCode)frame->opcode, &buffer[0], frame->payload_length);
return 0;
}
virtual void OnMessage(OpCode opcode, const void *data, int size) { }
virtual void OnError() { }
virtual void SendText(const void *data, int size)
{
if (Client)
{
WebbySendFrame(Client, WEBBY_WS_OP_TEXT_FRAME, data, size);
}
}
virtual void SendBinary(const void *data, int size)
{
if (Client)
{
WebbySendFrame(Client, WEBBY_WS_OP_BINARY_FRAME, data, size);
}
}
};
static void onLog(const char* text)
{
//printf("[WsOnLog] %s\n", text);
}
static int onDispatch(struct WebbyConnection *connection)
{
//printf("[WsOnDispatch] %s\n", connection->request.uri);
return 1;
}
static int onConnect(struct WebbyConnection *connection)
{
//printf("[WsOnConnect] %s\n", connection->request.uri);
return 0;
}
static void onConnected(struct WebbyConnection *connection)
{
//printf("[WsOnConnected]\n");
s_WebSocketServer->WsOnConnected(connection);
}
static void onDisconnected(struct WebbyConnection *connection)
{
//printf("[WsOnDisconnected]\n");
s_WebSocketServer->WsOnDisconnected(connection);
}
static int onFrame(struct WebbyConnection *connection, const struct WebbyWsFrame *frame)
{
//printf("[WsOnFrame]\n");
return s_WebSocketServer->WsOnFrame(connection, frame);
}
| [
"balachandran.c@gmail.com"
] | balachandran.c@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.