hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4ec9e4157e231051d2f80680e9a9352868fc454e | 260 | cpp | C++ | Cpp_primer_5th/code_part10/prog10_9.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | Cpp_primer_5th/code_part10/prog10_9.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | Cpp_primer_5th/code_part10/prog10_9.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void elimDups(vector<string> &words){
sort(words.begin(), words.end() );
auto end_unique = unique(words.begin(), words.end() );
words.erase(end_unique, words.end());
}
| 17.333333 | 55 | 0.684615 | [
"vector"
] |
4ecfd6c7f7074a3a39aa1f8dac4b85376da9cc84 | 5,012 | cc | C++ | src/lib/config/hooked_command_mgr.cc | telekom/dt-kea-netconf | f347df353d58827d6deb09f281d3680ab089e7af | [
"Apache-2.0"
] | 2 | 2021-06-29T09:56:34.000Z | 2021-06-29T09:56:39.000Z | src/lib/config/hooked_command_mgr.cc | telekom/dt-kea-netconf | f347df353d58827d6deb09f281d3680ab089e7af | [
"Apache-2.0"
] | null | null | null | src/lib/config/hooked_command_mgr.cc | telekom/dt-kea-netconf | f347df353d58827d6deb09f281d3680ab089e7af | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2017-2018 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <cc/command_interpreter.h>
#include <config/hooked_command_mgr.h>
#include <config/config_log.h>
#include <hooks/callout_handle.h>
#include <hooks/hooks_manager.h>
#include <hooks/server_hooks.h>
#include <vector>
using namespace isc::data;
using namespace isc::hooks;
namespace isc {
namespace config {
HookedCommandMgr::HookedCommandMgr()
: BaseCommandMgr() {
}
bool
HookedCommandMgr::delegateCommandToHookLibrary(const std::string& cmd_name,
const ElementPtr& params,
const ElementPtr& original_cmd,
ElementPtr& answer) {
ElementPtr hook_response;
if (HooksManager::commandHandlersPresent(cmd_name)) {
CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
// Set status to normal.
callout_handle->setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
// Delete previously set arguments.
callout_handle->deleteAllArguments();
ElementPtr command = original_cmd ? original_cmd :
createCommand(cmd_name, params);
// And pass it to the hook library.
callout_handle->setArgument("command", command);
callout_handle->setArgument("response", hook_response);
HooksManager::callCommandHandlers(cmd_name, *callout_handle);
// The callouts should set the response.
callout_handle->getArgument("response", hook_response);
answer = hook_response;
return (true);
}
return (false);
}
ElementPtr
HookedCommandMgr::handleCommand(const std::string& cmd_name,
const ElementPtr& params,
const ElementPtr& original_cmd) {
// The 'list-commands' is a special case. Hook libraries do not implement
// this command. We determine what commands are supported by the hook
// libraries by checking what hook points are present that have callouts
// registered.
if ((cmd_name != "list-commands")) {
ElementPtr hook_response;
// Check if there are any hooks libraries to process this command.
if (delegateCommandToHookLibrary(cmd_name, params, original_cmd,
hook_response)) {
// Hooks libraries processed this command so simply return a
// result.
return (hook_response);
}
}
// If we're here it means that the callouts weren't called. We need
// to handle the command using local Command Mananger.
ElementPtr response = BaseCommandMgr::handleCommand(cmd_name,
params,
original_cmd);
// If we're processing 'list-commands' command we may need to include
// commands supported by hooks libraries in the response.
if (cmd_name == "list-commands") {
// Hooks names can be used to decode what commands are supported.
const std::vector<std::string>& hooks =
ServerHooks::getServerHooksPtr()->getHookNames();
// Only update the response if there are any hooks present.
if (!hooks.empty()) {
ElementPtr hooks_commands = Element::createList();
for (auto h = hooks.cbegin(); h != hooks.end(); ++h) {
// Try to convert hook name to command name. If non-empty
// string is returned it means that the hook point may have
// command handlers associated with it. Otherwise, it means that
// existing hook points are not for command handlers but for
// regular callouts.
std::string command_name = ServerHooks::hookToCommandName(*h);
if (!command_name.empty()) {
// Final check: are command handlers registered for this
// hook point? If there are no command handlers associated,
// it means that the hook library was already unloaded.
if (HooksManager::commandHandlersPresent(command_name)) {
hooks_commands->add(Element::create(command_name));
}
}
}
// If there is at least one hook point with command handlers
// registered
// for it, combine the lists of commands.
if (!hooks_commands->empty()) {
response = combineCommandsLists(response, createAnswer(0, hooks_commands));
}
}
}
return (response);
}
} // end of namespace isc::config
} // end of namespace isc
| 37.684211 | 91 | 0.603152 | [
"vector"
] |
4ed35dee1246ae1f9542365169019f3c1192a60f | 1,274 | hpp | C++ | iow/io/acceptor/options_json.hpp | mambaru/iow | 986a7baa6a18eae73c5bc00e40a03c6d9d5e0d7c | [
"MIT"
] | 1 | 2018-07-30T20:46:33.000Z | 2018-07-30T20:46:33.000Z | iow/io/acceptor/options_json.hpp | mambaru/iow | 986a7baa6a18eae73c5bc00e40a03c6d9d5e0d7c | [
"MIT"
] | 11 | 2019-12-06T00:23:51.000Z | 2021-04-20T19:57:30.000Z | iow/io/acceptor/options_json.hpp | mambaru/iow | 986a7baa6a18eae73c5bc00e40a03c6d9d5e0d7c | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <iow/io/acceptor/options.hpp>
#include <wjson/json.hpp>
#include <wjson/name.hpp>
namespace iow{ namespace io{ namespace acceptor{
template<typename AcceptorOptions, typename ConnectionsOptionsJson>
struct options_json
{
typedef AcceptorOptions options_type;
typedef ConnectionsOptionsJson connection_options_json;
typedef typename connection_options_json::target connection_options_type;
JSON_NAME(max_connections)
JSON_NAME(connection)
JSON_NAME(addr)
JSON_NAME(port)
JSON_NAME(backlog)
typedef ::wjson::object<
options_type,
::wjson::member_list<
::wjson::member< n_addr, options_type, std::string, &options_type::addr>,
::wjson::member< n_port, options_type, std::string, &options_type::port>,
::wjson::member< n_backlog, options_type, int, &options_type::backlog>,
::wjson::member< n_max_connections, options_type, int, &options_type::max_connections >,
::wjson::member< n_connection, options_type, connection_options_type, &options_type::connection, connection_options_json>
>,
::wjson::strict_mode
> type;
typedef typename type::target target;
typedef typename type::serializer serializer;
typedef typename type::member_list member_list;
};
}}}
| 31.85 | 127 | 0.753532 | [
"object"
] |
4deee2450393bf7522a9c9fad43ccb80e7420d57 | 2,227 | cpp | C++ | MonteCarlo/BuffonNedlee/secuential/buffonNedlee.cpp | Jofemago/HPC | 6e19bb64ad4bc35a8ee00ec72a04fc3745027bec | [
"MIT"
] | null | null | null | MonteCarlo/BuffonNedlee/secuential/buffonNedlee.cpp | Jofemago/HPC | 6e19bb64ad4bc35a8ee00ec72a04fc3745027bec | [
"MIT"
] | null | null | null | MonteCarlo/BuffonNedlee/secuential/buffonNedlee.cpp | Jofemago/HPC | 6e19bb64ad4bc35a8ee00ec72a04fc3745027bec | [
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
using puntos = vector<double>;
using apuntador = vector<bool>;
double pi = M_PI;
double randiasDivGrades = pi/180.0;
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
//std::uniform_real_distribution<> dis(-1.0, 1.0);
void launchNedlee(int n, int t, puntos &xs, puntos &angulos, puntos &radians){
std::uniform_real_distribution<> disX(0, t/2);
std::uniform_real_distribution<> disAng(0, 90);
for(int i = 0; i < n; ++i){
xs[i] = disX(gen);
angulos[i] = disAng(gen);
radians[i] = angulos[i] * randiasDivGrades;
//cout << "distancia en X: "<< xs[i]<< endl;
//cout << "valor del angulo: " << angulos[i]<< endl;
//cout << endl;
}
}
void simulation(int n, int t, int d, puntos &xs, puntos &angulosradians){
double enlinea = 0.0;
for (size_t i = 0; i < n; i++)
{
if(xs[i] <= (d/2.0) * sin(angulosradians[i]))
enlinea++;
}
double picalculate = 2 * ((double(n) * double(d))/(double(t) * enlinea));
//cout << "value of pi: " << picalculate << endl;
}
int main(int argc, char *argv[]){
int n = 0, t = 0, d = 0;
try
{
n = stoi(argv[1]);//argv 0 , cantidad de agujas
t = stoi(argv[2]);//argv 1, separacion entre lineas
d = stoi(argv[3]);//argv 2, tamaño de las agujas
}
catch(const exception& e)
{
std::cerr << "los valores ingresados estan mal" << '\n';
}
assert(d < t);
puntos xs = puntos(n, 0.0 );
puntos angulos = puntos(n, 0.0 );
puntos angulosRadians = puntos(n,0.0);
launchNedlee(n,t, xs, angulos, angulosRadians);
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
simulation(n,t,d,xs,angulosRadians);
end = std::chrono::system_clock::now();
double time = std::chrono::duration_cast<std::chrono::nanoseconds>
(end-start).count();
cout << time<<",";
//cout << "los valores son: " << n << t << d << endl;
return 0;
} | 25.306818 | 84 | 0.569376 | [
"vector"
] |
4dfb1258b5fcea2d7680100db05ec8102bbc1512 | 312 | cpp | C++ | demo/main.cpp | SovesT1337/lab-04-boost-filesystem | 245e3e9c0bf8f23efbc3cfd8c1fa7cf3f434c709 | [
"MIT"
] | null | null | null | demo/main.cpp | SovesT1337/lab-04-boost-filesystem | 245e3e9c0bf8f23efbc3cfd8c1fa7cf3f434c709 | [
"MIT"
] | null | null | null | demo/main.cpp | SovesT1337/lab-04-boost-filesystem | 245e3e9c0bf8f23efbc3cfd8c1fa7cf3f434c709 | [
"MIT"
] | null | null | null | #include <magic.hpp>
int main() {
// int main(int argc, char* argv[]) {
path p = "/home/sovest/CLionProjects/lab-04-boost-filesystem/misc";
// if (argc >= 2)
// p = argv[1];
// else
// p = boost::filesystem::current_path();
vector<file> list;
walker(p, list);
print(list);
magic(list);
} | 22.285714 | 69 | 0.589744 | [
"vector"
] |
4dfd2e0f6663ce375a9be098dcedba57a91770f3 | 4,373 | hpp | C++ | include/bio_ik/ik_gradient.hpp | SammyRamone/bio_ik | f903cd3190f4acf15342aef70cddcef6cbbf8819 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T09:26:46.000Z | 2022-03-24T09:26:46.000Z | include/bio_ik/ik_gradient.hpp | SammyRamone/bio_ik | f903cd3190f4acf15342aef70cddcef6cbbf8819 | [
"BSD-3-Clause"
] | 9 | 2022-01-03T18:59:17.000Z | 2022-02-05T20:06:22.000Z | include/bio_ik/ik_gradient.hpp | SammyRamone/bio_ik | f903cd3190f4acf15342aef70cddcef6cbbf8819 | [
"BSD-3-Clause"
] | 2 | 2022-01-11T23:57:32.000Z | 2022-02-26T10:27:02.000Z | // Copyright (c) 2016-2017, Philipp Sebastian Ruppel
//
// 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 Universität Hamburg 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 HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <Eigen/Core> // For NumTraits
#include <bio_ik/ik_base.hpp> // for IKSolver
#include <bio_ik/problem.hpp> // for Problem, Problem::GoalInfo
#include <bio_ik/utils.hpp> // for FNPROFILER
#include <cmath> // for isfinite
#include <cstddef> // for size_t
#include <ext/alloc_traits.h> // for __alloc_traits<>::value_type
#include <kdl/frames.hpp> // for Twist, Vector
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <vector> // for vector, allocator
#include "bio_ik/frame.hpp" // for Frame, frameTwist
#include "bio_ik/robot_info.hpp" // for RobotInfo
namespace bio_ik {
// simple gradient descent
template <int IF_STRUCK, size_t N_THREADS>
struct IKGradientDescent : IKSolver {
std::vector<double> solution_, best_solution_, gradient_, temp_;
bool reset_;
IKGradientDescent(const IKParams& p) : IKSolver(p) {}
void initialize(const Problem& problem);
const std::vector<double>& getSolution() const { return best_solution_; }
void step();
size_t concurrency() const { return N_THREADS; }
};
// pseudoinverse jacobian solver
// (mainly for testing RobotFK_Jacobian::computeJacobian)
template <class BASE>
struct IKJacobianBase : BASE {
// IKSolver functions
using BASE::computeFitness;
// IKSolver variables
using BASE::model_;
using BASE::modelInfo_;
using BASE::params_;
using BASE::problem_;
std::vector<Frame> tipObjectives_;
Eigen::VectorXd tip_diffs_;
Eigen::VectorXd joint_diffs_;
Eigen::MatrixXd jacobian_;
std::vector<Frame> tip_frames_temp_;
IKJacobianBase(const IKParams& p) : BASE(p) {}
void initialize(const Problem& problem) {
BASE::initialize(problem);
tipObjectives_.resize(problem.tip_link_indices.size());
for (auto& goal : problem.goals)
tipObjectives_[goal.tip_index] = goal.frame;
}
void optimizeJacobian(std::vector<double>& solution);
};
// pseudoinverse jacobian only
template <size_t N_THREADS>
struct IKJacobian : IKJacobianBase<IKSolver> {
using IKSolver::initialize;
std::vector<double> solution_;
IKJacobian(const IKParams& params) : IKJacobianBase<IKSolver>(params) {}
void initialize(const Problem& problem);
const std::vector<double>& getSolution() const { return solution_; }
void step() { optimizeJacobian(solution_); }
size_t concurrency() const { return N_THREADS; }
};
std::optional<std::unique_ptr<IKSolver>> makeGradientDecentSolver(
const IKParams& params);
const auto getGradientDecentModes = []() {
return std::set<std::string>{
"gd", "gd_2", "gd_4", "gd_8", "gd_r", "gd_r_2",
"gd_r_4", "gd_r_8", "gd_c", "gd_c_2", "gd_c_4", "gd_c_8",
"jac", "jac_2", "jac_4", "jac_8",
};
};
} // namespace bio_ik
| 36.140496 | 78 | 0.721473 | [
"vector"
] |
1501973a43b9322b467e111fb067525d5e64bb8c | 4,000 | cc | C++ | chrome/browser/send_tab_to_self/send_tab_to_self_desktop_util.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/send_tab_to_self/send_tab_to_self_desktop_util.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/send_tab_to_self/send_tab_to_self_desktop_util.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/send_tab_to_self/send_tab_to_self_desktop_util.h"
#include <string>
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/send_tab_to_self/desktop_notification_handler.h"
#include "chrome/browser/sync/send_tab_to_self_sync_service_factory.h"
#include "chrome/browser/ui/send_tab_to_self/send_tab_to_self_bubble_controller.h"
#include "components/send_tab_to_self/features.h"
#include "components/send_tab_to_self/send_tab_to_self_model.h"
#include "components/send_tab_to_self/send_tab_to_self_sync_service.h"
#include "components/send_tab_to_self/target_device_info.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "url/gurl.h"
namespace send_tab_to_self {
void CreateNewEntry(content::WebContents* tab,
const std::string& target_device_name,
const std::string& target_device_guid,
const GURL& link_url) {
DCHECK(tab);
GURL shared_url = link_url;
std::string title;
base::Time navigation_time = base::Time();
content::NavigationEntry* navigation_entry =
tab->GetController().GetLastCommittedEntry();
// This should either be a valid link share or a valid tab share.
DCHECK(link_url.is_valid() || navigation_entry);
if (!link_url.is_valid()) {
// This is not link share, get the values from the last navigation entry.
shared_url = navigation_entry->GetURL();
title = base::UTF16ToUTF8(navigation_entry->GetTitle());
navigation_time = navigation_entry->GetTimestamp();
}
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
DCHECK(profile);
SendTabToSelfModel* model =
SendTabToSelfSyncServiceFactory::GetForProfile(profile)
->GetSendTabToSelfModel();
DCHECK(model);
if (!model->IsReady()) {
DesktopNotificationHandler(profile).DisplayFailureMessage(shared_url);
return;
}
model->AddEntry(shared_url, title, navigation_time, target_device_guid);
SendTabToSelfBubbleController* controller = send_tab_to_self::
SendTabToSelfBubbleController::CreateOrGetFromWebContents(tab);
controller->ShowConfirmationMessage();
}
void ShareToSingleTarget(content::WebContents* tab, const GURL& link_url) {
Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
DCHECK_EQ(GetValidDeviceCount(profile), 1u);
const std::vector<TargetDeviceInfo>& devices =
SendTabToSelfSyncServiceFactory::GetForProfile(profile)
->GetSendTabToSelfModel()
->GetTargetDeviceInfoSortedList();
CreateNewEntry(tab, devices.begin()->device_name, devices.begin()->cache_guid,
link_url);
}
void RecordSendTabToSelfClickResult(const std::string& entry_point,
SendTabToSelfClickResult state) {
base::UmaHistogramEnumeration("SendTabToSelf." + entry_point + ".ClickResult",
state);
}
size_t GetValidDeviceCount(Profile* profile) {
SendTabToSelfSyncService* service =
SendTabToSelfSyncServiceFactory::GetForProfile(profile);
DCHECK(service);
SendTabToSelfModel* model = service->GetSendTabToSelfModel();
DCHECK(model);
const std::vector<TargetDeviceInfo>& devices =
model->GetTargetDeviceInfoSortedList();
return devices.size();
}
base::string16 GetSingleTargetDeviceName(Profile* profile) {
DCHECK_EQ(GetValidDeviceCount(profile), 1u);
return base::UTF8ToUTF16(
SendTabToSelfSyncServiceFactory::GetForProfile(profile)
->GetSendTabToSelfModel()
->GetTargetDeviceInfoSortedList()
.begin()
->device_name);
}
} // namespace send_tab_to_self
| 37.383178 | 82 | 0.7415 | [
"vector",
"model"
] |
150c7fad1bfba6a5ab71980ea712414cdd893617 | 6,720 | cxx | C++ | src/Cxx/Visualization/ShadowsLightsDemo.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 2 | 2020-05-30T17:01:30.000Z | 2021-10-04T13:58:42.000Z | src/Cxx/Visualization/ShadowsLightsDemo.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | null | null | null | src/Cxx/Visualization/ShadowsLightsDemo.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 1 | 2020-01-28T01:27:03.000Z | 2020-01-28T01:27:03.000Z | // The scene consists of
// * 4 actors: a rectangle, a box, a cone and a sphere. The box, the cone and
// the sphere are above the rectangle.
// * 2 spotlights: one in the direction of the box, another one in the
// direction of the sphere. Both lights are above the box, the cone and
// the sphere.
#include <vtkSmartPointer.h>
#include <vtkCameraPass.h>
#include <vtkRenderPassCollection.h>
#include <vtkSequencePass.h>
#include <vtkShadowMapBakerPass.h>
#include <vtkShadowMapPass.h>
#include <vtkConeSource.h>
#include <vtkPlaneSource.h>
#include <vtkCubeSource.h>
#include <vtkSphereSource.h>
#include <vtkOpenGLRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderWindow.h>
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkCamera.h>
#include <vtkProperty.h>
#include <vtkLightActor.h>
#include <vtkLight.h>
#include <vtkLightCollection.h>
#include <vtkPolyDataNormals.h>
#include <vtkPointData.h>
#include <vtkNamedColors.h>
// For each spotlight, add a light frustum wireframe representation and a cone
// wireframe representation, colored with the light color.
void AddLightActors(vtkRenderer *r);
int main(int, char*[])
{
auto interactor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
auto renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->SetSize(400,400);
renderWindow->SetMultiSamples(0);
renderWindow->SetAlphaBitPlanes(1);
interactor->SetRenderWindow(renderWindow);
auto renderer =
vtkSmartPointer<vtkOpenGLRenderer>::New();
renderWindow->AddRenderer(renderer);
renderWindow->SetSize(640, 480);
auto rectangleSource =
vtkSmartPointer<vtkPlaneSource>::New();
rectangleSource->SetOrigin(-5.0,0.0,5.0);
rectangleSource->SetPoint1(5.0,0.0,5.0);
rectangleSource->SetPoint2(-5.0,0.0,-5.0);
rectangleSource->SetResolution(100,100);
auto rectangleMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
rectangleMapper->SetInputConnection(rectangleSource->GetOutputPort());
rectangleMapper->SetScalarVisibility(0);
auto shadows =
vtkSmartPointer<vtkShadowMapPass>::New();
auto seq =
vtkSmartPointer<vtkSequencePass>::New();
auto passes =
vtkSmartPointer<vtkRenderPassCollection>::New();
passes->AddItem(shadows->GetShadowMapBakerPass());
passes->AddItem(shadows);
seq->SetPasses(passes);
auto cameraP =
vtkSmartPointer<vtkCameraPass>::New();
cameraP->SetDelegatePass(seq);
// tell the renderer to use our render pass pipeline
vtkOpenGLRenderer *glrenderer =
dynamic_cast<vtkOpenGLRenderer*>(renderer.GetPointer());
glrenderer->SetPass(cameraP);
auto colors =
vtkSmartPointer<vtkNamedColors>::New();
vtkColor3d boxColor = colors->GetColor3d("Tomato");
vtkColor3d rectangleColor = colors->GetColor3d("Beige");
vtkColor3d coneColor = colors->GetColor3d("Peacock");
vtkColor3d sphereColor = colors->GetColor3d("Banana");
auto rectangleActor =
vtkSmartPointer<vtkActor>::New();
rectangleActor->SetMapper(rectangleMapper);
rectangleActor->SetVisibility(1);
rectangleActor->GetProperty()->SetColor(rectangleColor.GetData());
auto boxSource =
vtkSmartPointer<vtkCubeSource>::New();
boxSource->SetXLength(2.0);
auto boxNormals =
vtkSmartPointer<vtkPolyDataNormals>::New();
boxNormals->SetInputConnection(boxSource->GetOutputPort());
boxNormals->SetComputePointNormals(0);
boxNormals->SetComputeCellNormals(1);
boxNormals->Update();
boxNormals->GetOutput()->GetPointData()->SetNormals(0);
auto boxMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
boxMapper->SetInputConnection(boxNormals->GetOutputPort());
boxMapper->SetScalarVisibility(0);
auto boxActor =
vtkSmartPointer<vtkActor>::New();
boxActor->SetMapper(boxMapper);
boxActor->SetVisibility(1);
boxActor->SetPosition(-2.0,2.0,0.0);
boxActor->GetProperty()->SetColor(boxColor.GetData());
auto coneSource =
vtkSmartPointer<vtkConeSource>::New();
coneSource->SetResolution(24);
coneSource->SetDirection(1.0,1.0,1.0);
auto coneMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
coneMapper->SetInputConnection(coneSource->GetOutputPort());
coneMapper->SetScalarVisibility(0);
auto coneActor =
vtkSmartPointer<vtkActor>::New();
coneActor->SetMapper(coneMapper);
coneActor->SetVisibility(1);
coneActor->SetPosition(0.0,1.0,1.0);
coneActor->GetProperty()->SetColor(coneColor.GetData());
auto sphereSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereSource->SetThetaResolution(32);
sphereSource->SetPhiResolution(32);
auto sphereMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
sphereMapper->SetInputConnection(sphereSource->GetOutputPort());
sphereMapper->SetScalarVisibility(0);
auto sphereActor =
vtkSmartPointer<vtkActor>::New();
sphereActor->SetMapper(sphereMapper);
sphereActor->SetVisibility(1);
sphereActor->SetPosition(2.0,2.0,-1.0);
sphereActor->GetProperty()->SetColor(sphereColor.GetData());
renderer->AddViewProp(rectangleActor);
renderer->AddViewProp(boxActor);
renderer->AddViewProp(coneActor);
renderer->AddViewProp(sphereActor);
// Spotlights.
// lighting the box.
auto l1 =
vtkSmartPointer<vtkLight>::New();
l1->SetPosition(-4.0,4.0,-1.0);
l1->SetFocalPoint(boxActor->GetPosition());
l1->SetColor(1.0,1.0,1.0);
l1->SetPositional(1);
renderer->AddLight(l1);
l1->SetSwitch(1);
// lighting the sphere
auto l2 =
vtkSmartPointer<vtkLight>::New();
l2->SetPosition(4.0,5.0,1.0);
l2->SetFocalPoint(sphereActor->GetPosition());
l2->SetColor(1.0,0.0,1.0);
l2->SetPositional(1);
renderer->AddLight(l2);
l2->SetSwitch(1);
AddLightActors(renderer);
renderer->SetBackground2(colors->GetColor3d("Silver").GetData());
renderer->SetBackground(colors->GetColor3d("LightGrey").GetData());
renderer->SetGradientBackground(true);
renderWindow->Render();
renderer->ResetCamera();
auto camera =
renderer->GetActiveCamera();
camera->Azimuth(40.0);
camera->Elevation(10.0);
renderWindow->Render();
interactor->Start();
return EXIT_SUCCESS;
}
// For each spotlight, add a light frustum wireframe representation and a cone
// wireframe representation, colored with the light color.
void AddLightActors(vtkRenderer *r)
{
vtkLightCollection *lights = r->GetLights();
lights->InitTraversal();
vtkLight *l = lights->GetNextItem();
while(l != 0)
{
double angle = l->GetConeAngle();
if(l->LightTypeIsSceneLight()
&& l->GetPositional()
&& angle<180.0) // spotlight
{
auto la =
vtkSmartPointer<vtkLightActor>::New();
la->SetLight(l);
r->AddViewProp(la);
}
l=lights->GetNextItem();
}
}
| 28.474576 | 78 | 0.72619 | [
"render"
] |
150ec559543e9b7fc69b465c53ad6c4b525c1114 | 11,047 | cpp | C++ | spheroidal/sphwv/common_main.cpp | SabininGV/scattering | 68ffea5605d9da87db0593ba7c56c7f60f6b3fae | [
"BSD-2-Clause"
] | 5 | 2016-05-02T11:51:54.000Z | 2021-10-04T14:35:58.000Z | spheroidal/sphwv/common_main.cpp | SabininGV/scattering | 68ffea5605d9da87db0593ba7c56c7f60f6b3fae | [
"BSD-2-Clause"
] | null | null | null | spheroidal/sphwv/common_main.cpp | SabininGV/scattering | 68ffea5605d9da87db0593ba7c56c7f60f6b3fae | [
"BSD-2-Clause"
] | 10 | 2016-03-17T03:58:52.000Z | 2021-10-04T14:36:00.000Z | //
// Copyright (c) 2014, Ross Adelman, Nail A. Gumerov, and Ramani Duraiswami
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "common_main.hpp"
#include "common_spheroidal.hpp"
#include "io.hpp"
#include <iostream>
#include "real.hpp"
#include <string>
bool save_lambdamn(bool verbose, const real & c, const real & m, const real & n)
{
real lambda_approx;
real lambda;
if (!open_data(lambda_approx, generate_name(c, m, n, "lambda_approx")))
{
std::cout << "can't open lambda_approx..." << std::endl;
return false;
}
calculate_lambdamn(lambda, verbose, c, m, n, lambda_approx);
if (!save_data(generate_name(c, m, n, "lambda"), lambda))
{
std::cout << "can't save lambda..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_lambda"), lambda))
{
std::cout << "can't save log_abs_lambda..." << std::endl;
return false;
}
return true;
}
bool open_lambdamn(real & lambda, const real & c, const real & m, const real & n)
{
if (!open_data(lambda, generate_name(c, m, n, "lambda")))
{
std::cout << "can't open lambda..." << std::endl;
return false;
}
return true;
}
bool save_drmn(bool verbose, const real & c, const real & m, const real & n, real & n_dr, const real & dr_min)
{
real lambda;
std::vector<real> dr;
if (!open_lambdamn(lambda, c, m, n))
{
return false;
}
calculate_drmn(dr, verbose, c, m, n, lambda, n_dr, dr_min);
if (!save_data(generate_name(c, m, n, "dr"), dr))
{
std::cout << "can't save dr..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_dr"), dr))
{
std::cout << "can't save log_abs_dr..." << std::endl;
return false;
}
return true;
}
bool open_drmn(real & n_dr, std::vector<real> & dr, const real & c, const real & m, const real & n)
{
if (!open_data(dr, generate_name(c, m, n, "dr")))
{
std::cout << "can't open dr..." << std::endl;
return false;
}
n_dr = real((int)dr.size());
return true;
}
bool save_drmn_neg(bool verbose, const real & c, const real & m, const real & n, real & n_dr_neg, const real & dr_neg_min)
{
real lambda;
real n_dr;
std::vector<real> dr;
std::vector<real> dr_neg;
if (!open_lambdamn(lambda, c, m, n) ||
!open_drmn(n_dr, dr, c, m, n))
{
return false;
}
calculate_drmn_neg(dr_neg, verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, dr_neg_min);
if (!save_data(generate_name(c, m, n, "dr_neg"), dr_neg))
{
std::cout << "can't save dr_neg..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_dr_neg"), dr_neg))
{
std::cout << "can't save log_abs_dr_neg..." << std::endl;
return false;
}
return true;
}
bool open_drmn_neg(real & n_dr_neg, std::vector<real> & dr_neg, const real & c, const real & m, const real & n)
{
if (!open_data(dr_neg, generate_name(c, m, n, "dr_neg")))
{
std::cout << "can't open dr_neg..." << std::endl;
return false;
}
n_dr_neg = real((int)dr_neg.size());
return true;
}
bool save_Nmn(bool verbose, const real & c, const real & m, const real & n)
{
real lambda;
real n_dr;
std::vector<real> dr;
real N;
if (!open_lambdamn(lambda, c, m, n) ||
!open_drmn(n_dr, dr, c, m, n))
{
return false;
}
N = calculate_Nmn(verbose, c, m, n, lambda, n_dr, dr);
if (!save_data(generate_name(c, m, n, "N"), N))
{
std::cout << "can't save N..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_N"), N))
{
std::cout << "can't save log_abs_N..." << std::endl;
return false;
}
return true;
}
bool open_Nmn(real & N, const real & c, const real & m, const real & n)
{
if (!open_data(N, generate_name(c, m, n, "N")))
{
std::cout << "can't open N..." << std::endl;
return false;
}
return true;
}
bool save_Fmn(bool verbose, const real & c, const real & m, const real & n)
{
real lambda;
real n_dr;
std::vector<real> dr;
real F;
if (!open_lambdamn(lambda, c, m, n) ||
!open_drmn(n_dr, dr, c, m, n))
{
return false;
}
F = calculate_Fmn(verbose, c, m, n, lambda, n_dr, dr);
if (!save_data(generate_name(c, m, n, "F"), F))
{
std::cout << "can't save F..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_F"), F))
{
std::cout << "can't save log_abs_F..." << std::endl;
return false;
}
return true;
}
bool open_Fmn(real & F, const real & c, const real & m, const real & n)
{
if (!open_data(F, generate_name(c, m, n, "F")))
{
std::cout << "can't open F..." << std::endl;
return false;
}
return true;
}
bool save_kmn1(bool verbose, const real & c, const real & m, const real & n)
{
real n_dr;
std::vector<real> dr;
real F;
real k1;
if (!open_drmn(n_dr, dr, c, m, n) ||
!open_Fmn(F, c, m, n))
{
return false;
}
k1 = calculate_kmn1(verbose, c, m, n, n_dr, dr, F);
if (!save_data(generate_name(c, m, n, "k1"), k1))
{
std::cout << "can't save k1..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_k1"), k1))
{
std::cout << "can't save log_abs_k1.." << std::endl;
return false;
}
return true;
}
bool open_kmn1(real & k1, const real & c, const real & m, const real & n)
{
if (!open_data(k1, generate_name(c, m, n, "k1")))
{
std::cout << "can't open k1..." << std::endl;
return false;
}
return true;
}
bool save_kmn2(bool verbose, const real & c, const real & m, const real & n)
{
real lambda;
real n_dr;
std::vector<real> dr;
real n_dr_neg;
std::vector<real> dr_neg;
real F;
real k2;
if (!open_lambdamn(lambda, c, m, n) ||
!open_drmn(n_dr, dr, c, m, n) ||
!open_drmn_neg(n_dr_neg, dr_neg, c, m, n) ||
!open_Fmn(F, c, m, n))
{
return false;
}
k2 = calculate_kmn2(verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, dr_neg, F);
if (!save_data(generate_name(c, m, n, "k2"), k2))
{
std::cout << "can't save k2..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_k2"), k2))
{
std::cout << "can't save log_abs_k2..." << std::endl;
return false;
}
return true;
}
bool open_kmn2(real & k2, const real & c, const real & m, const real & n)
{
if (!open_data(k2, generate_name(c, m, n, "k2")))
{
std::cout << "can't open k2..." << std::endl;
return false;
}
return true;
}
bool save_c2kmn(bool verbose, const real & c, const real & m, const real & n, real & n_c2k, const real & c2k_min)
{
real lambda;
real n_dr;
std::vector<real> dr;
std::vector<real> c2k;
if (!open_lambdamn(lambda, c, m, n) ||
!open_drmn(n_dr, dr, c, m, n))
{
return false;
}
c2k.clear();
calculate_c2kmn(c2k, verbose, c, m, n, lambda, n_dr, dr, n_c2k, c2k_min);
if (!save_data(generate_name(c, m, n, "c2k"), c2k))
{
std::cout << "can't save c2k..." << std::endl;
return false;
}
if (!save_log_abs_data(generate_name(c, m, n, "log_abs_c2k"), c2k))
{
std::cout << "can't save log_abs_c2k..." << std::endl;
return false;
}
return true;
}
bool open_c2kmn(real & n_c2k, std::vector<real> & c2k, const real & c, const real & m, const real & n)
{
if (!open_data(c2k, generate_name(c, m, n, "c2k")))
{
std::cout << "can't open c2k..." << std::endl;
return false;
}
n_c2k = real((int)c2k.size());
return true;
}
bool save_Smn1(bool verbose, const real & c, const real & m, const real & n, const real & a, const real & b, const real & d, const std::string & arg_type, int p)
{
real n_dr;
std::vector<real> dr;
real N;
real n_c2k;
std::vector<real> c2k;
real eta;
real S1_1;
real S1p_1;
real S1_2;
real S1p_2;
real S1_log_abs_difference;
real S1p_log_abs_difference;
if (!open_drmn(n_dr, dr, c, m, n) ||
!open_Nmn(N, c, m, n) ||
!open_c2kmn(n_c2k, c2k, c, m, n))
{
return false;
}
for (real i = a; i <= b; i = i + d)
{
if (arg_type == "eta")
{
eta = i;
}
else
{
eta = cos(i * real::PI);
}
calculate_Smn1_1(S1_1, S1p_1, verbose, c, m, n, n_dr, dr, eta);
S1_1 = S1_1 / pow(N, real::ONE / real::TWO);
S1p_1 = S1p_1 / pow(N, real::ONE / real::TWO);
calculate_Smn1_2(S1_2, S1p_2, verbose, c, m, n, n_c2k, c2k, eta);
S1_2 = S1_2 / pow(N, real::ONE / real::TWO);
S1p_2 = S1p_2 / pow(N, real::ONE / real::TWO);
S1_log_abs_difference = log(abs(S1_1 - S1_2));
S1p_log_abs_difference = log(abs(S1p_1 - S1p_2));
std::cout << i.get_string(p) << ","
<< eta.get_string(p) << ","
<< S1_1.get_string(p) << "," << S1p_1.get_string(p) << ","
<< S1_2.get_string(p) << "," << S1p_2.get_string(p) << ","
<< S1_log_abs_difference.get_string(p) << "," << S1p_log_abs_difference.get_string(p) << std::endl;
}
return true;
}
//
// This is the main entrypoint of the program, both for pro_sphwv and
// obl_sphwv. It sets the default precision in MPFR and the maximum number of
// reals that can be used at any one time based on the -max_memory argument.
// At the end, it calls parse_args, which is defined differently for pro_sphwv
// and obl_sphwv.
//
int main(int argc, char **argv)
{
std::string argument;
std::string value;
int max_memory;
bool max_memory_entered;
int precision;
bool precision_entered;
max_memory_entered = false;
precision_entered = false;
for (int i = 1; i < argc; i = i + 2)
{
argument = std::string(argv[i]);
value = std::string(argv[i + 1]);
if (argument == "-max_memory")
{
max_memory = std::atoi(value.c_str());
max_memory_entered = true;
}
else if (argument == "-precision")
{
precision = std::atoi(value.c_str());
precision_entered = true;
}
}
if (!max_memory_entered || !precision_entered)
{
std::cout << "no value of max_memory and/or precision was entered..." << std::endl;
return 1;
}
real::begin(precision, (int)((double)max_memory * (8000000.0 / (double)precision)));
complex::begin();
return parse_args(argc, argv);
}
| 26.491607 | 161 | 0.637458 | [
"vector"
] |
15103718dc73be894c7c86a75da243d2f5720ff4 | 16,233 | cc | C++ | services/media_session/audio_focus_manager.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | services/media_session/audio_focus_manager.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | services/media_session/audio_focus_manager.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 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 "services/media_session/audio_focus_manager.h"
#include <iterator>
#include <utility>
#include "base/bind.h"
#include "base/containers/adapters.h"
#include "base/containers/cxx20_erase.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_observer.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/unguessable_token.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/media_session/audio_focus_request.h"
#include "services/media_session/public/cpp/features.h"
#include "services/media_session/public/mojom/audio_focus.mojom.h"
namespace media_session {
namespace {
mojom::EnforcementMode GetDefaultEnforcementMode() {
if (base::FeatureList::IsEnabled(features::kAudioFocusEnforcement)) {
if (base::FeatureList::IsEnabled(features::kAudioFocusSessionGrouping))
return mojom::EnforcementMode::kSingleGroup;
return mojom::EnforcementMode::kSingleSession;
}
return mojom::EnforcementMode::kNone;
}
} // namespace
// MediaPowerDelegate will pause all playback if the device is suspended.
class MediaPowerDelegate : public base::PowerSuspendObserver {
public:
explicit MediaPowerDelegate(base::WeakPtr<AudioFocusManager> owner)
: owner_(owner) {
base::PowerMonitor::AddPowerSuspendObserver(this);
}
MediaPowerDelegate(const MediaPowerDelegate&) = delete;
MediaPowerDelegate& operator=(const MediaPowerDelegate&) = delete;
~MediaPowerDelegate() override {
base::PowerMonitor::RemovePowerSuspendObserver(this);
}
// base::PowerSuspendObserver:
void OnSuspend() override {
DCHECK(owner_);
owner_->SuspendAllSessions();
}
private:
const base::WeakPtr<AudioFocusManager> owner_;
};
class AudioFocusManager::SourceObserverHolder {
public:
SourceObserverHolder(AudioFocusManager* owner,
const base::UnguessableToken& source_id,
mojo::PendingRemote<mojom::AudioFocusObserver> observer)
: identity_(source_id), observer_(std::move(observer)) {
// Set a connection error handler so that we will remove observers that have
// had an error / been closed.
observer_.set_disconnect_handler(base::BindOnce(
&AudioFocusManager::CleanupSourceObservers, base::Unretained(owner)));
}
SourceObserverHolder(const SourceObserverHolder&) = delete;
SourceObserverHolder& operator=(const SourceObserverHolder&) = delete;
~SourceObserverHolder() = default;
bool is_valid() const { return observer_.is_connected(); }
const base::UnguessableToken& identity() const { return identity_; }
void OnFocusGained(mojom::AudioFocusRequestStatePtr session) {
observer_->OnFocusGained(std::move(session));
}
void OnFocusLost(mojom::AudioFocusRequestStatePtr session) {
observer_->OnFocusLost(std::move(session));
}
void OnRequestIdReleased(const base::UnguessableToken& request_id) {
observer_->OnRequestIdReleased(request_id);
}
private:
const base::UnguessableToken identity_;
mojo::Remote<mojom::AudioFocusObserver> observer_;
};
void AudioFocusManager::RequestAudioFocus(
mojo::PendingReceiver<mojom::AudioFocusRequestClient> receiver,
mojo::PendingRemote<mojom::MediaSession> session,
mojom::MediaSessionInfoPtr session_info,
mojom::AudioFocusType type,
RequestAudioFocusCallback callback) {
auto request_id = base::UnguessableToken::Create();
RequestAudioFocusInternal(
std::make_unique<AudioFocusRequest>(
weak_ptr_factory_.GetWeakPtr(), std::move(receiver),
std::move(session), std::move(session_info), type, request_id,
GetBindingSourceName(), base::UnguessableToken::Create(),
GetBindingIdentity()),
type);
std::move(callback).Run(request_id);
}
void AudioFocusManager::RequestGroupedAudioFocus(
const base::UnguessableToken& request_id,
mojo::PendingReceiver<mojom::AudioFocusRequestClient> receiver,
mojo::PendingRemote<mojom::MediaSession> session,
mojom::MediaSessionInfoPtr session_info,
mojom::AudioFocusType type,
const base::UnguessableToken& group_id,
RequestGroupedAudioFocusCallback callback) {
if (IsFocusEntryPresent(request_id)) {
std::move(callback).Run(false /* success */);
return;
}
RequestAudioFocusInternal(
std::make_unique<AudioFocusRequest>(
weak_ptr_factory_.GetWeakPtr(), std::move(receiver),
std::move(session), std::move(session_info), type, request_id,
GetBindingSourceName(), group_id, GetBindingIdentity()),
type);
std::move(callback).Run(true /* success */);
}
void AudioFocusManager::GetFocusRequests(GetFocusRequestsCallback callback) {
std::vector<mojom::AudioFocusRequestStatePtr> requests;
for (const auto& row : audio_focus_stack_)
requests.push_back(row->ToAudioFocusRequestState());
std::move(callback).Run(std::move(requests));
}
void AudioFocusManager::GetDebugInfoForRequest(
const RequestId& request_id,
GetDebugInfoForRequestCallback callback) {
for (auto& row : audio_focus_stack_) {
if (row->id() != request_id)
continue;
row->ipc()->GetDebugInfo(base::BindOnce(
[](const base::UnguessableToken& group_id,
const base::UnguessableToken& identity,
GetDebugInfoForRequestCallback callback,
mojom::MediaSessionDebugInfoPtr info) {
// Inject the |group_id| into the state string. This is because in
// some cases the group id is automatically generated by the media
// session service so the session is unaware of it.
if (!info->state.empty())
info->state += " ";
info->state += "GroupId=" + group_id.ToString();
// Inject the identity into the state string.
info->state += " Identity=" + identity.ToString();
std::move(callback).Run(std::move(info));
},
row->group_id(), row->identity(), std::move(callback)));
return;
}
std::move(callback).Run(mojom::MediaSessionDebugInfo::New());
}
void AudioFocusManager::AbandonAudioFocusInternal(RequestId id) {
if (audio_focus_stack_.empty())
return;
bool was_top_most_session = audio_focus_stack_.back()->id() == id;
auto row = RemoveFocusEntryIfPresent(id);
if (!row)
return;
EnforceAudioFocus();
MaybeUpdateActiveSession();
// Notify observers that we lost audio focus.
mojom::AudioFocusRequestStatePtr session_state =
row->ToAudioFocusRequestState();
for (const auto& observer : observers_)
observer->OnFocusLost(session_state.Clone());
for (auto& holder : source_observers_) {
if (holder->identity() == row->identity())
holder->OnFocusLost(session_state.Clone());
}
if (!was_top_most_session || audio_focus_stack_.empty())
return;
// Notify observers that the session on top gained focus.
AudioFocusRequest* new_session = audio_focus_stack_.back().get();
for (const auto& observer : observers_)
observer->OnFocusGained(new_session->ToAudioFocusRequestState());
for (auto& holder : source_observers_) {
if (holder->identity() == new_session->identity())
holder->OnFocusGained(new_session->ToAudioFocusRequestState());
}
}
void AudioFocusManager::AddObserver(
mojo::PendingRemote<mojom::AudioFocusObserver> observer) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
observers_.Add(std::move(observer));
}
void AudioFocusManager::SetSource(const base::UnguessableToken& identity,
const std::string& name) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto& context = receivers_.current_context();
context->identity = identity;
context->source_name = name;
}
void AudioFocusManager::SetEnforcementMode(mojom::EnforcementMode mode) {
if (mode == mojom::EnforcementMode::kDefault)
mode = GetDefaultEnforcementMode();
if (mode == enforcement_mode_)
return;
enforcement_mode_ = mode;
if (audio_focus_stack_.empty())
return;
EnforceAudioFocus();
}
void AudioFocusManager::AddSourceObserver(
const base::UnguessableToken& source_id,
mojo::PendingRemote<mojom::AudioFocusObserver> observer) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
source_observers_.push_back(std::make_unique<SourceObserverHolder>(
this, source_id, std::move(observer)));
}
void AudioFocusManager::GetSourceFocusRequests(
const base::UnguessableToken& source_id,
GetFocusRequestsCallback callback) {
std::vector<mojom::AudioFocusRequestStatePtr> requests;
for (const auto& row : audio_focus_stack_) {
if (row->identity() == source_id)
requests.push_back(row->ToAudioFocusRequestState());
}
std::move(callback).Run(std::move(requests));
}
void AudioFocusManager::RequestIdReleased(
const base::UnguessableToken& request_id) {
for (const auto& observer : observers_)
observer->OnRequestIdReleased(request_id);
const base::UnguessableToken& source_id = GetBindingIdentity();
for (auto& holder : source_observers_) {
if (holder->identity() == source_id)
holder->OnRequestIdReleased(request_id);
}
}
void AudioFocusManager::CreateActiveMediaController(
mojo::PendingReceiver<mojom::MediaController> receiver) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
active_media_controller_.BindToInterface(std::move(receiver));
}
void AudioFocusManager::CreateMediaControllerForSession(
mojo::PendingReceiver<mojom::MediaController> receiver,
const base::UnguessableToken& receiver_id) {
for (auto& row : audio_focus_stack_) {
if (row->id() != receiver_id)
continue;
row->BindToMediaController(std::move(receiver));
break;
}
}
void AudioFocusManager::SuspendAllSessions() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
for (auto& row : audio_focus_stack_)
row->ipc()->Suspend(mojom::MediaSession::SuspendType::kUI);
}
void AudioFocusManager::BindToInterface(
mojo::PendingReceiver<mojom::AudioFocusManager> receiver) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
receivers_.Add(this, std::move(receiver),
std::make_unique<ReceiverContext>());
}
void AudioFocusManager::BindToDebugInterface(
mojo::PendingReceiver<mojom::AudioFocusManagerDebug> receiver) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
debug_receivers_.Add(this, std::move(receiver));
}
void AudioFocusManager::BindToControllerManagerInterface(
mojo::PendingReceiver<mojom::MediaControllerManager> receiver) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
controller_receivers_.Add(this, std::move(receiver));
}
void AudioFocusManager::RequestAudioFocusInternal(
std::unique_ptr<AudioFocusRequest> row,
mojom::AudioFocusType type) {
const auto& identity = row->identity();
row->set_audio_focus_type(type);
audio_focus_stack_.push_back(std::move(row));
EnforceAudioFocus();
MaybeUpdateActiveSession();
// Notify observers that we were gained audio focus.
mojom::AudioFocusRequestStatePtr session_state =
audio_focus_stack_.back()->ToAudioFocusRequestState();
for (const auto& observer : observers_)
observer->OnFocusGained(session_state.Clone());
for (auto& holder : source_observers_) {
if (holder->identity() == identity)
holder->OnFocusGained(session_state.Clone());
}
}
void AudioFocusManager::EnforceAudioFocus() {
DCHECK_NE(mojom::EnforcementMode::kDefault, enforcement_mode_);
if (audio_focus_stack_.empty())
return;
EnforcementState state;
for (auto& session : base::Reversed(audio_focus_stack_)) {
EnforceSingleSession(session.get(), state);
// Update the flags based on the audio focus type of this session. If the
// session is suspended then any transient audio focus type should not have
// an effect.
switch (session->audio_focus_type()) {
case mojom::AudioFocusType::kGain:
state.should_stop = true;
break;
case mojom::AudioFocusType::kGainTransient:
if (!session->IsSuspended())
state.should_suspend = true;
break;
case mojom::AudioFocusType::kGainTransientMayDuck:
if (!session->IsSuspended())
state.should_duck = true;
break;
case mojom::AudioFocusType::kAmbient:
break;
}
}
}
void AudioFocusManager::MaybeUpdateActiveSession() {
AudioFocusRequest* active = nullptr;
for (auto& row : base::Reversed(audio_focus_stack_)) {
if (!row->info()->is_controllable)
continue;
active = row.get();
break;
}
if (active) {
active_media_controller_.SetMediaSession(active);
} else {
active_media_controller_.ClearMediaSession();
}
}
AudioFocusManager::AudioFocusManager()
: enforcement_mode_(GetDefaultEnforcementMode()) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
power_delegate_ =
std::make_unique<MediaPowerDelegate>(weak_ptr_factory_.GetWeakPtr());
}
AudioFocusManager::~AudioFocusManager() = default;
std::unique_ptr<AudioFocusRequest> AudioFocusManager::RemoveFocusEntryIfPresent(
RequestId id) {
std::unique_ptr<AudioFocusRequest> row;
for (auto iter = audio_focus_stack_.begin(); iter != audio_focus_stack_.end();
++iter) {
if ((*iter)->id() == id) {
row.swap((*iter));
audio_focus_stack_.erase(iter);
break;
}
}
return row;
}
bool AudioFocusManager::IsFocusEntryPresent(
const base::UnguessableToken& id) const {
for (auto& row : audio_focus_stack_) {
if (row->id() == id)
return true;
}
return false;
}
const std::string& AudioFocusManager::GetBindingSourceName() const {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
return receivers_.current_context()->source_name;
}
const base::UnguessableToken& AudioFocusManager::GetBindingIdentity() const {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
return receivers_.current_context()->identity;
}
bool AudioFocusManager::IsSessionOnTopOfAudioFocusStack(
RequestId id,
mojom::AudioFocusType type) const {
return !audio_focus_stack_.empty() && audio_focus_stack_.back()->id() == id &&
audio_focus_stack_.back()->audio_focus_type() == type;
}
bool AudioFocusManager::ShouldSessionBeSuspended(
const AudioFocusRequest* session,
const EnforcementState& state) const {
bool should_suspend_any = state.should_stop || state.should_suspend;
switch (enforcement_mode_) {
case mojom::EnforcementMode::kSingleSession:
return should_suspend_any;
case mojom::EnforcementMode::kSingleGroup:
return should_suspend_any &&
session->group_id() != audio_focus_stack_.back()->group_id();
case mojom::EnforcementMode::kNone:
return false;
case mojom::EnforcementMode::kDefault:
NOTIMPLEMENTED();
return false;
}
}
bool AudioFocusManager::ShouldSessionBeDucked(
const AudioFocusRequest* session,
const EnforcementState& state) const {
switch (enforcement_mode_) {
case mojom::EnforcementMode::kSingleSession:
case mojom::EnforcementMode::kSingleGroup:
if (session->info()->force_duck)
return state.should_duck || ShouldSessionBeSuspended(session, state);
return state.should_duck;
case mojom::EnforcementMode::kNone:
return false;
case mojom::EnforcementMode::kDefault:
NOTIMPLEMENTED();
return false;
}
}
void AudioFocusManager::EnforceSingleSession(AudioFocusRequest* session,
const EnforcementState& state) {
if (ShouldSessionBeDucked(session, state)) {
session->ipc()->StartDucking();
} else {
session->ipc()->StopDucking();
}
// If the session wants to be ducked instead of suspended we should stop now.
if (session->info()->force_duck)
return;
if (ShouldSessionBeSuspended(session, state)) {
session->Suspend(state);
} else {
session->ReleaseTransientHold();
}
}
void AudioFocusManager::CleanupSourceObservers() {
base::EraseIf(source_observers_,
[](const auto& holder) { return !holder->is_valid(); });
}
} // namespace media_session
| 31.520388 | 80 | 0.721616 | [
"vector"
] |
15113c81e4a76a859b784874f25470dac927d168 | 42,259 | cpp | C++ | thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_types.0.split.cpp | nathanawmk/fbthrift | 557cab1738eac15a00075a62389b50a3b6d900fc | [
"Apache-2.0"
] | null | null | null | thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_types.0.split.cpp | nathanawmk/fbthrift | 557cab1738eac15a00075a62389b50a3b6d900fc | [
"Apache-2.0"
] | null | null | null | thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_types.0.split.cpp | nathanawmk/fbthrift | 557cab1738eac15a00075a62389b50a3b6d900fc | [
"Apache-2.0"
] | null | null | null | /**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#include "thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_types.h"
#include "thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_types.tcc"
#include <thrift/lib/cpp2/gen/module_types_cpp.h>
#include "thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_data.h"
namespace apache { namespace thrift {
constexpr std::size_t const TEnumTraits<::cpp2::MyEnum>::size;
folly::Range<::cpp2::MyEnum const*> const TEnumTraits<::cpp2::MyEnum>::values = folly::range(TEnumDataStorage<::cpp2::MyEnum>::values);
folly::Range<folly::StringPiece const*> const TEnumTraits<::cpp2::MyEnum>::names = folly::range(TEnumDataStorage<::cpp2::MyEnum>::names);
char const* TEnumTraits<::cpp2::MyEnum>::findName(type value) {
using factory = ::cpp2::_MyEnum_EnumMapFactory;
static folly::Indestructible<factory::ValuesToNamesMapType> const map{
factory::makeValuesToNamesMap()};
auto found = map->find(value);
return found == map->end() ? nullptr : found->second;
}
bool TEnumTraits<::cpp2::MyEnum>::findValue(char const* name, type* out) {
using factory = ::cpp2::_MyEnum_EnumMapFactory;
static folly::Indestructible<factory::NamesToValuesMapType> const map{
factory::makeNamesToValuesMap()};
auto found = map->find(name);
return found == map->end() ? false : (*out = found->second, true);
}
}} // apache::thrift
namespace cpp2 {
FOLLY_PUSH_WARNING
FOLLY_GNU_DISABLE_WARNING("-Wdeprecated-declarations")
const _MyEnum_EnumMapFactory::ValuesToNamesMapType _MyEnum_VALUES_TO_NAMES = _MyEnum_EnumMapFactory::makeValuesToNamesMap();
const _MyEnum_EnumMapFactory::NamesToValuesMapType _MyEnum_NAMES_TO_VALUES = _MyEnum_EnumMapFactory::makeNamesToValuesMap();
FOLLY_POP_WARNING
} // cpp2
namespace apache {
namespace thrift {
namespace detail {
void TccStructTraits<::cpp2::MyStructFloatFieldThrowExp>::translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept {
using data = apache::thrift::TStructDataStorage<::cpp2::MyStructFloatFieldThrowExp>;
static const st::translate_field_name_table table{
data::fields_size,
data::fields_names.data(),
data::fields_ids.data(),
data::fields_types.data()};
st::translate_field_name(_fname, fid, _ftype, table);
}
} // namespace detail
} // namespace thrift
} // namespace apache
namespace cpp2 {
MyStructFloatFieldThrowExp::MyStructFloatFieldThrowExp(const MyStructFloatFieldThrowExp&) = default;
MyStructFloatFieldThrowExp& MyStructFloatFieldThrowExp::operator=(const MyStructFloatFieldThrowExp&) = default;
MyStructFloatFieldThrowExp::MyStructFloatFieldThrowExp(MyStructFloatFieldThrowExp&& other) noexcept :
__fbthrift_field_myLongField(std::move(other.__fbthrift_field_myLongField)),
__fbthrift_field_MyByteField(std::move(other.__fbthrift_field_MyByteField)),
__fbthrift_field_myStringField(std::move(other.__fbthrift_field_myStringField)),
__fbthrift_field_myFloatField(std::move(other.__fbthrift_field_myFloatField)),
__isset(other.__isset) {
}
MyStructFloatFieldThrowExp& MyStructFloatFieldThrowExp::operator=(FOLLY_MAYBE_UNUSED MyStructFloatFieldThrowExp&& other) noexcept {
this->__fbthrift_field_myLongField = std::move(other.__fbthrift_field_myLongField);
this->__fbthrift_field_MyByteField = std::move(other.__fbthrift_field_MyByteField);
this->__fbthrift_field_myStringField = std::move(other.__fbthrift_field_myStringField);
this->__fbthrift_field_myFloatField = std::move(other.__fbthrift_field_myFloatField);
__isset = other.__isset;
return *this;
}
MyStructFloatFieldThrowExp::MyStructFloatFieldThrowExp(apache::thrift::FragileConstructor, ::std::int64_t myLongField__arg, ::std::int8_t MyByteField__arg, ::std::string myStringField__arg, float myFloatField__arg) :
__fbthrift_field_myLongField(std::move(myLongField__arg)),
__fbthrift_field_MyByteField(std::move(MyByteField__arg)),
__fbthrift_field_myStringField(std::move(myStringField__arg)),
__fbthrift_field_myFloatField(std::move(myFloatField__arg)) {
__isset.set(folly::index_constant<0>(), true);
__isset.set(folly::index_constant<1>(), true);
__isset.set(folly::index_constant<2>(), true);
__isset.set(folly::index_constant<3>(), true);
}
void MyStructFloatFieldThrowExp::__clear() {
// clear all fields
this->__fbthrift_field_myLongField = ::std::int64_t();
this->__fbthrift_field_MyByteField = ::std::int8_t();
this->__fbthrift_field_myStringField = apache::thrift::StringTraits<std::string>::fromStringLiteral("");
this->__fbthrift_field_myFloatField = float();
__isset = {};
}
bool MyStructFloatFieldThrowExp::operator==(const MyStructFloatFieldThrowExp& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.myLongField_ref() == rhs.myLongField_ref())) {
return false;
}
if (!(lhs.MyByteField_ref() == rhs.MyByteField_ref())) {
return false;
}
if (!(lhs.myStringField_ref() == rhs.myStringField_ref())) {
return false;
}
if (!(lhs.myFloatField_ref() == rhs.myFloatField_ref())) {
return false;
}
return true;
}
bool MyStructFloatFieldThrowExp::operator<(const MyStructFloatFieldThrowExp& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.myLongField_ref() == rhs.myLongField_ref())) {
return lhs.myLongField_ref() < rhs.myLongField_ref();
}
if (!(lhs.MyByteField_ref() == rhs.MyByteField_ref())) {
return lhs.MyByteField_ref() < rhs.MyByteField_ref();
}
if (!(lhs.myStringField_ref() == rhs.myStringField_ref())) {
return lhs.myStringField_ref() < rhs.myStringField_ref();
}
if (!(lhs.myFloatField_ref() == rhs.myFloatField_ref())) {
return lhs.myFloatField_ref() < rhs.myFloatField_ref();
}
return false;
}
void swap(MyStructFloatFieldThrowExp& a, MyStructFloatFieldThrowExp& b) {
using ::std::swap;
swap(a.myLongField_ref().value(), b.myLongField_ref().value());
swap(a.MyByteField_ref().value(), b.MyByteField_ref().value());
swap(a.myStringField_ref().value(), b.myStringField_ref().value());
swap(a.myFloatField_ref().value(), b.myFloatField_ref().value());
swap(a.__isset, b.__isset);
}
template void MyStructFloatFieldThrowExp::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
template uint32_t MyStructFloatFieldThrowExp::write<>(apache::thrift::BinaryProtocolWriter*) const;
template uint32_t MyStructFloatFieldThrowExp::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
template uint32_t MyStructFloatFieldThrowExp::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
template void MyStructFloatFieldThrowExp::readNoXfer<>(apache::thrift::CompactProtocolReader*);
template uint32_t MyStructFloatFieldThrowExp::write<>(apache::thrift::CompactProtocolWriter*) const;
template uint32_t MyStructFloatFieldThrowExp::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
template uint32_t MyStructFloatFieldThrowExp::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
} // cpp2
namespace apache {
namespace thrift {
namespace detail {
void TccStructTraits<::cpp2::SimpleStruct>::translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept {
using data = apache::thrift::TStructDataStorage<::cpp2::SimpleStruct>;
static const st::translate_field_name_table table{
data::fields_size,
data::fields_names.data(),
data::fields_ids.data(),
data::fields_types.data()};
st::translate_field_name(_fname, fid, _ftype, table);
}
} // namespace detail
} // namespace thrift
} // namespace apache
namespace cpp2 {
SimpleStruct::SimpleStruct(const SimpleStruct&) = default;
SimpleStruct& SimpleStruct::operator=(const SimpleStruct&) = default;
SimpleStruct::SimpleStruct(SimpleStruct&& other) noexcept :
__fbthrift_field_age(std::move(other.__fbthrift_field_age)),
__fbthrift_field_name(std::move(other.__fbthrift_field_name)),
__isset(other.__isset) {
}
SimpleStruct& SimpleStruct::operator=(FOLLY_MAYBE_UNUSED SimpleStruct&& other) noexcept {
this->__fbthrift_field_age = std::move(other.__fbthrift_field_age);
this->__fbthrift_field_name = std::move(other.__fbthrift_field_name);
__isset = other.__isset;
return *this;
}
SimpleStruct::SimpleStruct(apache::thrift::FragileConstructor, ::std::int64_t age__arg, ::std::string name__arg) :
__fbthrift_field_age(std::move(age__arg)),
__fbthrift_field_name(std::move(name__arg)) {
__isset.set(folly::index_constant<0>(), true);
__isset.set(folly::index_constant<1>(), true);
}
void SimpleStruct::__clear() {
// clear all fields
this->__fbthrift_field_age = static_cast<::std::int64_t>(60);
this->__fbthrift_field_name = apache::thrift::StringTraits<std::string>::fromStringLiteral("Batman");
__isset = {};
}
bool SimpleStruct::operator==(const SimpleStruct& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.age_ref() == rhs.age_ref())) {
return false;
}
if (!(lhs.name_ref() == rhs.name_ref())) {
return false;
}
return true;
}
bool SimpleStruct::operator<(const SimpleStruct& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.age_ref() == rhs.age_ref())) {
return lhs.age_ref() < rhs.age_ref();
}
if (!(lhs.name_ref() == rhs.name_ref())) {
return lhs.name_ref() < rhs.name_ref();
}
return false;
}
void swap(SimpleStruct& a, SimpleStruct& b) {
using ::std::swap;
swap(a.age_ref().value(), b.age_ref().value());
swap(a.name_ref().value(), b.name_ref().value());
swap(a.__isset, b.__isset);
}
template void SimpleStruct::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
template uint32_t SimpleStruct::write<>(apache::thrift::BinaryProtocolWriter*) const;
template uint32_t SimpleStruct::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
template uint32_t SimpleStruct::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
template void SimpleStruct::readNoXfer<>(apache::thrift::CompactProtocolReader*);
template uint32_t SimpleStruct::write<>(apache::thrift::CompactProtocolWriter*) const;
template uint32_t SimpleStruct::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
template uint32_t SimpleStruct::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
} // cpp2
namespace apache {
namespace thrift {
namespace detail {
void TccStructTraits<::cpp2::MyDataItem>::translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept {
using data = apache::thrift::TStructDataStorage<::cpp2::MyDataItem>;
static const st::translate_field_name_table table{
data::fields_size,
data::fields_names.data(),
data::fields_ids.data(),
data::fields_types.data()};
st::translate_field_name(_fname, fid, _ftype, table);
}
} // namespace detail
} // namespace thrift
} // namespace apache
namespace cpp2 {
MyDataItem::MyDataItem(apache::thrift::FragileConstructor) {}
void MyDataItem::__clear() {
// clear all fields
}
bool MyDataItem::operator==(const MyDataItem& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
return true;
}
bool MyDataItem::operator<(const MyDataItem& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
return false;
}
void swap(MyDataItem& a, MyDataItem& b) {
using ::std::swap;
(void)a;
(void)b;
}
template void MyDataItem::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
template uint32_t MyDataItem::write<>(apache::thrift::BinaryProtocolWriter*) const;
template uint32_t MyDataItem::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
template uint32_t MyDataItem::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
template void MyDataItem::readNoXfer<>(apache::thrift::CompactProtocolReader*);
template uint32_t MyDataItem::write<>(apache::thrift::CompactProtocolWriter*) const;
template uint32_t MyDataItem::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
template uint32_t MyDataItem::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
} // cpp2
namespace apache {
namespace thrift {
namespace detail {
void TccStructTraits<::cpp2::ComplexNestedStruct>::translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept {
using data = apache::thrift::TStructDataStorage<::cpp2::ComplexNestedStruct>;
static const st::translate_field_name_table table{
data::fields_size,
data::fields_names.data(),
data::fields_ids.data(),
data::fields_types.data()};
st::translate_field_name(_fname, fid, _ftype, table);
}
} // namespace detail
} // namespace thrift
} // namespace apache
namespace cpp2 {
ComplexNestedStruct::ComplexNestedStruct(const ComplexNestedStruct&) = default;
ComplexNestedStruct& ComplexNestedStruct::operator=(const ComplexNestedStruct&) = default;
ComplexNestedStruct::ComplexNestedStruct() {
}
ComplexNestedStruct::~ComplexNestedStruct() {}
ComplexNestedStruct::ComplexNestedStruct(ComplexNestedStruct&& other) noexcept :
__fbthrift_field_setOfSetOfInt(std::move(other.__fbthrift_field_setOfSetOfInt)),
__fbthrift_field_listofListOfListOfListOfEnum(std::move(other.__fbthrift_field_listofListOfListOfListOfEnum)),
__fbthrift_field_listOfListOfMyStruct(std::move(other.__fbthrift_field_listOfListOfMyStruct)),
__fbthrift_field_setOfListOfListOfLong(std::move(other.__fbthrift_field_setOfListOfListOfLong)),
__fbthrift_field_setOfSetOfsetOfLong(std::move(other.__fbthrift_field_setOfSetOfsetOfLong)),
__fbthrift_field_mapStructListOfListOfLong(std::move(other.__fbthrift_field_mapStructListOfListOfLong)),
__fbthrift_field_mKeyStructValInt(std::move(other.__fbthrift_field_mKeyStructValInt)),
__fbthrift_field_listOfMapKeyIntValInt(std::move(other.__fbthrift_field_listOfMapKeyIntValInt)),
__fbthrift_field_listOfMapKeyStrValList(std::move(other.__fbthrift_field_listOfMapKeyStrValList)),
__fbthrift_field_mapKeySetValLong(std::move(other.__fbthrift_field_mapKeySetValLong)),
__fbthrift_field_mapKeyListValLong(std::move(other.__fbthrift_field_mapKeyListValLong)),
__fbthrift_field_mapKeyMapValMap(std::move(other.__fbthrift_field_mapKeyMapValMap)),
__fbthrift_field_mapKeySetValMap(std::move(other.__fbthrift_field_mapKeySetValMap)),
__fbthrift_field_NestedMaps(std::move(other.__fbthrift_field_NestedMaps)),
__fbthrift_field_mapKeyIntValList(std::move(other.__fbthrift_field_mapKeyIntValList)),
__fbthrift_field_mapKeyIntValSet(std::move(other.__fbthrift_field_mapKeyIntValSet)),
__fbthrift_field_mapKeySetValInt(std::move(other.__fbthrift_field_mapKeySetValInt)),
__fbthrift_field_mapKeyListValSet(std::move(other.__fbthrift_field_mapKeyListValSet)),
__isset(other.__isset) {
}
ComplexNestedStruct& ComplexNestedStruct::operator=(FOLLY_MAYBE_UNUSED ComplexNestedStruct&& other) noexcept {
this->__fbthrift_field_setOfSetOfInt = std::move(other.__fbthrift_field_setOfSetOfInt);
this->__fbthrift_field_listofListOfListOfListOfEnum = std::move(other.__fbthrift_field_listofListOfListOfListOfEnum);
this->__fbthrift_field_listOfListOfMyStruct = std::move(other.__fbthrift_field_listOfListOfMyStruct);
this->__fbthrift_field_setOfListOfListOfLong = std::move(other.__fbthrift_field_setOfListOfListOfLong);
this->__fbthrift_field_setOfSetOfsetOfLong = std::move(other.__fbthrift_field_setOfSetOfsetOfLong);
this->__fbthrift_field_mapStructListOfListOfLong = std::move(other.__fbthrift_field_mapStructListOfListOfLong);
this->__fbthrift_field_mKeyStructValInt = std::move(other.__fbthrift_field_mKeyStructValInt);
this->__fbthrift_field_listOfMapKeyIntValInt = std::move(other.__fbthrift_field_listOfMapKeyIntValInt);
this->__fbthrift_field_listOfMapKeyStrValList = std::move(other.__fbthrift_field_listOfMapKeyStrValList);
this->__fbthrift_field_mapKeySetValLong = std::move(other.__fbthrift_field_mapKeySetValLong);
this->__fbthrift_field_mapKeyListValLong = std::move(other.__fbthrift_field_mapKeyListValLong);
this->__fbthrift_field_mapKeyMapValMap = std::move(other.__fbthrift_field_mapKeyMapValMap);
this->__fbthrift_field_mapKeySetValMap = std::move(other.__fbthrift_field_mapKeySetValMap);
this->__fbthrift_field_NestedMaps = std::move(other.__fbthrift_field_NestedMaps);
this->__fbthrift_field_mapKeyIntValList = std::move(other.__fbthrift_field_mapKeyIntValList);
this->__fbthrift_field_mapKeyIntValSet = std::move(other.__fbthrift_field_mapKeyIntValSet);
this->__fbthrift_field_mapKeySetValInt = std::move(other.__fbthrift_field_mapKeySetValInt);
this->__fbthrift_field_mapKeyListValSet = std::move(other.__fbthrift_field_mapKeyListValSet);
__isset = other.__isset;
return *this;
}
ComplexNestedStruct::ComplexNestedStruct(apache::thrift::FragileConstructor, ::std::set<::std::set<::std::int32_t>> setOfSetOfInt__arg, ::std::vector<::std::vector<::std::vector<::std::vector<::cpp2::MyEnum>>>> listofListOfListOfListOfEnum__arg, ::std::vector<::std::vector<::cpp2::MyStruct>> listOfListOfMyStruct__arg, ::std::set<::std::vector<::std::vector<::std::int64_t>>> setOfListOfListOfLong__arg, ::std::set<::std::set<::std::set<::std::int64_t>>> setOfSetOfsetOfLong__arg, ::std::map<::std::int32_t, ::std::vector<::std::vector<::cpp2::MyStruct>>> mapStructListOfListOfLong__arg, ::std::map<::cpp2::MyStruct, ::std::int32_t> mKeyStructValInt__arg, ::std::vector<::std::map<::std::int32_t, ::std::int32_t>> listOfMapKeyIntValInt__arg, ::std::vector<::std::map<::std::string, ::std::vector<::cpp2::MyStruct>>> listOfMapKeyStrValList__arg, ::std::map<::std::set<::std::int32_t>, ::std::int64_t> mapKeySetValLong__arg, ::std::map<::std::vector<::std::string>, ::std::int32_t> mapKeyListValLong__arg, ::std::map<::std::map<::std::int32_t, ::std::string>, ::std::map<::std::int32_t, ::std::string>> mapKeyMapValMap__arg, ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>> mapKeySetValMap__arg, ::std::map<::std::map<::std::map<::std::int32_t, ::std::string>, ::std::string>, ::std::map<::std::int32_t, ::std::string>> NestedMaps__arg, ::std::map<::std::int32_t, ::std::vector<::cpp2::MyStruct>> mapKeyIntValList__arg, ::std::map<::std::int32_t, ::std::set<bool>> mapKeyIntValSet__arg, ::std::map<::std::set<bool>, ::cpp2::MyEnum> mapKeySetValInt__arg, ::std::map<::std::vector<::std::int32_t>, ::std::set<::std::map<double, ::std::string>>> mapKeyListValSet__arg) :
__fbthrift_field_setOfSetOfInt(std::move(setOfSetOfInt__arg)),
__fbthrift_field_listofListOfListOfListOfEnum(std::move(listofListOfListOfListOfEnum__arg)),
__fbthrift_field_listOfListOfMyStruct(std::move(listOfListOfMyStruct__arg)),
__fbthrift_field_setOfListOfListOfLong(std::move(setOfListOfListOfLong__arg)),
__fbthrift_field_setOfSetOfsetOfLong(std::move(setOfSetOfsetOfLong__arg)),
__fbthrift_field_mapStructListOfListOfLong(std::move(mapStructListOfListOfLong__arg)),
__fbthrift_field_mKeyStructValInt(std::move(mKeyStructValInt__arg)),
__fbthrift_field_listOfMapKeyIntValInt(std::move(listOfMapKeyIntValInt__arg)),
__fbthrift_field_listOfMapKeyStrValList(std::move(listOfMapKeyStrValList__arg)),
__fbthrift_field_mapKeySetValLong(std::move(mapKeySetValLong__arg)),
__fbthrift_field_mapKeyListValLong(std::move(mapKeyListValLong__arg)),
__fbthrift_field_mapKeyMapValMap(std::move(mapKeyMapValMap__arg)),
__fbthrift_field_mapKeySetValMap(std::move(mapKeySetValMap__arg)),
__fbthrift_field_NestedMaps(std::move(NestedMaps__arg)),
__fbthrift_field_mapKeyIntValList(std::move(mapKeyIntValList__arg)),
__fbthrift_field_mapKeyIntValSet(std::move(mapKeyIntValSet__arg)),
__fbthrift_field_mapKeySetValInt(std::move(mapKeySetValInt__arg)),
__fbthrift_field_mapKeyListValSet(std::move(mapKeyListValSet__arg)) {
__isset.set(folly::index_constant<0>(), true);
__isset.set(folly::index_constant<1>(), true);
__isset.set(folly::index_constant<2>(), true);
__isset.set(folly::index_constant<3>(), true);
__isset.set(folly::index_constant<4>(), true);
__isset.set(folly::index_constant<5>(), true);
__isset.set(folly::index_constant<6>(), true);
__isset.set(folly::index_constant<7>(), true);
__isset.set(folly::index_constant<8>(), true);
__isset.set(folly::index_constant<9>(), true);
__isset.set(folly::index_constant<10>(), true);
__isset.set(folly::index_constant<11>(), true);
__isset.set(folly::index_constant<12>(), true);
__isset.set(folly::index_constant<13>(), true);
__isset.set(folly::index_constant<14>(), true);
__isset.set(folly::index_constant<15>(), true);
__isset.set(folly::index_constant<16>(), true);
__isset.set(folly::index_constant<17>(), true);
}
void ComplexNestedStruct::__clear() {
// clear all fields
this->__fbthrift_field_setOfSetOfInt.clear();
this->__fbthrift_field_listofListOfListOfListOfEnum.clear();
this->__fbthrift_field_listOfListOfMyStruct.clear();
this->__fbthrift_field_setOfListOfListOfLong.clear();
this->__fbthrift_field_setOfSetOfsetOfLong.clear();
this->__fbthrift_field_mapStructListOfListOfLong.clear();
this->__fbthrift_field_mKeyStructValInt.clear();
this->__fbthrift_field_listOfMapKeyIntValInt.clear();
this->__fbthrift_field_listOfMapKeyStrValList.clear();
this->__fbthrift_field_mapKeySetValLong.clear();
this->__fbthrift_field_mapKeyListValLong.clear();
this->__fbthrift_field_mapKeyMapValMap.clear();
this->__fbthrift_field_mapKeySetValMap.clear();
this->__fbthrift_field_NestedMaps.clear();
this->__fbthrift_field_mapKeyIntValList.clear();
this->__fbthrift_field_mapKeyIntValSet.clear();
this->__fbthrift_field_mapKeySetValInt.clear();
this->__fbthrift_field_mapKeyListValSet.clear();
__isset = {};
}
bool ComplexNestedStruct::operator==(const ComplexNestedStruct& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.setOfSetOfInt_ref() == rhs.setOfSetOfInt_ref())) {
return false;
}
if (!(lhs.listofListOfListOfListOfEnum_ref() == rhs.listofListOfListOfListOfEnum_ref())) {
return false;
}
if (!(lhs.listOfListOfMyStruct_ref() == rhs.listOfListOfMyStruct_ref())) {
return false;
}
if (!(lhs.setOfListOfListOfLong_ref() == rhs.setOfListOfListOfLong_ref())) {
return false;
}
if (!(lhs.setOfSetOfsetOfLong_ref() == rhs.setOfSetOfsetOfLong_ref())) {
return false;
}
if (!(lhs.mapStructListOfListOfLong_ref() == rhs.mapStructListOfListOfLong_ref())) {
return false;
}
if (!(lhs.mKeyStructValInt_ref() == rhs.mKeyStructValInt_ref())) {
return false;
}
if (!(lhs.listOfMapKeyIntValInt_ref() == rhs.listOfMapKeyIntValInt_ref())) {
return false;
}
if (!(lhs.listOfMapKeyStrValList_ref() == rhs.listOfMapKeyStrValList_ref())) {
return false;
}
if (!(lhs.mapKeySetValLong_ref() == rhs.mapKeySetValLong_ref())) {
return false;
}
if (!(lhs.mapKeyListValLong_ref() == rhs.mapKeyListValLong_ref())) {
return false;
}
if (!(lhs.mapKeyMapValMap_ref() == rhs.mapKeyMapValMap_ref())) {
return false;
}
if (!(lhs.mapKeySetValMap_ref() == rhs.mapKeySetValMap_ref())) {
return false;
}
if (!(lhs.NestedMaps_ref() == rhs.NestedMaps_ref())) {
return false;
}
if (!(lhs.mapKeyIntValList_ref() == rhs.mapKeyIntValList_ref())) {
return false;
}
if (!(lhs.mapKeyIntValSet_ref() == rhs.mapKeyIntValSet_ref())) {
return false;
}
if (!(lhs.mapKeySetValInt_ref() == rhs.mapKeySetValInt_ref())) {
return false;
}
if (!(lhs.mapKeyListValSet_ref() == rhs.mapKeyListValSet_ref())) {
return false;
}
return true;
}
bool ComplexNestedStruct::operator<(const ComplexNestedStruct& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.setOfSetOfInt_ref() == rhs.setOfSetOfInt_ref())) {
return lhs.setOfSetOfInt_ref() < rhs.setOfSetOfInt_ref();
}
if (!(lhs.listofListOfListOfListOfEnum_ref() == rhs.listofListOfListOfListOfEnum_ref())) {
return lhs.listofListOfListOfListOfEnum_ref() < rhs.listofListOfListOfListOfEnum_ref();
}
if (!(lhs.listOfListOfMyStruct_ref() == rhs.listOfListOfMyStruct_ref())) {
return lhs.listOfListOfMyStruct_ref() < rhs.listOfListOfMyStruct_ref();
}
if (!(lhs.setOfListOfListOfLong_ref() == rhs.setOfListOfListOfLong_ref())) {
return lhs.setOfListOfListOfLong_ref() < rhs.setOfListOfListOfLong_ref();
}
if (!(lhs.setOfSetOfsetOfLong_ref() == rhs.setOfSetOfsetOfLong_ref())) {
return lhs.setOfSetOfsetOfLong_ref() < rhs.setOfSetOfsetOfLong_ref();
}
if (!(lhs.mapStructListOfListOfLong_ref() == rhs.mapStructListOfListOfLong_ref())) {
return lhs.mapStructListOfListOfLong_ref() < rhs.mapStructListOfListOfLong_ref();
}
if (!(lhs.mKeyStructValInt_ref() == rhs.mKeyStructValInt_ref())) {
return lhs.mKeyStructValInt_ref() < rhs.mKeyStructValInt_ref();
}
if (!(lhs.listOfMapKeyIntValInt_ref() == rhs.listOfMapKeyIntValInt_ref())) {
return lhs.listOfMapKeyIntValInt_ref() < rhs.listOfMapKeyIntValInt_ref();
}
if (!(lhs.listOfMapKeyStrValList_ref() == rhs.listOfMapKeyStrValList_ref())) {
return lhs.listOfMapKeyStrValList_ref() < rhs.listOfMapKeyStrValList_ref();
}
if (!(lhs.mapKeySetValLong_ref() == rhs.mapKeySetValLong_ref())) {
return lhs.mapKeySetValLong_ref() < rhs.mapKeySetValLong_ref();
}
if (!(lhs.mapKeyListValLong_ref() == rhs.mapKeyListValLong_ref())) {
return lhs.mapKeyListValLong_ref() < rhs.mapKeyListValLong_ref();
}
if (!(lhs.mapKeyMapValMap_ref() == rhs.mapKeyMapValMap_ref())) {
return lhs.mapKeyMapValMap_ref() < rhs.mapKeyMapValMap_ref();
}
if (!(lhs.mapKeySetValMap_ref() == rhs.mapKeySetValMap_ref())) {
return lhs.mapKeySetValMap_ref() < rhs.mapKeySetValMap_ref();
}
if (!(lhs.NestedMaps_ref() == rhs.NestedMaps_ref())) {
return lhs.NestedMaps_ref() < rhs.NestedMaps_ref();
}
if (!(lhs.mapKeyIntValList_ref() == rhs.mapKeyIntValList_ref())) {
return lhs.mapKeyIntValList_ref() < rhs.mapKeyIntValList_ref();
}
if (!(lhs.mapKeyIntValSet_ref() == rhs.mapKeyIntValSet_ref())) {
return lhs.mapKeyIntValSet_ref() < rhs.mapKeyIntValSet_ref();
}
if (!(lhs.mapKeySetValInt_ref() == rhs.mapKeySetValInt_ref())) {
return lhs.mapKeySetValInt_ref() < rhs.mapKeySetValInt_ref();
}
if (!(lhs.mapKeyListValSet_ref() == rhs.mapKeyListValSet_ref())) {
return lhs.mapKeyListValSet_ref() < rhs.mapKeyListValSet_ref();
}
return false;
}
const ::std::set<::std::set<::std::int32_t>>& ComplexNestedStruct::get_setOfSetOfInt() const& {
return __fbthrift_field_setOfSetOfInt;
}
::std::set<::std::set<::std::int32_t>> ComplexNestedStruct::get_setOfSetOfInt() && {
return std::move(__fbthrift_field_setOfSetOfInt);
}
const ::std::vector<::std::vector<::std::vector<::std::vector<::cpp2::MyEnum>>>>& ComplexNestedStruct::get_listofListOfListOfListOfEnum() const& {
return __fbthrift_field_listofListOfListOfListOfEnum;
}
::std::vector<::std::vector<::std::vector<::std::vector<::cpp2::MyEnum>>>> ComplexNestedStruct::get_listofListOfListOfListOfEnum() && {
return std::move(__fbthrift_field_listofListOfListOfListOfEnum);
}
const ::std::vector<::std::vector<::cpp2::MyStruct>>& ComplexNestedStruct::get_listOfListOfMyStruct() const& {
return __fbthrift_field_listOfListOfMyStruct;
}
::std::vector<::std::vector<::cpp2::MyStruct>> ComplexNestedStruct::get_listOfListOfMyStruct() && {
return std::move(__fbthrift_field_listOfListOfMyStruct);
}
const ::std::set<::std::vector<::std::vector<::std::int64_t>>>& ComplexNestedStruct::get_setOfListOfListOfLong() const& {
return __fbthrift_field_setOfListOfListOfLong;
}
::std::set<::std::vector<::std::vector<::std::int64_t>>> ComplexNestedStruct::get_setOfListOfListOfLong() && {
return std::move(__fbthrift_field_setOfListOfListOfLong);
}
const ::std::set<::std::set<::std::set<::std::int64_t>>>& ComplexNestedStruct::get_setOfSetOfsetOfLong() const& {
return __fbthrift_field_setOfSetOfsetOfLong;
}
::std::set<::std::set<::std::set<::std::int64_t>>> ComplexNestedStruct::get_setOfSetOfsetOfLong() && {
return std::move(__fbthrift_field_setOfSetOfsetOfLong);
}
const ::std::map<::std::int32_t, ::std::vector<::std::vector<::cpp2::MyStruct>>>& ComplexNestedStruct::get_mapStructListOfListOfLong() const& {
return __fbthrift_field_mapStructListOfListOfLong;
}
::std::map<::std::int32_t, ::std::vector<::std::vector<::cpp2::MyStruct>>> ComplexNestedStruct::get_mapStructListOfListOfLong() && {
return std::move(__fbthrift_field_mapStructListOfListOfLong);
}
const ::std::map<::cpp2::MyStruct, ::std::int32_t>& ComplexNestedStruct::get_mKeyStructValInt() const& {
return __fbthrift_field_mKeyStructValInt;
}
::std::map<::cpp2::MyStruct, ::std::int32_t> ComplexNestedStruct::get_mKeyStructValInt() && {
return std::move(__fbthrift_field_mKeyStructValInt);
}
const ::std::vector<::std::map<::std::int32_t, ::std::int32_t>>& ComplexNestedStruct::get_listOfMapKeyIntValInt() const& {
return __fbthrift_field_listOfMapKeyIntValInt;
}
::std::vector<::std::map<::std::int32_t, ::std::int32_t>> ComplexNestedStruct::get_listOfMapKeyIntValInt() && {
return std::move(__fbthrift_field_listOfMapKeyIntValInt);
}
const ::std::vector<::std::map<::std::string, ::std::vector<::cpp2::MyStruct>>>& ComplexNestedStruct::get_listOfMapKeyStrValList() const& {
return __fbthrift_field_listOfMapKeyStrValList;
}
::std::vector<::std::map<::std::string, ::std::vector<::cpp2::MyStruct>>> ComplexNestedStruct::get_listOfMapKeyStrValList() && {
return std::move(__fbthrift_field_listOfMapKeyStrValList);
}
const ::std::map<::std::set<::std::int32_t>, ::std::int64_t>& ComplexNestedStruct::get_mapKeySetValLong() const& {
return __fbthrift_field_mapKeySetValLong;
}
::std::map<::std::set<::std::int32_t>, ::std::int64_t> ComplexNestedStruct::get_mapKeySetValLong() && {
return std::move(__fbthrift_field_mapKeySetValLong);
}
const ::std::map<::std::vector<::std::string>, ::std::int32_t>& ComplexNestedStruct::get_mapKeyListValLong() const& {
return __fbthrift_field_mapKeyListValLong;
}
::std::map<::std::vector<::std::string>, ::std::int32_t> ComplexNestedStruct::get_mapKeyListValLong() && {
return std::move(__fbthrift_field_mapKeyListValLong);
}
const ::std::map<::std::map<::std::int32_t, ::std::string>, ::std::map<::std::int32_t, ::std::string>>& ComplexNestedStruct::get_mapKeyMapValMap() const& {
return __fbthrift_field_mapKeyMapValMap;
}
::std::map<::std::map<::std::int32_t, ::std::string>, ::std::map<::std::int32_t, ::std::string>> ComplexNestedStruct::get_mapKeyMapValMap() && {
return std::move(__fbthrift_field_mapKeyMapValMap);
}
const ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>& ComplexNestedStruct::get_mapKeySetValMap() const& {
return __fbthrift_field_mapKeySetValMap;
}
::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>> ComplexNestedStruct::get_mapKeySetValMap() && {
return std::move(__fbthrift_field_mapKeySetValMap);
}
const ::std::map<::std::map<::std::map<::std::int32_t, ::std::string>, ::std::string>, ::std::map<::std::int32_t, ::std::string>>& ComplexNestedStruct::get_NestedMaps() const& {
return __fbthrift_field_NestedMaps;
}
::std::map<::std::map<::std::map<::std::int32_t, ::std::string>, ::std::string>, ::std::map<::std::int32_t, ::std::string>> ComplexNestedStruct::get_NestedMaps() && {
return std::move(__fbthrift_field_NestedMaps);
}
const ::std::map<::std::int32_t, ::std::vector<::cpp2::MyStruct>>& ComplexNestedStruct::get_mapKeyIntValList() const& {
return __fbthrift_field_mapKeyIntValList;
}
::std::map<::std::int32_t, ::std::vector<::cpp2::MyStruct>> ComplexNestedStruct::get_mapKeyIntValList() && {
return std::move(__fbthrift_field_mapKeyIntValList);
}
const ::std::map<::std::int32_t, ::std::set<bool>>& ComplexNestedStruct::get_mapKeyIntValSet() const& {
return __fbthrift_field_mapKeyIntValSet;
}
::std::map<::std::int32_t, ::std::set<bool>> ComplexNestedStruct::get_mapKeyIntValSet() && {
return std::move(__fbthrift_field_mapKeyIntValSet);
}
const ::std::map<::std::set<bool>, ::cpp2::MyEnum>& ComplexNestedStruct::get_mapKeySetValInt() const& {
return __fbthrift_field_mapKeySetValInt;
}
::std::map<::std::set<bool>, ::cpp2::MyEnum> ComplexNestedStruct::get_mapKeySetValInt() && {
return std::move(__fbthrift_field_mapKeySetValInt);
}
const ::std::map<::std::vector<::std::int32_t>, ::std::set<::std::map<double, ::std::string>>>& ComplexNestedStruct::get_mapKeyListValSet() const& {
return __fbthrift_field_mapKeyListValSet;
}
::std::map<::std::vector<::std::int32_t>, ::std::set<::std::map<double, ::std::string>>> ComplexNestedStruct::get_mapKeyListValSet() && {
return std::move(__fbthrift_field_mapKeyListValSet);
}
void swap(ComplexNestedStruct& a, ComplexNestedStruct& b) {
using ::std::swap;
swap(a.setOfSetOfInt_ref().value(), b.setOfSetOfInt_ref().value());
swap(a.listofListOfListOfListOfEnum_ref().value(), b.listofListOfListOfListOfEnum_ref().value());
swap(a.listOfListOfMyStruct_ref().value(), b.listOfListOfMyStruct_ref().value());
swap(a.setOfListOfListOfLong_ref().value(), b.setOfListOfListOfLong_ref().value());
swap(a.setOfSetOfsetOfLong_ref().value(), b.setOfSetOfsetOfLong_ref().value());
swap(a.mapStructListOfListOfLong_ref().value(), b.mapStructListOfListOfLong_ref().value());
swap(a.mKeyStructValInt_ref().value(), b.mKeyStructValInt_ref().value());
swap(a.listOfMapKeyIntValInt_ref().value(), b.listOfMapKeyIntValInt_ref().value());
swap(a.listOfMapKeyStrValList_ref().value(), b.listOfMapKeyStrValList_ref().value());
swap(a.mapKeySetValLong_ref().value(), b.mapKeySetValLong_ref().value());
swap(a.mapKeyListValLong_ref().value(), b.mapKeyListValLong_ref().value());
swap(a.mapKeyMapValMap_ref().value(), b.mapKeyMapValMap_ref().value());
swap(a.mapKeySetValMap_ref().value(), b.mapKeySetValMap_ref().value());
swap(a.NestedMaps_ref().value(), b.NestedMaps_ref().value());
swap(a.mapKeyIntValList_ref().value(), b.mapKeyIntValList_ref().value());
swap(a.mapKeyIntValSet_ref().value(), b.mapKeyIntValSet_ref().value());
swap(a.mapKeySetValInt_ref().value(), b.mapKeySetValInt_ref().value());
swap(a.mapKeyListValSet_ref().value(), b.mapKeyListValSet_ref().value());
swap(a.__isset, b.__isset);
}
template void ComplexNestedStruct::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
template uint32_t ComplexNestedStruct::write<>(apache::thrift::BinaryProtocolWriter*) const;
template uint32_t ComplexNestedStruct::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
template uint32_t ComplexNestedStruct::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
template void ComplexNestedStruct::readNoXfer<>(apache::thrift::CompactProtocolReader*);
template uint32_t ComplexNestedStruct::write<>(apache::thrift::CompactProtocolWriter*) const;
template uint32_t ComplexNestedStruct::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
template uint32_t ComplexNestedStruct::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
static_assert(
::apache::thrift::detail::st::gen_check_json<
ComplexNestedStruct,
::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>,
::std::vector<::std::vector<::cpp2::MyStruct>>>,
"inconsistent use of json option");
static_assert(
::apache::thrift::detail::st::gen_check_json<
ComplexNestedStruct,
::apache::thrift::type_class::map<::apache::thrift::type_class::integral, ::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>>,
::std::map<::std::int32_t, ::std::vector<::std::vector<::cpp2::MyStruct>>>>,
"inconsistent use of json option");
static_assert(
::apache::thrift::detail::st::gen_check_json<
ComplexNestedStruct,
::apache::thrift::type_class::map<::apache::thrift::type_class::structure, ::apache::thrift::type_class::integral>,
::std::map<::cpp2::MyStruct, ::std::int32_t>>,
"inconsistent use of json option");
static_assert(
::apache::thrift::detail::st::gen_check_json<
ComplexNestedStruct,
::apache::thrift::type_class::list<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>>,
::std::vector<::std::map<::std::string, ::std::vector<::cpp2::MyStruct>>>>,
"inconsistent use of json option");
static_assert(
::apache::thrift::detail::st::gen_check_json<
ComplexNestedStruct,
::apache::thrift::type_class::map<::apache::thrift::type_class::integral, ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>,
::std::map<::std::int32_t, ::std::vector<::cpp2::MyStruct>>>,
"inconsistent use of json option");
static_assert(
::apache::thrift::detail::st::gen_check_nimble<
ComplexNestedStruct,
::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>,
::std::vector<::std::vector<::cpp2::MyStruct>>>,
"inconsistent use of nimble option");
static_assert(
::apache::thrift::detail::st::gen_check_nimble<
ComplexNestedStruct,
::apache::thrift::type_class::map<::apache::thrift::type_class::integral, ::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>>,
::std::map<::std::int32_t, ::std::vector<::std::vector<::cpp2::MyStruct>>>>,
"inconsistent use of nimble option");
static_assert(
::apache::thrift::detail::st::gen_check_nimble<
ComplexNestedStruct,
::apache::thrift::type_class::map<::apache::thrift::type_class::structure, ::apache::thrift::type_class::integral>,
::std::map<::cpp2::MyStruct, ::std::int32_t>>,
"inconsistent use of nimble option");
static_assert(
::apache::thrift::detail::st::gen_check_nimble<
ComplexNestedStruct,
::apache::thrift::type_class::list<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>>,
::std::vector<::std::map<::std::string, ::std::vector<::cpp2::MyStruct>>>>,
"inconsistent use of nimble option");
static_assert(
::apache::thrift::detail::st::gen_check_nimble<
ComplexNestedStruct,
::apache::thrift::type_class::map<::apache::thrift::type_class::integral, ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>>,
::std::map<::std::int32_t, ::std::vector<::cpp2::MyStruct>>>,
"inconsistent use of nimble option");
} // cpp2
namespace apache {
namespace thrift {
namespace detail {
void TccStructTraits<::cpp2::reqXcep>::translateFieldName(
folly::StringPiece _fname,
int16_t& fid,
apache::thrift::protocol::TType& _ftype) noexcept {
using data = apache::thrift::TStructDataStorage<::cpp2::reqXcep>;
static const st::translate_field_name_table table{
data::fields_size,
data::fields_names.data(),
data::fields_ids.data(),
data::fields_types.data()};
st::translate_field_name(_fname, fid, _ftype, table);
}
} // namespace detail
} // namespace thrift
} // namespace apache
namespace cpp2 {
reqXcep::reqXcep(const reqXcep&) = default;
reqXcep& reqXcep::operator=(const reqXcep&) = default;
reqXcep::reqXcep() :
errorCode() {
}
reqXcep::~reqXcep() {}
reqXcep::reqXcep(reqXcep&& other) noexcept :
message(std::move(other.message)),
errorCode(std::move(other.errorCode)) {
}
reqXcep& reqXcep::operator=(FOLLY_MAYBE_UNUSED reqXcep&& other) noexcept {
this->message = std::move(other.message);
this->errorCode = std::move(other.errorCode);
return *this;
}
reqXcep::reqXcep(apache::thrift::FragileConstructor, ::std::string message__arg, ::std::int32_t errorCode__arg) :
message(std::move(message__arg)),
errorCode(std::move(errorCode__arg)) {
}
void reqXcep::__clear() {
// clear all fields
this->message = apache::thrift::StringTraits<std::string>::fromStringLiteral("");
this->errorCode = ::std::int32_t();
}
bool reqXcep::operator==(const reqXcep& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.message_ref() == rhs.message_ref())) {
return false;
}
if (!(lhs.errorCode_ref() == rhs.errorCode_ref())) {
return false;
}
return true;
}
bool reqXcep::operator<(const reqXcep& rhs) const {
(void)rhs;
auto& lhs = *this;
(void)lhs;
if (!(lhs.message_ref() == rhs.message_ref())) {
return lhs.message_ref() < rhs.message_ref();
}
if (!(lhs.errorCode_ref() == rhs.errorCode_ref())) {
return lhs.errorCode_ref() < rhs.errorCode_ref();
}
return false;
}
void swap(reqXcep& a, reqXcep& b) {
using ::std::swap;
swap(a.message_ref().value(), b.message_ref().value());
swap(a.errorCode_ref().value(), b.errorCode_ref().value());
}
template void reqXcep::readNoXfer<>(apache::thrift::BinaryProtocolReader*);
template uint32_t reqXcep::write<>(apache::thrift::BinaryProtocolWriter*) const;
template uint32_t reqXcep::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const;
template uint32_t reqXcep::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const;
template void reqXcep::readNoXfer<>(apache::thrift::CompactProtocolReader*);
template uint32_t reqXcep::write<>(apache::thrift::CompactProtocolWriter*) const;
template uint32_t reqXcep::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const;
template uint32_t reqXcep::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const;
} // cpp2
namespace cpp2 { namespace {
FOLLY_MAYBE_UNUSED FOLLY_ERASE void validateAdapters() {
}
}} // cpp2
| 44.577004 | 1,740 | 0.741073 | [
"vector"
] |
151d076d40bd9db5cd34ebe27bfb993a13b5deac | 5,763 | cpp | C++ | examples_oldgl_glfw/624_DefArapUi/main.cpp | nobuyuki83/delfem2 | 118768431ccc5b77ed10b8f76f625d38e0b552f0 | [
"MIT"
] | 153 | 2018-08-16T21:51:33.000Z | 2022-03-28T10:34:48.000Z | examples_oldgl_glfw/624_DefArapUi/main.cpp | nobuyuki83/delfem2 | 118768431ccc5b77ed10b8f76f625d38e0b552f0 | [
"MIT"
] | 63 | 2018-08-16T21:53:34.000Z | 2022-02-22T13:50:34.000Z | examples_oldgl_glfw/624_DefArapUi/main.cpp | nobuyuki83/delfem2 | 118768431ccc5b77ed10b8f76f625d38e0b552f0 | [
"MIT"
] | 18 | 2018-12-17T05:39:15.000Z | 2021-11-16T08:21:16.000Z | /*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#if defined(_WIN32) // windows
# define NOMINMAX // to remove min,max macro
# include <windows.h> // this should come before glfw3.h
#endif
#define GL_SILENCE_DEPRECATION
#include <GLFW/glfw3.h>
#include "delfem2/defarap.h"
#include "delfem2/gizmo_geo3.h"
#include "delfem2/geo3_v23m34q.h"
#include "delfem2/mshprimitive.h"
#include "delfem2/vec3.h"
#include "delfem2/quat.h"
#include "delfem2/mat4.h"
#include "delfem2/glfw/viewer3.h"
#include "delfem2/glfw/util.h"
#include "delfem2/opengl/old/gizmo.h"
#include "delfem2/opengl/old/funcs.h"
#include "delfem2/opengl/old/mshuni.h"
namespace dfm2 = delfem2;
// ----------------------------------------
int main() {
class MyViewer : public delfem2::glfw::CViewer3 {
public:
MyViewer() {
dfm2::MeshTri3D_CylinderClosed(
aXYZ0, aTri,
0.2, 1.6,
32, 32);
const auto np = static_cast<unsigned int>(aXYZ0.size() / 3);
aBCFlag.assign(np * 3, 0);
for (unsigned int ip = 0; ip < np; ++ip) {
double y0 = aXYZ0[ip * 3 + 1];
if (y0 < -0.65) {
aBCFlag[ip * 3 + 0] = 1;
aBCFlag[ip * 3 + 1] = 1;
aBCFlag[ip * 3 + 2] = 1;
}
if (y0 > +0.65) {
aBCFlag[ip * 3 + 0] = 2;
aBCFlag[ip * 3 + 1] = 2;
aBCFlag[ip * 3 + 2] = 2;
}
}
{ // initialize gizmo
unsigned int nbc = 2;
std::vector<dfm2::CVec3d> aCntBC;
aCntBC.assign(nbc, dfm2::CVec3d(0, 0, 0));
std::vector<unsigned int> aW(nbc, 0);
for (unsigned int ip = 0; ip < np; ++ip) {
if (aBCFlag[ip * 3 + 0] <= 0) { continue; }
unsigned int ibc = aBCFlag[ip * 3 + 0] - 1;
aCntBC[ibc] += dfm2::CVec3d(aXYZ0.data() + ip * 3);
aW[ibc] += 1;
}
for (unsigned int ibc = 0; ibc < nbc; ++ibc) {
aCntBC[ibc] /= (double) aW[ibc];
}
giz1.pivot0 = aCntBC[1].cast<float>();
giz1.gizmo_rot.pos = aCntBC[1].cast<float>();
giz1.gizmo_trnsl.pos = aCntBC[1].cast<float>();
giz1.gizmo_rot.size = 0.3f;
giz1.gizmo_trnsl.size = 0.3f;
}
aXYZ1 = aXYZ0;
aQuat1.resize(np * 4);
for (unsigned int ip = 0; ip < np; ++ip) {
dfm2::Quat_Identity(aQuat1.data() + 4 * ip);
}
def0.Init(aXYZ0, aTri, true);
}
void mouse_press(const float src[3], const float dir[3]) override {
giz1.Pick(src, dir);
}
void mouse_drag(const float src0[3], const float src1[3], const float dir[3]) override {
giz1.Drag(src0, src1, dir);
}
void key_release(
[[maybe_unused]] int key,
[[maybe_unused]] int mods) override {
}
void key_press(int key, [[maybe_unused]] int mods) override {
if (key == GLFW_KEY_R) { giz1.igizmo_mode = 1; }
if (key == GLFW_KEY_G) { giz1.igizmo_mode = 0; }
}
//
void Draw() {
{ // set boundary condition
const dfm2::CMat4<double> aff1 = giz1.Affine().cast<double>();
for (unsigned int ip = 0; ip < aXYZ0.size() / 3; ++ip) {
if (aBCFlag[ip * 3 + 0] == 0) { continue; }
if (aBCFlag[ip * 3 + 0] == 1) {
aXYZ1[ip * 3 + 0] = aXYZ0[ip * 3 + 0];
aXYZ1[ip * 3 + 1] = aXYZ0[ip * 3 + 1];
aXYZ1[ip * 3 + 2] = aXYZ0[ip * 3 + 2];
}
if (aBCFlag[ip * 3 + 0] == 2) {
dfm2::Vec3_Mat4Vec3_Homography(
aXYZ1.data() + ip * 3,
aff1.mat,
aXYZ0.data() + ip * 3);
}
}
for (int itr = 0; itr < 2; ++itr) {
dfm2::UpdateRotationsByMatchingCluster_Linear(
aQuat1,
aXYZ0, aXYZ1,
def0.psup_ind, def0.psup);
}
}
def0.Deform(
aXYZ1, aQuat1,
aXYZ0, aBCFlag);
def0.UpdateQuats_SVD(
aXYZ1, aQuat1,
aXYZ0);
// -------------------------------
DrawBegin_oldGL();
delfem2::opengl::DrawAxis(1);
{ // mesh
::glEnable(GL_LIGHTING);
::glColor3d(0, 0, 0);
delfem2::opengl::DrawMeshTri3D_Edge(
aXYZ1.data(), aXYZ1.size() / 3,
aTri.data(), aTri.size() / 3);
delfem2::opengl::DrawMeshTri3D_FaceNorm(
aXYZ1.data(),
aTri.data(), aTri.size() / 3);
}
{ // draw bc
::glDisable(GL_LIGHTING);
::glPointSize(10);
::glBegin(GL_POINTS);
for (unsigned int ip = 0; ip < aXYZ1.size() / 3; ++ip) {
if (aBCFlag[ip * 3 + 0] == 0) { continue; }
if (aBCFlag[ip * 3 + 0] == 1) { ::glColor3d(0, 0, 1); }
if (aBCFlag[ip * 3 + 0] == 2) { ::glColor3d(0, 1, 0); }
::glVertex3dv(aXYZ1.data() + ip * 3);
}
::glEnd();
}
/*
for(int ibc=0;ibc<aCntBC.size();++ibc){
dfm2::CVec3d p0 = aCntBC[ibc];
dfm2::opengl::DrawSphereAt(32, 32, 0.1, p0.x(), p0.y(), p0.z());
}
*/
delfem2::opengl::Draw(giz1);
SwapBuffers();
}
public:
delfem2::CGizmo_Affine<float> giz1; // bcflag==2
std::vector<unsigned int> aTri;
std::vector<double> aXYZ0, aXYZ1;
std::vector<double> aQuat1;
std::vector<int> aBCFlag;
delfem2::CDef_Arap def0;
} viewer;
// --------------------
dfm2::glfw::InitGLOld();
viewer.InitGL();
delfem2::opengl::setSomeLighting();
// --------------------
while (!glfwWindowShouldClose(viewer.window)) {
viewer.Draw();
glfwPollEvents();
viewer.ExitIfClosed();
}
glfwDestroyWindow(viewer.window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| 30.983871 | 92 | 0.516745 | [
"mesh",
"vector"
] |
151d36b6337b2ecaf86dcbfc5fc87aaee7132c4c | 3,425 | hpp | C++ | src/include/guinsoodb/main/appender.hpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | 1 | 2021-04-22T05:41:54.000Z | 2021-04-22T05:41:54.000Z | src/include/guinsoodb/main/appender.hpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | null | null | null | src/include/guinsoodb/main/appender.hpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | 1 | 2021-12-12T10:24:57.000Z | 2021-12-12T10:24:57.000Z | //===----------------------------------------------------------------------===//
// GuinsooDB
//
// guinsoodb/main/appender.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "guinsoodb/common/types/data_chunk.hpp"
#include "guinsoodb/common/winapi.hpp"
#include "guinsoodb/main/table_description.hpp"
namespace guinsoodb {
class ClientContext;
class GuinsooDB;
class TableCatalogEntry;
class Connection;
//! The Appender class can be used to append elements to a table.
class Appender {
//! A reference to a database connection that created this appender
shared_ptr<ClientContext> context;
//! The table description (including column names)
unique_ptr<TableDescription> description;
//! Internal chunk used for appends
DataChunk chunk;
//! The current column to append to
idx_t column = 0;
public:
GUINSOODB_API Appender(Connection &con, const string &schema_name, const string &table_name);
GUINSOODB_API Appender(Connection &con, const string &table_name);
GUINSOODB_API ~Appender();
//! Begins a new row append, after calling this the other AppendX() functions
//! should be called the correct amount of times. After that,
//! EndRow() should be called.
GUINSOODB_API void BeginRow();
//! Finishes appending the current row.
GUINSOODB_API void EndRow();
// Append functions
template <class T>
void Append(T value) {
throw Exception("Undefined type for Appender::Append!");
}
GUINSOODB_API void Append(const char *value, uint32_t length);
// prepared statements
template <typename... Args>
void AppendRow(Args... args) {
BeginRow();
AppendRowRecursive(args...);
}
//! Commit the changes made by the appender.
GUINSOODB_API void Flush();
//! Flush the changes made by the appender and close it. The appender cannot be used after this point
GUINSOODB_API void Close();
//! Obtain a reference to the internal vector that is used to append to the table
GUINSOODB_API DataChunk &GetAppendChunk() {
return chunk;
}
GUINSOODB_API idx_t CurrentColumn() {
return column;
}
private:
template <class T>
void AppendValueInternal(T value);
template <class SRC, class DST>
void AppendValueInternal(Vector &vector, SRC input);
void AppendRowRecursive() {
EndRow();
}
template <typename T, typename... Args>
void AppendRowRecursive(T value, Args... args) {
Append<T>(value);
AppendRowRecursive(args...);
}
void AppendValue(const Value &value);
};
template <>
void GUINSOODB_API Appender::Append(bool value);
template <>
void GUINSOODB_API Appender::Append(int8_t value);
template <>
void GUINSOODB_API Appender::Append(int16_t value);
template <>
void GUINSOODB_API Appender::Append(int32_t value);
template <>
void GUINSOODB_API Appender::Append(int64_t value);
template <>
void GUINSOODB_API Appender::Append(uint8_t value);
template <>
void GUINSOODB_API Appender::Append(uint16_t value);
template <>
void GUINSOODB_API Appender::Append(uint32_t value);
template <>
void GUINSOODB_API Appender::Append(uint64_t value);
template <>
void GUINSOODB_API Appender::Append(float value);
template <>
void GUINSOODB_API Appender::Append(double value);
template <>
void GUINSOODB_API Appender::Append(const char *value);
template <>
void GUINSOODB_API Appender::Append(Value value);
template <>
void GUINSOODB_API Appender::Append(std::nullptr_t value);
} // namespace guinsoodb | 28.07377 | 102 | 0.715036 | [
"vector"
] |
152112c81aaf4ad32513edfcceaa15efb0bd4108 | 19,308 | hpp | C++ | asmd/eita/Fmt1x_v170108_2.hpp | 00sapo/ASMD | 48e021f98d5fbecd09bed1cdd58024d9b471fad4 | [
"MIT"
] | 6 | 2021-09-18T08:36:26.000Z | 2022-03-25T16:37:04.000Z | asmd/eita/Fmt1x_v170108_2.hpp | 00sapo/ASMD | 48e021f98d5fbecd09bed1cdd58024d9b471fad4 | [
"MIT"
] | 4 | 2021-04-22T15:01:26.000Z | 2021-04-22T15:01:28.000Z | asmd/eita/Fmt1x_v170108_2.hpp | 00sapo/ASMD | 48e021f98d5fbecd09bed1cdd58024d9b471fad4 | [
"MIT"
] | 3 | 2021-07-13T15:11:38.000Z | 2021-11-26T07:38:00.000Z | /*
Copyright 2019 Eita Nakamura
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 FMT1X_HPP
#define FMT1X_HPP
#include<iostream>
#include<string>
#include<sstream>
#include<cmath>
#include<vector>
#include<fstream>
#include<cassert>
#include"BasicCalculation_v170122.hpp"
using namespace std;
inline void DeleteHeadSpace(string &buf){
size_t pos;
while((pos = buf.find_first_of(" \t")) == 0){
buf.erase(buf.begin());
if(buf.empty()) break;
}//endwhile
}//end DeleteHeadSpace
inline vector<string> UnspaceString(string str){
vector<string> vs;
while(str.size()>0){
DeleteHeadSpace(str);
if(str=="" || isspace(str[0])!=0){break;}
vs.push_back(str.substr(0,str.find_first_of(" \t")));
for(int i=0;i<vs[vs.size()-1].size();i+=1){str.erase(str.begin());}
}//endwhile
return vs;
}//end UnspaceString
inline string altername(string str){
string out="";
if(str=="0"){out="";
}else if(str=="1"){out="#";
}else if(str=="2"){out="##";
}else if(str=="3"){out="###";
}else if(str=="-1"){out="b";
}else if(str=="-2"){out="bb";
}else if(str=="-3"){out="bbb";
}//endif
return out;
}//end altername
inline char intToDitchclass(int i){
if(i==1){return 'C';
}else if(i==2){return 'D';
}else if(i==3){return 'E';
}else if(i==4){return 'F';
}else if(i==5){return 'G';
}else if(i==6){return 'A';
}else if(i==7){return 'B';
}else{
cout<<"Unknown int for ditchclass!"<<endl; return 'C';
}//endif
};
inline int ditchclassToInt(char dc){
if(dc=='C'){return 1;
}else if(dc=='D'){return 2;
}else if(dc=='E'){return 3;
}else if(dc=='F'){return 4;
}else if(dc=='G'){return 5;
}else if(dc=='A'){return 6;
}else if(dc=='B'){return 7;
}else{
cout<<"Unknown ditchclass name!"<<endl; return 1;
}//endif
};
inline string acc_norm(char dc,int curKeyFifth){
if(curKeyFifth==0){
return "";
}else if(curKeyFifth>0){
for(int i=1;i<=curKeyFifth;i+=1){
if(dc==intToDitchclass((i*4-1+70)%7+1)){return "#";}
}//endfor i
return "";
}else if(curKeyFifth<0){
for(int i=1;i<=-1*curKeyFifth;i+=1){
if(dc==intToDitchclass((i*3+4-1+70)%7+1)){return "b";}
}//endfor i
return "";
}else{
return "";
}//endif
};
inline string ditchUp(string principal,char acc_rel,int curKeyFifth){
char dc=intToDitchclass( (ditchclassToInt(principal[0])+7-1+1)%7+1 );
int oct=principal[principal.size()-1]-'0';
if(dc=='C'){oct+=1;}
string acc="";
if(acc_rel!='*'){
if(acc_rel=='n'){acc="";
}else if(acc_rel=='s'){acc="#";
}else if(acc_rel=='S'){acc="##";
}else if(acc_rel=='f'){acc="b";
}else if(acc_rel=='F'){acc="bb";
}//endif
}else{
acc=acc_norm(dc,curKeyFifth);
}//endif
stringstream ss;
ss.str(""); ss<<dc<<acc<<oct;
return ss.str();
};
inline string ditchDown(string principal,char acc_rel,int curKeyFifth){
char dc=intToDitchclass( (ditchclassToInt(principal[0])+7-1-1)%7+1 );
int oct=principal[principal.size()-1]-'0';
if(dc=='B'){oct-=1;}
string acc;
if(acc_rel!='*'){
if(acc_rel=='n'){acc="";
}else if(acc_rel=='s'){acc="#";
}else if(acc_rel=='S'){acc="##";
}else if(acc_rel=='f'){acc="b";
}else if(acc_rel=='F'){acc="bb";
}//endif
}else{
acc=acc_norm(dc,curKeyFifth);
}//endif
stringstream ss;
ss.str(""); ss<<dc<<acc<<oct;
return ss.str();
};
class Fmt1xEvt{
public:
int stime;
string barnum;
int part;
int staff;
int voice;
string eventtype;
int dur;
int tieinfo;
int numNotes;//=sitches.size()
vector<string> sitches;//size = numNotes
vector<string> notetypes;//size = numNotes
// vector<int> notenums;//size = numNotes
vector<string> fmt1IDs;//size = numNotes
vector<int> ties;// = 0(def)/1 if the note is NOT/is tied with a previous note. (Used only if tieinfo > 0) (size = numNotes)
string info;//used for type "attributes"
};//end class Fmt1xEvent
class Fmt1x{
public:
int TPQN;
vector<Fmt1xEvt> evts;
vector<string> comments;
void ReadFile(string filename){
vector<int> v(100);
vector<double> d(100);
vector<string> s(100);
stringstream ss;
evts.clear();
comments.clear();
ifstream ifs(filename.c_str());
if(!ifs.is_open()){cout<<"File not found: "<<filename<<endl; assert(false);}
Fmt1xEvt evt;
while(ifs>>s[0]){
if(s[0][0]=='/'||s[0][0]=='#'){
if(s[0]=="//TPQN:"){
ifs>>TPQN;
getline(ifs,s[99]);
}else if(s[0]=="//Fmt1xVersion:"){
ifs>>s[1];
if(s[1]!="170104"){
cout<<"Warning: The fmt1x version is not 170104!"<<endl;
}//endif
getline(ifs,s[99]);
}else{
getline(ifs,s[99]);
comments.push_back(s[99]);
}//endif
continue;
}//endif
evt.stime=atoi(s[0].c_str());
ifs>>evt.barnum>>evt.part>>evt.staff>>evt.voice>>evt.eventtype;
evt.sitches.clear(); evt.notetypes.clear(); evt.fmt1IDs.clear(); evt.ties.clear();
evt.info="";
if(evt.eventtype=="attributes"){
getline(ifs,evt.info);
evt.info+="\n";
}else if(evt.eventtype=="rest"||evt.eventtype=="chord"||evt.eventtype=="tremolo-s"||evt.eventtype=="tremolo-e"){
ifs>>evt.dur>>evt.tieinfo>>evt.numNotes;
for(int j=0;j<evt.numNotes;j+=1){ifs>>s[8]; evt.sitches.push_back(s[8]);}//endfor j
for(int j=0;j<evt.numNotes;j+=1){ifs>>s[8]; evt.notetypes.push_back(s[8]);}//endfor j
for(int j=0;j<evt.numNotes;j+=1){ifs>>s[8]; evt.fmt1IDs.push_back(s[8]);}//endfor j
for(int j=0;j<evt.numNotes;j+=1){ifs>>v[8]; evt.ties.push_back(v[8]);}//endfor j
getline(ifs,s[99]);
}else{
getline(ifs,s[99]);
continue;
}//endif
evts.push_back(evt);
}//endwhile
ifs.close();
//cout<<evts.size()<<endl;
}//end ReadFile
void WriteFile(string filename){
ofstream ofs(filename.c_str());
ofs<<"//TPQN: "<<TPQN<<"\n";
ofs<<"//Fmt1xVersion: "<<"170104\n";
for(int i=0;i<comments.size();i+=1){
ofs<<"//"<<comments[i]<<"\n";
}//endfor i
for(int i=0;i<evts.size();i+=1){
ofs<<evts[i].stime<<"\t"<<evts[i].barnum<<"\t"<<evts[i].part<<"\t"<<evts[i].staff<<"\t"<<evts[i].voice<<"\t"<<evts[i].eventtype;
if(evts[i].eventtype=="attributes"){
ofs<<evts[i].info;
continue;
}//endif
ofs<<"\t"<<evts[i].dur<<"\t"<<evts[i].tieinfo<<"\t"<<evts[i].numNotes<<"\t";
for(int j=0;j<evts[i].sitches.size();j+=1){
ofs<<evts[i].sitches[j]<<"\t";
}//endfor j
for(int j=0;j<evts[i].notetypes.size();j+=1){
ofs<<evts[i].notetypes[j]<<"\t";
}//endfor j
for(int j=0;j<evts[i].fmt1IDs.size();j+=1){
ofs<<evts[i].fmt1IDs[j]<<"\t";
}//endfor j
for(int j=0;j<evts[i].ties.size();j+=1){
ofs<<evts[i].ties[j]<<"\t";
}//endfor j
ofs<<"\n";
}//endfor i
ofs.close();
}//end WriteFile
void ReadMusicXML(string filename){
vector<int> v(100);
vector<double> d(100);
vector<string> s(100);
stringstream ss;
evts.clear();
comments.clear();
ifstream ifs(filename.c_str());
if(!ifs.is_open()){cout<<"File not found: "<<filename<<endl; assert(false);}
string all;
while(!ifs.eof()){
getline(ifs,s[99]);
all+=s[99];
}//endwhile
ifs.close();
vector<string> events;
vector<int> depths;
vector<bool> inout;
{
bool isInBracket=false;
int depth=0;
for(int i=0;i<all.size();i+=1){
if(all[i]=='<'){
isInBracket=true;
if(all[i+1]=='/'){depth-=1;
}else if(all[i+1]=='!' || all[i+1]=='?'){;
}else{depth+=1;
}//endif
events.push_back(s[0]);
depths.push_back(depth);
inout.push_back(false);
s[0]="";
continue;
}else if(all[i]=='>'){
isInBracket=false;
if(all[i-1]=='/'){depth-=1;}
events.push_back(s[0]);
depths.push_back(depth);
inout.push_back(true);
s[0]="";
continue;
}//endif
s[0]+=all[i];
}//endfor i
}//
{
vector<string> prev_events(events);
vector<int> prev_depths(depths);
vector<bool> prev_inout(inout);
events.clear();
depths.clear();
inout.clear();
for(int i=0;i<prev_events.size();i+=1){
DeleteHeadSpace(prev_events[i]);
if(prev_events[i]=="" || isspace(prev_events[i][0])!=0){continue;}
if(prev_inout[i]){
if(prev_events[i][0]!='/'&&prev_events[i][0]!='!'&&prev_events[i][0]!='?'){
prev_depths[i]-=1;
if(prev_events[i][prev_events[i].size()-1]=='/'){
prev_depths[i]+=1;
}//endif
}//endif
}//endif
events.push_back(prev_events[i]);
depths.push_back(prev_depths[i]);
inout.push_back(prev_inout[i]);
}//endfor i
}//
TPQN=32;
{
vector<int> divs;
for(int i=1;i<events.size();i+=1){
if(depths[i]==4&&UnspaceString(events[i])[0]=="divisions"){
divs.push_back(atoi(events[i+1].c_str()));
}//endif
}//endfor i
TPQN=divs[0];
for(int i=1;i<divs.size();i+=1){
TPQN=lcm(TPQN,divs[i]);
}//endfor i
//cout<<"TPQN = "<<TPQN<<endl;
}//
Fmt1xEvt evt;
bool notein=false;
bool backupin=false;
bool forwardin=false;
bool pitchin=false;
bool isChord=false;
string sitch;
string type,arpinfo,ferinfo;
int tie;
int curPart=1;
int curdivision;
int cumulativeStime=0;
int maxcumulativeStime=cumulativeStime;
int time_num=4, time_den=4;
int barDur=(time_num*TPQN*4)/time_den;
int curKeyFifth=0;
int clefNumToBeSpecified=0;
string curKeyMode="major";
int curNumOfStaves=1;
string curMeasureNumPrinted="0";
vector<string> curClefLab;
vector<int> curClefOctChange;
curClefLab.push_back("G2");
curClefOctChange.push_back(0);
v[0]=0;
int notenum;
string trem;
for(int i=1;i<events.size();i+=1){
//cout<<i<<"\t"<<events[i]<<endl;
string eventTag=UnspaceString(events[i])[0];
if(depths[i]==1&&eventTag=="part"){
s[0]=UnspaceString(events[i])[1];
s[0]=s[0].substr(s[0].find("\"")+2);//if '+2' delete 'P' in 'P1' etc.
s[0]=s[0].substr(0,s[0].find("\""));
curPart=atoi(s[0].c_str());
cumulativeStime=0;
maxcumulativeStime=cumulativeStime;
curNumOfStaves=1;
curClefLab.assign(curNumOfStaves,"G4");
curClefOctChange.assign(curNumOfStaves,0);
}else if(depths[i]==4&&eventTag=="divisions"){
curdivision=atoi(events[i+1].c_str());
barDur=(time_num*TPQN*4)/time_den;
}else if(depths[i]==5&&eventTag=="fifths"){
curKeyFifth=atoi(events[i+1].c_str());
}else if(depths[i]==5&&eventTag=="mode"){
curKeyMode=events[i+1];
}else if(depths[i]==5&&eventTag=="beats"){
time_num=atoi(events[i+1].c_str());
barDur=(time_num*TPQN*4)/time_den;
}else if(depths[i]==5&&eventTag=="beat-type"){
time_den=atoi(events[i+1].c_str());
barDur=(time_num*TPQN*4)/time_den;
}else if(depths[i]==4&&eventTag=="staves"){
curNumOfStaves=atoi(events[i+1].c_str());
curClefLab.assign(curNumOfStaves,"G4");
curClefOctChange.assign(curNumOfStaves,0);
}else if(depths[i]==4&&eventTag=="clef"){
if(UnspaceString(events[i]).size()==1){
clefNumToBeSpecified=0;
}else{
s[0]=UnspaceString(events[i])[1];
s[0]=s[0].substr(s[0].find("number")+8);
s[0]=s[0].substr(0,s[0].find("\""));
clefNumToBeSpecified=atoi(s[0].c_str())-1;
}//endif
}else if(depths[i]==5&&eventTag=="sign"){
curClefLab[clefNumToBeSpecified]=events[i+1];
curClefOctChange[clefNumToBeSpecified]=0;
}else if(depths[i]==5&&eventTag=="line"){
curClefLab[clefNumToBeSpecified]+=events[i+1];
}else if(depths[i]==5&&eventTag=="clef-octave-change"){
curClefOctChange[curClefOctChange.size()-1]=atoi(events[i+1].c_str());
}else if(depths[i]==2&&eventTag=="measure"){
notenum=0;
s[0]="NA";
for(int k=1;k<UnspaceString(events[i]).size();k+=1){
if(UnspaceString(events[i])[k].find("number")!=string::npos){
s[0]=UnspaceString(events[i])[k];
s[0]=s[0].substr(s[0].find("\"")+1);
s[0]=s[0].substr(0,s[0].find("\""));
break;
}//endif
}//endfor k
curMeasureNumPrinted=s[0];
if(maxcumulativeStime!=cumulativeStime){
cumulativeStime=maxcumulativeStime;
ss.str("");
ss<<"//warning: maxcumulativeStime!=cumulativeStime at bar onset at "<<s[0]<<"\t"<<cumulativeStime;
cout<<"//warning: maxcumulativeStime!=cumulativeStime at bar onset at "<<s[0]<<"\t"<<cumulativeStime<<endl;;
comments.push_back(ss.str());
}//endif
}else if(depths[i]==3&&eventTag=="backup"){
backupin=true;
}else if(depths[i]==3&&eventTag=="forward"){
forwardin=true;
}else if(depths[i]==3&&eventTag=="note"){
notenum+=1;
notein=true;
isChord=false;
evt.stime=cumulativeStime;
evt.barnum=curMeasureNumPrinted;
evt.part=curPart;
evt.staff=1;
evt.voice=1;
evt.dur=0;
evt.tieinfo=0;
tie=0;
trem="";
sitch="C4";
type="N";
arpinfo="";
ferinfo="";
v[0]+=1;
}else if(depths[i]==3&&eventTag=="/attributes"){
evt.stime=cumulativeStime;
evt.barnum=curMeasureNumPrinted;
evt.part=curPart;
evt.staff=1;
evt.voice=1;
evt.eventtype="attributes";
evt.dur=0;
evt.tieinfo=0;
evt.numNotes=0;
evt.sitches.clear();
evt.notetypes.clear();
evt.fmt1IDs.clear();
ss.str("");
ss<<"\t"<<TPQN<<"\t"<<curKeyFifth<<"\t"<<curKeyMode<<"\t"<<time_num<<"\t"<<time_den<<"\t";
ss<<curNumOfStaves<<"\t";
for(int j=0;j<curNumOfStaves;j+=1){
ss<<curClefLab[j]<<"\t"<<curClefOctChange[j]<<"\t";
}//endfor j
ss<<"\n";
evt.info=ss.str();
evts.push_back(evt);
}//endif
if(notein){
if(depths[i]==4&&eventTag=="chord/"){
isChord=true;
evt.stime-=evts[evts.size()-1].dur;
cumulativeStime-=evts[evts.size()-1].dur;
}else if(depths[i]==4&&events[i].find("rest")!=string::npos){
sitch="rest";
}else if(depths[i]==4&&events[i].find("pitch")!=string::npos){
pitchin=true;
}else if(depths[i]==4&&eventTag=="staff"){
evt.staff=atoi(events[i+1].c_str());
}else if(depths[i]==4&&eventTag=="voice"){
evt.voice=atoi(events[i+1].c_str());
}else if(depths[i]==4&&eventTag=="duration"){
evt.dur=(atoi(events[i+1].c_str())*TPQN)/curdivision;
cumulativeStime+=evt.dur;
if(maxcumulativeStime<cumulativeStime){maxcumulativeStime=cumulativeStime;}
}else if(depths[i]==4&&eventTag=="tie"){
if(UnspaceString(events[i])[1].find("stop")!=string::npos){tie+=2;}//endif
if(UnspaceString(events[i])[1].find("start")!=string::npos){tie+=1;}//endif
}else if(depths[i]==5&&eventTag=="ornaments"){
if(UnspaceString(events[i+1])[0]=="wavy-line"){
}else if(UnspaceString(events[i+1])[0]=="tremolo"){
type="N";
if(UnspaceString(events[i+1])[1].find("start")!=string::npos){
trem="tremolo-s";
}else if(UnspaceString(events[i+1])[1].find("stop")!=string::npos){
trem="tremolo-e";
}else{
trem="tremolo-m";
}//endif
}else{
type=UnspaceString(events[i+1])[0];
type+="**";
}//endif
}else if(depths[i]==6&&eventTag=="accidental-mark"){
v[10]=-1;//accMarkPlace
for(int j=0;j<UnspaceString(events[i]).size();j+=1){
if(UnspaceString(events[i])[j].find("above")!=string::npos){
v[10]=2; break;
}else if(UnspaceString(events[i])[j].find("below")!=string::npos){
v[10]=1; break;
}//endif
}//endfor j
if(v[10]<0){
v[10]=2;
if(type[type.size()-2]!='*'){v[10]=1;}
}//endif
if(events[i+1]=="natural"){type[type.size()-v[10]]='n';
}else if(events[i+1]=="sharp"){type[type.size()-v[10]]='s';
}else if(events[i+1]=="double-sharp"){type[type.size()-v[10]]='S';
}else if(events[i+1]=="flat"){type[type.size()-v[10]]='f';
}else if(events[i+1]=="flat-flat"){type[type.size()-v[10]]='F';
}//endif
}else if(depths[i]==5&&eventTag=="arpeggiate"){
v[10]=UnspaceString(events[i]).size();
for(int j=1;j<v[10];j+=1){
if(UnspaceString(events[i])[j].find("number")!=string::npos){
s[0]=UnspaceString(events[i])[j];
s[0]=s[0].substr(s[0].find("num")+8,s[0].size());
arpinfo="Arp"+s[0].substr(0,s[0].find("\""));
}//endif
}//endfor j
}else if(depths[i]==5&&eventTag=="fermata"){
ferinfo="Fer";
}//endif
if(pitchin){
if(depths[i]==5&&eventTag=="step"){
sitch[0]=events[i+1][0];
}else if(depths[i]==5&&eventTag=="octave"){
sitch[sitch.size()-1]=events[i+1][0];
}else if(depths[i]==5&&eventTag=="alter"){
ss.str("");
ss<<sitch[0]<<altername(events[i+1])<<sitch[sitch.size()-1];
sitch=ss.str();
}else if(depths[i]==4&&eventTag=="pitch/"){
pitchin=false;
}//endif
}//endif
}//endif
if(backupin){
if(depths[i]==4&&eventTag=="duration"){
cumulativeStime-=(atoi(events[i+1].c_str())*TPQN)/curdivision;
}else if(depths[i]==3&&eventTag=="/backup"){
backupin=false;
}//endif
}//endif
if(forwardin){
if(depths[i]==4&&eventTag=="duration"){
cumulativeStime+=(atoi(events[i+1].c_str())*TPQN)/curdivision;
if(maxcumulativeStime<cumulativeStime){maxcumulativeStime=cumulativeStime;}
}else if(depths[i]==3&&eventTag=="/forward"){
forwardin=false;
}//endif
}//endif
if(depths[i]==3&&eventTag=="/note"){
if(!isChord){
ss.str("");
if(sitch=="rest"){
evt.eventtype="rest";
ss<<"N";
}else if(trem!=""){
evt.eventtype=trem;
ss<<type<<"."<<arpinfo<<"."<<ferinfo;
}else{//standard chord
evt.eventtype="chord";
ss<<type<<"."<<arpinfo<<"."<<ferinfo;
}//endif
evt.numNotes=1;
evt.sitches.clear();
evt.sitches.push_back(sitch);
evt.notetypes.clear();
evt.notetypes.push_back(ss.str());
evt.fmt1IDs.clear();
ss.str("");
ss<<"P"<<evt.part<<"-"<<evt.barnum<<"-"<<notenum;
evt.fmt1IDs.push_back(ss.str());
evt.ties.clear();
evt.ties.push_back( ((tie>1)? 1:0) );
evt.tieinfo=tie;
evts.push_back(evt);
}else{
ss.str("");
ss<<type<<"."<<arpinfo<<"."<<ferinfo;
evts[evts.size()-1].numNotes+=1;
evts[evts.size()-1].sitches.push_back(sitch);
evts[evts.size()-1].notetypes.push_back(ss.str());
ss.str("");
ss<<"P"<<evts[evts.size()-1].part<<"-"<<evts[evts.size()-1].barnum<<"-"<<notenum;
evts[evts.size()-1].fmt1IDs.push_back(ss.str());
evts[evts.size()-1].ties.push_back( ((tie>1)? 1:0) );
if(tie%2==1 && evts[evts.size()-1].tieinfo%2==0){
evts[evts.size()-1].tieinfo+=1;
}//enduf
if(tie/2==1 && evts[evts.size()-1].tieinfo/2==0){
evts[evts.size()-1].tieinfo+=2;
}//enduf
}//endif
notein=false;
}//endif
}//endfor i
}//end ReadMusicXML
};//endclass Fmt1x
#endif // FMT1X_HPP
| 30.406299 | 460 | 0.607727 | [
"vector"
] |
152a213a4f46e89ef8d7656b37895e9a196f816f | 12,349 | cpp | C++ | storage/src/tests/distributor/bucketdbmetricupdatertest.cpp | kennyeric/vespa | f69f960d5ae48d246f56a60e6e46c90a58f836ba | [
"Apache-2.0"
] | 1 | 2018-12-30T05:42:18.000Z | 2018-12-30T05:42:18.000Z | storage/src/tests/distributor/bucketdbmetricupdatertest.cpp | kennyeric/vespa | f69f960d5ae48d246f56a60e6e46c90a58f836ba | [
"Apache-2.0"
] | 1 | 2021-01-21T01:37:37.000Z | 2021-01-21T01:37:37.000Z | storage/src/tests/distributor/bucketdbmetricupdatertest.cpp | kennyeric/vespa | f69f960d5ae48d246f56a60e6e46c90a58f836ba | [
"Apache-2.0"
] | 1 | 2020-02-01T07:21:28.000Z | 2020-02-01T07:21:28.000Z | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vdstestlib/cppunit/macros.h>
#include <string>
#include <sstream>
#include <vespa/storage/bucketdb/bucketdatabase.h>
#include <vespa/storage/distributor/bucketdb/bucketdbmetricupdater.h>
#include <vespa/storage/distributor/distributormetricsset.h>
#include <vespa/storage/distributor/idealstatemetricsset.h>
#include <vespa/storage/config/config-stor-distributormanager.h>
namespace storage {
namespace distributor {
using document::BucketId;
class BucketDBMetricUpdaterTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(BucketDBMetricUpdaterTest);
CPPUNIT_TEST(testDocAndByteCountsAreUpdated);
CPPUNIT_TEST(testBucketsWithTooFewAndTooManyCopies);
CPPUNIT_TEST(testBucketsWithVaryingTrustedness);
CPPUNIT_TEST(testPickCountsFromTrustedCopy);
CPPUNIT_TEST(testPickLargestCopyIfNoTrusted);
CPPUNIT_TEST(testCompleteRoundClearsWorkingState);
CPPUNIT_TEST(testMinBucketReplicaTrackedAndReportedPerNode);
CPPUNIT_TEST(nonTrustedReplicasAlsoCountedInModeAny);
CPPUNIT_TEST(minimumReplicaCountReturnedForNodeInModeAny);
CPPUNIT_TEST_SUITE_END();
void visitBucketWith2Copies1Trusted(BucketDBMetricUpdater& metricUpdater);
void visitBucketWith2CopiesBothTrusted(
BucketDBMetricUpdater& metricUpdater);
void visitBucketWith1Copy(BucketDBMetricUpdater& metricUpdater);
using NodeToReplicasMap = std::unordered_map<uint16_t, uint32_t>;
NodeToReplicasMap replicaStatsOf(BucketDBMetricUpdater& metricUpdater);
metrics::LoadTypeSet _loadTypes;
public:
BucketDBMetricUpdaterTest();
void testDocAndByteCountsAreUpdated();
void testBucketsWithTooFewAndTooManyCopies();
void testBucketsWithVaryingTrustedness();
void testPickCountsFromTrustedCopy();
void testPickLargestCopyIfNoTrusted();
void testCompleteRoundClearsWorkingState();
void testMinBucketReplicaTrackedAndReportedPerNode();
void nonTrustedReplicasAlsoCountedInModeAny();
void minimumReplicaCountReturnedForNodeInModeAny();
};
CPPUNIT_TEST_SUITE_REGISTRATION(BucketDBMetricUpdaterTest);
BucketDBMetricUpdaterTest::BucketDBMetricUpdaterTest()
{
_loadTypes.push_back(metrics::LoadType(0, "foo"));
}
namespace {
void addNode(BucketInfo& info, uint16_t node, uint32_t crc) {
auto apiInfo = api::BucketInfo(crc, crc + 1, crc + 2);
std::vector<uint16_t> order;
info.addNode(BucketCopy(1234, node, apiInfo), order);
}
typedef bool Trusted;
BucketInfo
makeInfo(uint32_t copy0Crc)
{
BucketInfo info;
addNode(info, 0, copy0Crc);
return info;
}
BucketInfo
makeInfo(uint32_t copy0Crc, uint32_t copy1Crc)
{
BucketInfo info;
addNode(info, 0, copy0Crc);
addNode(info, 1, copy1Crc);
return info;
}
} // anonymous namespace
void
BucketDBMetricUpdaterTest::testDocAndByteCountsAreUpdated()
{
BucketDBMetricUpdater metricUpdater;
IdealStateMetricSet ims;
DistributorMetricSet dms(_loadTypes);
CPPUNIT_ASSERT_EQUAL(false, metricUpdater.hasCompletedRound());
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
metricUpdater.completeRound(false);
CPPUNIT_ASSERT_EQUAL(true, metricUpdater.hasCompletedRound());
CPPUNIT_ASSERT_EQUAL(int64_t(0), dms.docsStored.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(0), dms.bytesStored.getLast());
{
BucketDatabase::Entry e(document::BucketId(16, 1), makeInfo(10));
metricUpdater.visit(e, 1);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(true, metricUpdater.hasCompletedRound());
CPPUNIT_ASSERT_EQUAL(int64_t(11), dms.docsStored.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(12), dms.bytesStored.getLast());
{
BucketDatabase::Entry e(document::BucketId(16, 1), makeInfo(20));
metricUpdater.visit(e, 1);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(32), dms.docsStored.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(34), dms.bytesStored.getLast());
}
void
BucketDBMetricUpdaterTest::testBucketsWithTooFewAndTooManyCopies()
{
BucketDBMetricUpdater metricUpdater;
IdealStateMetricSet ims;
DistributorMetricSet dms(_loadTypes);
metricUpdater.completeRound();
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(0), ims.buckets_toofewcopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(0), ims.buckets_toomanycopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(0), ims.buckets.getLast());
// 1 copy too little
{
BucketDatabase::Entry e(document::BucketId(16, 1), makeInfo(10));
metricUpdater.visit(e, 2);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(1), ims.buckets_toofewcopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(0), ims.buckets_toomanycopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(1), ims.buckets.getLast());
// 1 copy too many
{
BucketDatabase::Entry e(document::BucketId(16, 1), makeInfo(40, 40));
metricUpdater.visit(e, 1);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(1), ims.buckets_toofewcopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(1), ims.buckets_toomanycopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(2), ims.buckets.getLast());
// Right amount of copies, just inc bucket counter.
{
BucketDatabase::Entry e(document::BucketId(16, 1), makeInfo(40, 40));
metricUpdater.visit(e, 2);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(1), ims.buckets_toofewcopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(1), ims.buckets_toomanycopies.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(3), ims.buckets.getLast());
}
void
BucketDBMetricUpdaterTest::testBucketsWithVaryingTrustedness()
{
BucketDBMetricUpdater metricUpdater;
IdealStateMetricSet ims;
DistributorMetricSet dms(_loadTypes);
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(0), ims.buckets_notrusted.getLast());
// Has only trusted (implicit for first added)
{
BucketDatabase::Entry e(document::BucketId(16, 1), makeInfo(100));
metricUpdater.visit(e, 2);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(0), ims.buckets_notrusted.getLast());
// Has at least one trusted (implicit for first added)
{
BucketDatabase::Entry e(document::BucketId(16, 2), makeInfo(100, 200));
metricUpdater.visit(e, 2);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(0), ims.buckets_notrusted.getLast());
// Has no trusted
{
BucketInfo info(makeInfo(100, 200));
info.resetTrusted();
BucketDatabase::Entry e(document::BucketId(16, 3), info);
metricUpdater.visit(e, 2);
}
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(1), ims.buckets_notrusted.getLast());
}
void
BucketDBMetricUpdaterTest::testPickCountsFromTrustedCopy()
{
BucketDBMetricUpdater metricUpdater;
IdealStateMetricSet ims;
DistributorMetricSet dms(_loadTypes);
// First copy added is implicitly trusted, but it is not the largest.
BucketDatabase::Entry e(document::BucketId(16, 2), makeInfo(100, 200));
metricUpdater.visit(e, 2);
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(101), dms.docsStored.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(102), dms.bytesStored.getLast());
}
void
BucketDBMetricUpdaterTest::testPickLargestCopyIfNoTrusted()
{
BucketDBMetricUpdater metricUpdater;
IdealStateMetricSet ims;
DistributorMetricSet dms(_loadTypes);
// No trusted copies, so must pick second copy.
BucketInfo info(makeInfo(100, 200));
info.resetTrusted();
BucketDatabase::Entry e(document::BucketId(16, 2), info);
metricUpdater.visit(e, 2);
metricUpdater.completeRound(false);
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(201), dms.docsStored.getLast());
CPPUNIT_ASSERT_EQUAL(int64_t(202), dms.bytesStored.getLast());
}
void
BucketDBMetricUpdaterTest::testCompleteRoundClearsWorkingState()
{
BucketDBMetricUpdater metricUpdater;
IdealStateMetricSet ims;
DistributorMetricSet dms(_loadTypes);
{
BucketDatabase::Entry e(document::BucketId(16, 1), makeInfo(10));
metricUpdater.visit(e, 1);
}
metricUpdater.completeRound();
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(11), dms.docsStored.getLast());
// Completing the round again with no visits having been done will
// propagate an empty working state to the complete state.
metricUpdater.completeRound();
metricUpdater.getLastCompleteStats().propagateMetrics(ims, dms);
CPPUNIT_ASSERT_EQUAL(int64_t(0), dms.docsStored.getLast());
}
// Replicas on nodes 0 and 1.
void
BucketDBMetricUpdaterTest::visitBucketWith2Copies1Trusted(
BucketDBMetricUpdater& metricUpdater)
{
BucketInfo info;
addNode(info, 0, 100);
addNode(info, 1, 101); // Note different checksums => #trusted = 1
BucketDatabase::Entry e(document::BucketId(16, 1), info);
metricUpdater.visit(e, 2);
}
// Replicas on nodes 0 and 2.
void
BucketDBMetricUpdaterTest::visitBucketWith2CopiesBothTrusted(
BucketDBMetricUpdater& metricUpdater)
{
BucketInfo info;
addNode(info, 0, 200);
addNode(info, 2, 200);
BucketDatabase::Entry e(document::BucketId(16, 2), info);
metricUpdater.visit(e, 2);
}
// Single replica on node 2.
void
BucketDBMetricUpdaterTest::visitBucketWith1Copy(
BucketDBMetricUpdater& metricUpdater)
{
BucketInfo info;
addNode(info, 2, 100);
BucketDatabase::Entry e(document::BucketId(16, 1), info);
metricUpdater.visit(e, 2);
}
BucketDBMetricUpdaterTest::NodeToReplicasMap
BucketDBMetricUpdaterTest::replicaStatsOf(BucketDBMetricUpdater& metricUpdater)
{
metricUpdater.completeRound(true);
return metricUpdater.getLastCompleteStats()._minBucketReplica;
}
void BucketDBMetricUpdaterTest::testMinBucketReplicaTrackedAndReportedPerNode()
{
BucketDBMetricUpdater metricUpdater;
// Node 0 and 1 should have min replica 1, while node 2 should have min
// replica 2.
visitBucketWith2Copies1Trusted(metricUpdater);
visitBucketWith2CopiesBothTrusted(metricUpdater);
CPPUNIT_ASSERT_EQUAL(NodeToReplicasMap({{0, 1}, {1, 1}, {2, 2}}),
replicaStatsOf(metricUpdater));
}
void
BucketDBMetricUpdaterTest::nonTrustedReplicasAlsoCountedInModeAny()
{
BucketDBMetricUpdater metricUpdater;
using CountingMode = BucketDBMetricUpdater::ReplicaCountingMode;
metricUpdater.setMinimumReplicaCountingMode(CountingMode::ANY);
visitBucketWith2Copies1Trusted(metricUpdater);
visitBucketWith2CopiesBothTrusted(metricUpdater);
CPPUNIT_ASSERT_EQUAL(NodeToReplicasMap({{0, 2}, {1, 2}, {2, 2}}),
replicaStatsOf(metricUpdater));
}
void
BucketDBMetricUpdaterTest::minimumReplicaCountReturnedForNodeInModeAny()
{
BucketDBMetricUpdater metricUpdater;
using CountingMode = BucketDBMetricUpdater::ReplicaCountingMode;
metricUpdater.setMinimumReplicaCountingMode(CountingMode::ANY);
visitBucketWith2CopiesBothTrusted(metricUpdater);
visitBucketWith1Copy(metricUpdater);
// Node 2 has a bucket with only 1 replica.
CPPUNIT_ASSERT_EQUAL(NodeToReplicasMap({{0, 2}, {2, 1}}),
replicaStatsOf(metricUpdater));
}
} // distributor
} // storage
| 34.207756 | 118 | 0.749372 | [
"vector"
] |
15314d0f2c4ec6f4c98f37b43182f870222e7237 | 2,691 | cpp | C++ | 830.PositionsOfLargeGroups.cpp | mrdrivingduck/leet-code | fee008f3a62849a21ca703e05f755378996a1ff5 | [
"MIT"
] | null | null | null | 830.PositionsOfLargeGroups.cpp | mrdrivingduck/leet-code | fee008f3a62849a21ca703e05f755378996a1ff5 | [
"MIT"
] | null | null | null | 830.PositionsOfLargeGroups.cpp | mrdrivingduck/leet-code | fee008f3a62849a21ca703e05f755378996a1ff5 | [
"MIT"
] | null | null | null | /**
* @author Mr Dk.
* @version 2021/01/05
*/
/*
In a string s of lowercase letters, these letters form consecutive groups
of the same character.
For example, a string like s = "abbxxxxzyy" has the groups "a", "bb",
"xxxx", "z", and "yy".
A group is identified by an interval [start, end], where start and end
denote the start and end indices (inclusive) of the group. In the above
example, "xxxx" has the interval [3,6].
A group is considered large if it has 3 or more characters.
Return the intervals of every large group sorted in increasing order by start index.
Example 1:
Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.
Example 2:
Input: s = "abc"
Output: []
Explanation: We have groups "a", "b", and "c", none of which are large groups.
Example 3:
Input: s = "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Explanation: The large groups are "ddd", "eeee", and "bbb".
Example 4:
Input: s = "aba"
Output: []
Constraints:
1 <= s.length <= 1000
s contains lower-case English letters only.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/positions-of-large-groups
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/*
遍历一遍字符串即可,记录相同字母开始的区间,在字母不同时封闭区间并判断
是否要加入到结果集合中。
循环结束后不要忘记判断最后一个区间是否符合要求。
*/
#include <cassert>
#include <iostream>
#include <vector>
#include <string>
using std::cout;
using std::endl;
using std::vector;
using std::string;
class Solution {
public:
vector<vector<int>> largeGroupPositions(string s) {
vector<vector<int>> groups;
int length = 1;
int start = 0;
for (int i = 1; i < (int) s.length(); i++) {
if (s[i] == s[start]) {
length++;
} else {
if (length >= 3) {
groups.push_back({ start, i - 1 });
}
start = i;
length = 1;
}
}
if (length >= 3) {
groups.push_back({ start, (int) s.length() - 1 });
}
return groups;
}
};
int main()
{
Solution s;
vector<vector<int>> groups;
vector<vector<int>> result;
result = { { 3,6 } };
assert(result == s.largeGroupPositions("abbxxxxzzy"));
result = { };
assert(result == s.largeGroupPositions("abc"));
result = { { 3,5 }, { 6,9 }, { 12,14 } };
assert(result == s.largeGroupPositions("abcdddeeeeaabbbcd"));
result = { };
assert(result == s.largeGroupPositions("aba"));
return 0;
}
| 23.814159 | 88 | 0.563359 | [
"vector"
] |
1536794b543265d7b5872c5099d816deba82f44b | 435 | cpp | C++ | design_add_and_search_words_data_structure.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | null | null | null | design_add_and_search_words_data_structure.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | 1 | 2020-12-17T07:54:03.000Z | 2020-12-17T08:00:22.000Z | design_add_and_search_words_data_structure.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | null | null | null | package leetcode
// https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/
class WordDictionary {
public:
WordDictionary() {
}
void addWord(string word) {
}
bool search(string word) {
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/ | 18.125 | 79 | 0.657471 | [
"object"
] |
15387248f6f1ea6a72933444b7b6fc4952d2ffe0 | 2,260 | hpp | C++ | inc/concept/swappable_with.hpp | matrixjoeq/concepts | d9bac8343e44c62f22913ec41ac0856b767bedc4 | [
"MIT"
] | null | null | null | inc/concept/swappable_with.hpp | matrixjoeq/concepts | d9bac8343e44c62f22913ec41ac0856b767bedc4 | [
"MIT"
] | null | null | null | inc/concept/swappable_with.hpp | matrixjoeq/concepts | d9bac8343e44c62f22913ec41ac0856b767bedc4 | [
"MIT"
] | null | null | null | /** @file */
#ifndef __STL_CONCEPT_SWAPPABLE_WITH_HPP__
#define __STL_CONCEPT_SWAPPABLE_WITH_HPP__
#include "concept/referenceable.hpp"
#include <type_traits>
#include <utility>
#include <boost/concept/usage.hpp>
#include <boost/concept/detail/concept_def.hpp>
#include "concept/detail/unuse.hpp"
#if (defined _MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4197) // topmost volatile ignored
#pragma warning(disable : 4510) // default constructor could not be generated
#pragma warning(disable : 4610) // object 'class' can never be instantiated - user-defined constructor required
#endif
namespace stl_concept {
/**
* @addtogroup library_wide_group Library-wide Requirements
* @struct SwappableWith
* @brief Specifies that lvalues of type T and type U are swappable.
*
* <p>
* <b>Requirements</b>
* </p><p>
* The type T and type U satisfies <i>SwappableWith</i> if<br/>
* Given
* <ul style="list-style-type:disc">
* <li>t1 and t2, distinct equal objects of type std::remove_cvref_t<T></li>
* </ul>
* <i>SwappableWith</i> is satisfied only if, after evaluating either swap(a1, b1) or swap(b1, a1),
* a1 is equal to b2 and b1 is equal to a2.
* </p>
* @tparam T - first type to be checked
* @tparam U - second type to be checked
* @see https://en.cppreference.com/w/cpp/named_req/Swappable
* @see https://en.cppreference.com/w/cpp/concepts/Swappable
*/
#ifdef DOXYGEN_WORKING
template <typename T, typename U>
struct SwappableWith {};
#else // DOXYGEN_WORKING
BOOST_concept(SwappableWith, (T)(U))
{
BOOST_CONCEPT_USAGE(SwappableWith)
{
BOOST_CONCEPT_ASSERT((Referenceable<T>));
BOOST_CONCEPT_ASSERT((Referenceable<U>));
swap_constraint<T, T>();
swap_constraint<T, U>();
swap_constraint<U, T>();
swap_constraint<U, U>();
}
private:
template <typename _T, typename _U>
void swap_constraint()
{
using std::swap;
using __Return = decltype(swap(std::declval<_T&>(), std::declval<_U&>()));
__detail::__Unuse<__Return>();
}
};
#endif // DOXYGEN_WORKING
} // namespace stl_concept
#if (defined _MSC_VER)
#pragma warning(pop)
#endif
#include <boost/concept/detail/concept_undef.hpp>
#endif // __STL_CONCEPT_SWAPPABLE_WITH_HPP__
| 28.607595 | 111 | 0.702212 | [
"object"
] |
15399c02c3c17ddc8ecd79c6a1d2a6f7453ff560 | 5,662 | cpp | C++ | test/main.cpp | JeffM2501/RLGameGui | 76577f889855b45e29bd287196f0b0c678a7dfe8 | [
"MIT"
] | 1 | 2021-04-08T16:12:42.000Z | 2021-04-08T16:12:42.000Z | test/main.cpp | JeffM2501/RLGameGui | 76577f889855b45e29bd287196f0b0c678a7dfe8 | [
"MIT"
] | 1 | 2021-02-03T16:16:57.000Z | 2021-02-03T16:16:57.000Z | test/main.cpp | JeffM2501/RLGameGui | 76577f889855b45e29bd287196f0b0c678a7dfe8 | [
"MIT"
] | 1 | 2021-02-03T10:26:49.000Z | 2021-02-03T10:26:49.000Z | /**********************************************************************************************
*
* RLGameGUi * A game gui for raylib
*
* LICENSE: MIT
*
* Copyright (c) 2020 Jeffery Myers
*
* 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 "raylib.h"
#include "RLGameGui.h"
#include "StandardElements.h"
using namespace RLGameGUI;
int main( int argc, char** argv)
{
SetConfigFlags(FLAG_WINDOW_RESIZABLE);
InitWindow(1000, 600, "GUI Test");
Texture2D background = LoadTexture("resources/hex.png");
Color backgroundColor = GetColor(0x1F252D);
Texture2D logo = LoadTexture("resources/raylib_logo.png");
Texture2D panelBG = LoadTexture("resources/KeyValueBackground.png");
Texture2D imageButton = LoadTexture("resources/ButtonBackground.png");
Texture2D imageButtonHover = LoadTexture("resources/ButtonBackground.hover.png");
Texture2D imageButtonDisabled = LoadTexture("resources/ButtonBackground.disabled.png");
Texture2D imageButtonPressed = LoadTexture("resources/ButtonBackground.active.png");
int fontSize = 26;
Font textFont = LoadFontEx("resources/fonts/BebasNeue Book.otf", fontSize, NULL, 0);
Color textColor = RAYWHITE;
GUIScreen::Ptr rootScreen = GUIScreen::Create();
GUIPanel::Ptr panel = GUIPanel::Create();
panel->Name = "panel1";
panel->RelativeBounds = RelativeRect(RelativeValue(1.0f, true), RelativeValue(1.0f, false), RelativeValue(0.75f, false), RelativeValue(0.75f, false), AlignmentTypes::Maximum, AlignmentTypes::Maximum, Vector2{ 10,10 });
panel->Background = panelBG;
panel->Padding = RelativePoint(16, 16);
panel->Fillmode = PanelFillModes::NPatch;
panel->NPatchGutters = Vector2{ 16, 16 };
panel->Tint = WHITE;
rootScreen->AddElement(panel);
GUIPanel::Ptr panel2 = GUIPanel::Create();
panel2->Name = "Panel2";
panel2->RelativeBounds = RelativeRect{ 0.0f, 0.0f, 1.0f, 0.25f };
panel2->Tint = GRAY;
panel2->Outline = BLACK;
panel2->OutlineThickness = 4;
panel->AddChild(panel2);
GUILabel::Ptr label = GUILabel::Create("I am IRON MAN",textFont,fontSize);
label->RelativeBounds = RelativeRect{ 0, 10, 500, 40 };
label->Tint = textColor;
rootScreen->AddElement(label);
GUILabel::Ptr label2 = GUILabel::Create("Centered", textFont, fontSize);
label2->Tint = textColor;
label2->RelativeBounds = RelativeRect{ 0, 20, 500, 40 };
label2->HorizontalAlignment = AlignmentTypes::Center;
rootScreen->AddElement(label2);
GUILabel::Ptr label3 = GUILabel::Create("Right", textFont, fontSize);
label3->Tint = textColor;
label3->RelativeBounds = RelativeRect{ 0, 40, 500, 40 };
label3->HorizontalAlignment = AlignmentTypes::Maximum;
rootScreen->AddElement(label3);
GUIImage::Ptr panel3 = GUIImage::Create();
panel3->RelativeBounds = RelativeRect(RelativeValue(0.0f, true), RelativeValue(1.0f, false), RelativeValue(0.125f, true), RelativeValue(0.125f, true), AlignmentTypes::Minimum, AlignmentTypes::Maximum, Vector2{ 10,10 });
panel3->Tint = WHITE;
panel3->Background = logo;
rootScreen->AddElement(panel3);
GUIButton::Ptr button = GUIButton::Create(imageButton);
button->RelativeBounds = RelativeRect(RelativeValue(1.0f, true), RelativeValue(0.0f, false), RelativeValue(150, true), RelativeValue(50, true), AlignmentTypes::Maximum, AlignmentTypes::Minimum, Vector2{ 10,10 });
button->TextColor = WHITE;
button->TextFont = textFont;
button->TextSize = (float)fontSize;
button->SetText("Button");
button->Fillmode = PanelFillModes::NPatch;
button->NPatchGutters = Vector2{ 16, 16 };
button->HoverTexture = imageButtonHover;
button->DisableTexture = imageButtonDisabled;
button->PressTexture = imageButtonPressed;
button->ElementClicked = [&label3](GUIElement*) {label3->SetText("Clicked"); };
rootScreen->AddElement(button);
Manager::PushScreen(rootScreen);
while (!WindowShouldClose())
{
Manager::Update();
BeginDrawing();
ClearBackground(backgroundColor);
float scale = 4;
float offset = (float)GetTime() * 200;
DrawTexturePro(background, Rectangle{ offset, offset,GetScreenWidth() * scale,GetScreenHeight() * scale }, Rectangle{ 0,0,(float)GetScreenWidth(),(float)GetScreenHeight() }, Vector2{ 0,0 }, 0, Color{ 255,255,255,64 });
// DrawTextureTiled(background, Rectangle{ 0,0,(float)background.width,(float)background.height }, Rectangle{ 0,0,(float)GetScreenWidth(),(float)GetScreenHeight() }, Vector2{ 0,0 }, 0, 0, WHITE);
// DrawLine(GetScreenWidth()/2, 0, GetScreenWidth()/2, GetScreenHeight(), RED);
Manager::Render();
EndDrawing();
}
UnloadTexture(logo);
CloseWindow();
return 0;
} | 40.733813 | 220 | 0.716355 | [
"render"
] |
1539d9a99f3983a928940511c6f28e21bdbe53e5 | 1,366 | hxx | C++ | src/Query.hxx | Caltech-IPAC/libtinyhtm | abc3394f3d37b3729a625989d2fc144f14a7d208 | [
"BSD-3-Clause"
] | 1 | 2019-06-17T21:56:31.000Z | 2019-06-17T21:56:31.000Z | src/Query.hxx | Caltech-IPAC/libtinyhtm | abc3394f3d37b3729a625989d2fc144f14a7d208 | [
"BSD-3-Clause"
] | null | null | null | src/Query.hxx | Caltech-IPAC/libtinyhtm | abc3394f3d37b3729a625989d2fc144f14a7d208 | [
"BSD-3-Clause"
] | null | null | null | #ifndef TINYHTM_QUERY_HXX
#define TINYHTM_QUERY_HXX
#include <memory>
#include <vector>
#include <functional>
#include "Exception.hxx"
#include "Circle.hxx"
#include "Cartesian.hxx"
#include "Ellipse.hxx"
#include "Box.hxx"
#include "Polygon.hxx"
#include "Tree.hxx"
namespace tinyhtm
{
class Query
{
public:
Tree tree;
std::unique_ptr<Shape> shape;
/// Circle
Query (const std::string &data_file, const Spherical &spherical,
const double &R)
: tree (data_file), shape (std::make_unique<Circle>(spherical, R))
{
}
/// Ellipse
Query (const std::string &data_file, const Ellipse &e)
: tree (data_file), shape (std::make_unique<Ellipse>(e))
{
}
/// Box
Query (const std::string &data_file, const Spherical &ra_dec,
const Spherical &width_height)
: tree (data_file), shape (std::make_unique<Box>(ra_dec, width_height))
{
}
/// Polygon
Query (const std::string &data_file, const std::vector<Spherical> &vertices)
: tree (data_file), shape (std::make_unique<Polygon>(vertices))
{
}
/// Generic string
Query (const std::string &data_file, const std::string &query_shape,
const std::string &vertex_string);
int64_t count () const { return shape->count (tree); }
int64_t search (htm_callback callback) const
{
return shape->search (tree, callback);
}
};
}
#endif
| 22.032258 | 78 | 0.671303 | [
"shape",
"vector"
] |
153c7c4cf729e8ed3fe075f727e2bf6f6ffb02aa | 2,481 | hpp | C++ | datatools/backend/merge_regions.hpp | torms3/DataTools | 8144a9485ca69dc2208bbcc20f59132def977b7a | [
"MIT"
] | null | null | null | datatools/backend/merge_regions.hpp | torms3/DataTools | 8144a9485ca69dc2208bbcc20f59132def977b7a | [
"MIT"
] | null | null | null | datatools/backend/merge_regions.hpp | torms3/DataTools | 8144a9485ca69dc2208bbcc20f59132def977b7a | [
"MIT"
] | 2 | 2018-05-29T18:27:18.000Z | 2018-06-01T13:36:24.000Z | //
// Copyright (C) 2012-2019 Aleksandar Zlateski <zlateski@mit.edu>
// Kisuk Lee <kisuklee@mit.edu>
// ---------------------------------------------------------------
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#pragma once
#include <vector>
#include <boost/pending/disjoint_sets.hpp>
#include "types.hpp"
namespace backend {
template< typename ID, typename F >
inline void
merge_regions( ID const * seg,
ID * out,
size_t n,
F const * dend_values,
ID const * dend_pairs,
size_t nedges,
F threshold )
{
// Find the largest ID in segmentation
ID max_segid = seg[0];
for ( size_t i = 1; i < n; ++i )
{
if ( seg[i] > max_segid )
max_segid = seg[i];
}
// Intitialize disjoint set
std::vector<ID> p(max_segid+1);
std::vector<uint8_t> r(max_segid+1);
for ( ID i = 0; i < max_segid+1; ++i )
{
p[i] = i;
r[i] = 0;
}
boost::disjoint_sets<uint8_t*,ID*> sets(&r[0],&p[0]);
// Merging
for ( size_t i = 0; i < nedges; ++i )
{
if ( dend_values[i] < threshold )
{
break;
}
ID s1 = sets.find_set(dend_pairs[2*i]);
ID s2 = sets.find_set(dend_pairs[2*i+1]);
if ( s1 != s2 && s1 && s2 )
{
sets.link(s1,s2);
uint32_t s = sets.find_set(s1);
}
}
// Remapping
std::vector<ID> remaps(max_segid+1);
ID next_id = 1;
for ( ID id = 0; id < max_segid+1; ++id )
{
ID s = sets.find_set(id);
if ( s && (remaps[s] == 0) )
{
remaps[s] = next_id++;
}
}
for ( std::ptrdiff_t idx = 0; idx < n; ++idx )
{
out[idx] = remaps[sets.find_set(seg[idx])];
}
}
} // namespace backend
| 25.84375 | 72 | 0.536477 | [
"vector"
] |
154de20b48191ec8f6c8379bd617704b5fcee174 | 19,659 | cpp | C++ | deps/libgeos/geos/src/algorithm/LineIntersector.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 42 | 2021-03-26T17:34:52.000Z | 2022-03-18T14:15:31.000Z | deps/libgeos/geos/src/algorithm/LineIntersector.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 29 | 2021-06-03T14:24:01.000Z | 2022-03-23T15:43:58.000Z | deps/libgeos/geos/src/algorithm/LineIntersector.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 8 | 2021-05-14T19:26:37.000Z | 2022-03-21T13:44:42.000Z | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2005-2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/RobustLineIntersector.java r785 (JTS-1.13+)
*
**********************************************************************/
#include <geos/constants.h>
#include <geos/algorithm/LineIntersector.h>
#include <geos/algorithm/Distance.h>
#include <geos/algorithm/Orientation.h>
#include <geos/algorithm/Intersection.h>
#include <geos/algorithm/NotRepresentableException.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/Envelope.h>
#include <algorithm> // for max()
#include <string>
#include <cmath> // for fabs()
#include <cassert>
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
#ifdef GEOS_DEBUG
#include <iostream>
#endif
using namespace geos::geom;
namespace geos {
namespace algorithm { // geos.algorithm
/*public static*/
double
LineIntersector::computeEdgeDistance(const Coordinate& p, const Coordinate& p0, const Coordinate& p1)
{
double dx = fabs(p1.x - p0.x);
double dy = fabs(p1.y - p0.y);
double dist = -1.0; // sentinel value
if(p == p0) {
dist = 0.0;
}
else if(p == p1) {
if(dx > dy) {
dist = dx;
}
else {
dist = dy;
}
}
else {
double pdx = fabs(p.x - p0.x);
double pdy = fabs(p.y - p0.y);
if(dx > dy) {
dist = pdx;
}
else {
dist = pdy;
}
// <FIX>
// hack to ensure that non-endpoints always have a non-zero distance
if(dist == 0.0 && !(p == p0)) {
dist = std::max(pdx, pdy);
}
}
assert(!(dist == 0.0 && !(p == p0))); // Bad distance calculation
return dist;
}
/*public*/
void
LineIntersector::computeIntersection(const Coordinate& p1, const Coordinate& p2, const Coordinate& p3,
const Coordinate& p4)
{
inputLines[0][0] = &p1;
inputLines[0][1] = &p2;
inputLines[1][0] = &p3;
inputLines[1][1] = &p4;
result = computeIntersect(p1, p2, p3, p4);
//numIntersects++;
}
/*public*/
std::string
LineIntersector::toString() const
{
std::string str = inputLines[0][0]->toString() + "_"
+ inputLines[0][1]->toString() + " "
+ inputLines[1][0]->toString() + "_"
+ inputLines[1][1]->toString() + " : ";
if(isEndPoint()) {
str += " endpoint";
}
if(isProperVar) {
str += " proper";
}
if(isCollinear()) {
str += " collinear";
}
return str;
}
/*public static*/
bool
LineIntersector::isSameSignAndNonZero(double a, double b)
{
if(a == 0 || b == 0) {
return false;
}
return (a < 0 && b < 0) || (a > 0 && b > 0);
}
/*private*/
void
LineIntersector::computeIntLineIndex()
{
computeIntLineIndex(0);
computeIntLineIndex(1);
}
/*public*/
const Coordinate&
LineIntersector::getIntersectionAlongSegment(std::size_t segmentIndex, std::size_t intIndex)
{
// lazily compute int line array
computeIntLineIndex();
return intPt[intLineIndex[segmentIndex][intIndex]];
}
/*public*/
size_t
LineIntersector::getIndexAlongSegment(std::size_t segmentIndex, std::size_t intIndex)
{
computeIntLineIndex();
return intLineIndex[segmentIndex][intIndex];
}
/*private*/
void
LineIntersector::computeIntLineIndex(std::size_t segmentIndex)
{
double dist0 = getEdgeDistance(segmentIndex, 0);
double dist1 = getEdgeDistance(segmentIndex, 1);
if(dist0 > dist1) {
intLineIndex[segmentIndex][0] = 0;
intLineIndex[segmentIndex][1] = 1;
}
else {
intLineIndex[segmentIndex][0] = 1;
intLineIndex[segmentIndex][1] = 0;
}
}
/*public*/
double
LineIntersector::getEdgeDistance(std::size_t segmentIndex, std::size_t intIndex) const
{
double dist = computeEdgeDistance(intPt[intIndex],
*inputLines[segmentIndex][0],
*inputLines[segmentIndex][1]);
return dist;
}
/*public static*/
double
LineIntersector::interpolateZ(const Coordinate& p,
const Coordinate& p1, const Coordinate& p2)
{
#if GEOS_DEBUG
std::cerr << "LineIntersector::interpolateZ(" << p.toString() << ", " << p1.toString() << ", " << p2.toString() << ")" <<
std::endl;
#endif
if(std::isnan(p1.z)) {
#if GEOS_DEBUG
std::cerr << " p1 do not have a Z" << std::endl;
#endif
return p2.z; // might be DoubleNotANumber again
}
if(std::isnan(p2.z)) {
#if GEOS_DEBUG
std::cerr << " p2 do not have a Z" << std::endl;
#endif
return p1.z; // might be DoubleNotANumber again
}
if(p == p1) {
#if GEOS_DEBUG
std::cerr << " p==p1, returning " << p1.z << std::endl;
#endif
return p1.z;
}
if(p == p2) {
#if GEOS_DEBUG
std::cerr << " p==p2, returning " << p2.z << std::endl;
#endif
return p2.z;
}
//double zgap = fabs(p2.z - p1.z);
double zgap = p2.z - p1.z;
if(zgap == 0.0) {
#if GEOS_DEBUG
std::cerr << " no zgap, returning " << p2.z << std::endl;
#endif
return p2.z;
}
double xoff = (p2.x - p1.x);
double yoff = (p2.y - p1.y);
double seglen = (xoff * xoff + yoff * yoff);
xoff = (p.x - p1.x);
yoff = (p.y - p1.y);
double pdist = (xoff * xoff + yoff * yoff);
double fract = sqrt(pdist / seglen);
double zoff = zgap * fract;
//double interpolated = p1.z < p2.z ? p1.z+zoff : p1.z-zoff;
double interpolated = p1.z + zoff;
#if GEOS_DEBUG
std::cerr << " zgap:" << zgap << " seglen:" << seglen << " pdist:" << pdist
<< " fract:" << fract << " z:" << interpolated << std::endl;
#endif
return interpolated;
}
/*public*/
void
LineIntersector::computeIntersection(const Coordinate& p, const Coordinate& p1, const Coordinate& p2)
{
isProperVar = false;
// do between check first, since it is faster than the orientation test
if(Envelope::intersects(p1, p2, p)) {
if((Orientation::index(p1, p2, p) == 0) &&
(Orientation::index(p2, p1, p) == 0)) {
isProperVar = true;
if((p == p1) || (p == p2)) { // 2d only test
isProperVar = false;
}
result = POINT_INTERSECTION;
return;
}
}
result = NO_INTERSECTION;
}
/* public static */
bool
LineIntersector::hasIntersection(const Coordinate& p, const Coordinate& p1, const Coordinate& p2)
{
if(Envelope::intersects(p1, p2, p)) {
if((Orientation::index(p1, p2, p) == 0) &&
(Orientation::index(p2, p1, p) == 0)) {
return true;
}
}
return false;
}
/*private*/
uint8_t
LineIntersector::computeIntersect(const Coordinate& p1, const Coordinate& p2,
const Coordinate& q1, const Coordinate& q2)
{
#if GEOS_DEBUG
std::cerr << "LineIntersector::computeIntersect called" << std::endl;
std::cerr << " p1:" << p1.toString() << " p2:" << p2.toString() << " q1:" << q1.toString() << " q2:" << q2.toString() <<
std::endl;
#endif // GEOS_DEBUG
isProperVar = false;
// first try a fast test to see if the envelopes of the lines intersect
if(!Envelope::intersects(p1, p2, q1, q2)) {
#if GEOS_DEBUG
std::cerr << " NO_INTERSECTION" << std::endl;
#endif
return NO_INTERSECTION;
}
// for each endpoint, compute which side of the other segment it lies
// if both endpoints lie on the same side of the other segment,
// the segments do not intersect
int Pq1 = Orientation::index(p1, p2, q1);
int Pq2 = Orientation::index(p1, p2, q2);
if((Pq1 > 0 && Pq2 > 0) || (Pq1 < 0 && Pq2 < 0)) {
#if GEOS_DEBUG
std::cerr << " NO_INTERSECTION" << std::endl;
#endif
return NO_INTERSECTION;
}
int Qp1 = Orientation::index(q1, q2, p1);
int Qp2 = Orientation::index(q1, q2, p2);
if((Qp1 > 0 && Qp2 > 0) || (Qp1 < 0 && Qp2 < 0)) {
#if GEOS_DEBUG
std::cerr << " NO_INTERSECTION" << std::endl;
#endif
return NO_INTERSECTION;
}
/**
* Intersection is collinear if each endpoint lies on the other line.
*/
bool collinear = Pq1 == 0 && Pq2 == 0 && Qp1 == 0 && Qp2 == 0;
if(collinear) {
#if GEOS_DEBUG
std::cerr << " computingCollinearIntersection" << std::endl;
#endif
return computeCollinearIntersection(p1, p2, q1, q2);
}
/*
* At this point we know that there is a single intersection point
* (since the lines are not collinear).
*/
/*
* Check if the intersection is an endpoint.
* If it is, copy the endpoint as
* the intersection point. Copying the point rather than
* computing it ensures the point has the exact value,
* which is important for robustness. It is sufficient to
* simply check for an endpoint which is on the other line,
* since at this point we know that the inputLines must
* intersect.
*/
Coordinate p;
double z = DoubleNotANumber;
if(Pq1 == 0 || Pq2 == 0 || Qp1 == 0 || Qp2 == 0) {
isProperVar = false;
#if GEOS_DEBUG
std::cerr << " intersection is NOT proper" << std::endl;
#endif
/* Check for two equal endpoints.
* This is done explicitly rather than by the orientation tests
* below in order to improve robustness.
*
* (A example where the orientation tests fail
* to be consistent is:
*
* LINESTRING ( 19.850257749638203 46.29709338043669,
* 20.31970698357233 46.76654261437082 )
* and
* LINESTRING ( -48.51001596420236 -22.063180333403878,
* 19.850257749638203 46.29709338043669 )
*
* which used to produce the INCORRECT result:
* (20.31970698357233, 46.76654261437082, NaN)
*/
if (p1.equals2D(q1)) {
p = p1;
z = zGet(p1, q1);
}
else if (p1.equals2D(q2)) {
p = p1;
z = zGet(p1, q2);
}
else if (p2.equals2D(q1)) {
p = p2;
z = zGet(p2, q1);
}
else if (p2.equals2D(q2)) {
p = p2;
z = zGet(p2, q2);
}
/*
* Now check to see if any endpoint lies on the interior of the other segment.
*/
else if(Pq1 == 0) {
p = q1;
z = zGetOrInterpolate(q1, p1, p2);
}
else if(Pq2 == 0) {
p = q2;
z = zGetOrInterpolate(q2, p1, p2);
}
else if(Qp1 == 0) {
p = p1;
z = zGetOrInterpolate(p1, q1, q2);
}
else if(Qp2 == 0) {
p = p2;
z = zGetOrInterpolate(p2, q1, q2);
}
}
else {
#if GEOS_DEBUG
std::cerr << " intersection is proper" << std::endl;
#endif // GEOS_DEBUG
isProperVar = true;
p = intersection(p1, p2, q1, q2);
#if GEOS_DEBUG
std::cerr << " computed intersection point: " << p << std::endl;
#endif // GEOS_DEBUG
z = zInterpolate(p, p1, p2, q1, q2);
#if GEOS_DEBUG
std::cerr << " computed proper intersection Z: " << z << std::endl;
#endif // GEOS_DEBUG
}
intPt[0] = Coordinate(p.x, p.y, z);
#if GEOS_DEBUG
std::cerr << " POINT_INTERSECTION; intPt[0]:" << intPt[0].toString() << std::endl;
#endif // GEOS_DEBUG
return POINT_INTERSECTION;
}
/*private*/
uint8_t
LineIntersector::computeCollinearIntersection(const Coordinate& p1, const Coordinate& p2,
const Coordinate& q1, const Coordinate& q2)
{
#if GEOS_DEBUG
std::cerr << "LineIntersector::computeCollinearIntersection called" << std::endl;
std::cerr << " p1:" << p1.toString() << " p2:" << p2.toString() << " q1:" << q1.toString() << " q2:" << q2.toString() <<
std::endl;
#endif // GEOS_DEBUG
bool q1inP = Envelope::intersects(p1, p2, q1);
bool q2inP = Envelope::intersects(p1, p2, q2);
bool p1inQ = Envelope::intersects(q1, q2, p1);
bool p2inQ = Envelope::intersects(q1, q2, p2);
if(q1inP && q2inP) {
#if GEOS_DEBUG
std::cerr << " q1inP && q2inP" << std::endl;
#endif
intPt[0] = zGetOrInterpolateCopy(q1, p1, p2);
intPt[1] = zGetOrInterpolateCopy(q2, p1, p2);
#if GEOS_DEBUG
std::cerr << " intPt[0]: " << intPt[0].toString() << std::endl;
std::cerr << " intPt[1]: " << intPt[1].toString() << std::endl;
#endif
return COLLINEAR_INTERSECTION;
}
if(p1inQ && p2inQ) {
#if GEOS_DEBUG
std::cerr << " p1inQ && p2inQ" << std::endl;
#endif
intPt[0] = zGetOrInterpolateCopy(p1, q1, q2);
intPt[1] = zGetOrInterpolateCopy(p2, q1, q2);
return COLLINEAR_INTERSECTION;
}
if(q1inP && p1inQ) {
#if GEOS_DEBUG
std::cerr << " q1inP && p1inQ" << std::endl;
#endif
// if pts are equal Z is chosen arbitrarily
intPt[0] = zGetOrInterpolateCopy(q1, p1, p2);
intPt[1] = zGetOrInterpolateCopy(p1, q1, q2);
#if GEOS_DEBUG
std::cerr << " intPt[0]: " << intPt[0].toString() << std::endl;
std::cerr << " intPt[1]: " << intPt[1].toString() << std::endl;
#endif
return (q1 == p1) && !q2inP && !p2inQ ? POINT_INTERSECTION : COLLINEAR_INTERSECTION;
}
if(q1inP && p2inQ) {
#if GEOS_DEBUG
std::cerr << " q1inP && p2inQ" << std::endl;
#endif
// if pts are equal Z is chosen arbitrarily
intPt[0] = zGetOrInterpolateCopy(q1, p1, p2);
intPt[1] = zGetOrInterpolateCopy(p2, q1, q2);
#if GEOS_DEBUG
std::cerr << " intPt[0]: " << intPt[0].toString() << std::endl;
std::cerr << " intPt[1]: " << intPt[1].toString() << std::endl;
#endif
return (q1 == p2) && !q2inP && !p1inQ ? POINT_INTERSECTION : COLLINEAR_INTERSECTION;
}
if(q2inP && p1inQ) {
#if GEOS_DEBUG
std::cerr << " q2inP && p1inQ" << std::endl;
#endif
// if pts are equal Z is chosen arbitrarily
intPt[0] = zGetOrInterpolateCopy(q2, p1, p2);
intPt[1] = zGetOrInterpolateCopy(p1, q1, q2);
#if GEOS_DEBUG
std::cerr << " intPt[0]: " << intPt[0].toString() << std::endl;
std::cerr << " intPt[1]: " << intPt[1].toString() << std::endl;
#endif
return (q2 == p1) && !q1inP && !p2inQ ? POINT_INTERSECTION : COLLINEAR_INTERSECTION;
}
if(q2inP && p2inQ) {
#if GEOS_DEBUG
std::cerr << " q2inP && p2inQ" << std::endl;
#endif
// if pts are equal Z is chosen arbitrarily
intPt[0] = zGetOrInterpolateCopy(q2, p1, p2);
intPt[1] = zGetOrInterpolateCopy(p2, q1, q2);
#if GEOS_DEBUG
std::cerr << " intPt[0]: " << intPt[0].toString() << std::endl;
std::cerr << " intPt[1]: " << intPt[1].toString() << std::endl;
#endif
return (q2 == p2) && !q1inP && !p1inQ ? POINT_INTERSECTION : COLLINEAR_INTERSECTION;
}
return NO_INTERSECTION;
}
/*private*/
Coordinate
LineIntersector::intersection(const Coordinate& p1, const Coordinate& p2,
const Coordinate& q1, const Coordinate& q2) const
{
Coordinate intPtOut = intersectionSafe(p1, p2, q1, q2);
/*
* Due to rounding it can happen that the computed intersection is
* outside the envelopes of the input segments. Clearly this
* is inconsistent.
* This code checks this condition and forces a more reasonable answer
*
* MD - May 4 2005 - This is still a problem. Here is a failure case:
*
* LINESTRING (2089426.5233462777 1180182.3877339689,
* 2085646.6891757075 1195618.7333999649)
* LINESTRING (1889281.8148903656 1997547.0560044837,
* 2259977.3672235999 483675.17050843034)
* int point = (2097408.2633752143,1144595.8008114607)
*/
if(! isInSegmentEnvelopes(intPtOut)) {
//intPt = CentralEndpointIntersector::getIntersection(p1, p2, q1, q2);
intPtOut = nearestEndpoint(p1, p2, q1, q2);
#if GEOS_DEBUG
std::cerr << "Intersection outside segment envelopes, snapped to "
<< intPtOut.toString() << std::endl;
#endif
}
if(precisionModel != nullptr) {
precisionModel->makePrecise(intPtOut);
}
return intPtOut;
}
/* private static */
double
LineIntersector::zInterpolate(const Coordinate& p, const Coordinate& p1, const Coordinate& p2)
{
#if GEOS_DEBUG
std::cerr << " zInterpolate " << p << ", " << p1 << ", " << p2 << std::endl;
#endif
double p1z = p1.z;
double p2z = p2.z;
if (std::isnan(p1z)) {
return p2z; // may be NaN
}
if (std::isnan(p2z)) {
return p1z; // may be NaN
}
if (p.equals2D(p1)) {
return p1z; // not NaN
}
if (p.equals2D(p2)) {
return p2z; // not NaN
}
double dz = p2z - p1z;
if (dz == 0.0) {
return p1z;
}
#if GEOS_DEBUG
std::cerr << " Interpolating Z from distance of p along p1-p2" << std::endl;
#endif
// interpolate Z from distance of p along p1-p2
double dx = (p2.x - p1.x);
double dy = (p2.y - p1.y);
// seg has non-zero length since p1 < p < p2
double seglen = (dx * dx + dy * dy);
double xoff = (p.x - p1.x);
double yoff = (p.y - p1.y);
double plen = (xoff * xoff + yoff * yoff);
double frac = sqrt(plen / seglen);
double zoff = dz * frac;
double zInterpolated = p1z + zoff;
#if GEOS_DEBUG
std::cerr << " interpolated Z: " << zInterpolated << std::endl;
#endif
return zInterpolated;
}
double
LineIntersector::zInterpolate(const Coordinate& p,
const Coordinate& p1,
const Coordinate& p2,
const Coordinate& q1,
const Coordinate& q2)
{
#if GEOS_DEBUG
std::cerr << " zInterpolate(5 coords) called" << std::endl;
#endif // GEOS_DEBUG
double zp = zInterpolate(p, p1, p2);
#if GEOS_DEBUG
std::cerr << " zp: " << zp << std::endl;
#endif // GEOS_DEBUG
double zq = zInterpolate(p, q1, q2);
#if GEOS_DEBUG
std::cerr << " zq: " << zq << std::endl;
#endif // GEOS_DEBUG
if (std::isnan(zp)) {
return zq; // may be NaN
}
if (std::isnan(zq)) {
return zp; // may be NaN
}
#if GEOS_DEBUG
std::cerr << " averaging Z" << std::endl;
#endif // GEOS_DEBUG
// both Zs have values, so average them
return (zp + zq) / 2.0;
}
/* private static */
Coordinate
LineIntersector::nearestEndpoint(const Coordinate& p1, const Coordinate& p2,
const Coordinate& q1, const Coordinate& q2)
{
const Coordinate* nearestPt = &p1;
double minDist = Distance::pointToSegment(p1, q1, q2);
double dist = Distance::pointToSegment(p2, q1, q2);
if(dist < minDist) {
minDist = dist;
nearestPt = &p2;
}
dist = Distance::pointToSegment(q1, p1, p2);
if(dist < minDist) {
minDist = dist;
nearestPt = &q1;
}
dist = Distance::pointToSegment(q2, p1, p2);
if(dist < minDist) {
nearestPt = &q2;
}
return *nearestPt;
}
} // namespace geos.algorithm
} // namespace geos
#ifndef GEOS_INLINE
# include "geos/algorithm/LineIntersector.inl"
#endif
| 29.038405 | 125 | 0.567323 | [
"geometry"
] |
155422ffb88519b32501e28aa0b3426dff3ead8a | 695 | cpp | C++ | C++/unique-letter-string.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/unique-letter-string.cpp | pnandini/LeetCode | e746c3298be96dec8e160da9378940568ef631b1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/unique-letter-string.cpp | pnandini/LeetCode | e746c3298be96dec8e160da9378940568ef631b1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(1)
class Solution {
public:
int uniqueLetterString(string S) {
static const int M = 1e9 + 7;
int result = 0;
vector<vector<int>> index(26, vector<int>(2, -1));
for (int i = 0; i < S.length(); ++i) {
int c = S[i] - 'A';
result = (result + (i - index[c][1]) *
(index[c][1] - index[c][0])) % M;
index[c][0] = index[c][1];
index[c][1] = i;
}
for (int c = 0; c < 26; ++c) {
result = (result + (S.length() - index[c][1]) *
(index[c][1] - index[c][0])) % M;
}
return result;
}
};
| 28.958333 | 64 | 0.385612 | [
"vector"
] |
15562d4df3f69416c3a7ba0c2e5affe6e6d1ce70 | 2,826 | cpp | C++ | pelin/pelin.cpp | wowcube/wasm | 438c0b4a38a7754dd349684c0305d61f0e6bf01f | [
"MIT"
] | 1 | 2020-11-05T21:25:41.000Z | 2020-11-05T21:25:41.000Z | pelin/pelin.cpp | wowcube/wasm | 438c0b4a38a7754dd349684c0305d61f0e6bf01f | [
"MIT"
] | 4 | 2021-01-22T16:19:27.000Z | 2021-02-11T16:58:10.000Z | pelin/pelin.cpp | wowcube/wasm | 438c0b4a38a7754dd349684c0305d61f0e6bf01f | [
"MIT"
] | 3 | 2021-02-12T20:14:33.000Z | 2021-04-01T03:16:06.000Z | #include "cube_api.h"
#include <cstdio>
#include <string>
#include <cmath>
#include "PerlinNoise.h"
class CEventLoopEx : public CEventLoop
{
uint8_t m_cid = 0;
Get_TRBL_1_0 m_trbl;
double m_cache[240 * 240] = {};
protected:
bool OnTick(uint32_t time) override
{
for (int display = 0; display < 3; ++display) {
CDisplay disp(display);
disp.Fill(fColor(1, 1, 1));
unsigned int height = 240, width = 240;
// Visit every pixel of the image and assign a color generated with Perlin noise
for (unsigned int i = 0; i < height; ++i) { // y
for (unsigned int j = 0; j < width; ++j) { // x
double x = (double)j / ((double)width);
double y = (double)i / ((double)height);
// Typical Perlin noise
double n = ((time / 2000) % 10 + 10) * m_cache[i * width + j];
n = float(n - floor(n));
// Map the values to the [0, 255] interval, for simplicity we use
// tones of grey
disp.DrawPixelAlpha(i, j, fColor(n, n, n), 255);
}
}
}
return CEventLoop::OnTick(time);
}
void OnGyroChanged(const Get_Gyro_1_0& _gyro) override {
}
void OnAccelChanged(const Get_Accel_1_0& _accel) override {
}
void OwnCID(uint8_t cid) override
{
NativePrint("MY CID IS %d", cid);
m_cid = cid;
}
void OnMessage(uint32_t size, const Get_Message_1_0& msg) override {
NativePrint("WASM OnMessage from: %d, size: %d, message: %s", msg.from_cid, msg.size, (char*)msg.data);
};
void OnTRBLChanged(const Get_TRBL_1_0& trbl) override {
}
void InitCache()
{
unsigned int height = 240, width = 240;
// Create a PerlinNoise object with a random permutation vector generated with seed
unsigned int seed = 237;
PerlinNoise pn(seed);
// Visit every pixel of the image and assign a color generated with Perlin noise
for (unsigned int i = 0; i < height; ++i) { // y
for (unsigned int j = 0; j < width; ++j) { // x
double x = (double)j / ((double)width);
double y = (double)i / ((double)height);
// Typical Perlin noise
m_cache[i * width + j] = pn.noise(x, y, 0.8);
}
}
}
public:
int Main() override
{
InitCache();
$( Send_Message_1_0{ estSelf, 0, NULL} );
return CEventLoop::Main();
}
};
WASM_EXPORT int run() // native cube code searches for this function and runs as a main()
{
//whatever you return here will just be recorded into logs
return CEventLoopEx().Main();
}
| 27.980198 | 111 | 0.54034 | [
"object",
"vector"
] |
1556fd4d40d1c89e42c20ac30407caaea64558b2 | 1,157 | cc | C++ | RecoLocalCalo/HcalRecAlgos/src/PedestalSub.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | RecoLocalCalo/HcalRecAlgos/src/PedestalSub.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | RecoLocalCalo/HcalRecAlgos/src/PedestalSub.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cmath>
#include <climits>
#include "RecoLocalCalo/HcalRecAlgos/interface/PedestalSub.h"
using namespace std;
PedestalSub::PedestalSub() : fThreshold(2.7),fQuantile(0.0),fCondition(0){
}
PedestalSub::~PedestalSub() {
}
void PedestalSub::init(int runCond=0, float threshold=0.0, float quantile=0.0) {
fThreshold=threshold;
fQuantile=quantile;
fCondition=runCond;
}
void PedestalSub::calculate(const std::vector<double> & inputCharge, const std::vector<double> & inputPedestal, std::vector<double> & corrCharge) const {
double bseCorr=PedestalSub::getCorrection(inputCharge, inputPedestal);
for (auto i=0; i<10; i++) {
corrCharge.push_back(inputCharge[i]-inputPedestal[i]-bseCorr);
}
}
double PedestalSub::getCorrection(const std::vector<double> & inputCharge, const std::vector<double> & inputPedestal) const {
double baseline=0;
for (auto i=0; i<10; i++) {
if (i==4||i==5) continue;
if ( (inputCharge[i]-inputPedestal[i])<fThreshold) {
baseline+=(inputCharge[i]-inputPedestal[i]);
}
else {
baseline+=fThreshold;
}
}
baseline/=8;
return baseline;
}
| 25.711111 | 153 | 0.695765 | [
"vector"
] |
15611da6af4e81025ddd92e3622c6fcc0e0d03d0 | 6,446 | cpp | C++ | module-utils/bootconfig/src/bootconfig.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-utils/bootconfig/src/bootconfig.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-utils/bootconfig/src/bootconfig.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <boot/bootconfig.hpp>
#include <boot/bootconstants.hpp>
#include <gsl/util>
#include <limits.h>
#include <purefs/filesystem_paths.hpp>
#include <product/version.hpp>
#include <time/time_conversion.hpp>
#include <ticks.hpp>
#include <cstdio>
#include <log/log.hpp>
#include <array>
#include <Utils.hpp>
#include <fstream>
#include <purefs/filesystem_paths.hpp>
namespace boot
{
namespace
{
std::string loadFileAsString(const std::filesystem::path &fileToLoad)
{
std::string content;
std::ifstream in(fileToLoad);
std::getline(in, content, std::string::traits_type::to_char_type(std::string::traits_type::eof()));
return content;
}
bool verifyCRC(const std::filesystem::path &file, const unsigned long crc32)
{
auto fp = fopen(file.c_str(), "r");
if (!fp) {
LOG_ERROR("verifyCRC can't open %s", file.c_str());
return false;
}
auto fpCloseAct = gsl::finally([fp] { fclose(fp); });
unsigned long crc32Read = utils::filesystem::computeFileCRC32(fp);
LOG_INFO(
"verifyCRC computed crc32 for %s is %08" PRIX32, file.c_str(), static_cast<std::uint32_t>(crc32Read));
return crc32Read == crc32;
}
bool readAndVerifyCRC(const std::filesystem::path &file)
{
std::filesystem::path crcFilePath(file);
crcFilePath += boot::consts::ext_crc32;
auto fp = fopen(crcFilePath.c_str(), "r");
if (!fp) {
LOG_ERROR("verifyCRC can't open %s", crcFilePath.c_str());
return false;
}
auto fpCloseAct = gsl::finally([fp] { fclose(fp); });
std::array<char, boot::consts::crc_char_size + 1> crcBuf;
size_t readSize = std::fread(crcBuf.data(), 1, boot::consts::crc_char_size, fp);
if (readSize != boot::consts::crc_char_size) {
LOG_ERROR("verifyCRC fread on %s returned different size then %d [%zu]",
crcFilePath.c_str(),
boot::consts::crc_char_size,
readSize);
return false;
}
crcBuf[boot::consts::crc_char_size] = 0;
const unsigned long crc32Read = strtoull(crcBuf.data(), nullptr, boot::consts::crc_radix);
LOG_INFO("verifyCRC read %s string:\"%s\" hex:%08lX", crcFilePath.c_str(), crcBuf.data(), crc32Read);
return verifyCRC(file, crc32Read);
}
} // namespace
BootConfig::BootConfig() : m_os_root_path(purefs::dir::getRootDiskPath())
{}
json11::Json BootConfig::to_json() const
{
return json11::Json::object{
{boot::json::main,
json11::Json::object{{boot::json::os_image, m_os_image},
{boot::json::os_type, m_os_type},
{boot::json::os_version, m_os_version},
{boot::json::timestamp, m_timestamp}}},
{boot::json::git_info,
json11::Json::object{{boot::json::os_git_revision, std::string(GIT_REV)},
{boot::json::os_git_branch, std::string(GIT_BRANCH)}}},
{boot::json::bootloader, json11::Json::object{{boot::json::os_version, m_bootloader_version}}}};
}
int BootConfig::load()
{
return !loadBootConfig(getCurrentBootJSON());
}
// Method to compare two version strings
// v1 < v2 -> -1
// v1 == v2 -> 0
int BootConfig::version_compare(const std::string &v1, const std::string &v2)
{
size_t i = 0, j = 0;
while (i < v1.length() || j < v2.length()) {
int acc1 = 0, acc2 = 0;
while (i < v1.length() && v1[i] != '.') {
acc1 = acc1 * 10 + (v1[i] - '0');
i++;
}
while (j < v2.length() && v2[j] != '.') {
acc2 = acc2 * 10 + (v2[j] - '0');
j++;
}
if (acc1 < acc2)
return -1;
if (acc1 > acc2)
return +1;
++i;
++j;
}
return 0;
}
bool BootConfig::loadBootConfig(const std::filesystem::path &bootJsonPath)
{
std::string parseErrors = "";
std::string jsonContents = loadFileAsString(bootJsonPath);
LOG_INFO("parsed %s: \"%s\"", bootJsonPath.c_str(), jsonContents.c_str());
m_boot_json_parsed = json11::Json::parse(jsonContents, parseErrors);
if (parseErrors == "") {
m_os_type = m_boot_json_parsed[boot::json::main][boot::json::os_type].string_value();
m_os_image = m_boot_json_parsed[boot::json::main][boot::json::os_image].string_value();
m_os_root_path = purefs::createPath(purefs::dir::getRootDiskPath(), m_os_type);
m_boot_json = bootJsonPath;
m_bootloader_version = m_boot_json_parsed[boot::json::bootloader][boot::json::os_version].string_value();
m_timestamp = utils::time::getCurrentTimestamp().str("%c");
m_os_version = std::string(VERSION);
LOG_INFO("boot_config: %s", to_json().dump().c_str());
return true;
}
else {
m_os_type = purefs::dir::getCurrentOSPath();
m_os_image = purefs::file::boot_bin;
m_os_root_path = purefs::createPath(purefs::dir::getRootDiskPath(), m_os_type);
m_boot_json = bootJsonPath;
m_timestamp = utils::time::getCurrentTimestamp().str("%c");
m_os_version = std::string(VERSION);
LOG_WARN("%s failed to parse %s: \"%s\"", __FUNCTION__, bootJsonPath.c_str(), parseErrors.c_str());
return false;
}
}
std::filesystem::path BootConfig::getCurrentBootJSON()
{
auto boot_json_path = purefs::dir::getRootDiskPath() / purefs::file::boot_json;
if (!readAndVerifyCRC(boot_json_path)) {
LOG_INFO("CRC check failed on %s", boot_json_path.c_str());
}
return boot_json_path;
}
} // namespace boot
| 37.045977 | 118 | 0.546385 | [
"object"
] |
d08485b447fecfbac0eeee9da1bbd1197f8b3a82 | 20,844 | cpp | C++ | test/graph_partition.cpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | test/graph_partition.cpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | test/graph_partition.cpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// 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 <memory>
#include <sstream>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <vector>
#include "gtest/gtest.h"
#include "ngraph/graph_util.hpp"
#include "ngraph/ngraph.hpp"
#include "ngraph/pass/assign_placement.hpp"
#include "ngraph/pass/manager.hpp"
#include "ngraph/runtime/host_tensor_view.hpp"
#include "ngraph/util.hpp"
#include "util/ndarray.hpp"
#include "util/test_tools.hpp"
using namespace std;
using namespace ngraph;
// Perform all operations on INTERPRETER and fallback Multiply to CPU
static function<Placement(shared_ptr<Node>)> int_with_cpu_mul_policy = [](shared_ptr<Node> node) {
Placement placement;
string node_op = node->description();
if (node_op == "Multiply")
{
placement = Placement::CPU;
}
else
{
placement = Placement::INTERPRETER;
}
return placement;
};
// HybridCallFrame servers 2 purposes:
// 1. HybridBackend's main use case is to test device placement and graph partition routines.
// 2. It also shows how glued-hybrid runtime can be built by combining different runtimes.
//
// By default, HybridBackend operates on INTERPRETER (for example, the primary tensor view is
// INTERPRETER tensor view). It falls back to CPU when requested by placement.
class HybridBackend
{
public:
HybridBackend(const function<Placement(shared_ptr<Node>)>& placement_policy)
: m_placement_policy(placement_policy)
{
}
~HybridBackend() {}
shared_ptr<runtime::TensorView> create_tensor(const element::Type& element_type,
const Shape& shape)
{
return get_cached_backend(Placement::INTERPRETER)->create_tensor(element_type, shape);
}
bool compile(const shared_ptr<Function>& func)
{
if (!contains_key(m_function_map, func))
{
// Clone function
FunctionInstance instance;
instance.m_function = clone_function(*func);
// Run placement pass
pass::Manager pass_manager;
pass_manager.register_pass<pass::AssignPlacement>(int_with_cpu_mul_policy);
pass_manager.run_passes(instance.m_function);
// Split function to sub_functions
tie(instance.m_sub_functions, instance.m_map_parameter_to_result) =
split_function_by_placement(instance.m_function);
m_function_map.insert({func, instance});
// Compile subfunctions in corresponding backends
for (shared_ptr<Function>& sub_function : instance.m_sub_functions)
{
Placement placement = get_colocated_function_placement(sub_function);
auto backend = get_cached_backend(placement);
backend->compile(sub_function);
}
}
return true;
}
bool call_with_validate(const shared_ptr<Function>& func,
const vector<shared_ptr<runtime::TensorView>>& outputs,
const vector<shared_ptr<runtime::TensorView>>& inputs)
{
// Get FunctionInstance
bool rc = true;
auto it = m_function_map.find(func);
if (it == m_function_map.end())
{
compile(func);
it = m_function_map.find(func);
}
if (it == m_function_map.end())
{
throw runtime_error("Error constructing backend.");
}
FunctionInstance& instance = it->second;
// Parameter and result node in sub_function maps to one TensorView
unordered_map<shared_ptr<Node>, shared_ptr<runtime::TensorView>> map_node_to_tensor_view;
for (size_t i = 0; i < inputs.size(); ++i)
{
map_node_to_tensor_view[instance.m_function->get_parameters()[i]] = inputs[i];
}
for (size_t i = 0; i < outputs.size(); ++i)
{
map_node_to_tensor_view[instance.m_function->get_results()[i]] = outputs[i];
}
// Call subfunctions
for (shared_ptr<Function>& sub_function : instance.m_sub_functions)
{
// Init backend
Placement placement = get_colocated_function_placement(sub_function);
auto backend = get_cached_backend(placement);
// Prepare parameter TensorViews
vector<shared_ptr<runtime::TensorView>> parameter_tvs;
for (auto parameter_node : sub_function->get_parameters())
{
if (map_node_to_tensor_view.find(parameter_node) != map_node_to_tensor_view.end())
{
parameter_tvs.push_back(map_node_to_tensor_view.at(parameter_node));
}
else
{
auto result_node = instance.m_map_parameter_to_result.at(parameter_node);
auto result_tv = map_node_to_tensor_view.at(result_node);
auto parameter_tv = backend->create_tensor(parameter_node->get_element_type(),
parameter_node->get_shape());
copy_data(parameter_tv, read_vector<float>(result_tv));
map_node_to_tensor_view[parameter_node] = parameter_tv;
parameter_tvs.push_back(parameter_tv);
}
}
// Prepare result TensorViews
vector<shared_ptr<runtime::TensorView>> result_tvs;
for (auto result_node : sub_function->get_results())
{
if (map_node_to_tensor_view.find(result_node) != map_node_to_tensor_view.end())
{
result_tvs.push_back(map_node_to_tensor_view.at(result_node));
}
else
{
auto result_tv = backend->create_tensor(result_node->get_element_type(),
result_node->get_shape());
map_node_to_tensor_view[result_node] = result_tv;
result_tvs.push_back(result_tv);
}
}
// Call
backend->call_with_validate(sub_function, result_tvs, parameter_tvs);
}
return rc;
}
protected:
class FunctionInstance
{
public:
shared_ptr<Function> m_function;
vector<shared_ptr<Function>> m_sub_functions;
unordered_map<shared_ptr<op::Parameter>, shared_ptr<op::Result>> m_map_parameter_to_result;
};
shared_ptr<runtime::Backend> get_cached_backend(Placement placement)
{
if (m_cached_backends.find(placement) == m_cached_backends.end())
{
m_cached_backends[placement] = runtime::Backend::create(placement_to_string(placement));
}
return m_cached_backends.at(placement);
}
map<Placement, shared_ptr<runtime::Backend>> m_cached_backends;
map<shared_ptr<Function>, FunctionInstance> m_function_map;
function<Placement(shared_ptr<Node>)> m_placement_policy;
};
TEST(graph_partition, placement_all_cpu_policy)
{
Shape shape = Shape{2, 2};
shared_ptr<op::Parameter> A = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> B = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> C = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<Node> AplusB = A + B;
shared_ptr<Node> AplusBtimesC = AplusB * C;
shared_ptr<Function> f = make_shared<Function>(AplusBtimesC, op::ParameterVector{A, B, C});
for (auto node : f->get_ordered_ops())
{
EXPECT_EQ(node->get_placement(), Placement::DEFAULT);
}
pass::Manager pass_manager;
pass_manager.register_pass<pass::AssignPlacement>(
[](shared_ptr<Node> node) { return Placement::CPU; });
pass_manager.run_passes(f);
for (auto node : f->get_ordered_ops())
{
EXPECT_EQ(node->get_placement(), Placement::CPU);
}
}
#ifdef NGRAPH_CPU_ENABLE
TEST(graph_partition, placement_int_with_cpu_mul_policy)
{
Shape shape = Shape{2, 2};
shared_ptr<op::Parameter> A = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> B = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> C = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<Node> AplusB = A + B;
shared_ptr<Node> AplusBtimesC = AplusB * C;
shared_ptr<Function> f = make_shared<Function>(AplusBtimesC, op::ParameterVector{A, B, C});
for (auto node : f->get_ordered_ops())
{
EXPECT_EQ(node->get_placement(), Placement::DEFAULT);
}
pass::Manager pass_manager;
pass_manager.register_pass<pass::AssignPlacement>(int_with_cpu_mul_policy);
pass_manager.run_passes(f);
for (auto node : f->get_ordered_ops())
{
string node_op = node->description();
if (node_op == "Multiply")
{
EXPECT_EQ(node->get_placement(), Placement::CPU);
}
else
{
EXPECT_EQ(node->get_placement(), Placement::INTERPRETER);
}
}
}
TEST(graph_partition, hybrid_abc_manual)
{
// A B C A B C
// \ / / \ / /
// +D / +D /
// \ / | /
// *E R0 R1 f0(INT)
// | ------------------
// R P0 P1
// \ /
// *E
// |
// R2 f1(CPU)
// ------------------
// P2
// |
// R f2(INT)
// ------------------
Shape shape = Shape{2, 2};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto B = make_shared<op::Parameter>(element::f32, shape);
auto C = make_shared<op::Parameter>(element::f32, shape);
auto D = A + B;
auto E = D * C;
auto R = make_shared<op::Result>(E);
auto f = make_shared<Function>(ResultVector{R}, op::ParameterVector{A, B, C});
pass::Manager pass_manager;
pass_manager.register_pass<pass::AssignPlacement>(int_with_cpu_mul_policy);
pass_manager.run_passes(f);
// Insert parameter
auto RP0 = insert_result_parameter_split(D, E);
shared_ptr<op::Result> R0 = RP0.first;
shared_ptr<op::Parameter> P0 = RP0.second;
auto RP1 = insert_result_parameter_split(C, E);
shared_ptr<op::Result> R1 = RP1.first;
shared_ptr<op::Parameter> P1 = RP1.second;
auto RP2 = insert_result_parameter_split(E, R);
shared_ptr<op::Result> R2 = RP2.first;
shared_ptr<op::Parameter> P2 = RP2.second;
// Backends
auto int_backend = runtime::Backend::create(placement_to_string(Placement::INTERPRETER));
auto cpu_backend = runtime::Backend::create(placement_to_string(Placement::CPU));
// f0 on INT
auto a = int_backend->create_tensor(element::f32, shape);
auto b = int_backend->create_tensor(element::f32, shape);
auto c = int_backend->create_tensor(element::f32, shape);
auto r0 = int_backend->create_tensor(element::f32, shape);
auto r1 = int_backend->create_tensor(element::f32, shape);
copy_data(a, test::NDArray<float, 2>({{1, 2}, {3, 4}}).get_vector());
copy_data(b, test::NDArray<float, 2>({{5, 6}, {7, 8}}).get_vector());
copy_data(c, test::NDArray<float, 2>({{9, 10}, {11, 12}}).get_vector());
auto f0 = make_shared<Function>(ResultVector{R0, R1}, op::ParameterVector{A, B, C});
int_backend->compile(f0);
int_backend->call_with_validate(f0, {r0, r1}, {a, b, c});
// f1 on CPU
auto p0 = cpu_backend->create_tensor(element::f32, shape);
auto p1 = cpu_backend->create_tensor(element::f32, shape);
auto r2 = cpu_backend->create_tensor(element::f32, shape);
copy_data(p0, read_vector<float>(r0));
copy_data(p1, read_vector<float>(r1));
auto f1 = make_shared<Function>(ResultVector{R2}, op::ParameterVector{P0, P1});
cpu_backend->compile(f1);
cpu_backend->call_with_validate(f1, {r2}, {p0, p1});
// f2 on INT
auto p2 = int_backend->create_tensor(element::f32, shape);
auto r = int_backend->create_tensor(element::f32, shape);
copy_data(p2, read_vector<float>(r2));
auto f2 = make_shared<Function>(ResultVector{R}, op::ParameterVector{P2});
int_backend->compile(f2);
int_backend->call_with_validate(f2, {r}, {p2});
// Check final result on INT
EXPECT_EQ(read_vector<float>(r),
(test::NDArray<float, 2>({{54, 80}, {110, 144}})).get_vector());
}
TEST(graph_partition, hybrid_abc)
{
// Same as hybrid_abc_manual, but using the test hybrid transformer
//
// A B C A B C
// \ / / \ / /
// +D / +D /
// \ / | /
// *E R0 R1 f0(INT)
// | ------------------
// R P0 P1
// \ /
// *E
// |
// R2 f1(CPU)
// ------------------
// P2
// |
// R f2(INT)
// ------------------
Shape shape = Shape{2, 2};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto B = make_shared<op::Parameter>(element::f32, shape);
auto C = make_shared<op::Parameter>(element::f32, shape);
auto D = A + B;
auto E = D * C;
auto R = make_shared<op::Result>(E);
auto f = make_shared<Function>(ResultVector{R}, op::ParameterVector{A, B, C});
auto backend = make_shared<HybridBackend>(int_with_cpu_mul_policy);
shared_ptr<runtime::TensorView> a = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> b = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> c = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> r = backend->create_tensor(element::f32, shape);
copy_data(a, test::NDArray<float, 2>({{1, 2}, {3, 4}}).get_vector());
copy_data(b, test::NDArray<float, 2>({{5, 6}, {7, 8}}).get_vector());
copy_data(c, test::NDArray<float, 2>({{9, 10}, {11, 12}}).get_vector());
backend->call_with_validate(f, {r}, {a, b, c});
EXPECT_EQ(read_vector<float>(r),
(test::NDArray<float, 2>({{54, 80}, {110, 144}})).get_vector());
}
TEST(graph_partition, hybrid_abcd)
{
// A B
// \ /
// C E* D
// \ / \ /
// F+ G+
// \ /
// H+
Shape shape = Shape{2, 2};
shared_ptr<op::Parameter> A = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> B = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> C = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> D = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<Node> E = A * B;
shared_ptr<Node> F = C + E;
shared_ptr<Node> G = E + D;
shared_ptr<Node> H = F + G;
shared_ptr<Function> f = make_shared<Function>(H, op::ParameterVector{A, B, C, D});
auto backend = make_shared<HybridBackend>(int_with_cpu_mul_policy);
backend->compile(f);
shared_ptr<runtime::TensorView> a = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> b = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> c = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> d = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> r = backend->create_tensor(element::f32, shape);
copy_data(a, test::NDArray<float, 2>({{1, 2}, {3, 4}}).get_vector());
copy_data(b, test::NDArray<float, 2>({{5, 6}, {7, 8}}).get_vector());
copy_data(c, test::NDArray<float, 2>({{9, 10}, {11, 12}}).get_vector());
copy_data(d, test::NDArray<float, 2>({{13, 14}, {15, 16}}).get_vector());
backend->call_with_validate(f, {r}, {a, b, c, d});
EXPECT_EQ(read_vector<float>(r), (test::NDArray<float, 2>({{32, 48}, {68, 92}})).get_vector());
}
TEST(graph_partition, hybrid_back_and_forth)
{
// A B
// \ / \
// D* |
// \ /
// E+ C
// \ /
// F*
Shape shape = Shape{2, 2};
shared_ptr<op::Parameter> A = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> B = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> C = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<Node> D = A * B;
shared_ptr<Node> E = D + B;
shared_ptr<Node> F = E * C;
shared_ptr<Function> f = make_shared<Function>(F, op::ParameterVector{A, B, C});
auto backend = make_shared<HybridBackend>(int_with_cpu_mul_policy);
backend->compile(f);
shared_ptr<runtime::TensorView> a = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> b = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> c = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> r = backend->create_tensor(element::f32, shape);
copy_data(a, test::NDArray<float, 2>({{1, 2}, {3, 4}}).get_vector());
copy_data(b, test::NDArray<float, 2>({{5, 6}, {7, 8}}).get_vector());
copy_data(c, test::NDArray<float, 2>({{9, 10}, {11, 12}}).get_vector());
backend->call_with_validate(f, {r}, {a, b, c});
EXPECT_EQ(read_vector<float>(r),
(test::NDArray<float, 2>({{90, 180}, {308, 480}})).get_vector());
}
TEST(graph_partition, hybrid_multi_middle_nodes)
{
// A B C
// \ / \ / \
// D+ E+ |
// \ / \ /
// F* G*
// \ /
// H+
Shape shape = Shape{2, 2};
shared_ptr<op::Parameter> A = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> B = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> C = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<Node> D = A + B;
shared_ptr<Node> E = B + C;
shared_ptr<Node> F = D * E;
shared_ptr<Node> G = E * C;
shared_ptr<Node> H = F + G;
shared_ptr<Function> f = make_shared<Function>(H, op::ParameterVector{A, B, C});
auto backend = make_shared<HybridBackend>(int_with_cpu_mul_policy);
backend->compile(f);
shared_ptr<runtime::TensorView> a = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> b = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> c = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> r = backend->create_tensor(element::f32, shape);
copy_data(a, test::NDArray<float, 2>({{1, 2}, {3, 4}}).get_vector());
copy_data(b, test::NDArray<float, 2>({{5, 6}, {7, 8}}).get_vector());
copy_data(c, test::NDArray<float, 2>({{9, 10}, {11, 12}}).get_vector());
backend->call_with_validate(f, {r}, {a, b, c});
EXPECT_EQ(read_vector<float>(r),
(test::NDArray<float, 2>({{210, 288}, {378, 480}})).get_vector());
}
TEST(graph_partition, hybrid_no_split)
{
// A B
// \ /
// +
Shape shape = Shape{2, 2};
shared_ptr<op::Parameter> A = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<op::Parameter> B = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<Node> C = A + B;
shared_ptr<Function> f = make_shared<Function>(C, op::ParameterVector{A, B});
auto backend = make_shared<HybridBackend>(int_with_cpu_mul_policy);
backend->compile(f);
shared_ptr<runtime::TensorView> a = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> b = backend->create_tensor(element::f32, shape);
shared_ptr<runtime::TensorView> c = backend->create_tensor(element::f32, shape);
copy_data(a, test::NDArray<float, 2>({{1, 2}, {3, 4}}).get_vector());
copy_data(b, test::NDArray<float, 2>({{5, 6}, {7, 8}}).get_vector());
backend->call_with_validate(f, {c}, {a, b});
EXPECT_EQ(read_vector<float>(c), (test::NDArray<float, 2>({{6, 8}, {10, 12}})).get_vector());
}
#endif
| 39.328302 | 100 | 0.60521 | [
"shape",
"vector"
] |
d0886fa51bec961d094afd1d20f536119ba2d8ed | 2,968 | cpp | C++ | Matlab/source/bipl_sdnn_train.cpp | BIPL-HORIE/BIPL-SDNN-LIB-BETA | fb7aebf863f264c679ffaf477b3cd79622c59a72 | [
"BSD-3-Clause"
] | null | null | null | Matlab/source/bipl_sdnn_train.cpp | BIPL-HORIE/BIPL-SDNN-LIB-BETA | fb7aebf863f264c679ffaf477b3cd79622c59a72 | [
"BSD-3-Clause"
] | null | null | null | Matlab/source/bipl_sdnn_train.cpp | BIPL-HORIE/BIPL-SDNN-LIB-BETA | fb7aebf863f264c679ffaf477b3cd79622c59a72 | [
"BSD-3-Clause"
] | null | null | null | #include "mex.h"
#include "BIPL_LIB_SDNN.h"
#pragma comment(lib,"BIPL.SDNN.lib")
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
void sdnnTrain(const std::string &setting_filename,mwSize input_number, double *train_sample, double *train_target, mwSize train_n, const std::string &save_filename)
{
bipl::sdnn::SDNN sdnn;
sdnn.InitSDNN(setting_filename);
sdnn.Train4Matlab(train_sample,train_target,train_n);
sdnn.Save(save_filename);
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
if(nrhs!=4)
{
mexErrMsgIdAndTxt("bipl:sdnn:SDNN:nrhs",
"Four inputs required.");
}
if(nlhs!=0)
{
mexErrMsgIdAndTxt("bipl:sdnn:SDNN:nlhs",
"No output required.");
}
if ( mxIsChar(prhs[0]) != 1)
{
mexErrMsgIdAndTxt( "bipl:sdnn:SDNN:sdnnTrainAndEstimate:inputNotString",
"Input must be a string.");
}
if( !mxIsDouble(prhs[1]) ||
mxIsComplex(prhs[1]))
{
mexErrMsgIdAndTxt("bipl:sdnn:SDNN:sdnnTrainAndEstimate:notDouble",
"Input matrix must be type double.");
}
if( !mxIsDouble(prhs[2]) ||
mxIsComplex(prhs[2]))
{
mexErrMsgIdAndTxt("bipl:sdnn:SDNN:sdnnTrainAndEstimate:notDouble",
"Input matrix must be type double.");
}
if ( mxIsChar(prhs[3]) != 1)
{
mexErrMsgIdAndTxt( "bipl:sdnn:SDNN:sdnnTrainAndEstimate:inputNotString",
"Input must be a string.");
}
if(mxGetM(prhs[1]) < 2)
{
mexErrMsgIdAndTxt("bipl:sdnn:SDNN:sdnnTrainAndEstimate:input_number < 2",
"Input number must be 2 and more.");
}
if(mxGetN(prhs[1])!=mxGetN(prhs[2]))
{
mexErrMsgIdAndTxt("bipl:sdnn:SDNN:sdnnTrainAndEstimate:sample_number_collumped",
"input_sample_number != target_sample_number.");
}
double *train_sample;
train_sample = mxGetPr(prhs[1]);
double *train_target;
train_target = mxGetPr(prhs[2]);
mwSize train_n = (mwSize)mxGetN(prhs[1]);
char *setting_filename = mxArrayToString(prhs[0]);
char *save_filename = mxArrayToString(prhs[3]);
std::ifstream test_file(setting_filename);
if(test_file.is_open() != 1)
{
mxFree(setting_filename);
mexErrMsgIdAndTxt( "bipl:sdnn:SDNN:sdnnTrainAndEstimate:is_not_open",
"Could not open setting file");
}
test_file.close();
const std::string buffer(bipl::sdnn::CheckParameterFile(setting_filename));
if(buffer != "OK")
{
mexErrMsgIdAndTxt( "bipl:sdnn:SDNN:sdnnTrainAndEstimate:incorrect_parameter",
buffer.c_str());
}
sdnnTrain(setting_filename,mxGetM(prhs[1]),train_sample,train_target,train_n,save_filename);
mxFree(setting_filename);
mxFree(save_filename);
} | 29.68 | 165 | 0.618598 | [
"vector"
] |
d0894aa229519a48a430d6e59609686892cee636 | 1,233 | cpp | C++ | C++/Array/80. Remove Duplicates from Sorted Array II.cpp | iyybpatrick/LeetCode | 588171ee7de44383ea2b37d0c054fd0303288572 | [
"MIT"
] | 3 | 2017-02-13T16:06:23.000Z | 2017-09-02T18:05:29.000Z | C++/Array/80. Remove Duplicates from Sorted Array II.cpp | iyybpatrick/LeetCode | 588171ee7de44383ea2b37d0c054fd0303288572 | [
"MIT"
] | null | null | null | C++/Array/80. Remove Duplicates from Sorted Array II.cpp | iyybpatrick/LeetCode | 588171ee7de44383ea2b37d0c054fd0303288572 | [
"MIT"
] | 1 | 2022-01-24T06:27:07.000Z | 2022-01-24T06:27:07.000Z | //
// 80. Remove Duplicates from Sorted Array II.cpp
// leetcode
//
// Created by Yuebin Yang on 2017/2/7.
// Copyright © 2017年 yuebin. All rights reserved.
//
// Question:
//What if duplicates are allowed at most twice?
//
//For example,
//Given sorted array nums = [1,1,1,2,2,3],
//
//Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
// idea:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len=nums.size();
if(len<=1)
return len;
int count=1;
int index=1;
for(int i=1;i<len;i++){
if(nums[i]==nums[i-1]){
count++;
if(count>=3)
continue;
}//if
else{
count=1;
}//else
nums[index++]=nums[i];
}//for
return index;
}
};
int main(){
vector<int> A={1,1,1,2,2,2,3,4,4,4};
Solution s;
int len=s.removeDuplicates(A);
cout<<"len="<<len<<endl;
return 0;
}
| 22.418182 | 166 | 0.509327 | [
"vector"
] |
d08993a448adcda214a3b8d6e4996158080cb6ce | 6,191 | cpp | C++ | src/talker.cpp | Prat33k-dev/beginner_tutorials | 329117874485d148f1baa2d564e753261571b793 | [
"MIT"
] | null | null | null | src/talker.cpp | Prat33k-dev/beginner_tutorials | 329117874485d148f1baa2d564e753261571b793 | [
"MIT"
] | null | null | null | src/talker.cpp | Prat33k-dev/beginner_tutorials | 329117874485d148f1baa2d564e753261571b793 | [
"MIT"
] | null | null | null | /**
* MIT License
*
* Copyright (c) 2021 Pratik Bhujbal
*
* 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.
*
* @file listener.cpp
* @author Pratik Bhujbal
* @brief publisher ("talker") node which will continually broadcast a message
* @version 1.0
* @date 11/07/2021
* @copyright Copyright (c) 2021
*
*/
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <tf/transform_broadcaster.h>
#include <sstream>
#include "beginner_tutorials/Str.h"
// Initialize value to a string to publish
extern std::string pub_msg = "Hello from Patrick";
/**
* @brief A service Fucntion for changing the output string of the publisher.
* @param req service request
* @param res service response
* @return returns true when string changes
*/
bool SetString(beginner_tutorials::Str::Request &req,
beginner_tutorials::Str::Response &res) {
res.output = req.data;
pub_msg = req.data;
ROS_DEBUG_STREAM("Initial String changed to : " << req.data);
return true;
}
/**
* This tutorial demonstrates simple sending of messages over the ROS sys tem.
*/
int main(int argc, char **argv) {
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line.
* For programmatic remappings you can use a different version of init() which takes
* remappings directly, but for most command-line programs, passing argc and argv is
* the easiest way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.simple_rostest
*/
ros::init(argc, argv, "talker");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
// To create service and advertise over ROS.
ros::ServiceServer service = n.advertiseService("SrvChgStr", &SetString);
/**
* The advertise() function is how you tell ROS that you want to
* publish on a given topic name. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. After this advertise() call is made, the master
* node will notify anyone who is trying to subscribe to this topic name,
* and they will in turn negotiate a peer-to-peer connection with this
* node. advertise() returns a Publisher object which allows you to
* publish messages on that topic through a call to publish(). Once
* all copies of the returned Publisher object are destroyed, the topic
* will be automatically unadvertised.
*
* The second parameter to advertise() is the size of the message queue
* used for publishing messages. If messages are published more quickly
* than we can send them, the number here specifies how many messages to
* buffer up before throwing some away.
*/
ros::Publisher chatter_pub = n.advertise < std_msgs::String
> ("chatter", 1000);
// Setting default frequency for 20 Hz
int frequency = 20;
if (argc > 1) {
frequency = atoi(argv[1]);
}
// Stream information once about frequency set from argument
ROS_INFO_STREAM_ONCE("Set frequency= " << frequency);
if (frequency <= 0) {
// If frequency is negative or zero- Fatal
ROS_FATAL_STREAM("Frequency must be greater than zero !");
ROS_DEBUG_STREAM("Changing to default value i.e. 20 Hz");
frequency = 20;
} else if (frequency > 100) {
// If frequency is greater than expected- ERROR
ROS_ERROR_STREAM("Expected frequency is less than 100 Hz");
ROS_DEBUG_STREAM("Changing to default value i.e. 20 Hz");
frequency = 20;
} else if (0 < frequency && frequency < 5) {
// If frequency is less than 5 and greater than 0- WARN
ROS_WARN_STREAM("Input Frequency too low");
ROS_DEBUG_STREAM("Changing to default value i.e. 20 Hz");
frequency = 20;
}
ros::Rate loop_rate(frequency);
// Creates a TransformBroadcaster object
static tf::TransformBroadcaster pb;
// Creates a Transform object
tf::Transform transform;
// Creates a Quaternion object
tf::Quaternion quat;
while (ros::ok()) {
// Send the transformations
transform.setOrigin(tf::Vector3(1, 4, 3));
quat.setRPY(0, 0, 90);
transform.setRotation(quat);
pb.sendTransform(
tf::StampedTransform(transform, ros::Time::now(), "world", "talk"));
/**
* This is a message object. You stuff it with data, and then publish it.
*/
std_msgs::String msg;
std::stringstream ss;
ss << "ROS says " << pub_msg;
msg.data = ss.str();
ROS_INFO_STREAM(msg.data.c_str());
/**
* The publish() function is how you send messages. The parameter
* is the message object. The type of this object must agree with the type
* given as a template parameter to the advertise<>() call, as was done
* in the constructor above.
*/
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
| 38.453416 | 86 | 0.702794 | [
"object",
"transform"
] |
d092c16cf0095e8fd329a1e388e952ce0c31dc2a | 6,806 | cpp | C++ | Classes/Scenes/Demo2Scene.cpp | HoangTrongMinhDuc/JMOK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | 1 | 2019-07-11T08:06:06.000Z | 2019-07-11T08:06:06.000Z | Classes/Scenes/Demo2Scene.cpp | HoangTrongMinhDuc/JOMK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | null | null | null | Classes/Scenes/Demo2Scene.cpp | HoangTrongMinhDuc/JOMK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | 1 | 2021-09-13T12:00:12.000Z | 2021-09-13T12:00:12.000Z | #include "Scenes\Demo2Scene.h"
#include "ui\UIButton.h"
#include"Scenes\SettingOverlay.h"
#include "Character\Items\Key.h"
#define SCALE_RATIO 32.0
Scene* Demo2Scene::createScene()
{
auto scene = Scene::create();
#if SHOW_PHYSICS
#endif
// 'layer' is an autorelease object
GameObjectManager::getInstance()->getGameHub()->removeMapLayer();
auto layer = Demo2Scene::create();
GameObjectManager::getInstance()->getGameHub()->setMapLayer(layer);
// add layer as a child to scene
scene->addChild(GameObjectManager::getInstance()->getGameHub()->getLayer());
// return the scene
return scene;
}
void Demo2Scene::createMap()
{
m_tileMap = GameObjectManager::getInstance()->getTileMap();
addChild(m_tileMap);
m_tileMap->release();
}
void Demo2Scene::createSetup()
{
createMap();
createCharacter();
createMonsters();
createTraps();
createKeyAndDoor();
}
void Demo2Scene::createCharacter()
{
m_mainCharacter = GameObjectManager::getInstance()->getMainCharacter();
m_mainCharacter->addParent(this);
}
void Demo2Scene::createMonsters()
{
m_monsters = GameObjectManager::getInstance()->getMonsters();
for (int i = 0; i < m_monsters.size(); i++)
m_monsters[i]->addParent(this);
}
void Demo2Scene::createTraps()
{
m_traps = GameObjectManager::getInstance()->getTraps();
for (int i = 0; i < m_traps.size(); i++)
m_traps[i]->addParent(this);
}
void Demo2Scene::createKeyAndDoor()
{
m_keyMonster = GameObjectManager::getInstance()->getKeyMonster();
m_keyMonster->addParent(this);
m_door = GameObjectManager::getInstance()->getDoor();
m_door->addParent(this);
}
bool Demo2Scene::init()
{
Size screenSize = Director::getInstance()->getVisibleSize();
if (!Layer::init())
return false;
AudioConfig::getInstance()->playTheme(1);
m_physicsWorld = GameObjectManager::getInstance()->getPhysicsWorld();
m_isUpdate = true;
debugDraw = new (std::nothrow) GLESDebugDraw(32.0);
//m_physicsWorld->SetDebugDraw(debugDraw);
// m_physicsWorld->SetDebugDraw(debugDraw);
uint32 flags = 0;
flags += b2Draw::e_shapeBit; // xem hình dạng
debugDraw->SetFlags(flags);
m_physicsWorld->SetAllowSleeping(false);
PhysicsContactManager *pcm = new PhysicsContactManager();
m_physicsWorld->SetContactListener(pcm);
this->scheduleUpdate();
/*auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(Demo2Scene::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(Demo2Scene::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);*/
createSetup();
return true;
}
void Demo2Scene::draw(Renderer * renderer, const Mat4 & transform, uint32_t flags)
{
// // IMPORTANT:
// This is only for debug purposes
// It is recommend to disable it //
Layer::draw(renderer, transform, flags);
GL::enableVertexAttribs(cocos2d::GL::VERTEX_ATTRIB_FLAG_POSITION);
Director* director = Director::getInstance();
CCASSERT(nullptr != director, "Director is null when seting matrix stack");
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
_modelViewMV = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
//_customCommand.init(_globalZOrder);
_customCommand.init(1);
_customCommand.func = CC_CALLBACK_0(Demo2Scene::onDraw, this);
renderer->addCommand(&_customCommand);
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
void Demo2Scene::onDraw()
{
Director* director = Director::getInstance();
CCASSERT(nullptr != director, "Director is null when seting matrix stack");
auto oldMV = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewMV);
m_physicsWorld->DrawDebugData();
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, oldMV);
}
void Demo2Scene::addWall(float w, float h, float px, float py) {
b2PolygonShape floorShape; // Hình dạng Sàn
floorShape.SetAsBox(w / SCALE_RATIO, h / SCALE_RATIO); // Hình vuông, hoặc chữ nhật
b2FixtureDef floorFixture;
floorFixture.density = 0;
floorFixture.friction = 10;
floorFixture.restitution = 0.5;
floorFixture.shape = &floorShape;
b2BodyDef floorBodyDef;
floorBodyDef.position.Set(px / SCALE_RATIO, py / SCALE_RATIO);
b2Body *floorBody = m_physicsWorld->CreateBody(&floorBodyDef);
floorBody->CreateFixture(&floorFixture);
}
void Demo2Scene::update(float deltaTime) {
if (!m_isUpdate)
return;
int positionIterations = 3; // Vị trí
int velocityIterations = 8; // Vận tốc
m_physicsWorld->Step(deltaTime, velocityIterations, positionIterations);
// update hub
for (int i = 0; i < m_monsters.size(); i++)
m_monsters[i]->update(deltaTime);
for (int i = 0; i < m_traps.size(); i++)
m_traps[i]->update(deltaTime);
if (m_keyMonster != NULL)
m_keyMonster->update(deltaTime);
if (m_door != NULL)
m_door->update(deltaTime);
// update character
if (!m_mainCharacter->isAlive())
return;
bool isIDLE = true;
/*if (m_key[EventKeyboard::KeyCode::KEY_RIGHT_ARROW])
m_mainCharacter->moveRight(deltaTime), isIDLE = false;
if (m_key[EventKeyboard::KeyCode::KEY_LEFT_ARROW])
m_mainCharacter->moveLeft(deltaTime), isIDLE = false;
if (m_key[EventKeyboard::KeyCode::KEY_SPACE])
m_mainCharacter->jumpUp(), isIDLE = false;
if (m_key[EventKeyboard::KeyCode::KEY_X])
m_mainCharacter->hitWithStick(), isIDLE = false;
if (m_key[EventKeyboard::KeyCode::KEY_C])
m_mainCharacter->runSkill("IRON_FIST"), isIDLE = false;
if (m_key[EventKeyboard::KeyCode::KEY_V])
m_mainCharacter->runSkill("RAGE_MODE"), isIDLE = false;*/
m_mainCharacter->update(deltaTime);
if (isIDLE)
GameObjectManager::getInstance()->getGameHub()->update(deltaTime);
setViewPointCenter(m_mainCharacter->getPosition());
}
void Demo2Scene::setViewPointCenter(Point pos) {
auto visibleSize = Director::getInstance()->getVisibleSize();
int x = MAX(pos.x, visibleSize.width / 2);
int y = MAX(pos.y, visibleSize.height / 2);
x = MIN(x, (m_tileMap->getMapSize().width* m_tileMap->getTileSize().width) - visibleSize.width / 2);
y = MIN(y, (m_tileMap->getMapSize().height * m_tileMap->getTileSize().height) - visibleSize.height / 2);
auto actualPos = ccp(x, y);
auto centerOfView = ccp(visibleSize.width / 2, visibleSize.height / 2);
auto viewPoint = ccpSub(centerOfView, actualPos);
GameObjectManager::getInstance()->getGameHub()->setViewPointCenter(viewPoint);
this->setPosition(viewPoint);
}
void Demo2Scene::stopUpdate()
{
m_isUpdate = false;
}
//
//void Demo2Scene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event)
//{
// log("Key with keycode %d pressed", keyCode);
//
// m_key[keyCode] = true;
//}
//
//void Demo2Scene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
//{
// log("Key with keycode %d released", keyCode);
//
// m_key[keyCode] = false;
//} | 28.476987 | 105 | 0.739348 | [
"object",
"shape",
"transform"
] |
d0a0149a466ad712215faa4ea1a1ca11a14b77c2 | 1,059 | cc | C++ | prac-cpp/strings_0.cc | benjaminchang23/jackson-street-problems | 99f4f254dc43e57462657207131ae94882ae54f9 | [
"MIT"
] | null | null | null | prac-cpp/strings_0.cc | benjaminchang23/jackson-street-problems | 99f4f254dc43e57462657207131ae94882ae54f9 | [
"MIT"
] | null | null | null | prac-cpp/strings_0.cc | benjaminchang23/jackson-street-problems | 99f4f254dc43e57462657207131ae94882ae54f9 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string sanatized_file_name = "---adf--[]as * df-k----";
const std::string unallowed = " /\\*?<>:;=[]!@|.";
while (sanatized_file_name.front() == '-')
{
sanatized_file_name.erase(sanatized_file_name.begin());
}
while (sanatized_file_name.back() == '-' && sanatized_file_name.size() > 0)
{
sanatized_file_name.pop_back();
}
std::transform(sanatized_file_name.begin(), sanatized_file_name.end(), sanatized_file_name.begin(),
[&unallowed](char ch)
{
return (std::find(unallowed.begin(), unallowed.end(), ch) != unallowed.end()) ? '-' : ch;
});
std::cout << "after 1st replace: " << sanatized_file_name << std::endl;
size_t pos = sanatized_file_name.find("--");
while (pos != std::string::npos)
{
sanatized_file_name.replace(pos, 2, "-");
pos = sanatized_file_name.find("--");
}
std::cout << "after 2nd replace: " << sanatized_file_name << std::endl;
return 0;
} | 27.153846 | 103 | 0.594901 | [
"transform"
] |
d0a2075ebf13487bdc7a669f952bc745fc163859 | 46,911 | hpp | C++ | SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/doc/doxygen/src/snippetspage.hpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/doc/doxygen/src/snippetspage.hpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/doc/doxygen/src/snippetspage.hpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | /*****************************************************************************
* GATB : Genome Assembly Tool Box
* Copyright (C) 2014 R.Chikhi, G.Rizk, E.Drezen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
/**\page snippets_page How to use the library ?
*
* \subpage compilation \n
* \subpage new_project \n
* \subpage snippets_graph \n
* \subpage snippets_bank \n
* \subpage snippets_kmer \n
* \subpage snippets_iterators \n
* \subpage snippets_multithread \n
* \subpage snippets_storage \n
* \subpage snippets_tools \n
*
*************************************************************************************
*************************************************************************************
* \page compilation Compilation instructions
************************************************************************************
*
* \section compilation_library Compiling the library (and other artifacts)
*
* The gatb::core library is generated by the cmake tool.
*
* In the following, we will call GATB the main directory of the gatb core project (ie.
* the root directory of the source archive).
*
* You have then to do the following:
*
* \code
* cd GATB; mkdir build ; cd build ; cmake .. ; make
* \endcode
*
* You can force compilation in debug mode by calling cmake in a specific way:
* \code
* cmake -Ddebug=1 ..
* \endcode
*
* Several artifacts are generated:
*
* - the gatb core library is available in the generated <tt>build/lib</tt> directory
* - the gatb core binaries are available in the generated <tt>build/bin</tt> directory
*
* you can type 'make help' to know all the available targets.
*
* If CppUnit is installed, a unit tests binary should be generated; you can launch it with
* \code
* bin/gatb-core-cppunit
* \endcode
* You can use the exit status code of the command to know the success status (0 for success).
*
* Note that one may set the environment variable CPPUNIT_VERBOSE to 1 to known which tests pass.
*
* By default, gatb::core supports kmer sizes up to 128. In fact, it has 4 different implementations
* of kmers, one for KSIZE_1=32, KSIZE_2=64, KSIZE_3=96 and KSIZE_4=128. If you need bigger kmers
* sizes, you can compile this way:
* \code
* cmake -Dk1=32 -Dk2=64 -Dk3=96 -Dk4=256 ..
* \endcode
*
*
************************************************************************************
* \section compilation_snippets Compiling the snippets
*
* A directory named 'examples' holds some snippets that show how to use services provided by the library.
*
* In order to compile them, you will first need to compile the library.
*
* A simple way to generate the snippets is to type:
* \code
* make examples
* \endcode
*
*************************************************************************************
* \page new_project Quick project creation
************************************************************************************
*
* It is possible to create a new project based on gatb::core with a script provided in
* the distribution (see directory 'scripts').
*
* You have to provide a name for the project and the location of the generated directory holding
* all the needed material. For instance:
* \code
* sh scripts/NewProject/NewProject.sh MyProject /tmp
* \endcode
*
* Then you can go in the generated directory and browse its content:
* \code
* cd /tmp/MyProject; ls -l
* \endcode
*
* By default, the generated project is designed to produce two binaries called
* MyProject_1 and MyProject_2. For instance, the associated sources for the MyProject_1
* tool are located in the directory tools/MyProject_1/src. The sources may be used as
* a skeleton to build an application based on gatb::core.
*
* Note that you can keep only one tool, for instance MyProject_1 and rename it as you
* want. You can also add as many tools as you want in the 'tools' directory.
*
* You can set a version number to your project by editing the CMakeLists.txt file located
* in the archive main directory. This is done by changing the default "1.0.0" value of
* the CPACK_PACKAGE_VERSION variable.
*
* For compiling the project, you have to follow the same process than compiling the
* distribution (note that you can set a version number with the variable CPACK_PACKAGE_VERSION):
* \code
* cd /tmp/MyProject; mkdir build ; cd build ; cmake -DCPACK_PACKAGE_VERSION="3.14.92" .. ; make
* \endcode
*
* Note that all the needed material is included in the generated project (in particular
* the gatb::core library and the header files), so you can move it wherever you want.
* Note also that you won't have to do any tricky configuration to build the binary; you
* just have to do cmake+make and you will have your binaries in the build/tools directory.
*
* Finally, you have two targets to archive the project:
* - make package => package of the binaries
* - make package_source => package of the sources
*
* The source archive holds all the material needed for compilation.
*
* Note that the version number (set with CPACK_PACKAGE_VERSION) will be used for naming the archive files.
*
* If you finally want to put the archive files on the GATB server, you can use "make delivery". Note
* that it is possible only if you have a GForge INRIA account and have been defined as a
* GATB contributor.
*
************************************************************************************
************************************************************************************
* \page snippets_iterators Iterators snippets
************************************************************************************
* \tableofcontents
*************************************************************************************
*
* \section snippets_iterators_snippet1 Iterate a list
*
* This snippet shows how to iterate a STL list with our iterator design.
*
*\snippet iterators1.cpp snippet1
*
************************************************************************************
* \section snippets_iterators_snippet2 Iterate the Cartesian product of two lists
*
* This snippet shows how to iterate the Cartesian product of two lists:
*
* 1) Declare two iterators \n
* 2) Declare one Cartesian iterator configured with the two iterators \n
* 3) Iterate the Cartesian iterator. \n
*
* The current item of the iteration is a pair, so one should retrieve the couple of
* values with methods 'first' and 'second'.
*
*\snippet iterators2.cpp snippet1
*
************************************************************************************
* \section snippets_iterators_snippet7 Iterate two lists by pairs
*
* This snippet shows how to iterate two iterators at the same time, providing pairs
* of items at each iteration.
*
* A usage of such an iterator is to iterate two paired ends banks.
*
*\snippet iterators7.cpp snippet1
*
************************************************************************************
* \section snippets_iterators_snippet3 Truncating an iteration
*
* This snippet shows how to truncate the iteration of some iterator.
*
*\snippet iterators3.cpp snippet1
*
*
************************************************************************************
* \section snippets_iterators_snippet4 Iterate a list with progress feedback
*
* This snippet shows how to iterate a STL list and being notified as a listener about
* its progression.
*
* The idea is to use a SubjectIterator instance that refers the actual iterator we want
* to iterate.
*
* Then, it is possible to subscribe some callback function (here as a functor) to the
* SubjectIterator instance.
*
* The listener will then receive at regular interval the number of currently iterated
* items.
*
*\snippet iterators4.cpp snippet1
*
************************************************************************************
* \section snippets_iterators_snippet5 Iterate a list with progress feedback (simple)
*
* This snippet is the same as before but here we use a default console progress bar.
* In most case, it allows to avoid an explicit listener configuration.
*
*\snippet iterators5.cpp snippet1
*
************************************************************************************
* \section snippets_iterators_snippet6 Iterate a list and filter out some items
*
* This snippet shows how to iterate a STL list while filtering out some items that
* don't check some condition.
*
*\snippet iterators6.cpp snippet1
*
************************************************************************************
* \section snippets_iterators_snippet8 Mixing iterators
*
* This snippet shows how mix several iterators. Note again that the iteration loop
* is still the same.
*
*\snippet iterators8.cpp snippet1
*
*
************************************************************************************
************************************************************************************
* \page snippets_multithread Multithreading snippets
************************************************************************************
*
* \tableofcontents
*
* *************************************************************************************
*
* \section snippets_multithread_snippet1 Iteration in a multithreaded fashion
*
* This snippet shows how to iterate some Iterator object (here a range of integers)
* with N threads in order to speed up the iteration.
*
* This snippet introduces the Dispatcher class and shows how to simply use it for
* parallelizing one iteration.
*
* <b>Note: this approach can work only if the items can be iterated and processed independently
* from each other.</b>
*
*\snippet multithreading1.cpp snippet1
*
*************************************************************************************
*
* \section snippets_multithread_snippet2 Multithreaded iteration and shared resources
*
* This snippet shows how to parallelize an iteration and how several threads can modify
* a common resource throughout the iteration.
*
* The important point here is to understand that shared resources must be modified
* cautiously by different threads running at the same time.
*
*\snippet multithreading2.cpp snippet1
*
*************************************************************************************
*
* \section snippets_multithread_snippet3 Multithreaded iteration with synchronization of a shared resource
*
* Here, our shared resource is a file, so we can't use intrinsic instruction like we
* did before for integer addition.
*
* We need some general synchronization mechanism that will ensure that a portion of code
* can be executed only by one thread at one time.
*
*\snippet multithreading3.cpp snippet1
*
*
*************************************************************************************
*
* \section snippets_multithread_snippet4 Multithreaded iteration with synchronization of a shared resource (bis)
*
* This snippet is similar to the previous one. It only shows how to use the LocalSynchronizer
* class to simply lock/unlock the containing instruction block.
*
* This is useful for avoiding classical deadlock bugs when one forgets to unlock a
* synchronizer.
*
*\snippet multithreading4.cpp snippet1
*
*************************************************************************************
*
* \section snippets_multithread_snippet5 Multithreaded iteration without shared resources management
*
* This snippet introduces the ThreadObject class designed to avoid concurrent accesses
* issues.
*
* Instead of working on a single shared resource, threads use local resources during
* the iteration and then, a final aggregation of the local resources is done after
* the iteration.
*
* Such an approach skips the need of synchronization mechanisms when threads directly
* uses a single shared resource. This may be interesting since synchronization mechanisms
* may introduce time overheads.
*
*\snippet multithreading5.cpp snippet1
*
*************************************************************************************
*
* \section snippets_multithread_snippet6 Multithreaded iteration of a bank
*
* This snippet shows how to iterate sequences of a bank and counts how many A,C,G,T it
* contains. The interesting part is to see that the Bank class can create Iterator instances
* that can be iterated through a Dispatcher instance.
*
* Note: iterating a bank from a disk makes a lot of I/O, so parallelizing such an iteration
* may not lead to significant better performance. However, if the snippet is launched
* once, the bank (if not too big) may be in the RAM cache, so it is interesting to
* relaunch the snippet with varying number of cores and see how execution time evolves.
*
*\snippet multithreading6.cpp snippet1
*
************************************************************************************
************************************************************************************
* \page snippets_bank Bank snippets
************************************************************************************
*
* \tableofcontents
*
************************************************************************************
*
* \section snippets_bank_snippet1 Parsing a single FASTA bank without checks
*
* This snippet shows how to read one FASTA bank in a simple way. No check is done about
* the correctness of the FASTA bank file path.
*
* Some information of each iterated sequence are diplayed as output.
*
*\snippet bank1.cpp snippet1
*
************************************************************************************
* \section snippets_bank_snippet2 Parsing several banks
*
* This snippet shows how to read one ore more banks in a simple way. The idea is to use
* the Bank::open method that analyzes the provided uri and get the correct IBank handle for
* one or more banks. For instance, one can run this snippet with:
* - bank2 reads1.fa,reads2.fa,reads3.fa
*
* Some information of each iterated sequence are diplayed as output.
*
*\snippet bank2.cpp snippet1
*
*************************************************************************************
* \section snippets_bank_snippet3 Parsing a FASTA bank in a different way
*
* This snippet shows how to read one or more FASTA banks in a "push" model;
* it means that the sequence iterator calls some function for each sequence.
*
* This is another way to iterate items and opposite to the "pull" model where the
* iterator is called to provide the current item, instead of calling some function to
* do as we do in this sample.
*
*\snippet bank3.cpp snippet1
*
**************************************************************************************
* \section snippets_bank_snippet4 Parsing a FASTA bank and getting progress information
*
* This snippet shows how to create an iterator on something (here sequences from a FASTA
* file) and encapsulate it with another iterator that adds the possibility to notify some
* listener every 10 iterated sequences (used here for showing some progression during the
* iteration).
*
* Note: the "notifying" iterator is generic and could be reused to send progress notification
* with any kind of iterator, not only on sequences.
*
*\snippet bank4.cpp snippet1
*
**************************************************************************************
* \section snippets_bank_snippet5 Parsing a FASTA bank and getting percentage progress information
*
* This snippet shows how to read one or more FASTA banks and get a percentage progress
* information during the iteration.
*
* We use there a ProgressIterator on Sequence. By default, we got progress information with
* remaining time estimation and resources usage (cpu and memory).
* Note that the ProgressIterator class has a second template parameter that can provide other
* progress information, try for instance:
* - ProgressIterator<Sequence,ProgressTimer>
*
*\snippet bank5.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet6 Output a FASTA file with data line of given size
*
* This snippet provides a small utility for cutting lines of data with a given size.
*
*\snippet bank6.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet7 Filter sequences with a given data size
*
* This snippet shows how to parse a bank with a functor used to filter out some items.
*
*\snippet bank7.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet8 Conversion of a FASTA bank to a binary format
*
* This snippet shows how to parse a nucleic bank and convert it to a binary format.
*
*\snippet bank8.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet9 Conversion of a bank with some filtering
*
* This snippet shows how to parse a bank, check whether the sequences match a criteria
* and dump the matching sequences into an output FASTA bank.s
*
*\snippet bank9.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet10 Split a bank
*
* This snippet shows how to split an input bank into parts. It creates an output album
* bank by using the BankAlbum class. Example of use:
* \code
* bank10 -in reads.fa -max-size 10000000
* \endcode
* This example will create a directory 'reads_S1000000' where we can find:
* - album.txt => album file containing all reads_X split parts
* - reads_0
* - reads_1
* - ...
* - reads_N
*
* All the 'reads_X' files are about 1000000 bytes. Now, the generated album.txt file
* can be used as a bank and could be the input bank of the snippet bank14 for instance
* (and we should get the same results as using directly the 'reads.fa' bank)
*
*\snippet bank10.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet11 Iterating a bank whose sequences are kmers
*
* This snippet shows how to iterate a BankKmers. Such a bank iterates all possible
* kmers for a given kmers size.
*
* Each sequence is saved into an output FASTA file.
*
*\snippet bank11.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet12 Extracting sequences with specific ids with FilterIterator
*
* This snippet shows how to extract sequences from a bank. A sequence is kept if its
* index in its bank belongs to a set (provided as an input file holding one index per line)
*
* It uses the FilterIterator feature.
*
*\snippet bank12.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet13 Extracting sequences with too many N characters
*
* This snippet shows how to extract sequences that don't have too many N.
*
* It uses the FilterIterator feature.
*
*\snippet bank13.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet14 Computing statistics on a bank
*
* This snippet shows how to read a bank and get statistics on it.
*
*\snippet bank14.cpp snippet1
*
* \n
*
**************************************************************************************
* \section snippets_bank_snippet18 Iterating paired end banks
*
* This snippet shows how to read two banks in the same time, and each item is a pair
* of items of bank1 and bank2.
*
* This is good example how to reads paired end banks.
*
*\snippet bank18.cpp snippet1
*
* \n
*
************************************************************************************
************************************************************************************
* \page snippets_kmer Kmer snippets
************************************************************************************
*
* \tableofcontents
*
*************************************************************************************
*
* \section snippets_kmer_snippet1 Using a kmer model
*
* This snippet shows how to create kmer models.
*
*\snippet kmer1.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet2 Computing kmers with a model
*
* This snippet shows how to get kmers from a model. Here, we can see that we can
* use 3 different kinds of models, giving different kinds of kmers:
* - ModelDirect : direct kmers
* - ModelCanonical : minimum value of the direct kmer and its reverse complement
* - ModelMinimizer : provides also a minimizer for the kmer
*
* The snippet shows different methods usable for each kind of model.
*
*\snippet kmer2.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet3 Iterating kmers from a sequence
*
* This snippet shows how to iterate the kmers from a sequence, for a given model.
*
*\snippet kmer3.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet4 Iterating kmers from one or several banks
*
* This snippet shows how to iterate the kmers from banks. In particular, we use two
* iterators and two loops:
* - outer loop on sequences of the bank
* - inner loop on kmer on the current sequence from the outer loop
*
*\snippet kmer4.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet5 Computing statistics about minimizers
*
* This snippet shows iterate the kmers of an input bank and computes some statistics
* about the iterated minimizers.
*
* It also computes the following distribution : number of times a read has X different
* minimizers (in other words, the number of super kmers).
*
*\snippet kmer5.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet6 Checking span of kmers model
*
* This snippet shows what is legal in terms of kmers size.
*
* Actually, a kmers model has a type with a 'span' template. This span represents the
* maximum kmer size reachable for this type. For instance, a span of 32 allows up to
* kmer size of 31, a span of 64 up to 63, etc...
*
* The 'span' value must be one of the project defined constants: KSIZE_1, KSIZE_2, KSIZE_3
* and KSIZE_4. By default, we have KSIZE_n = 32*n. Note that it is possible to compile
* GATB-CORE with a bigger value of KSIZE_4=128. See \ref compilation.
*
* It is important to understand that each one of the four span values defines a specific
* kmers model with a specific integer type that represents the kmers values. For instance:
* - KSIZE_1=32 implies that we need 64 bits integers (2 bits per nucleotide), which is available
* as a native type on 64 bits architecture
* - KSIZE_2=64 implies that we need 128 bits integers which may (or not) be available as native
* integer type
* - for KSIZE_3 and KSIZE_4, we need to switch to specific large integer representations that
* are no more native on the system, which implies bigger computation times.
*
*\snippet kmer6.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet7 Other kind of statistics about minimizers
*
* This snippet shows how to iterate the kmers of an input bank and computes some statistics
* about the iterated minimizers.
*
*\snippet kmer7.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet8 Setting custom minimizers definition
*
* This snippet shows how to configure custom minimizer definition through a functor.
*
*\snippet kmer8.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet9 Counting kmers from a bank with the sorting count algorithm
*
* This snippet shows how to use the SortingCountAlgorithm class for counting kmers in
* a bank
*
*\snippet kmer9.cpp snippet1
* \n
*
************************************************************************************
* \section snippets_kmer_snippet10 Reading a file generated by the sorting count algorithm
*
* This snippet shows how to read the output of the SortingCountAlgorithm.
*
* We use two ways for reading the couples [kmer,abundance]
* - we read all the couples with a single iterator
* - we read each solid collection and use an iterator on it
*
*\snippet kmer10.cpp snippet1
* \n
*
*
*
************************************************************************************
*************************************************************************************
* \page snippets_graph De Bruijn graph snippets
*************************************************************************************
*************************************************************************************
*
*\tableofcontents
*
* We propose here a few snippets related to De Bruijn graphs.
*
************************************************************************************
* \section snippets_dbg_1 Build / Load De Bruijn graphs
************************************************************************************
* \subsection snippets_kmer_dbg_1 Building a De Bruijn graph from command line options
*
* This snippet shows how to create a Graph object thanks to command line options with at
* least a mandatory FASTA file URI.
*
* The first thing to do is to get a parser that analyzes the command line options
* from (argc,argv). Such a parser can be retrieved with a static method from Graph class.
*
* Then, the parsed options can be provided to the Graph::create method and then we get
* a Graph object on which we can do anything we want.
*
* The only mandatory option is '-in fastafile'. All other options have default values if not
* set through command line.
*
* In this snippet, we dump information about the Graph object building with Graph::getInfo method.
*
* \remark This snippet essentially does the same job as the \b dbgh5 tool provided by the
* gatb-core project: it takes a set of reads (as a FASTA file) and generates the corresponding
* De Bruijn graph as a HDF5 file.
*
*\snippet debruijn1.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_2 Building a De Bruijn graph from a command-line-like string
*
* Like the previous snippet, we create a Graph object with command line options, but
* here the options are directly provided as a string.
*
* \snippet debruijn2.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_3 Building a De Bruijn graph from a bank object
*
* Here, we create a Graph object by providing a bank object, more precisely a IBank
* object.
*
* It is therefore possible to provide a Bank instance (ie a FASTA bank), or
* another kind of bank that implements the IBank interface.
*
* Note in the example that we can provide additional options after the bank object.
*
* \snippet debruijn3.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_4 Building a De Bruijn graph from a fake bank object
*
* Like the previous snippet, we create a Graph object by providing a bank object, but
* here this is a 'fake' bank built "on the fly".
*
* Such banks are often useful for testing purposes.
*
* In such a case, the output file for the graph will be named "noname", unless a specific
* name is set through the command line option "-out mygraph".
*
* \snippet debruijn4.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_5 Load a De Bruijn graph from a graph file
*
* Once we have built a graph, it is saved as a file (likely a HDF5 file).
*
* This snippet shows how to load such a file to get a Graph object.
*
* \snippet debruijn5.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
************************************************************************************
* \section snippets_dbg_2 Iterating nodes
*************************************************************************************
*
* \subsection snippets_kmer_dbg_6 Iterate the nodes of a De Bruijn graph
*
* This snippet shows how to iterate all the nodes of a graph (the graph is loaded
* from a graph file).
*
* The idea is to get an iterator from the graph and use it to get each node of the graph.
*
* Here, the nodes are retrieved regardless of any edges between them.
*
* \snippet debruijn6.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_7 Iterate the nodes of a De Bruijn graph in a multithread way
*
* As the previous example, this snippet shows how to iterate all the nodes of a graph.
*
* The difference here is that the iteration is parallelized, using all possible available
* cores, which should speed up the iteration.
*
* WARNING ! don't forget this is parallel execution, so you have be careful if you want to
* modify the same object in different thread execution contexts.
*
* Note: lambda expressions are used here to have code conciseness (which suppose to use
* an up-to-date compiler). You can have some information at
* http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
*
* \snippet debruijn7.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
************************************************************************************
* \section snippets_dbg_3 Neighborhoods
*************************************************************************************
*
* \subsection snippets_kmer_dbg_9 Working with neighborhoods of nodes in the De Bruijn graph
*
* This snippet shows how to use some methods related to neighbors in a graph.
*
* We use a fake bank with one sequence of size 5 and use a kmer size of 4, so we will have 2 possible
* nodes in the graph.
*
* We iterate these two nodes, and for one of them, we ask for its neighbors with the Graph::successors method.
* We can then check that the retrieved neighbor is the correct one by analyzing the node string representations.
*
* In this example, we use the successors method, but note it is possible to get the incoming neighbors with the
* Graph::predecessors method. By the way, it is possible to know the in and out degree of a given node with the two
* corresponding methods Graph::indegree and Graph::outdegree
*
* \snippet debruijn9.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_10 Working with neighborhoods of nodes in the De Bruijn graph (continued)
*
* This snippet shows how to use some methods related to neighbors in a graph.
*
* We do the same work as the previous example. The only difference is that we retrieve the neighbors as
* Edge objects rather than Node objects, so we will have the full information about each transition between
* the source node and the retrieved neighbors (including the transition nucleotide for instance).
*
* In particular, we use some of the Edge attributes (Edge::to, Edge::nt)
*
* \snippet debruijn10.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_11 Working with a specific neighbor for a specific node
*
* This snippet shows how to get a specific neighbor for a specific node.
*
* Sometimes, it is interesting to ask the graph for only one neighbor for a given node.
* It may happen when one has already got neighbors information through a Graph::neighbors
* call and memorized only the transition nucleotides for valid neighbors.
*
* The Graph::neighbor fulfills this need. This method has two forms, with or without check
* to graph membership, according to performance considerations.
*
* \snippet debruijn11.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
************************************************************************************
* \section snippets_dbg_4 Branching nodes
************************************************************************************
*
* In the De Bruijn graph, we can define two types of nodes:
* - a node N is 'simple' <=> indegree(N)==1 && outdegree(N)
* - a node N is 'branching' <=> N is not simple
*
* Branching nodes set is an important subset in the whole nodes set of the De Bruijn graph, so it is of most
* interest to have some graph methods that work on such nodes. In particular, we can:
* - iterate all the branching nodes of the De Bruijn graph
* - get the branching neighbors of some node
*
* \remarks - With this definition, a branching node may have 0 outcoming neighbors or 0 incoming neighbors.
*
* \remarks - Since we are considering assembly matters, we should have few branching nodes compared to the simple
* nodes.
*
* \subsection snippets_kmer_dbg_8 Iterate the branching nodes of a De Bruijn graph
*
* This snippet shows how to iterate the branching nodes of a graph (the graph is loaded
* from a graph file).
*
* The idea is to get an iterator from the graph and use it to get each branching node of the graph.
*
* \snippet debruijn8.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_16 Working with branching neighbors of a node
*
* This snippet shows how to get the branching neighbors of a node. Such neighbors are
* computed as follow:
* - the immediate neighbors of the node are retrieved
* - a simple path is done from each neighbor in order to reach the first non simple node
*
* Here, we use directly the Graph::successors<BranchingNode> method that encapsulates
* this behavior.
*
* \snippet debruijn16.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_17 Working with branching neighbors of a node (continued)
*
* This snippet shows how to get the branching neighbors of a node.
*
* It is similar to the previous snippet. The difference here is that we retrieve BranchingEdge
* objects. A BranchingEdge object is made of:
* - the source branching node
* - the target branching node
* - the direction of the neighbors (in/out coming)
* - the nucleotide of the transition between the initial branching node and the first neighbor
* on the simple path between the two branching nodes.
* - the number of transitions that link the two branching nodes.
*
* \snippet debruijn17.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
* ************************************************************************************
* \section snippets_dbg_14 Simple path
************************************************************************************
*
* \subsection snippets_kmer_dbg_14 Iterating simple path from a node
*
* As we saw previously, a simple node is defined as having indegree==1 and outdegree==1.
* It is often useful to iterate successive simple nodes in order to build some path in the De Bruijn graph.
*
* This snippet shows how to iterate such a simple path. Here, the iterated items are the
* successive nodes of the path.
*
* \snippet debruijn14.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
*************************************************************************************
* \subsection snippets_kmer_dbg_15 Iterating simple path from a node (continued)
*
* Like the previous example, this snippet shows how to iterate a simple path.
* Here, the iterated items are the successive edges of the path. If we note E an edge
* in this path, we will have:
* - outdegree(E.from)==1 && indegree(E.to)==1
*
* \snippet debruijn15.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
************************************************************************************
* \section snippets_dbg_6 Miscellanous
*************************************************************************************
* \subsection snippets_kmer_dbg_12 Playing with node strands
*
* A Node object is fully defined by a kmer value and a strand that disambiguates how to
* interpret the kmer.
*
* It is often required to change the reading strand of a node. This can be done with the
* Graph::reverse method.
*
* \snippet debruijn12.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*************************************************************************************
* \subsection snippets_kmer_dbg_13 Playing with fake nodes
*
* Sometimes, it is useful to build "fake" nodes from a simple sequence, without having
* a graph holding true data.
*
* It is possible to get an empty Graph object (its kmer size must be nevertheless specified),
* and then use the Graph::buildNode to get a node based on a Data object.
*
* \snippet debruijn13.cpp snippet1
* [go back to \ref snippets_graph "top"]
* \n
*
************************************************************************************
* \section snippets_dbg_7 To go further...
*************************************************************************************
*
* \subsection snippets_kmer_dbg_18 Getting branching nodes statistics in a parallel way
*
* This example is a little bit harder than the previous ones. Its purpose is to show how
* to use the graph API for extracting some information. In particular, we will try to
* take care about time execution by using available cores.
*
* The idea here is to compute information about branching nodes and their in and out degrees.
* For instance, we want to know how many branching nodes have indegree==2 and outdegree=3.
* We compute therefore the number of branching nodes having indegree==X and outdegree==Y,
* with X and Y in [0..4] and the constraint that we can't have X==Y==1 (otherwise the node
* wouldn't be a branching one).
*
* We can do it easily by using the methods:
* - Graph::successors<BranchingNode>
* - Graph::predecessors<BranchingNode>
*
* Moreover, we want to do it in a parallel way in order to speed up the computation. The idea is
* to get an iterator over the branching nodes and iterate it through a Dispatcher object; such a
* dispatcher will create as many threads as wanted and will feed each threads with branching nodes.
* Note that this scheme can work here because the processing of one branching node is independant of
* the others.
*
* We need also some container for the in/out degrees statistics. A natural choice is to use a map,
* with the key being a unique identifier for a couple (indegree/outdegree) and the value the number
* of occurrences for the key. The idea is to use one map per thread and to merge the N maps into a global
* one after the parallel iteration of the branching nodes. We use here a ThreadObject object
* that allows to do it in a simple way. This object clones N time the global map and each clone is used in
* a specific thread. The ThreadObject class allows to hide many cumbersome points for the parallelization.
*
* In this example, we also use progress notification feature (with ProgressIterator) in order to have
* some user feedback during the iteration of the branching nodes.
*
* \snippet debruijn18.cpp snippet1
* [go back to \ref snippets_graph "top"]
*
*************************************************************************************
*
* \subsection snippets_kmer_dbg_19 Computing connected components of the branching nodes sub graph
*
* \snippet debruijn19.cpp snippet1
* [go back to \ref snippets_graph "top"]
*
*************************************************************************************
*
* \subsection snippets_kmer_dbg_24 Generate dot file from a graph
*
* This snippet generates a dot file from a de Bruijn graph. It is then possible to
* generate a pdf output of the graph (dot -Tpdf graph.dot -o graph.pdf)
*
* \snippet debruijn24.cpp snippet1
* [go back to \ref snippets_graph "top"]
*
*************************************************************************************
*
* \subsection snippets_kmer_dbg_26 Retrieve extra information from a node
*
* This snippet shows how to use the 'queryAbundance' method that returns the occurrences
* number of the node in the initial set of reads.
*
* This feature uses the EMPHF feature, and the graph must therefore build with the
* "-mphf emphf" option (otherwise the 'queryAbundance' method won't work).
*
* \snippet debruijn26.cpp snippet1
* [go back to \ref snippets_graph "top"]
*
* ************************************************************************************
************************************************************************************
* \page snippets_storage Storage snippets
************************************************************************************
*
* \tableofcontents
*
*************************************************************************************
*
* These snippets show how to use the persistency layer used in gatb-core
*
* \section snippets_storage_snippet1 Create and save a collection with a Storage object
*
* This snippet shows how to use a Storage object for creating a collection of integers.
* We use the HDF5 format, so we can control the result of our snippet with HDF5 tools.
*
*\snippet storage1.cpp snippet1
*
*************************************************************************************
* \section snippets_storage_snippet2 Create and save two collections with a Storage object
*
* This snippet shows how to use a Storage object for creating collections of integers.
* We use the HDF5 format, so we can control the result of our snippet with HDF5 tools.
*
*\snippet storage2.cpp snippet1
*
*************************************************************************************
* \section snippets_storage_snippet3 Load a collection from a Storage object
*
* This snippet shows how to load a Storage object and get a saved collection from it.
*
*\snippet storage3.cpp snippet1
*
*************************************************************************************
* \section snippets_storage_snippet4 Load collections from a Storage object
*
* This snippet shows how to load a Storage object and get saved collections from it.
* Note that we use lambda expressions in this example.
*
*\snippet storage4.cpp snippet1
*
*************************************************************************************
* \section snippets_storage_snippet6 Iterate solid kmers from a HDF5 file
*
* This snippet shows how to use a HDF5 Storage object holding solid kmers and iterate
* the kmers.
*
* It also uses a Model instance in order to convert the solid kmers values into the
* corresponding nucleotides sequence.
*
* The input file is likely to have been generated by dbgh5 for instance, or by dsk.
*
* If you want to know the structure of the HDF5 file, you can use the h5dump utility,
* for instance: h5dump -H file.h5
*
*\snippet storage6.cpp snippet1
*
*************************************************************************************
* \section snippets_storage_snippet7 Associate metadata to HDF5 collections
*
* This snippet shows how to associate metadata to HDF5 collections.
*
* You can dump such values with h5dump:
* h5dump -a myIntegers/myData foo.h5
*
*\snippet storage7.cpp snippet1
*
*************************************************************************************
* \section snippets_storage_snippet8 Using C++ like streams with HDF5
*
* This snippet shows how to use binary input/output streams with HDF5. There are two
* types:
* - Storage::ostream : used for saving binary data into a HDF5 collection
* - Storage::istream : used for retrieving binary data from a HDF5 collection
*
*\snippet storage8.cpp snippet1
*
************************************************************************************
* \page snippets_tools Tools snippets
************************************************************************************
*
* \tableofcontents
*
*************************************************************************************
*
* These snippets provide several miscellaneous tools that ease the developper's life.
*
*************************************************************************************
* \section snippets_tools_snippet1 Using the Tool class for quick tool development
*
* This snippet shows how to quickly create a new tool by subclassing the Tool class.
*
* Using the Tool class will give to use some useful features for developing our toy tool.
*
*\snippet ToyTool.cpp snippet1
*
*/
| 42.919488 | 116 | 0.596534 | [
"object",
"model",
"solid"
] |
d0a6bebaa1d6d8ca5984ad1aac997e45a76ceeef | 5,788 | cpp | C++ | src/online/VCRaceDetectorTest.cpp | zhanglu623/EventRacer-WebKit | 0be75fef811657fd5fceeca20c5777e9447e12b2 | [
"Apache-2.0"
] | 6 | 2018-11-06T00:17:42.000Z | 2021-01-23T20:57:49.000Z | src/online/VCRaceDetectorTest.cpp | sema/EventRacer | 1fcd5899f57e569743d5cca9bc1f27dfc6e27d71 | [
"Apache-2.0"
] | null | null | null | src/online/VCRaceDetectorTest.cpp | sema/EventRacer | 1fcd5899f57e569743d5cca9bc1f27dfc6e27d71 | [
"Apache-2.0"
] | 1 | 2021-03-08T15:14:29.000Z | 2021-03-08T15:14:29.000Z | /*
Copyright 2013 Software Reliability Lab, ETH Zurich
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 "VCRaceDetector.h"
#include <stdio.h>
#include <string>
void printRaces(const std::vector<RaceDetector::Race>& races) {
printf("%d races\n", static_cast<int>(races.size()));
for (size_t i = 0; i < races.size(); ++i) {
printf("%d - %d\n", races[i].eventAction1, races[i].eventAction2);
}
}
void expectRace(RaceDetector::VCRaceDetector* rd, RaceDetector::Race::Operation op, const char* var, const char* exp_races) {
std::vector<RaceDetector::Race> races;
rd->recordOperation(op, var, &races);
std::string races_str;
for (size_t i = 0; i < races.size(); ++i) {
char tmp[32];
sprintf(tmp, "[%s%d-%s%d]",
races[i].op1 == RaceDetector::Race::WRITE ? "w" : "r",
races[i].eventAction1,
races[i].op2 == RaceDetector::Race::WRITE ? "w" : "r",
races[i].eventAction2);
races_str.append(tmp);
}
if (races_str != exp_races) {
fprintf(stderr, "Test failed on variable %s! Expected races: %s, actual %s\n^^^ FAIL ^^^\n",
var, exp_races, races_str.c_str());
throw 0;
}
}
void testAllIsRacing() {
printf("Starting test testAllIsRacing...\n");
RaceDetector::VCRaceDetector rd;
rd.beginEventAction(0);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
rd.beginEventAction(1);
expectRace(&rd, RaceDetector::Race::READ, "a", "[w0-r1]");
rd.endEventAction();
rd.beginEventAction(2);
expectRace(&rd, RaceDetector::Race::READ, "a", "[w0-r2]");
expectRace(&rd, RaceDetector::Race::READ, "b", "");
expectRace(&rd, RaceDetector::Race::READ, "c", "");
rd.endEventAction();
rd.beginEventAction(3);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "[w0-w3][r1-w3][r2-w3]");
expectRace(&rd, RaceDetector::Race::WRITE, "b", "[r2-w3]");
rd.endEventAction();
rd.beginEventAction(4);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "[w3-w4]");
expectRace(&rd, RaceDetector::Race::READ, "c", "");
rd.endEventAction();
rd.beginEventAction(5);
expectRace(&rd, RaceDetector::Race::READ, "a", "[w4-r5]");
rd.endEventAction();
rd.beginEventAction(6);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "[w4-w6][r5-w6]");
expectRace(&rd, RaceDetector::Race::WRITE, "c", "[r2-w6][r4-w6]");
rd.endEventAction();
printf("Success\n");
}
void testNoneIsRacing() {
printf("Starting test testNoneIsRacing...\n");
RaceDetector::VCRaceDetector rd;
rd.beginEventAction(0);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
rd.beginEventAction(1);
rd.denoteCurrentEventAfter(0);
expectRace(&rd, RaceDetector::Race::READ, "a", "");
rd.endEventAction();
rd.beginEventAction(2);
rd.denoteCurrentEventAfter(0);
expectRace(&rd, RaceDetector::Race::READ, "a", "");
rd.endEventAction();
rd.beginEventAction(3);
rd.denoteCurrentEventAfter(1);
rd.denoteCurrentEventAfter(2);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
rd.beginEventAction(4);
rd.denoteCurrentEventAfter(3);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
rd.beginEventAction(5);
rd.denoteCurrentEventAfter(4);
expectRace(&rd, RaceDetector::Race::READ, "a", "");
rd.endEventAction();
rd.beginEventAction(6);
rd.denoteCurrentEventAfter(5);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
printf("Success\n");
}
void testSomeIsRacing1() {
printf("Starting test testSomeIsRacing1...\n");
RaceDetector::VCRaceDetector rd;
rd.beginEventAction(0);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
rd.beginEventAction(1);
rd.denoteCurrentEventAfter(0);
expectRace(&rd, RaceDetector::Race::READ, "a", "");
rd.endEventAction();
rd.beginEventAction(2);
rd.denoteCurrentEventAfter(0);
expectRace(&rd, RaceDetector::Race::READ, "a", "");
rd.endEventAction();
rd.beginEventAction(3);
rd.denoteCurrentEventAfter(2);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "[r1-w3]");
rd.endEventAction();
rd.beginEventAction(4);
rd.denoteCurrentEventAfter(3);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
rd.beginEventAction(5);
rd.denoteCurrentEventAfter(3);
expectRace(&rd, RaceDetector::Race::READ, "a", "[w4-r5]");
rd.endEventAction();
rd.beginEventAction(6);
rd.denoteCurrentEventAfter(5);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "[w4-w6]");
rd.endEventAction();
rd.beginEventAction(7);
rd.denoteCurrentEventAfter(5);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "[w6-w7]");
rd.endEventAction();
printf("Success\n");
}
void testCoveringRaces() {
printf("Starting test testCoveringRaces...\n");
RaceDetector::VCRaceDetector rd;
rd.beginEventAction(0);
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
rd.beginEventAction(1);
expectRace(&rd, RaceDetector::Race::READ, "a", "[w0-r1]");
expectRace(&rd, RaceDetector::Race::READ, "a", "[w0-r1]");
RaceDetector::Race r;
r.eventAction1 = 0;
r.eventAction2 = 1;
rd.recordRaceIsSync(r);
expectRace(&rd, RaceDetector::Race::READ, "a", "");
expectRace(&rd, RaceDetector::Race::WRITE, "a", "");
rd.endEventAction();
}
int main(void) {
testAllIsRacing();
testNoneIsRacing();
testSomeIsRacing1();
testCoveringRaces();
return 0;
}
| 27.826923 | 125 | 0.687975 | [
"vector"
] |
d0aa252bac5e457b407898c589bdf8cb15aca93b | 1,504 | cpp | C++ | projects/view3d/render/scene_view.cpp | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 2 | 2020-11-11T16:19:04.000Z | 2021-01-19T01:53:29.000Z | projects/view3d/render/scene_view.cpp | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2020-07-27T09:00:21.000Z | 2020-07-27T10:58:10.000Z | projects/view3d/render/scene_view.cpp | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2021-04-04T01:39:55.000Z | 2021-04-04T01:39:55.000Z | //*********************************************
// Renderer
// Copyright (c) Rylogic Ltd 2012
//*********************************************
#include "pr/view3d/forward.h"
#include "pr/view3d/render/scene_view.h"
namespace pr::rdr
{
// Construct scene views
SceneView::SceneView()
:pr::Camera()
,m_shadow_zfar(10.0f)
,m_shadow_max_caster_dist(20.0f)
{
PR_ASSERT(PR_DBG_RDR, pr::meta::is_aligned<SceneView>(this), "My alignment is broke");
}
SceneView::SceneView(pr::Camera const& cam)
:pr::Camera(cam)
,m_shadow_zfar(3.0f * cam.FocusDist())
,m_shadow_max_caster_dist(4.0f * cam.FocusDist())
{}
SceneView::SceneView(m4x4 const& c2w, float fovY, float aspect, float focus_dist, bool orthographic, float near_, float far_)
:pr::Camera(c2w, fovY, aspect, focus_dist, orthographic, near_, far_)
,m_shadow_zfar(3.0f * focus_dist)
,m_shadow_max_caster_dist(4.0f * focus_dist)
{}
// Return the scene views for the left and right eye in stereoscopic view
void SceneView::Stereo(float separation, SceneView (&eye)[Enum<EEye>::NumberOf]) const
{
auto sep = 0.5f * separation * m_c2w.x;
auto focus_point = FocusPoint();
auto lc2w = m4x4::LookAt(m_c2w.pos - sep, focus_point, m_c2w.y);
auto rc2w = m4x4::LookAt(m_c2w.pos + sep, focus_point, m_c2w.y);
eye[(int)EEye::Left ] = SceneView(lc2w, m_fovY, m_aspect, Length(lc2w.pos - focus_point), m_orthographic);
eye[(int)EEye::Right] = SceneView(rc2w, m_fovY, m_aspect, Length(rc2w.pos - focus_point), m_orthographic);
}
} | 37.6 | 126 | 0.672207 | [
"render"
] |
d0aa416c4ed5e46507f5146f091ae4ddb898069e | 4,063 | hpp | C++ | src/vlCore/Plane.hpp | Christophe-ABEL/VisualizationLibrary | 936fe9e5047970b23d97ff0088725e9016b470ee | [
"BSD-2-Clause"
] | 281 | 2016-04-16T14:11:04.000Z | 2022-03-24T14:48:52.000Z | src/vlCore/Plane.hpp | Christophe-ABEL/VisualizationLibrary | 936fe9e5047970b23d97ff0088725e9016b470ee | [
"BSD-2-Clause"
] | 91 | 2016-04-20T19:55:45.000Z | 2022-01-04T02:59:33.000Z | src/vlCore/Plane.hpp | Christophe-ABEL/VisualizationLibrary | 936fe9e5047970b23d97ff0088725e9016b470ee | [
"BSD-2-Clause"
] | 83 | 2016-04-26T01:28:40.000Z | 2022-03-21T13:23:55.000Z | /**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2020, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef Plane_INCLUDE_ONCE
#define Plane_INCLUDE_ONCE
#include <vlCore/Object.hpp>
#include <vlCore/glsl_math.hpp>
#include <vlCore/Transform.hpp>
namespace vl
{
class AABB;
//-----------------------------------------------------------------------------
// Plane
//-----------------------------------------------------------------------------
/**
* The Plane class defines a plane using a normal and an origin.
*/
class VLCORE_EXPORT Plane: public Object
{
VL_INSTRUMENT_CLASS(vl::Plane, Object)
public:
Plane( real o=0.0f, vec3 n=vec3(0,0,0) ): mNormal(n), mOrigin(o)
{
VL_DEBUG_SET_OBJECT_NAME()
}
Plane( const vec3& o, const vec3& n )
{
VL_DEBUG_SET_OBJECT_NAME()
mNormal = n;
mOrigin = dot(o, n);
}
real distance(const vec3 &v) const;
//! returns 0 if the AABB intersects the plane, 1 if it's in the positive side,
//! -1 if it's in the negative side.
int classify(const AABB&) const;
bool isOutside(const AABB&) const;
const vec3& normal() const { return mNormal; }
real origin() const { return mOrigin; }
void setNormal(const vec3& normal) { mNormal = normal; }
void setOrigin(real origin) { mOrigin = origin; }
protected:
vec3 mNormal;
real mOrigin;
};
}
#endif
| 45.651685 | 89 | 0.452375 | [
"object",
"transform"
] |
d0ab58181d3e5a0e97f97d305d4c8886a8eefffa | 7,171 | cxx | C++ | Src/Decimation/qslim-2.1/mixkit/src/MxFitFrame-2.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Decimation/qslim-2.1/mixkit/src/MxFitFrame-2.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Decimation/qslim-2.1/mixkit/src/MxFitFrame-2.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | /************************************************************************
Frame-to-frame distance functions.
Since the code for computing frame-to-frame distances is reasonably
large, and not always necessary, I've placed it here in a separate file.
Copyright (C) 1998 Michael Garland. See "COPYING.txt" for details.
$Id: MxFitFrame-2.cxx,v 1.1.1.1 2006/09/20 01:42:05 marc Exp $
************************************************************************/
#include "stdmix.h"
#include "MxFitFrame.h"
#include "MxVector.h"
void MxFitFrame::compute_distance_bounds(const MxFitFrame& F,
double *min, double *max) const
{
Vec3 K1[8], K2[8];
uint i,j;
worldspace_corners(K1);
F.worldspace_corners(K2);
// Compute maximum possible distance -- No two points are
// further apart than this.
//
*max = 0.0;
for(i=0; i<8; i++) for(j=0; j<8; j++)
{
double d2 = norm2(K1[i] - K2[j]);
if( d2 > *max ) *max = d2;
}
// Compute the minimum possible distance -- No two points
// are closer together than this.
//
if( check_intersection(F) )
*min = 0.0;
else
{
*min = HUGE;
for(i=0; i<8; i++)
{
double d_1 = F.compute_closest_sqrdistance(K1[i]);
double d_2 = compute_closest_sqrdistance(K2[i]);
if( d_1 < *min ) *min = d_1;
if( d_2 < *min ) *min = d_2;
}
}
}
/************************************************************************
*
* This code for intersection testing was adapted from code written by
* David Eberly <eberly@cs.unc.edu>. His original code is available at
* http://www.cs.unc.edu/~eberly/graphics.htm and was distributed
* under the following license:
*
* Permission is granted to use, copy, and distribute at no
* charge the MAGIC library code. Permission is also granted to
* the user to modify the code. However, if the modified code
* is distributed, then all such modifications must be
* documented to indicate that they are not part of the
* original package. The original code comes with absolutely no
* warranty and no guarantee is made that the code is bug-free.
*
* My changes to the original code:
*
* - Added new external interface to underlying code
* - Some simple reformatting
* - Use MixKit vector classes
* - C++ conversion
*
************************************************************************/
typedef Vec3 Vector;
/* oriented bounding boxes without velocity */
struct OBBox0 {
Vector C; /* center */
Vector B[3]; /* orthonormal basis */
Vector E; /* extent along basis vectors */
};
static
double Dot(const Vector& P, const Vector& Q)
{ return P[0]*Q[0]+P[1]*Q[1]+P[2]*Q[2]; }
#define Dot(P,Q) ((P)*(Q))
static
bool TestIntersection0(const OBBox0* b0, const OBBox0* b1)
{
double d0, d1, d2;
double r0, r1, r2;
double C[3][3];
Vector D(b1->C[0]-b0->C[0], b1->C[1]-b0->C[1], b1->C[2]-b0->C[2]);
/* L = A0 */
C[0][0] = Dot(b0->B[0],b1->B[0]);
C[0][1] = Dot(b0->B[0],b1->B[1]);
C[0][2] = Dot(b0->B[0],b1->B[2]);
d0 = Dot(D,b0->B[0]);
r0 = fabs(b0->E[0]);
r1 = fabs(b1->E[0]*C[0][0])+fabs(b1->E[1]*C[0][1])+fabs(b1->E[2]*C[0][2]);
r2 = fabs(d0);
if ( r2 > r0+r1 )
return false;
/* L = A1 */
C[1][0] = Dot(b0->B[1],b1->B[0]);
C[1][1] = Dot(b0->B[1],b1->B[1]);
C[1][2] = Dot(b0->B[1],b1->B[2]);
d1 = Dot(D,b0->B[1]);
r0 = fabs(b0->E[1]);
r1 = fabs(b1->E[0]*C[1][0])+fabs(b1->E[1]*C[1][1])+fabs(b1->E[2]*C[1][2]);
r2 = fabs(d1);
if ( r2 > r0+r1 )
return false;
/* L = A2 */
C[2][0] = Dot(b0->B[2],b1->B[0]);
C[2][1] = Dot(b0->B[2],b1->B[1]);
C[2][2] = Dot(b0->B[2],b1->B[2]);
d2 = Dot(D,b0->B[2]);
r0 = fabs(b0->E[2]);
r1 = fabs(b1->E[0]*C[2][0])+fabs(b1->E[1]*C[2][1])+fabs(b1->E[2]*C[2][2]);
r2 = fabs(d2);
if ( r2 > r0+r1 )
return false;
/* L = B0 */
r0 = fabs(b0->E[0]*C[0][0])+fabs(b0->E[1]*C[1][0])+fabs(b0->E[2]*C[2][0]);
r1 = fabs(b1->E[0]);
r2 = fabs(Dot(D,b1->B[0]));
if ( r2 > r0+r1 )
return false;
/* L = B1 */
r0 = fabs(b0->E[0]*C[0][1])+fabs(b0->E[1]*C[1][1])+fabs(b0->E[2]*C[2][1]);
r1 = fabs(b1->E[1]);
r2 = fabs(Dot(D,b1->B[1]));
if ( r2 > r0+r1 )
return false;
/* L = B2 */
r0 = fabs(b0->E[0]*C[0][2])+fabs(b0->E[1]*C[1][2])+fabs(b0->E[2]*C[2][2]);
r1 = fabs(b1->E[2]);
r2 = fabs(Dot(D,b1->B[2]));
if ( r2 > r0+r1 )
return false;
/* L = A0xB0 */
r0 = fabs(b0->E[1]*C[2][0])+fabs(b0->E[2]*C[1][0]);
r1 = fabs(b1->E[1]*C[0][2])+fabs(b1->E[2]*C[0][1]);
r2 = fabs(d2*C[1][0]-d1*C[2][0]);
if ( r2 > r0+r1 )
return false;
/* L = A0xB1 */
r0 = fabs(b0->E[1]*C[2][1])+fabs(b0->E[2]*C[1][1]);
r1 = fabs(b1->E[0]*C[0][2])+fabs(b1->E[2]*C[0][0]);
r2 = fabs(d2*C[1][1]-d1*C[2][1]);
if ( r2 > r0+r1 )
return false;
/* L = A0xB2 */
r0 = fabs(b0->E[1]*C[2][2])+fabs(b0->E[2]*C[1][2]);
r1 = fabs(b1->E[0]*C[0][1])+fabs(b1->E[1]*C[0][0]);
r2 = fabs(d2*C[1][2]-d1*C[2][2]);
if ( r2 > r0+r1 )
return false;
/* L = A1xB0 */
r0 = fabs(b0->E[0]*C[2][0])+fabs(b0->E[2]*C[0][0]);
r1 = fabs(b1->E[1]*C[1][2])+fabs(b1->E[2]*C[1][1]);
r2 = fabs(d0*C[2][0]-d2*C[0][0]);
if ( r2 > r0+r1 )
return false;
/* L = A1xB1 */
r0 = fabs(b0->E[0]*C[2][1])+fabs(b0->E[2]*C[0][1]);
r1 = fabs(b1->E[0]*C[1][2])+fabs(b1->E[2]*C[1][0]);
r2 = fabs(d0*C[2][1]-d2*C[0][1]);
if ( r2 > r0+r1 )
return false;
/* L = A1xB2 */
r0 = fabs(b0->E[0]*C[2][2])+fabs(b0->E[2]*C[0][2]);
r1 = fabs(b1->E[0]*C[1][1])+fabs(b1->E[1]*C[1][0]);
r2 = fabs(d0*C[2][2]-d2*C[0][2]);
if ( r2 > r0+r1 )
return false;
/* L = A2xB0 */
r0 = fabs(b0->E[0]*C[1][0])+fabs(b0->E[1]*C[0][0]);
r1 = fabs(b1->E[1]*C[2][2])+fabs(b1->E[2]*C[2][1]);
r2 = fabs(d1*C[0][0]-d0*C[1][0]);
if ( r2 > r0+r1 )
return false;
/* L = A2xB1 */
r0 = fabs(b0->E[0]*C[1][1])+fabs(b0->E[1]*C[0][1]);
r1 = fabs(b1->E[0]*C[2][2])+fabs(b1->E[2]*C[2][0]);
r2 = fabs(d1*C[0][1]-d0*C[1][1]);
if ( r2 > r0+r1 )
return false;
/* L = A2xB2 */
r0 = fabs(b0->E[0]*C[1][2])+fabs(b0->E[1]*C[0][2]);
r1 = fabs(b1->E[0]*C[2][1])+fabs(b1->E[1]*C[2][0]);
r2 = fabs(d1*C[0][2]-d0*C[1][2]);
if ( r2 > r0+r1 )
return false;
return true;
}
static
void frame_to_obb(const MxFitFrame& F, OBBox0 b0)
{
// Must reparameterize cluster bounding box so that it extends equally
// in all directions from the center
Vec3 avg;
Vec3& diff = b0.E;
Vec3& ctr = b0.C;
// avg = (max + min)/2
mxv_add(avg, F.max(), F.min(), 3); mxv_scale(avg, 0.5, 3);
// diff = (max - min)/2
mxv_sub(diff, F.max(), F.min(), 3); mxv_scale(diff, 0.5, 3);
F.from_frame(avg, ctr);
mxv_set(b0.B[0], F.axis(0), 3);
mxv_set(b0.B[1], F.axis(1), 3);
mxv_set(b0.B[2], F.axis(2), 3);
}
bool MxFitFrame::check_intersection(const MxFitFrame& c1) const
{
OBBox0 b0, b1;
frame_to_obb(*this, b0);
frame_to_obb(c1, b1);
return TestIntersection0(&b0, &b1);
}
| 28.011719 | 78 | 0.49993 | [
"vector"
] |
d0ab9208f270e1a27ffbb8b0a0c505eacc001192 | 3,364 | hpp | C++ | libs/TwoDLib/Triangle.hpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 13 | 2015-09-15T17:28:25.000Z | 2022-03-22T20:26:47.000Z | libs/TwoDLib/Triangle.hpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 41 | 2015-08-25T07:50:55.000Z | 2022-03-21T16:20:37.000Z | libs/TwoDLib/Triangle.hpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 9 | 2015-09-14T20:52:07.000Z | 2022-03-08T12:18:18.000Z | // Copyright (c) 2005 - 2015 Marc de Kamps
// 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 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.
//
#ifndef _CODE_LIBS_TWODLIB_TRIANGLE_INCLUDE_GUARD
#define _CODE_LIBS_TWODLIB_TRIANGLE_INCLUDE_GUARD
#include <vector>
#include "Cell.hpp"
#include "Point.hpp"
namespace TwoDLib {
/**
* \brief A class supporting triangles
*
* A Triangle is defined by three points. The Quadrilateral is assumed to be
* non-degenerate.
*/
class Triangle : public Cell {
public:
Triangle
(
const Point&,
const Point&,
const Point&
);
Triangle
(
const vector<Point>& //!< a vector of exactly three points
);
//! Constructor, requires two vectors of 3 coordinates each.
Triangle
(
const vector<double>&, //!< a vector of exactly three v values
const vector<double>& //!< a vector of exactly three w values
);
//! Copy constructor
Triangle(const Triangle&);
//! Destructor
virtual ~Triangle();
static const unsigned int _nr_points;
static int get_line_intersection(double p0_x, double p0_y, double p1_x, double p1_y,
double p2_x, double p2_y, double p3_x, double p3_y, double *i_x, double *i_y);
static double get_overlap_area(const Triangle& t1, const Triangle& t2);
static double sign (Point p1, Point p2, Point p3);
static bool pointInTriangle(const Point& pt, const Triangle& t);
static int orientation(Point p, Point q, Point r);
static vector<Point> convexHull(const vector<Point>& points);
void print() {
std::cout << "Tri : " << _vec_points[0][0] << "," << _vec_points[0][1] << " | "
<< _vec_points[1][0] << "," << _vec_points[1][1] << " | "
<< _vec_points[2][0] << "," << _vec_points[2][1] << "\n";
}
private:
friend class TriangleGenerator;
vector<Point> VectorFromPoints(const Point& p1, const Point& p2, const Point& p3) const;
Point _base;
Point _span_1;
Point _span_2;
};
}
#endif /* TRIANGLE_HPP_ */
| 36.565217 | 162 | 0.724435 | [
"vector"
] |
d0bed9c3b88ccca6363dc6d3795da771243f2f3b | 1,917 | hpp | C++ | libiop/relations/sparse_matrix.hpp | guipublic/libiop | 01dc1b567bc5058cbe54d12760aa7a35e27cfba7 | [
"MIT"
] | null | null | null | libiop/relations/sparse_matrix.hpp | guipublic/libiop | 01dc1b567bc5058cbe54d12760aa7a35e27cfba7 | [
"MIT"
] | null | null | null | libiop/relations/sparse_matrix.hpp | guipublic/libiop | 01dc1b567bc5058cbe54d12760aa7a35e27cfba7 | [
"MIT"
] | null | null | null | /** @file
*****************************************************************************
Interfaces for sparse matrices together with adapters for R1CS A/B/C matrices.
*****************************************************************************
* @author This file is part of libiop (see AUTHORS)
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LIBIOP_RELATIONS_SPARSE_MATRIX_HPP_
#define LIBIOP_RELATIONS_SPARSE_MATRIX_HPP_
#include <cstddef>
#include <memory>
#include "libiop/relations/r1cs.hpp"
#include "libiop/relations/variable.hpp"
namespace libiop {
template<typename FieldT>
class sparse_matrix {
public:
sparse_matrix() = default;
virtual linear_combination<FieldT> get_row(const std::size_t row_index) const;
virtual std::size_t num_rows() const;
virtual std::size_t num_columns() const;
virtual std::size_t num_nonzero_entries() const;
virtual ~sparse_matrix() = default;
};
enum r1cs_sparse_matrix_type {
r1cs_sparse_matrix_A = 1,
r1cs_sparse_matrix_B = 2,
r1cs_sparse_matrix_C = 3
};
extern std::vector<r1cs_sparse_matrix_type> all_r1cs_sparse_matrix_types;
template<typename FieldT>
class r1cs_sparse_matrix : public sparse_matrix<FieldT> {
protected:
std::shared_ptr<r1cs_constraint_system<FieldT> > constraint_system_;
r1cs_sparse_matrix_type matrix_type_;
public:
r1cs_sparse_matrix(
std::shared_ptr<r1cs_constraint_system<FieldT> > constraint_system,
const r1cs_sparse_matrix_type matrix_type);
virtual linear_combination<FieldT> get_row(const std::size_t row_index) const;
virtual std::size_t num_rows() const;
virtual std::size_t num_columns() const;
virtual std::size_t num_nonzero_entries() const;
};
} // libiop
#include "libiop/relations/sparse_matrix.tcc"
#endif // LIBIOP_RELATIONS_SPARSE_MATRIX_HPP_
| 30.919355 | 82 | 0.671362 | [
"vector"
] |
d0d3b981ffcb65956098f82358d4f64eb5df8e45 | 1,559 | cc | C++ | uva/chapter_4/452.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | uva/chapter_4/452.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | uva/chapter_4/452.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <queue>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <memory>
using namespace std;
using vi = vector<int>;
using ii = pair<int,int>;
using ll = long long;
using llu = unsigned long long;
const int INF = numeric_limits<int>::max();
struct node;
using pnode = shared_ptr<node>;
struct node {
int t, m, in;
vector<pnode> adjusted;
};
int main() {
int tcc, r; string s;
cin >> tcc;
getline(cin, s);
getline(cin, s);
for (int tc = 0; tc < tcc; tc++) {
if (tc) cout << endl;
vector<pnode> g(26);
for (auto &u : g) {
u = make_shared<node>();
u->m = 0;
u->in = 0;
}
while (getline(cin,s)) {
if (s == "") break;
stringstream ss(s);
char a; string adjusted; int t;
ss >> a >> t >> adjusted;
auto &u = g[a - 'A'];
u->t = u->m = t;
for (auto c : adjusted) {
u->adjusted.push_back(g[c - 'A']);
g[c - 'A']->in++;
}
}
r = 0;
queue<pnode> q;
for (auto u : g) if (u->in == 0) q.push(u);
while (!q.empty()) {
auto u = q.front(); q.pop();
r = max(r, u->m);
for (auto v : u->adjusted) {
v->m = max(v->m, u->m + v->t);
v->in--;
if (v->in == 0) q.push(v);
}
}
cout << r << endl;
}
}
| 19.987179 | 47 | 0.527261 | [
"vector"
] |
d0dad78b13b3924b70f3f0be7195a03573915afe | 1,350 | cpp | C++ | Models/Chapter5_MBT/GearShiftingTestComponent/GSC_Test_Animation/MainGearShiftingTestComponent.cpp | PacktPublishing/Agile-Model-Based-Systems-Engineering-Cookbook | 459c90a7b5af0aa9c16f517fd6caafc39d83f545 | [
"MIT"
] | 9 | 2021-04-08T02:13:26.000Z | 2021-12-17T02:53:39.000Z | Models/Chapter5_MBT/GearShiftingTestComponent/GSC_Test_Animation/MainGearShiftingTestComponent.cpp | PacktPublishing/Agile-Model-Based-Systems-Engineering-Cookbook | 459c90a7b5af0aa9c16f517fd6caafc39d83f545 | [
"MIT"
] | null | null | null | Models/Chapter5_MBT/GearShiftingTestComponent/GSC_Test_Animation/MainGearShiftingTestComponent.cpp | PacktPublishing/Agile-Model-Based-Systems-Engineering-Cookbook | 459c90a7b5af0aa9c16f517fd6caafc39d83f545 | [
"MIT"
] | 3 | 2021-04-29T15:15:17.000Z | 2022-01-28T09:44:55.000Z | /********************************************************************
Rhapsody : 9.0
Login : Bruce
Component : GearShiftingTestComponent
Configuration : GSC_Test_Animation
Model Element : GSC_Test_Animation
//! Generated Date : Sat, 28, Nov 2020
File Path : GearShiftingTestComponent/GSC_Test_Animation/MainGearShiftingTestComponent.cpp
*********************************************************************/
//## auto_generated
#include "MainGearShiftingTestComponent.h"
//## auto_generated
#include "RiderInteractionDesignPkg.h"
//## auto_generated
#include "TestPkg.h"
GearShiftingTestComponent::GearShiftingTestComponent() {
TestPkg_initRelations();
TestPkg_startBehavior();
}
int main(int argc, char* argv[]) {
int status = 0;
if(OXF::initialize(argc, argv, 6423))
{
GearShiftingTestComponent initializer_GearShiftingTestComponent;
//#[ configuration GearShiftingTestComponent::GSC_Test_Animation
//#]
OXF::start();
status = 0;
}
else
{
status = 1;
}
return status;
}
/*********************************************************************
File Path : GearShiftingTestComponent/GSC_Test_Animation/MainGearShiftingTestComponent.cpp
*********************************************************************/
| 32.142857 | 91 | 0.548148 | [
"model"
] |
d0dd44cd42a964e20d928ce739af65ea0a59a189 | 5,728 | cc | C++ | src/indexing/main.cc | rainerdun/recomm_engine | 8433150fc25d4af83253250b2c4cd18a269e796c | [
"MIT"
] | 7 | 2016-01-14T15:53:59.000Z | 2021-08-25T03:47:10.000Z | src/indexing/main.cc | BaiGang/recomm_engine | 8433150fc25d4af83253250b2c4cd18a269e796c | [
"MIT"
] | null | null | null | src/indexing/main.cc | BaiGang/recomm_engine | 8433150fc25d4af83253250b2c4cd18a269e796c | [
"MIT"
] | 9 | 2015-04-14T10:18:46.000Z | 2018-12-20T08:18:21.000Z | // Copyright 2013 Sina Inc. All rights reserved.
// Author: yanbing3@staff.sina.com.cn (Yan-Bing Bai)
// Only for testing
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
#include <string>
#include <vector>
#include <map>
#include <iostream> // NOLINT
#include "./instant_index.h"
#include "glog/logging.h"
#include "./posting.h"
#include "gflags/gflags.h"
#include "./recomm_engine_types.h"
#include "./iterator.h"
#include "util/base/timer.h"
using recomm_engine::idl::StoryProfile;
using recomm_engine::idl::StoryAddingRequest;
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::map;
using boost::shared_ptr;
using namespace recomm_engine::indexing; // NOLINT
using util::Timer;
const int NUM_TOKEN = 1000;
const int NUM_DOCS = 50000;
const int NUM_KEYWORDS = 50;
unsigned int retrieval_counter = 0;
unsigned int latency = 0;
void ParseInput(vector<StoryProfile>* stories) {
int cnt;
scanf("%d", &cnt);
for (int k = 0; k < cnt; k++) {
char buf[10];
sprintf(buf, "%d", k); // NOLINT
int num;
scanf("%d", &num);
StoryProfile story;
story.story_id = string(buf);
for (int i = 0; i < num; i++) {
int word;
scanf("%d", &word);
story.keywords[word] = 1;
}
stories->push_back(story);
}
}
void TestIndex() {
using recomm_engine::indexing::InstantIndex;
boost::shared_ptr<InstantIndex> index(InstantIndex::GetInstance());
// Fake doc
vector<StoryProfile> stories;
// for (int i = 0; i < 5; i++) {
// StoryProfile s;
// char buf[10];
// buf[1] = '\0';
// buf[0] = '0' + i;
// // itoa(i, buf, 10);
// s.story_id = string(buf);
// s.keywords[i] = 1;
// s.keywords[i+5] = 1;
// stories.push_back(s);
// LOG(INFO) << "Creating story " << s.story_id;
// }
ParseInput(&stories);
for (int i = 0; i < 5; i++) {
StoryAddingRequest req;
req.story = stories[i];
sleep(3);
LOG(INFO) << "Adding Story " << req.story.story_id;
index->AddStory(req);
}
// sleep(80);
while (true) {
sleep(1);
LOG(INFO) << "Printing index";
// Print index
for (int i = 0; i < 10; i++) {
shared_ptr<PostingIterator> it = index->GetPostingList(i);
if (!it.get()) {
LOG(ERROR) << "No posting list for token " << i;
continue;
}
cout << "Posting list for " << i << ":";
while (it->HasValue()) {
Posting p = it->GetValue();
cout << p.local_docid << ",";
it->Next();
}
cout << endl;
}
}
sleep(60);
}
void Retrieval() {
while (true) {
Timer timer;
timer.Begin();
InstantIndex* index = InstantIndex::GetInstance();
using boost::unordered_set;
unordered_set<int64_t> global_id_set;
unordered_set<LocalDocID> local_id_set;
const int NUM_R_TOKEN = 5;
vector<int64_t> tokens;
for (int i = 0; i < NUM_R_TOKEN; i++) {
tokens.push_back(rand() % NUM_TOKEN); // NOLINT
}
map<int64_t, shared_ptr<PostingIterator> > iter_map =
index->GetPostingListBatch(tokens);
typedef map<int64_t, shared_ptr<PostingIterator> >::iterator Iter;
for (Iter it = iter_map.begin(); it != iter_map.end(); ++it) {
if (!it->second.get()) {
continue;
}
shared_ptr<PostingIterator> pt = it->second;
int cnt = 0;
while (pt->HasValue()) {
Posting p = pt->GetValue();
local_id_set.insert(p.local_docid);
pt->Next();
cnt++;
}
}
vector<LocalDocID> local_id_vec(local_id_set.begin(), local_id_set.end());
map<LocalDocID, int64_t> global_id_map;
index->TranslateToGlobalIDBatch(local_id_vec, &global_id_map);
/*
for (int i = 0; i < NUM_R_TOKEN; i++) {
shared_ptr<PostingIterator> it = index->GetPostingList(
rand() % NUM_TOKEN); // NOLINT
if (!it.get()) {
continue;
}
int cnt = 0;
while (it->HasValue()) {
Posting p = it->GetValue();
local_id_set.insert(p.local_docid);
it->Next();
cnt++;
}
}
for (unordered_set<LocalDocID>::iterator it = local_id_set.begin();
it != local_id_set.end(); ++it) {
int64_t global_id;
if (index->TranslateToGlobalID(*it, &global_id)) {
global_id_set.insert(global_id);
}
}
*/
retrieval_counter++;
timer.End();
latency = timer.GetMs();
// if (timer.GetMs() > latency) {
// latency = timer.GetMs();
// }
}
}
void LoadTestIndexBuilding() {
InstantIndex* index = InstantIndex::GetInstance();
for (int i = 0; i < NUM_DOCS; i++) {
StoryAddingRequest req;
for (int k = 0; k < NUM_KEYWORDS; k++) {
int word_id = rand() % NUM_TOKEN; // NOLINT
req.story.keywords[word_id] = 1;
}
req.story.__isset.keywords = true;
usleep(5*1000);
index->AddStory(req);
}
}
int main(int argc, char** argv) {
google::ParseCommandLineFlags(&argc, &argv, false);
InstantIndex* index = InstantIndex::GetInstance();
// shared_ptr<boost::thread> build_thread(new boost::thread(
// LoadTestIndexBuilding));
vector<shared_ptr<boost::thread> > r_threads;
for (int i = 0; i < 10; i++) {
shared_ptr<boost::thread> r_thread(new boost::thread(Retrieval));
r_threads.push_back(r_thread);
}
unsigned int last_counter = retrieval_counter;
while (true) {
sleep(1);
LOG(INFO) << "Retrieval done:" << retrieval_counter - last_counter
<< " Latency: " << latency;
last_counter = retrieval_counter;
string info;
index->GetState(&info);
LOG(INFO) << info;
}
sleep(1000 * 1000);
return 0;
}
| 27.671498 | 78 | 0.597242 | [
"vector"
] |
d0e2a3e1984874a5f719add61100efdcee5371b2 | 23,236 | cpp | C++ | Source/Manager/Resource/ResourceType/MeshResource.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | 2 | 2020-01-09T07:48:24.000Z | 2020-01-09T07:48:26.000Z | Source/Manager/Resource/ResourceType/MeshResource.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null | Source/Manager/Resource/ResourceType/MeshResource.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null | #include "MeshResource.hpp"
#include <fstream>
#include <sstream>
#include "../../../System/Graphics/DataType/MeshInfo.hpp"
#include "../../../System/Math/Algebra/Vector3.hpp"
#include "../../../System/Math/Algebra/Vector2.hpp"
#include "../../../System/Math/Primitive/ConvexHull2D/Triangle.hpp"
namespace Engine5
{
MeshResource::MeshResource(const std::wstring& path)
: Resource(path)
{
m_type = eResourceType::Mesh;
}
MeshResource::~MeshResource()
{
}
void MeshResource::Initialize()
{
std::ifstream file_stream;
// Open the model file.
file_stream.open(m_file_path_w);
// If it could not open the file then exit.
if (file_stream.fail())
{
return;
}
m_mesh_data.b_resource = true;
CheckMeshType();
switch (m_mesh_type)
{
case eMeshType::Invalid:
break;
case eMeshType::CustomTXT:
LoadCustomTXT(file_stream);
m_b_loaded = true;
break;
case eMeshType::WaveFrontOBJ:
LoadOBJOnlyPos(file_stream);
m_b_loaded = true;
break;
default:
break;
}
file_stream.close();
}
void MeshResource::Shutdown()
{
m_b_unloaded = true;
}
void MeshResource::LoadWaveFrontOBJ(std::ifstream& file)
{
// Read in the vertices, texture coordinates, and normals into the data structures.
// Important: Also convert to left hand coordinate system since Maya uses right hand coordinate system.
size_t vertex_index = 0;
size_t uv_index = 0;
size_t normal_index = 0;
size_t face_index = 0;
char input, input2;
std::vector<Vector3> points;
std::vector<Vector3> normals;
std::vector<Vector2> uvs;
std::vector<MeshFaceIndexInfo> faces;
file.get(input);
while (!file.eof())
{
if (input == 'v')
{
file.get(input);
// Read in the vertices.
if (input == ' ')
{
Vector3 vertex;
file >> vertex.x >> vertex.y >> vertex.z;
// Invert the Z vertex to change to left hand system.
vertex.z = vertex.z * -1.0f;
vertex_index++;
points.push_back(vertex);
}
// Read in the texture uv coordinates.
if (input == 't')
{
Vector2 uv;
file >> uv.x >> uv.y;
// Invert the V texture coordinates to left hand system.
uv.y = 1.0f - uv.y;
uv_index++;
uvs.push_back(uv);
}
// Read in the normals.
if (input == 'n')
{
Vector3 normal;
file >> normal.x >> normal.y >> normal.z;
// Invert the Z normal to change to left hand system.
normal.z = normal.z * -1.0f;
normal_index++;
normals.push_back(normal);
}
}
// Read in the faces.
if (input == 'f')
{
file.get(input);
if (input == ' ')
{
MeshFaceIndexInfo face;
// Read the face data in backwards to convert it to a left hand system from right hand system.
file >> face.point_index_c;
file.get(input2);
if (input2 == ' ')
{
file >> face.point_index_b;
file >> face.point_index_a;
}
else if (input2 == '/')
{
file.get(input2);
if (input2 != '/')
{
file.unget();
file >> face.uv_index_c;
file.get(input2);
if (input2 == ' ')
{
file >> face.point_index_b;
file.get(input2);
file >> face.uv_index_b;
file >> face.point_index_a;
file.get(input2);
file >> face.uv_index_a;
}
else if (input2 == '/')
{
file >> face.normal_index_c;
file >> face.point_index_b;
file.get(input2);
file >> face.uv_index_b;
file.get(input2);
file >> face.normal_index_b;
file >> face.point_index_a;
file.get(input2);
file >> face.uv_index_a;
file.get(input2);
file >> face.normal_index_a;
}
}
else
{
file >> face.normal_index_c;
file >> face.point_index_b;
file.get(input2);
file.get(input2);
file >> face.normal_index_b;
file >> face.point_index_a;
file.get(input2);
file.get(input2);
file >> face.normal_index_a;
}
}
face_index++;
faces.push_back(face);
}
}
// Read in the remainder of the line.
while (input != '\n')
{
file.get(input);
}
// Start reading the beginning of the next line.
file.get(input);
}
bool b_uv = !uvs.empty();
bool b_normal = !normals.empty();
U32 index = 0;
size_t count = faces.size() * 3;
m_mesh_data.vertices.reserve(count);
m_mesh_data.indices.reserve(count);
for (auto& face : faces)
{
VertexCommon vertex_a, vertex_b, vertex_c;
vertex_a.SetPosition(points[face.point_index_a - 1]);
vertex_b.SetPosition(points[face.point_index_b - 1]);
vertex_c.SetPosition(points[face.point_index_c - 1]);
if (b_uv)
{
vertex_a.SetUV(uvs[face.uv_index_a - 1]);
vertex_b.SetUV(uvs[face.uv_index_b - 1]);
vertex_c.SetUV(uvs[face.uv_index_c - 1]);
}
if (b_normal)
{
vertex_a.SetNormal(normals[face.normal_index_a - 1]);
vertex_b.SetNormal(normals[face.normal_index_b - 1]);
vertex_c.SetNormal(normals[face.normal_index_c - 1]);
}
else
{
Vector3 normal = Triangle::Normal(vertex_a.GetPosition(), vertex_b.GetPosition(), vertex_c.GetPosition());
vertex_a.SetNormal(normal);
vertex_b.SetNormal(normal);
vertex_c.SetNormal(normal);
}
vertex_a.CalculateTangentAndBinormal();
vertex_b.CalculateTangentAndBinormal();
vertex_c.CalculateTangentAndBinormal();
m_mesh_data.vertices.push_back(vertex_a);
m_mesh_data.vertices.push_back(vertex_b);
m_mesh_data.vertices.push_back(vertex_c);
m_mesh_data.indices.push_back(index);
m_mesh_data.indices.push_back(index + 1);
m_mesh_data.indices.push_back(index + 2);
index += 3;
}
}
void MeshResource::LoadGeneralOBJ(std::ifstream& file)
{
std::string name = m_file_name_m;
//indices
U32 point_index = 0;
size_t uv_index = 0;
size_t normal_index = 0;
size_t face_index = 0;
//container
std::vector<Vector3> points;
std::vector<Vector3> normals;
std::vector<Vector2> uvs;
std::vector<MeshFaceIndexInfo> faces;
//line, char
String line;
char next_input;
while (std::getline(file, line))
{
String text;
std::istringstream string_stream(line);
string_stream >> text;
// Read points.
if (text == "v")
{
Vector3 point;
string_stream >> point.x >> point.y >> point.z;
point.z = point.z * -1.0f;
points.push_back(point);
point_index++;
}
// Read texture uv coordinates.
if (text == "vt")
{
Vector2 uv;
string_stream >> uv.x >> uv.y;
uv.y = 1.0f - uv.y;
uv_index++;
uvs.push_back(uv);
}
// Read normals.
if (text == "vn")
{
Vector3 normal;
string_stream >> normal.x >> normal.y >> normal.z;
normal.z = normal.z * -1.0f;
normal_index++;
normals.push_back(normal);
}
// Read faces.
if (text == "f")
{
size_t index_count = std::count(line.begin(), line.end(), ' ');
size_t slash_count = std::count(line.begin(), line.end(), '/');
std::vector<MeshVertexIndexInfo> model_indices;
size_t line_of_faces_size = index_count - 2;
model_indices.resize(index_count);
eOBJFaceType type = eOBJFaceType::Point;
if (slash_count == 0)
{
type = eOBJFaceType::Point;
}
else if (slash_count == index_count)
{
type = eOBJFaceType::PointTexture;
}
else if (slash_count == index_count * 2)
{
if (line.find("//") != String::npos)
{
type = eOBJFaceType::PointNormal;
}
else
{
type = eOBJFaceType::PointTextureNormal;
}
}
else
{
return;
}
for (size_t i = 0; i < index_count; ++i)
{
if (type == eOBJFaceType::Point)
{
string_stream >> model_indices[i].point_index;
}
else if (type == eOBJFaceType::PointTexture)
{
string_stream >> model_indices[i].point_index;
string_stream.get(next_input);
string_stream >> model_indices[i].uv_index;
}
else if (type == eOBJFaceType::PointNormal)
{
string_stream >> model_indices[i].point_index;
string_stream.get(next_input);
string_stream.get(next_input);
string_stream >> model_indices[i].normal_index;
}
else if (type == eOBJFaceType::PointTextureNormal)
{
string_stream >> model_indices[i].point_index;
string_stream.get(next_input);
string_stream >> model_indices[i].uv_index;
string_stream.get(next_input);
string_stream >> model_indices[i].normal_index;
}
}
for (size_t i = 0; i < line_of_faces_size; ++i)
{
faces.emplace_back(model_indices[i + 2], model_indices[i + 1], model_indices[0]);
}
face_index += line_of_faces_size;
}
}
bool b_uv = !uvs.empty();
bool b_normal = !normals.empty();
U32 index = 0;
for (auto& face : faces)
{
VertexCommon vertex_a, vertex_b, vertex_c;
vertex_a.SetPosition(points[face.point_index_a - 1]);
vertex_b.SetPosition(points[face.point_index_b - 1]);
vertex_c.SetPosition(points[face.point_index_c - 1]);
if (b_uv)
{
if (face.uv_index_a > 0)
vertex_a.SetUV(uvs[face.uv_index_a - 1]);
if (face.uv_index_b > 0)
vertex_b.SetUV(uvs[face.uv_index_b - 1]);
if (face.uv_index_c > 0)
vertex_c.SetUV(uvs[face.uv_index_c - 1]);
}
if (b_normal)
{
if (face.normal_index_a > 0)
vertex_a.SetNormal(normals[face.normal_index_a - 1]);
if (face.normal_index_b > 0)
vertex_b.SetNormal(normals[face.normal_index_b - 1]);
if (face.normal_index_c > 0)
vertex_c.SetNormal(normals[face.normal_index_c - 1]);
}
//Add vertex info into mesh data
m_mesh_data.vertices.push_back(vertex_a);
m_mesh_data.vertices.push_back(vertex_b);
m_mesh_data.vertices.push_back(vertex_c);
//Add face info and index info into mesh data
m_mesh_data.faces.emplace_back(index, index + 1, index + 2);
m_mesh_data.indices.push_back(index);
m_mesh_data.indices.push_back(index + 1);
m_mesh_data.indices.push_back(index + 2);
index += 3;
}
//process point based calculation
}
void MeshResource::LoadOBJOnlyPos(std::ifstream& file)
{
std::string name = m_file_name_m;
//indices
U32 point_index = 0;
U32 face_index = 0;
//container
std::vector<MeshFaceIndexInfo> faces;
std::vector<GeometryPointIndex> point_indices;
//line, char
String line;
char next_input;
while (std::getline(file, line))
{
String text;
std::istringstream string_stream(line);
string_stream >> text;
// Read points.
if (text == "v")
{
Vector3 point;
string_stream >> point.x >> point.y >> point.z;
point.z = point.z * -1.0f;
m_mesh_data.vertices.emplace_back(point);
point_indices.emplace_back(point_index);
point_index++;
}
// Read faces.
if (text == "f")
{
U32 index_count = (U32)std::count(line.begin(), line.end(), ' ');
U32 slash_count = (U32)std::count(line.begin(), line.end(), '/');
std::vector<MeshVertexIndexInfo> model_indices;
U32 line_of_faces_size = index_count - 2;
model_indices.resize(index_count);
eOBJFaceType type = eOBJFaceType::Point;
if (slash_count == 0)
{
type = eOBJFaceType::Point;
}
else if (slash_count == index_count)
{
type = eOBJFaceType::PointTexture;
}
else if (slash_count == index_count * 2)
{
if (line.find("//") != String::npos)
{
type = eOBJFaceType::PointNormal;
}
else
{
type = eOBJFaceType::PointTextureNormal;
}
}
else
{
return;
}
for (U32 i = 0; i < index_count; ++i)
{
if (type == eOBJFaceType::Point)
{
string_stream >> model_indices[i].point_index;
}
else if (type == eOBJFaceType::PointTexture)
{
string_stream >> model_indices[i].point_index;
string_stream.get(next_input);
string_stream >> model_indices[i].uv_index;
}
else if (type == eOBJFaceType::PointNormal)
{
string_stream >> model_indices[i].point_index;
string_stream.get(next_input);
string_stream.get(next_input);
string_stream >> model_indices[i].normal_index;
}
else if (type == eOBJFaceType::PointTextureNormal)
{
string_stream >> model_indices[i].point_index;
string_stream.get(next_input);
string_stream >> model_indices[i].uv_index;
string_stream.get(next_input);
string_stream >> model_indices[i].normal_index;
}
}
for (size_t i = 0; i < line_of_faces_size; ++i)
{
faces.emplace_back(model_indices[i + 2], model_indices[i + 1], model_indices[0]);
}
face_index += line_of_faces_size;
}
}
U32 index = 0;
std::string test_name = m_file_name_m;
for (auto& face : faces)
{
//set index start from 0.
U32 point_a = face.point_index_a - 1;
U32 point_b = face.point_index_b - 1;
U32 point_c = face.point_index_c - 1;
//add adjacent faces
point_indices[point_a].faces.emplace_back(point_a, point_b, point_c);
point_indices[point_b].faces.emplace_back(point_a, point_b, point_c);
point_indices[point_c].faces.emplace_back(point_a, point_b, point_c);
//Add face info and index info into mesh data
m_mesh_data.faces.emplace_back(point_a, point_b, point_c);
m_mesh_data.indices.push_back(point_a);
m_mesh_data.indices.push_back(point_b);
m_mesh_data.indices.push_back(point_c);
index += 3;
}
Vector3 min, max;
m_mesh_data.Normalize(min, max);
//Calculate Vertex Normal
std::vector<Vector3> normals;
Vector3 accumulated_normal;
for (auto& point : point_indices)
{
normals.clear();
accumulated_normal.SetZero();
for (auto& face : point.faces)
{
Vector3 normal = m_mesh_data.GetFaceNormal(face.a, face.b, face.c);
auto found = std::find(normals.begin(), normals.end(), normal);
if (found == normals.end())
{
accumulated_normal += normal;
normals.push_back(normal);
}
}
m_mesh_data.vertices[point.index].SetNormal(accumulated_normal.Normalize());
m_mesh_data.vertices[point.index].CalculateTangentAndBinormal();
}
//Calculate Planar UV Mapping
size_t size = m_mesh_data.vertices.size();
for (size_t i = 0; i < size; ++i)
{
Vector2 uv;
Vector3 point = m_mesh_data.vertices[i].GetPosition();
Vector3 abs_vec = point.Absolute();
// +-X
if (abs_vec.x >= abs_vec.y && abs_vec.x >= abs_vec.z)
{
if (point.x < 0.0)
{
uv.x = point.z / abs_vec.x;
}
else
{
uv.x = -point.z / abs_vec.x;
}
uv.y = point.y / abs_vec.x;
}
// +-Y
if (abs_vec.y >= abs_vec.x && abs_vec.y >= abs_vec.z)
{
if (point.y < 0.0)
{
uv.y = point.x / abs_vec.y;
}
else
{
uv.y = -point.x / abs_vec.y;
}
uv.x = -point.z / abs_vec.y;
}
// +-Z
if (abs_vec.z >= abs_vec.x && abs_vec.z >= abs_vec.y)
{
if (point.z < 0.0)
{
uv.x = -point.x / abs_vec.z;
}
else
{
uv.x = point.x / abs_vec.z;
}
uv.y = point.y / abs_vec.z;
}
Vector2 tex_coords = 0.5f * (uv + Vector2(1.0, 1.0));
m_mesh_data.vertices[i].SetUV(tex_coords);
}
}
void MeshResource::LoadCustomTXT(std::ifstream& file)
{
char input;
// Read up to the value of vertex count.
file.get(input);
while (input != ':')
{
file.get(input);
}
// Read in the vertex count.
U32 count = 0;
file >> count;
if (count == 0)
{
return;
}
// Create the model using the vertex count that was read in.
m_mesh_data.vertices.reserve(count);
m_mesh_data.indices.reserve(count);
// Read up to the beginning of the data.
file.get(input);
while (input != ':')
{
file.get(input);
}
file.get(input);
file.get(input);
// Read in the vertex data.
for (U32 i = 0; i < count; i++)
{
VertexCommon vertex;
file >> vertex.position.x >> vertex.position.y >> vertex.position.z;
file >> vertex.uv.x >> vertex.uv.y;
file >> vertex.normal.x >> vertex.normal.y >> vertex.normal.z;
m_mesh_data.vertices.push_back(vertex);
m_mesh_data.indices.push_back(i);
}
}
void MeshResource::CheckMeshType()
{
if (m_file_type_w == L".obj")
{
m_mesh_type = eMeshType::WaveFrontOBJ;
}
else if (m_file_type_w == L".txtmdl")
{
m_mesh_type = eMeshType::CustomTXT;
}
}
MeshData* MeshResource::GetMeshData()
{
return &m_mesh_data;
}
}
| 36.941176 | 122 | 0.439577 | [
"mesh",
"vector",
"model"
] |
d0e3a9c0b621b9a555bd726ee54282c339a4c1bd | 71,030 | cpp | C++ | tools/DeCoSTAR_01042020/source/ReconciledTree.cpp | danydoerr/spp_dcj | 1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a | [
"MIT"
] | 2 | 2021-08-24T16:03:30.000Z | 2022-03-18T14:52:43.000Z | tools/DeCoSTAR_01042020/source/ReconciledTree.cpp | danydoerr/spp_dcj | 1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a | [
"MIT"
] | null | null | null | tools/DeCoSTAR_01042020/source/ReconciledTree.cpp | danydoerr/spp_dcj | 1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a | [
"MIT"
] | null | null | null | /*
Copyright or © or Copr. CNRS
This software is a computer program whose purpose is to estimate
phylogenies and evolutionary parameters from a dataset according to
the maximum likelihood principle.
This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors have only limited
liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.
*/
/*
This file contains a class for reconciled trees
Created the: 26-10-2015
by: Wandrille Duchemin
Last modified the: 16-03-2020
by: Wandrille Duchemin
*/
#include "ReconciledTree.h"
#include "ReconciliationEvent.h"
//Variables used to get and set some node properties
/*const string spe = "S"; //name of the node property containing their species
const string ev = "Ev"; //name of the node property containing their event
const string clnum = "Cnum";//name of the node property containing their clade id
const string porder = "Po";//name of the node property containing their post order
//const string alpha = "Al";//name of the node property containing their alpha status (whether they are in a dead lineage or no)
const string ts = "TS";//name of the node property containing their time slice
*/
/*
Takes:
- int currentNode : a node in the reconciled tree
- &map <int, vector <string> > cladeToLeafList : associates cladeId to list of leaf names
*/
vector <string> ReconciledTree::cladeToLeafListAssociationAux(int currentNode, map <int, vector <string> > & cladeToLeafList )
{
vector <string> leafList;
if(isRealLeaf(currentNode))
{
leafList.push_back(getNodeName(currentNode));
}
else
{
vector <int> SonsIds = getSonsId(currentNode);
for(unsigned i = 0 ; i < SonsIds.size(); i++)
{
vector <string> tmp = cladeToLeafListAssociationAux(SonsIds[i], cladeToLeafList );
for(unsigned j = 0 ; j < tmp.size(); j++)
leafList.push_back(tmp[j]);
}
}
if(leafList.size()>0)
{
int cladeId = getNodeCladeNum(currentNode);
if(cladeToLeafList.find(cladeId) == cladeToLeafList.end())
{
cladeToLeafList[cladeId] = leafList;
}
}
return leafList;
}
/*
Auxiliary recursive function to extract a MyGeneTree instance copying the topology of the reconciled tree.
Takes:
- Node * currentNode : a pointer to the currenNode in the reconciled tree
Returns:
MyGeneNode * : my gene node representation of currentNode, along with the underlying subtree
*/
MyGeneNode * ReconciledTree::getMyGeneTreeTopologyAux(Node * currentNode)
{
MyGeneNode *node;
vector<Node *> Sons = currentNode->getSons();
int evt = dynamic_cast<BppInteger *> ( currentNode->getNodeProperty(ev) )->getValue() ;
//cout << "ReconciledTree::getMyGeneTreeTopologyAux " << Sons.size() << ' ' << evt << endl;
if(Sons.size() == 0) // no sons -> loss or leaf
{
int evt = dynamic_cast<BppInteger *> ( currentNode->getNodeProperty(ev) )->getValue() ;
if(isExtant(evt)) // leaf -> create a node that has the name of the leaf
{
node = new MyGeneNode();
node->setName( currentNode->getName() );
}
else // loss -> return NULL that will signal its parent in order not to include branches leading to losses
{
return NULL;
}
}
else // tehre are some sons
{
vector <MyGeneNode *> GeneSons;
for(unsigned i =0; i < Sons.size(); i++) // iterate over the sons
{
MyGeneNode * placeholder = getMyGeneTreeTopologyAux( Sons[i] ); // getting that subtree
if(placeholder != NULL) //if there is something else than a branch leading to a loss -> add it
{
GeneSons.push_back(placeholder);
}
}
if(GeneSons.size() == 0) // no sons that don't lead to losses -> should not occur but if it does, return NULL
{
return NULL;
}
else if(GeneSons.size() == 1) // only one son -> we return it so Nodes with only one son are contracted and only the bifurcation + leaves are kept
{
node = GeneSons[0];
}
else //2 (or more but should not happen) sons
{
node = new MyGeneNode();
for(unsigned i =0; i < GeneSons.size(); i++) // iterate over the MyGeneNode sons
{
node->addSon(GeneSons[i]); // adding children
}
}
}
return node;
}
int ReconciledTree::countAnyEvent( int evttype)
{
int counter = 0;
vector<int> NodesIds = getNodesId();
int NodeId;
for (unsigned j=0; j<NodesIds.size() ; j++)
{
NodeId = NodesIds[j];
if(getNodeEvent(NodeId) == evttype)
counter++;
}
return counter;
}
/*
Adds the reconciliation to the given NodeId associated with idU.
This function additionally creates and annotates a loss node when necessary (dependent on the event).
Takes:
- RE (ReconciliationEvent) : a reconciliation event specifying the species it occurs in and the type of event
- NodeId (int) : node id
- VERBOSE (bool) (default = false)
Returns:
(int) node id to branch the next nodes to
*/
int ReconciledTree::addReconciliationEvent(ReconciliationEvent RE, int NodeId, Node * currentNode, bool VERBOSE)
{
//here we define correspondance between TERA's event notation and our event notation
bool loss = false;//is there a loss node to create
bool Rtoadd = false;//is there a reception node with the same cladenum to add (only in the case of TL)
bool TStoadd = RE.hasTimeSlice();
string evtName = RE.getevtName();
if(VERBOSE)
cout << "ReconciledTree::addReconciliationEvent. NodeId: " << NodeId << " event: " << evtName << endl;
if(evtName.length()>1)
if(RE.getevtName()[1] == 'L') // there is a loss node if the second letter of the event name is L
loss = true;
int evtcode;
if(evtName == "O")
{
evtcode = N; //nothing happened
}
else if(evtName == "C")
{
evtcode = C; //leaf
}
else if(evtName[0] == 'S') //S and SL
evtcode = S;
else if(evtName[0] == 'D') //D and DD
{
if(evtName.length()>1)//DD
evtcode = Bout;
else
evtcode = D;
}
else //T TL TTD TFD TLTD TLFD
{
if(evtName.length()==1)//T -> the reception Node will be handled in the next clade
evtcode = Sout;
else if(evtName.length()==2)//TL
{
evtcode = Sout;
Rtoadd = true;
}
else//TTD TFD TLTD TLFD
{
//check the second to last letter to know if we are From the dead or To the dead
if(evtName[evtName.length() - 2] == 'F')// TFD or TLFD
{
if(evtName.length() == 4)// TLFD -> the lost is implicit
{
loss = false;
evtcode = R;
}
else //TFD -> this is actually a Bifurcation out (Bout) and the reception node (R) will be handled in the next clade
evtcode = Bout;
}
else//TTD or TLTD
{
evtcode = Sout;
}
}
}
if(VERBOSE)
cout << " -> assigned event code: " << evtcode << " loss? " << loss << endl;
//which species is assigned to the node depends on the event code
int speciesid;
if(evtcode == Bout)
speciesid = -1;
else if(evtcode == R)
{
//in this case we chose the child species that is not -1
if(RE.getidXl() == -1)
speciesid = RE.getidXr();
else
speciesid = RE.getidXl();
}
else//default case: use idX
speciesid = RE.getidX();
//Node * currentNode = getNode(NodeId);
//setting the species and evt
setNodeSpecies(currentNode,speciesid);
setNodeEvent(currentNode, evtcode);
if(TStoadd)
{
setNodeUpperBoundaryTS(currentNode,RE.gettimeSlice());//we set the time slice
setNodeLowerBoundaryTS(currentNode,RE.gettimeSlice());//the upper and lower boundaries are the same here
}
//adding the loss node
if(loss)
{
//the speciesid stays the same if the event is not a SL
if(evtcode == S)//SL case
speciesid = RE.getidXl();
evtcode = L;
int newId = MyNextId();//getNextId();
Node * newLossNode = new Node(newId);
nbNodes++;
//Node * currentNode = getNode(NodeId);
currentNode->addSon(newLossNode);
//setting new loss node properties
setNodeSpecies(newLossNode,speciesid);
setNodeEvent(newLossNode, evtcode);
setNodeCladeNum(newLossNode, -1); // the clade num of the loss node is -1 -> the empty clade
if(TStoadd)
{
setNodeUpperBoundaryTS(newLossNode,RE.gettimeSlice() -1 );//we set the time slice of the loss node as its father -1.
setNodeLowerBoundaryTS(newLossNode,RE.gettimeSlice() -1 );//the upper and lower boundaries are the same here
}
}
//finally, we check if the event is TL. If this is the case, we will then add a reception node
if(Rtoadd)
{
//the speciesid is the child that is not equal to its parent
if(RE.getidXl() == speciesid)
speciesid = RE.getidXr();
else
speciesid = RE.getidXl();
evtcode = R;
int newId = MyNextId(); //getNextId();
Node * newRecNode = new Node(newId);
nbNodes++;
//Node * currentNode = getNode(NodeId);
currentNode->addSon(newRecNode);
//setting new reception node properties
setNodeSpecies(newRecNode,speciesid);
setNodeEvent(newRecNode, evtcode);
setNodeCladeNum(newRecNode, getNodeCladeNum(NodeId) ); // the clade num of the rec node is the same as its parent
if(TStoadd)
{
setNodeUpperBoundaryTS(newRecNode,RE.gettimeSlice());//we set the time slice of the loss as its father.
setNodeLowerBoundaryTS(newRecNode,RE.gettimeSlice());//the upper and lower boundaries are the same here
}
NodeId = newId;//set NodeId as the id of the Reception node that will serve to continue the lineage
}
return NodeId;
}
/*
This function look for T and TFD events in order to add the correct Reception event to the tree.
If warranted, it annotates NodeId as a Reception and create its son.
Takes:
- PRE (ReconciliationEvent) : the previous reconciliation event undergone to arrive to NodeId
- NodeId (int) : node id
- VERBOSE (bool) (default = false)
Returns:
(int) node id to branch the next nodes to
*/
int ReconciledTree::accountForPreviousSplit(ReconciliationEvent PRE, int NodeId, bool VERBOSE)
{
if((PRE.getevtName().compare("T") != 0)&&(PRE.getevtName().compare("TFD") != 0))//neither T or TFD -> no pre-treatment to do
return NodeId;
if(getNodeSpecies(NodeId) == PRE.getidX())//if we are of the the same species as the parent, no need for a reception node. This is used in the case of TFD only
return NodeId;
int evtcode = R;
if(VERBOSE)
cout << "ReconciledTree::accountForPreviousSplit. NodeId: " << NodeId << " PRE: " << PRE.getevtName() << " " << PRE.getidX() << ":" << PRE.getidXl() << "," << PRE.getidXr() << endl;
//we want the child species id that is different to the species id of its father
int speciesid;
if(PRE.getidX() == PRE.getidXl())
speciesid = PRE.getidXr();
else
speciesid = PRE.getidXl();
setNodeSpecies(NodeId,speciesid); // this may have already been set
setNodeEvent(NodeId, evtcode);
if(PRE.hasTimeSlice())
{
setNodeUpperBoundaryTS(NodeId,PRE.gettimeSlice());//we set the time slice of the node as its father.
setNodeLowerBoundaryTS(NodeId,PRE.gettimeSlice());//the upper and lower boundaries are the same here
}
//creating the new node
int newId = MyNextId();//getNextId();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
Node * currentNode = getNode(NodeId);
currentNode->addSon(newNode);
setNodeCladeNum(newId, getNodeCladeNum(NodeId));//setting the new node cladenum property and updating the map
return newId;
}
/*
Creates or annotate a leaf node at NodeId
Checks if he parent is a transfer ((Sout and different species from the parent)or Bout). If it is, the function will annotate NodeId as a reception node and create a leaf node.
Otherwise just annotate the node as a leaf.
Takes:
- NodeId (int): id of the node to annotate with species and clade already set
*/
void ReconciledTree::CreateLeafNode(int NodeId)
{
if(getNodeEvent(NodeId)!= C)//this is not already a leaf
{
int FatherEventId = getNodeEvent(getFatherId(NodeId));
int FatherSpecies = getNodeSpecies(getFatherId(NodeId));
if( ( (FatherEventId == Sout)&&(FatherSpecies != getNodeSpecies(NodeId) ) ) || (FatherEventId == Bout))
{
//annotate NodeId as a reception
setNodeEvent(NodeId,R);
int newId = MyNextId() ;// getNextId();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
Node * currentNode = getNode(NodeId);
currentNode->addSon(newNode);
//annotating
setNodeSpecies(newId,getNodeSpecies(NodeId));
setNodeCladeNum(newId,getNodeCladeNum(NodeId));
NodeId = newId;
}
//setting NodeId as a leaf
setNodeEvent(NodeId,C);
setNodeUpperBoundaryTS(NodeId,0);//the time slice of a leaf is 0
setNodeLowerBoundaryTS(NodeId,0);
}
}
/*
Adds the reconciliation and return idUl and idUr or -1,-1 if idU is a leaf
Takes:
- CR (CladeReconciliation) : a clade reconciliation of id idU
- VERBOSE (bool) (default = false)
Returns:
pair<int,int> : idUl and idUr or -1,-1 if idU is a leaf
*/
pair<int,int> ReconciledTree::addCladeReconciliation(CladeReconciliation CR, bool VERBOSE)
{
//clock_t begin;
//clock_t end;
//double elapsed_secs;
//if(VERBOSE)
//{
// begin = clock();
//}
vector<int> NodeIds = getNodeIdsFromCladeId(CR.idU);
int NodeId;
if(VERBOSE)
cout << "Adding clade " << CR.idU << " -> " << NodeIds.size() << " Nodes" << endl;
if(NodeIds.size() == 0) //node absent from the tree: create it. THIS SHOULD ONLY HAPPEN ONCE: for the root
{
if(!CR.isRoot())
throw Exception("ReconciledTree::addCladeReconciliation : CladeReconciliation with clade absent from tree while not root!");
//node creation
NodeId = 0;//getNextId(); //should set the id to 0. as this will be the root, this should be the first node added. Furthermore, getNextId() segfaults if there is no node in the tree...
Node * newnode = new Node(NodeId);
setRootNode(newnode);//setting as the new root
setNodeCladeNum(NodeId, CR.idU);//setting the new node cladenum property and updating the map
nbNodes=1;
}
else //At least one node has the current clade id. We are interested in the last one as this is the one that was created last.
{
NodeId = NodeIds.back();
NodeId = accountForPreviousSplit(CR.previousEvent, NodeId, VERBOSE);
}
if(VERBOSE)
cout << "done pre-treatment." << endl;
//if(VERBOSE)
//{
// end = clock();
// elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
// cout << "time elapsed for CRadding PRE:" << elapsed_secs << endl;
// begin = clock();
//}
clock_t Sbegin;
double elapsed_secsB1=0;
double elapsed_secsB2=0;
double elapsed_secsB3=0;
//setting the node properties (and supplementary loss nodes if needed): species, event
Node * currentNode = getNode(NodeId);
//using the first event (always at least one event)
int current_event = 0;
NodeId = addReconciliationEvent(CR.Events[current_event],NodeId,currentNode,VERBOSE);
if(VERBOSE)
cout << " added event " << current_event << endl;
current_event++;
//for each event after the first
while(current_event < CR.Events.size())
{
Sbegin = clock();
//creating the new node
//int newId = getNextId();
//if(newId != MyNextId())
// cout << "idstuff "<< newId << "<->" << MyNextId()<<endl;
int newId = MyNextId();
elapsed_secsB1 += double(clock() - Sbegin) / CLOCKS_PER_SEC;
Sbegin = clock();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
Node * currentNode = getNode(NodeId);
currentNode->addSon(newNode);
elapsed_secsB2 += double(clock() - Sbegin) / CLOCKS_PER_SEC;
Sbegin = clock();
setNodeCladeNum(newNode, CR.idU);//setting the new node cladenum property and updating the map
NodeId = newId; // setting as current node
//assigning the event
NodeId = addReconciliationEvent(CR.Events[current_event],NodeId, newNode,VERBOSE);
elapsed_secsB3 += double(clock() - Sbegin) / CLOCKS_PER_SEC;
if(VERBOSE)
cout << " added event " << current_event << endl;
current_event++;
}
// if(VERBOSE)
// {
// end = clock();
// elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
// cout << "time elapsed for CRadding EVadd:" << elapsed_secs << endl;
//
// if(elapsed_secs > 0.01)
// {
// cout << "time elapsed->" << CR.Events.size() << "events" << elapsed_secs;
// for(unsigned i = 0; i < CR.Events.size();i++)
// cout << " - " << CR.Events[i].getevtName() ;
//
// cout << " - " << elapsed_secsB1 << " " << elapsed_secsB2 << " " << elapsed_secsB3 ;
// cout << endl;
//
// }
//
// begin = clock();
// }
pair<int,int> idsToReturn;
//adding children, if there are some
if(!CR.isLeaf())
{
Node * currentNode = getNode(NodeId);
int newId;
Node * newNode;
//adding left child
newId = MyNextId();//getNextId();
newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
currentNode->addSon(newNode);
setNodeCladeNum(newId, CR.idUl);//setting the new node cladenum property and updating the map
setNodeSpecies(newId, CR.Events.back().getidXl());//setting the node species to the one specified in the last event
//adding right child
newId = MyNextId();//getNextId();
newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
currentNode->addSon(newNode);
setNodeCladeNum(newId, CR.idUr);//setting the new node cladenum property and updating the map
setNodeSpecies(newId, CR.Events.back().getidXr());//setting the node species to the one specified in the last event
//setting the return value
idsToReturn.first = CR.idUl;
idsToReturn.second = CR.idUr;
}
else
{
if(getNodeEvent(NodeId) != C)//the current event is not already a leaf event
{
//we have a leaf node to add and annotate
int newId = MyNextId();//getNextId();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
Node * currentNode = getNode(NodeId);
currentNode->addSon(newNode);
setNodeCladeNum(newId, CR.idU);//setting the new node cladenum property and updating the map
int evtcode = C;//Current (leaf)
int speciesid;
//choosing the correct leaf species
//NB: this case happen when the last event is either TL, SL or TLFD
if(getNodeEvent(NodeId) == R) // The last event is a reception -> the species stays the same
speciesid = getNodeSpecies(NodeId);
else // SL -> species is, by convention, the right child in the last reconciliation event
speciesid = CR.Events.back().getidXr();
//setting properties
setNodeSpecies(newId, speciesid);
setNodeEvent(newId, evtcode);
setNodeUpperBoundaryTS(newId,0);//the time slice of a leaf is 0
setNodeLowerBoundaryTS(newId,0);
NodeId = newId;
}
//Trying to get a leaf Name
if(CR.name != "")
setNodeName(NodeId, CR.name);
//setting the return value
idsToReturn.first = -1;
idsToReturn.second = -1;
}
//if(VERBOSE)
//{
// end = clock();
// elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
// cout << "time elapsed for CRadding CHadd:" << elapsed_secs << endl;
// begin = clock();
//}
return idsToReturn;
}
/*
Takes:
- Nodeid (int): a node id
- evtLine (string): recPhyloXML line describing a reconciliation event
*/
void ReconciledTree::setNodeDetailsFromXMLLine(int Nodeid, string evtLine , map< string , int > & speciesNameToNodeId , bool VERBOSE)
{
map <string, string> * properties = new map <string,string>;
string * value = new string("");
string Tname = InterpretLineXML(evtLine,properties,value);
setNodeDetailsFromXMLLine( Nodeid, Tname, properties, value , speciesNameToNodeId , VERBOSE);
}
/*
Takes:
- Nodeid (int): a node id
- Tname (string) : name of the tag (here, event name)
- properties (map <string, string> *): container for informations like species, timeSlice, ...
- value ( string * ): should be empty, technically not used here
*/
void ReconciledTree::setNodeDetailsFromXMLLine(int Nodeid, string Tname, map <string, string> * properties, string * value,map< string , int > & speciesNameToNodeId , bool VERBOSE)
{
char * pEnd; // for str -> int conversion
for (map<string,string>::iterator it=properties->begin(); it!=properties->end(); ++it)
{
if(it->first.compare("timeSlice") == 0)
{
int TS = (int) strtol(it->second.c_str(), &pEnd, 10) ;
setNodeUpperBoundaryTS(Nodeid,TS);
setNodeLowerBoundaryTS(Nodeid,TS);
}
else if (it->first.compare("speciesLocation") == 0)
{
string species = it->second.c_str() ;
auto speciesIt = speciesNameToNodeId.find(species) ;
if( speciesIt == speciesNameToNodeId.end() )
{
// species not found ...
throw Exception("ReconciledTree::setNodeDetailsFromXMLLine : unknown species : " + species );
}
setNodeSpecies(Nodeid , speciesIt->second);
}
else if (it->first.compare("destinationSpecies") == 0)
setNodeSpecies(Nodeid, (int) strtol(it->second.c_str(), &pEnd, 10) );
else if (it->first.compare("geneName") == 0)
setNodeName(Nodeid,it->second);
}
/*
C --> Current (leaf)
S --> Speciation (in the species tree)
L --> Loss (in the species tree)
D --> Duplication (in the species tree)
Sout --> Speciation to an extinct/unsampled lineage (otherwise called SpeciationOut)
R --> Transfer reception
N --> no event (to account for time slices)
Bout --> Bifurcation in an extinct/unsampled lineage (otherwise called BifurcationOut)
*/
int evtCode = -1;
//3. finding which event is implied
if(Tname.compare("leaf") == 0)
{
setNodeUpperBoundaryTS(Nodeid,0);//leaves at time 0
setNodeLowerBoundaryTS(Nodeid,0);
evtCode = C;
}
else if(Tname.compare("speciation") == 0)
{
evtCode = S;
}
else if( (Tname.compare("branchingOut") == 0) || (Tname.compare("speciationOut") == 0))
{
evtCode = Sout;
}
else if(Tname.compare("bifurcationOut") == 0)
{
evtCode = Bout;
setNodeSpecies(Nodeid, -1 );
}
else if(Tname.compare("duplication") == 0)
{
evtCode = D;
}
else if(Tname.compare("transferLoss") == 0) // here for retrocompatibility to the original recPhyloXML format
{
evtCode = R;
}
else if(Tname.compare("transferBack") == 0)
{
evtCode = R;
}
else if( (Tname.compare("branchingOutLoss") == 0) || (Tname.compare("speciationOutLoss") == 0))
{
evtCode = Sout;
//create some Loss son in the same species, with the same time slice
int newId = MyNextId(); //getNextId();
Node * newLossNode = new Node(newId);
nbNodes++;
Node * currentNode = getNode(Nodeid);
currentNode->addSon(newLossNode);
//setting new loss node properties
setNodeSpecies(newId,getNodeSpecies(Nodeid));
setNodeEvent(newId, L); // setting as a LOSS
setNodeCladeNum(newId, -1); // the clade num of the loss node is -1 -> the empty clade
}
else if(Tname.compare("speciationLoss") == 0)
{
evtCode = S;
//create some Loss son, but in a unknown species... with time slice = current -1
/// The loss node will be added in a later post-treatment phase as it requires a species tree to determine in which species the loss is.
// This won't get forgotten as these are speciations nodes with only one son
}
else if(Tname.compare("loss") == 0)
{
evtCode = L;
}
if(evtCode == -1)
throw Exception("ReconciledTree::setNodeDetailsFromXMLLine : unknown event : " + Tname );
else
setNodeEvent(Nodeid,evtCode);
if(VERBOSE)
{
cout << "set details of node " << Nodeid << ";" << evtCode << ";" << getNodeSpecies(Nodeid) << ";" ;
if(hasNodeProperty(Nodeid,uts))
cout <<getNodeTimeSlice(Nodeid) << endl;
else
cout << "NOTS" << endl;
}
}
/*
read and add a clade from a recPhyloXML stream
!!! This function is recursive
Takes:
- fileIN (ifstream): streaam to a recPhyloXML file
- Nodeid (int) : node to put the clade IN
- VERBOSE (bool) (default = false)
*/
void ReconciledTree::addXMLClade(ifstream& fileIN,int Nodeid, map< string , int > & speciesNameToNodeId , bool VERBOSE) // will need a species tree
{
int Cnum = CladeIdToNodeIds.size(); //the clade num will be some equivalent to a BFO index
setNodeCladeNum(Nodeid , Cnum);
//cout << "before "<< Cnum << "- after " << CladeIdToNodeIds.size() << endl;
//cout << nbNodes << endl;
if(VERBOSE)
cout << "parsing clade " << Cnum << " id " << Nodeid<< endl;
vector <string> evtLines;
//2. parsing of the clade
string line;
getline( fileIN, line );
map <string, string> * properties = new map <string,string>;
string * value = new string("");
string Tname = InterpretLineXML(line,properties,value);
//cout << "value:" << *value << endl;
while(Tname.compare("/clade") != 0) //--> line signing the end of the clade
{
if(Tname.compare("name") == 0) // found name
{
if(VERBOSE)
cout << "found name : " << *value << endl;
setNodeName(Nodeid, *value);
}
else if(Tname.compare("eventsRec") == 0) // reading reconciliation events
{
if(VERBOSE)
cout << "parsing events" << endl;
*value = "";
delete properties;
getline( fileIN, line );
properties = new map <string,string>;
Tname = InterpretLineXML(line,properties,value);
while(Tname.compare("/eventsRec") != 0) // here, add some nodes ...
{
evtLines.push_back(line); // maybe give in the already interpreted line rather than re-interpret it inside constructor...
//looping
*value = "";
delete properties;
getline( fileIN, line );
properties = new map <string,string>;
Tname = InterpretLineXML(line,properties,value);
if(Tname.compare("") == 0)
throw Exception("ReconciledTree::addXMLClade : error while parsing...");
}
}
else if(Tname.compare("clade") == 0) // found a child --> recursion
{
//create child clade
//creating the new node
int newId = MyNextId(); //getNextId();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
Node * currentNode = getNode(Nodeid);
currentNode->addSon(newNode);
//recursing
addXMLClade(fileIN, newId, speciesNameToNodeId , VERBOSE );
}
//reading new line
*value = "";
delete properties;
getline( fileIN, line );
properties = new map <string,string>;
Tname = InterpretLineXML(line,properties,value);
}
//3. Event parsing
if(evtLines.size() == 0)
{
throw Exception("ReconciledTree::addXMLClade : no reconciliation events found");
}
else if(evtLines.size()>1)
{
for(unsigned i = 0; i < evtLines.size() - 1; i++ ) // all events but the last
{
//creating parent node
//cout << "creating evt" << evtLines[i] << endl;
int newId = MyNextId(); //getNextId();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the existing structure
bool ROOT = isRoot(Nodeid);
Node * currentNode = getNode(Nodeid);
if(!ROOT)
{
Node * FNode = currentNode->getFather();
FNode->removeSon(currentNode);
FNode->addSon(newNode);
newNode->addSon(currentNode);
}
else
{
currentNode->addSon(newNode);
rootAt(newNode); // rerooting
}
//new putting correct attributes to in the new node
setNodeCladeNum(newId , Cnum);
setNodeDetailsFromXMLLine(newId,evtLines[i] , speciesNameToNodeId , VERBOSE);
}
}
setNodeDetailsFromXMLLine(Nodeid,evtLines.back() , speciesNameToNodeId , VERBOSE); // setting details on the last node == the bifurcation or leaf
}
/*
Constructor that uses a stream from a recPhyloXML file
Takes
- fileIN (ifstream): stream rom a recPhyloXML file
- Stree (MySpeciesTree *): a pointer to the species tree
- map< string , int > & speciesNameToNodeId
- VERBOSE (bool) [fdefault : false]
*/
void ReconciledTree::readPhyloXMLFile(ifstream& fileIN, MySpeciesTree * Stree, map< string , int > & speciesNameToNodeId , bool VERBOSE )
{
// presuming that the stream will yield a <clade> line forming the root of the tree
//first find the root
if(VERBOSE)
cout << "Creating Reconciled_Tree." << endl;
int rootid = 0;
Node * newnode = new Node(rootid);
setRootNode(newnode);//setting as the new root
nbNodes++;
addXMLClade( fileIN,rootid, speciesNameToNodeId, VERBOSE );
///post-treatment requiring species tree
vector <int> NodesIds = getNodesId();
for(unsigned i = 0 ; i < NodesIds.size(); i++)
{
int evt = getNodeEvent(NodesIds[i]);
vector <int> SonsIds = getSonsId(NodesIds[i]);
if((evt == S) && (SonsIds.size() == 1)) //speciation with only one child --> speciation loss
{
int spF = getNodeSpecies(NodesIds[i]);
int spC = getNodeSpecies(SonsIds[0]);
///ugly as ****
vector <int> Snodes = Stree->getNodesId();
for(unsigned j = 0 ; j < Snodes.size(); j++)
if(Stree->getRPO(Snodes[j]) == spF)
{
spF = Snodes[j];
break;
}
vector <int> spSons = Stree->getSonsId(spF);
//there should be 2 sons in spSons
if(spSons.size() != 2)
throw Exception("ReconciledTree::readPhyloXMLFile : species in the species tree without son as a speciation.");
int LostIndex = 0;
if(spC == Stree->getRPO(spSons[LostIndex]))
LostIndex++;
if(VERBOSE)
cout << "Adding Loss node in species " << spSons[LostIndex] << "->" << Stree->getRPO(spSons[LostIndex]) << endl;
//creating new loss node
int newId = MyNextId(); //getNextId();
Node * newLossNode = new Node(newId);
nbNodes++;
Node * currentNode = getNode(NodesIds[i]);
currentNode->addSon(newLossNode);
//setting new loss node properties
setNodeSpecies(newId,Stree->getRPO(spSons[LostIndex]));
setNodeEvent(newId, L); // setting as a LOSS
setNodeCladeNum(newId, -1); // the clade num of the loss node is -1 -> the empty clade
}
else if((evt == S) && (SonsIds.size() == 0))
throw Exception("ReconciledTree::readPhyloXMLFile : speciation without any son.");
}
/// determining timeSlice Status
if(hasNodeProperty(getRootId(),uts))
TimeSliceStatus = 1;
else
TimeSliceStatus = 0;
}
/*
* *RECURSIVE*
* @arg int nodeid : id of the node whose subtree string is built
* @arg bool hideLosses (default: false): if true, losses and the branches leading to them wil be removed from the newick string
*
* @return string : newick representation of the subtree rooted at nodeid
*/
string ReconciledTree::NodeString(int nodeid, bool hideLosses)
{
string Str = "";
vector<int> sons = getSonsId(nodeid);
if(sons.size()> 0)
{
vector <string> sonStr;
for(unsigned i = 0; i < sons.size(); i++)
{
string tmp = NodeString(sons[i], hideLosses); // recursion
if(tmp.size() >0) // don't add it the the representation is an empty str
sonStr.push_back(tmp);
}
if(sonStr.size() == 0) // no son with a non-empty representation
return Str; // return empty string
//building Str
Str += "(";
for(unsigned i = 0; i < sonStr.size(); i++)
{
if(i != 0)
Str += ",";
Str += sonStr[i];
}
Str += ")";
}
if(hasNodeName(nodeid))
Str += getNodeName(nodeid);
else
{
Str += static_cast<ostringstream*>( &(ostringstream() << nodeid) )->str() ;
}
Str += "|";
if(!hasNodeProperty(nodeid,ev))
Str += "NOEVENT";
else
{
int evt = getNodeEvent(nodeid);
switch(evt)
{
case C :
Str += "Extant"; //Current (leaf)
break;
case S :
Str += "Spe"; //Speciation (in the species tree)
break;
case L :
if(hideLosses)// soecial option so that losses and their branch oare not in the final newick tree
{
return ""; // return empty string
}
Str += "Loss"; //Loss (in the species tree)
break;
case D :
Str += "Dup"; //Duplication (in the species tree)
break;
case Sout :
Str += "SpeOut"; //Speciation to an extinct/unsampled lineage (otherwise called SpeciationOut)
break;
case R :
Str += "Reception"; //Transfer reception
break;
case N :
Str += "Null"; //no event (to account for time slices)
break;
case Bout :
Str += "BifOut"; //Bifurcation in an extinct/unsampled lineage (otherwise called BifurcationOut)
break;
default:
Str += "NOEVENT";
}
}
Str += "|";
if(!hasNodeProperty(nodeid,spe))
Str += "no species";
else
{
int Number = getNodeSpecies(nodeid);
Str += static_cast<ostringstream*>( &(ostringstream() << Number) )->str() ;
}
Str += "|";
if(hasNodeProperty(nodeid,uts))
{
int UTS = getNodeUpperBoundaryTS(nodeid);
int LTS = getNodeLowerBoundaryTS(nodeid);
if(UTS != LTS)
{
Str += static_cast<ostringstream*>( &(ostringstream() << UTS) )->str() ;
Str += "-";
Str += static_cast<ostringstream*>( &(ostringstream() << LTS) )->str() ;
}
else
Str += static_cast<ostringstream*>( &(ostringstream() << UTS) )->str() ;
}
else
Str += "NOTS";
return Str;
}
/*
Constructor from a root and a time slice status.
Intended to be used by CloneSubtree
*/
ReconciledTree::ReconciledTree(Node * root, int TSstatus): TreeTemplate<Node>(root)
{
TimeSliceStatus = TSstatus;
}
/**
Constructor that takes a pointer to a vector of CladeReconciliation
Takes:
- CladeRecs (vector<CladeReconciliation> * ) : pointer to a vector of CladeReconciliation
- bool VERBOSE (default=false): wether the function talks or not
*/
ReconciledTree::ReconciledTree(vector<CladeReconciliation> * CladeRecs, bool VERBOSE): TreeTemplate<Node>()
{
clock_t begin;
clock_t end;
double elapsed_secs;
//VERBOSE=true;
if(VERBOSE)
{
begin = clock();
}
//we do not make the assumption that the CladeReconciliation are in correct order, where correct means that the root is first and a parent always occur before its child(ren)
//first find the root
if(VERBOSE)
cout << "Creating Reconciled_Tree." << endl;
vector <int> CladeRecToaDD;
int current_index = 0;
int nbCladeRecs = CladeRecs->size();
map<int,int> cladeNumToIndex; //mapping the cladenumber to their index in the vector *CladeRecs
for(int i=0;i<nbCladeRecs;i++)
{
if(CladeRecs->at(i).isRoot())
{
CladeRecToaDD.push_back(CladeRecs->at(i).idU);//adding the root as the first element to do
}
cladeNumToIndex[CladeRecs->at(i).idU] = i;//mapping
}
if(CladeRecToaDD.size() == 0)//no root found -> error
throw Exception("ReconciledTree::ReconciledTree : root reconciliation not found!");
if(VERBOSE)
cout << " -> map of the Clade Reconciliation done." << endl;
if(VERBOSE)
{
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time elapsed for TREE CRmapping:" << elapsed_secs << endl;
begin = clock();
}
int counter = 0;
//we can now make a depth-first traversal of the CladeReconciliations
while(! CladeRecToaDD.empty())
{
clock_t Sbegin = clock();
int cladeIdToAdd = CladeRecToaDD.back();
//CladeRecToaDD.erase(CladeRecToaDD.rbegin());//erasing the clade we just added
CladeRecToaDD.pop_back();
if(cladeNumToIndex.count( cladeIdToAdd ) != 0 )//the clade is present in the CladeReconciliation (it can be absent if it is a branch without any partiular event)
{
if(VERBOSE)
{
cout << "Adding clade id " << cladeIdToAdd << endl;
}
int current_index = cladeNumToIndex[cladeIdToAdd];
if(VERBOSE)
{
cout << " -> Adding Clade reconciliation :" << endl;
CladeRecs->at(current_index).printMe();
}
pair<int,int> new_index = addCladeReconciliation(CladeRecs->at(current_index), VERBOSE);//add the reconciliation and return idUl and idUr or -1,-1 if idU is a leaf
if(VERBOSE)
cout << "new indexes " << new_index.first << "," << new_index.second << endl;
if(new_index.first != -1)//adding if they exists
CladeRecToaDD.push_back(new_index.first);
if(new_index.second != -1)
CladeRecToaDD.push_back(new_index.second);
}
else
{
if(VERBOSE)
{
cout << "Annotating as a leaf clade id " << cladeIdToAdd << endl;
}
//means that this is a leaf which have (at least) a node that has not been annotated as a leaf (however clade and species are set)
int NodeId = getNodeIdsFromCladeId( cladeIdToAdd ).back();//retrieving the last node with that clade id
CreateLeafNode(NodeId);//cleaner, accounts for eventual reception node tha we missed...
}
if(VERBOSE)
cout << "size of CladeRecToaDD : " << CladeRecToaDD.size() << endl;
if(VERBOSE)
{
counter++;
clock_t Send = clock();
elapsed_secs = double(Send - Sbegin) / CLOCKS_PER_SEC;
cout << "time elapsed for CRadding " << counter << ":" << elapsed_secs << endl;
}
}
if(VERBOSE)
{
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time elapsed for TREE CRadding:" << elapsed_secs << " for " << counter << " clades->" << elapsed_secs / counter << endl;
begin = clock();
}
//post treatment: decide ifthere are TS or no
if(hasNodeProperty(getRootId(),uts))
TimeSliceStatus = 1;
else
TimeSliceStatus = 0;
if(VERBOSE)
cout << "done" << endl;
}
/*
Constructor that uses a stream from a recPhyloXML file
Takes
- fileIN (ifstream): stream rom a recPhyloXML file
- Stree (MySpeciesTree *): a pointer to the species tree
- map< string , int > & speciesNameToNodeId : associates the name of species to their node Id
- VERBOSE (bool) [fdefault : false]
*/
ReconciledTree::ReconciledTree(ifstream& fileIN, MySpeciesTree * Stree, map< string , int > & speciesNameToNodeId, bool VERBOSE): TreeTemplate<Node>()
{
readPhyloXMLFile( fileIN, Stree, speciesNameToNodeId , VERBOSE );
}
/**
Constructor that uses a recPhyloXML file name
Takes
- fileIN (ifstream): stream rom a recPhyloXML file
- Stree (MySpeciesTree *): a pointer to the species tree
- map< string , int > & speciesNameToNodeId : associates the name of species to their node Id
- VERBOSE (bool) [fdefault : false]
*/
ReconciledTree::ReconciledTree(string phyloxmlFileName, MySpeciesTree * Stree , map< string , int > & speciesNameToNodeId , bool VERBOSE )
{
ifstream fileStream(phyloxmlFileName.c_str());
if( !fileStream.is_open() )
{
throw Exception("ReconciledTree::ReconciledTree : could not open reconciled tree file : " + phyloxmlFileName);
exit(1);
}
while( !fileStream.eof() )
{
string line;
getline( fileStream, line );
map <string, string> * properties = new map <string,string>;
string * value;
string Tname = InterpretLineXML(line,properties,value);
if(Tname.compare("clade") == 0)
{
readPhyloXMLFile(fileStream,Stree, speciesNameToNodeId , VERBOSE);
break;
}
}
}
/*
Returns 0 if there is no time slices (NTS), 1 if there are time slices (TS) or 2 if there are bounded time slices (BTS)
*/
int ReconciledTree::getTimeSliceStatus()
{
return TimeSliceStatus;
}
/*
Access to NodeId with CladeId
Takes:
- CladeId (int): id of a clade
Returns:
vector<int>: NodeIds of the nodes with that clade OR empty vector if the clade is absent
*/
vector<int> ReconciledTree::getNodeIdsFromCladeId(int CladeId)
{
if(CladeIdToNodeIds.count(CladeId) == 0)
return vector<int>();
return CladeIdToNodeIds[CladeId];
}
/*
Adds NodeId to CladeId
Takes:
- CladeId (int): id of a clade
- NodeId (int): if of the node with that clade
*/
void ReconciledTree::addNodeIdToCladeIdMap(int CladeId, int NodeId)
{
//cout << "ReconciledTree::addNodeIdToCladeIdMap " << CladeId << "," << NodeId << endl;
if(CladeIdToNodeIds.count(CladeId) == 0)//key is absent from the map -> add it
CladeIdToNodeIds[CladeId] = vector<int>();
CladeIdToNodeIds[CladeId].push_back(NodeId);
}
//getter of node properties
/*
retrieve the specified node species.
Takes:
- NodeId (int): id of a node in the tree
Returns:
(int): speciesid of the node
*/
int ReconciledTree::getNodeSpecies(int nodeid)
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
return dynamic_cast<BppInteger *> ( it->second->getNodeProperty(spe) )->getValue();
}
//else we update the map
NodeIdToNodeP[nodeid] = getNode(nodeid);*/
return dynamic_cast<BppInteger *> (getNodeProperty(nodeid, spe))->getValue();
}
int ReconciledTree::getNodePostOrder(int nodeid)
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
return dynamic_cast<BppInteger *> ( it->second->getNodeProperty(porder) )->getValue();
}
//else we update the map
NodeIdToNodeP[nodeid] = getNode(nodeid);*/
return dynamic_cast<BppInteger *> (getNodeProperty(nodeid, porder))->getValue();
}
int ReconciledTree::getNodeTimeSlice(int nodeid)
{
if(hasNodeProperty(nodeid,ts))
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
return dynamic_cast<BppInteger *> ( it->second->getNodeProperty(ts) )->getValue();
}
//else we update the map
NodeIdToNodeP[nodeid] = getNode(nodeid);*/
return dynamic_cast<BppInteger *> (getNodeProperty(nodeid, ts))->getValue();
}
//in case the property is not set, return the upper time slice
return getNodeUpperBoundaryTS(nodeid);
}
int ReconciledTree::getNodeUpperBoundaryTS(int nodeid)
{
/*map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
return dynamic_cast<BppInteger *> ( it->second->getNodeProperty(uts) )->getValue();
}
//else we update the map
NodeIdToNodeP[nodeid] = getNode(nodeid);*/
return dynamic_cast<BppInteger *> (getNodeProperty(nodeid, uts))->getValue();
}
int ReconciledTree::getNodeLowerBoundaryTS(int nodeid)
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
return dynamic_cast<BppInteger *> ( it->second->getNodeProperty(lts) )->getValue();
}
//else we update the map
NodeIdToNodeP[nodeid] = getNode(nodeid);*/
return dynamic_cast<BppInteger *> (getNodeProperty(nodeid, lts))->getValue();
}
int ReconciledTree::getNodeEvent(int nodeid) // retrieves the eventid of the node. eventid is an int corresponding to a reconciliation event
{
/*map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
return dynamic_cast<BppInteger *> ( it->second->getNodeProperty(ev) )->getValue();
}
//else we update the map
NodeIdToNodeP[nodeid] = getNode(nodeid);*/
return dynamic_cast<BppInteger *> (getNodeProperty(nodeid, ev))->getValue();
}
int ReconciledTree::getNodeCladeNum(int nodeid) // retrieves the clade id of the node. Clade id is a concept used for CCPs and will typically be defined in a reference CladesAndTripartitions instance
{
/*map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
return dynamic_cast<BppInteger *> ( it->second->getNodeProperty(clnum) )->getValue();
}
//else we update the map
NodeIdToNodeP[nodeid] = getNode(nodeid);*/
return dynamic_cast<BppInteger *> (getNodeProperty(nodeid, clnum))->getValue();
}
//setter of node properties
void ReconciledTree::setNodeSpecies(int nodeid, int speciesid) // set the specified node species.
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
it->second->setNodeProperty(spe, BppInteger(speciesid) );
}
else
{
//else we update the map
Node * NP = getNode(nodeid);
NodeIdToNodeP[nodeid] = NP;
NP->setNodeProperty(spe, BppInteger(speciesid));
}*/
Node * NP = getNode(nodeid);
NP->setNodeProperty(spe, BppInteger(speciesid));
}
void ReconciledTree::setNodeSpecies(Node * NP, int speciesid) // set the specified node species.
{
NP->setNodeProperty(spe, BppInteger(speciesid));
}
void ReconciledTree::setNodePostOrder(int nodeid, int postorder)
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
it->second->setNodeProperty(porder, BppInteger(postorder) );
}
else
{
//else we update the map
Node * NP = getNode(nodeid);
NodeIdToNodeP[nodeid] = NP;
NP->setNodeProperty(porder, BppInteger(postorder));
}*/
Node * NP = getNode(nodeid);
NP->setNodeProperty(porder, BppInteger(postorder));
}
void ReconciledTree::setNodePostOrder(Node * NP, int postorder)
{
NP->setNodeProperty(porder, BppInteger(postorder));
}
void ReconciledTree::setNodeTimeSlice(int nodeid, int timeslice)
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
it->second->setNodeProperty(ts, BppInteger(timeslice) );
}
else
{
//else we update the map
Node * NP = getNode(nodeid);
NodeIdToNodeP[nodeid] = NP;
NP->setNodeProperty(ts, BppInteger(timeslice));
}*/
Node * NP = getNode(nodeid);
NP->setNodeProperty(ts, BppInteger(timeslice));
}
void ReconciledTree::setNodeTimeSlice(Node * NP, int timeslice)
{
NP->setNodeProperty(ts, BppInteger(timeslice));
}
void ReconciledTree::setNodeUpperBoundaryTS(int nodeid, int timeslice)
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
it->second->setNodeProperty(uts, BppInteger(timeslice) );
}
else
{
//else we update the map
Node * NP = getNode(nodeid);
NodeIdToNodeP[nodeid] = NP;
NP->setNodeProperty(uts, BppInteger(timeslice));
}*/
Node * NP = getNode(nodeid);
NP->setNodeProperty(uts, BppInteger(timeslice));
}
void ReconciledTree::setNodeUpperBoundaryTS(Node * NP, int timeslice)
{
NP->setNodeProperty(uts, BppInteger(timeslice));
}
void ReconciledTree::setNodeLowerBoundaryTS(int nodeid, int timeslice)
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
it->second->setNodeProperty(lts, BppInteger(timeslice) );
}
else
{
//else we update the map
Node * NP = getNode(nodeid);
NodeIdToNodeP[nodeid] = NP;
NP->setNodeProperty(lts, BppInteger(timeslice));
}*/
Node * NP = getNode(nodeid);
NP->setNodeProperty(lts, BppInteger(timeslice));
}
void ReconciledTree::setNodeLowerBoundaryTS(Node * NP, int timeslice)
{
NP->setNodeProperty(lts, BppInteger(timeslice));
}
void ReconciledTree::setNodeEvent(int nodeid, int eventid) // assigns an event to the node according to the eventid
{
/*
map<int,Node * >::iterator it = NodeIdToNodeP.find(nodeid);
if(it != NodeIdToNodeP.end())
{
it->second->setNodeProperty(ev, BppInteger(eventid) );
}
else
{
//else we update the map
Node * NP = getNode(nodeid);
NodeIdToNodeP[nodeid] = NP;
NP->setNodeProperty(ev, BppInteger(eventid));
}*/
Node * NP = getNode(nodeid);
NP->setNodeProperty(ev, BppInteger(eventid));
}
void ReconciledTree::setNodeEvent(Node * NP, int eventid)
{
NP->setNodeProperty(ev, BppInteger(eventid));
}
void ReconciledTree::setNodeCladeNum(int nodeid, int cladenum) // sets the clade id of the node. Clade id is a concept used for CCPs and will typically be defined in a reference CladesAndTripartitions instance
{
if(hasNodeProperty(nodeid, clnum))//property already set
{
if(getNodeCladeNum(nodeid) == cladenum)//already the correct property -> don't change anything
return;
else
resetNodeCladeNum(nodeid); // reset the property and update the map cladeid -> nodeid
}
addNodeIdToCladeIdMap(cladenum, nodeid);//updating the map cladeid -> nodeid
setNodeProperty(nodeid, clnum, BppInteger(cladenum));
}
void ReconciledTree::setNodeCladeNum(Node * NP, int cladenum) // sets the clade id of the node. Clade id is a concept used for CCPs and will typically be defined in a reference CladesAndTripartitions instance
{
int nodeid = NP->getId();
if(NP->hasNodeProperty(clnum))
{
if(getNodeCladeNum(nodeid) == cladenum)
return;
else
resetNodeCladeNum(nodeid);
}
addNodeIdToCladeIdMap(cladenum, nodeid);//updating the map cladeid -> nodeid
NP->setNodeProperty(clnum, BppInteger(cladenum));
}
//unset the clade id of the node. Always use this function because it also updates the CladeIdToNodeIds map
void ReconciledTree::resetNodeCladeNum(int nodeid)
{
int CladeId = getNodeCladeNum(nodeid);
getNode(nodeid)->deleteNodeProperty(clnum);
///updating the map
if(CladeIdToNodeIds.count(CladeId) != 0)//key is not absent from the map
{
vector<int>::iterator it;
for (it = CladeIdToNodeIds[CladeId].begin() ; it != CladeIdToNodeIds[CladeId].end(); ++it)
if(*it == nodeid)
break;
if(it != CladeIdToNodeIds[CladeId].end())
CladeIdToNodeIds[CladeId].erase(it);//erasing
if(CladeIdToNodeIds[CladeId].size() == 0)
CladeIdToNodeIds.erase(CladeId);
}
//the else case should never happen if the cladenum was set properly
}
/*
Prints node information
Takes:
- NodeId (int): id of a node in the tree
*/
void ReconciledTree::printNode(int nodeid)
{
cout << "Node : " << nodeid ;
if(hasNodeName(nodeid))
cout << " " <<getNodeName(nodeid);
if(hasFather(nodeid))
cout << " ; father : " << getFatherId(nodeid);
else
cout << " ; root ";
if(hasNodeProperty(nodeid, spe))
cout << " ; Species " << getNodeSpecies(nodeid);
else
cout << " ; no Species";
if(hasNodeProperty(nodeid, ev))
cout << " ; Event " << getNodeEvent(nodeid);
else
cout << " ; no Event";
if(hasNodeProperty(nodeid,clnum))
cout << " ; CladeNum " << getNodeCladeNum(nodeid);
else
cout << " ; no CladeNum";
if(hasNodeProperty(nodeid,uts))
{
int UTS = getNodeUpperBoundaryTS(nodeid);
int LTS = getNodeLowerBoundaryTS(nodeid);
if(UTS != LTS)
{
cout << " ; Upper Time Slice " << UTS;
cout << " ; Lower Time Slice " << LTS;
}
else
cout << " ; Time Slice " << UTS;
}
else
cout << " ; no TS";
// if(!isLeaf(nodeid))
// {
// cout << " ; sons :" ;
// vector <int> SonIds = getSonsId(nodeid);
// for(unsigned i = 0; i < SonIds.size(); i++)
// cout << SonIds[i] << " ";
// }
cout << endl;
}
void ReconciledTree::printMe()//prints all nodes
{
vector <int> NodesIds = getNodesId();
for (unsigned j=0; j<NodesIds.size() ; j++)
printNode(NodesIds[j]);
}
string ReconciledTree::NewickString(bool hideLosses )
{
return NodeString(getRootId(), hideLosses);
}
/*
Removes all nodes whose event is No Event: 6
*/
void ReconciledTree::removeNoEventNodes()
{
vector<int> NodesIds = getNodesId();
int NodeId;
for (unsigned j=0; j<NodesIds.size() ; j++)
{
NodeId= NodesIds[j];
if(getNodeEvent(NodeId) == N)//NoEvent node
{
resetNodeCladeNum(NodeId);//forgetting that the node has this cladenum
Node * NoEventNode = getNode(NodeId);
Node * fatherNode = NoEventNode->getFather();
Node * sonNode = NoEventNode->getSon(0);//we want the 1st son (there should be 1 and only 1 son to a NoEvent node)
fatherNode->removeSon(NoEventNode);
fatherNode->addSon(sonNode);// also tells the son that its father is the fatherNode
delete NoEventNode;
}
}
}
/*
Precomputes time slices at speciation and leaves nodes
Takes:
- idXToLTS (map <int,int>) : map of species id to minimum associated time slice
*/
void ReconciledTree::PreComputeBoundedTimeSlices(map <int,int> idXToLTS)
{
vector <int> IDS = getNodesId();
for(unsigned i = 0; i < IDS.size(); i++)
{
int NodeId = IDS[i];
int evt = getNodeEvent(NodeId);
if(evt == C)// trivial case of leaves
{
setNodeUpperBoundaryTS(NodeId, 0);
setNodeLowerBoundaryTS(NodeId, 0);
}
else if(evt == S)
{
int TS = idXToLTS[getNodeSpecies(NodeId)];
setNodeUpperBoundaryTS(NodeId,TS);
setNodeLowerBoundaryTS(NodeId,TS);
}
}
}
/*
!!! presumes that LTS and BTS proerties have been set for all nodes !!!
Used to fix the holes than can be left after all null nodes are deleted in BTS mode
Acts in a recursive fashion from the given node.
Check if the UTS (upper) of NodeId has a difference >1 with the LTS (lower) of its parent. If this is the case, an intermediary Null node is added
Takes:
- int NodeId : the id of a node in the tree
*/
void ReconciledTree::addIntermediaryNullBTS(int NodeId)
{
vector <int> SonsIds = getSonsId(NodeId);
for(unsigned i = 0 ; i < SonsIds.size() ; i++)
{ // recursion
addIntermediaryNullBTS(SonsIds[i]);
}
if( isRoot(NodeId) ) // the root has no parent -> nothing more to do
return ;
int parentId = getFatherId(NodeId);
//these properties shall be set and there will be errors if they aren't
int selfUTS = getNodeUpperBoundaryTS(NodeId);
int parentLTS = getNodeLowerBoundaryTS(parentId);
if( (parentLTS - selfUTS) > 1 )
{
// means that there is a "time-hole" between this node and it parent.
// we add a Null event node to guarantee that all time slices can be represented
int nullUTS = parentLTS - 1;
int nullLTS = selfUTS + 1;
int evt = N;
int cladenum = getNodeCladeNum(NodeId);
int species = getNodeSpecies(NodeId);
Node * FatherNode = getNode(parentId);
Node * currentNode = getNode(NodeId);
int newId = MyNextId(); // getNextId();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the father
FatherNode->addSon(newNode);
//setting the new node properties
setNodeSpecies(newNode,species);
setNodeEvent(newNode,evt);
setNodeCladeNum(newNode,cladenum);
setNodeTimeSlice(newNode, nullUTS);
setNodeUpperBoundaryTS(newNode, nullUTS);
setNodeLowerBoundaryTS(newNode, nullLTS);
// rebranching to existing structure
FatherNode->removeSon(currentNode);
newNode->addSon(currentNode);//branching current node to the Null node before it
}
}
/*
Recursively sets the upper and lower boundaries of a subtree.
Takes:
- NodeId (int) : id of the root of the subtree
- idXToUTS (map <int,int>) : map of species id to maximum associated time slice
- idXToLTS (map <int,int>) : map of species id to minimum associated time slice
*/
void ReconciledTree::setSubtreeBoundaryTS(int NodeId, map <int,int> idXToUTS, map <int,int> idXToLTS)
{
//first step : set the time slice as the current upper boundary time slice (which may be changed) so that we can keep this information
//!!! in case there is no time slice set (example of loss nodes from XML input)
if(! hasNodeProperty(NodeId , uts) ) // special loss cases
{
int currentTS = getNodeTimeSlice(getFatherId(NodeId)) - 1;
if(currentTS < 0)
currentTS = 0;
//correcting the tree while we're at it
setNodeUpperBoundaryTS(NodeId, currentTS);//set them at the current time slice
setNodeLowerBoundaryTS(NodeId, currentTS);
}
setNodeTimeSlice(NodeId, getNodeUpperBoundaryTS(NodeId));
//rest of the function
int evt = getNodeEvent(NodeId);
if(evt == C)
return; //this is a leaf, LTS = UTS and is already set
bool isSpeciation = false;
if(evt == S)
isSpeciation = true;//in this case, LTS = UTS and is already set
if(!isSpeciation)
{
//setting UTS as the UTS of its father
int UTS;
if(!hasFather(NodeId)) //in case the root is not a speciation
UTS = idXToUTS[getNodeSpecies(NodeId)] ;
else
UTS = getNodeUpperBoundaryTS(getFatherId(NodeId));
if(evt != Bout) // Bout event are in a lost species, so we only have to check their parent in the gene tree
{
//check the max TS on the species branch we are in to compare
int altUTS = idXToUTS[getNodeSpecies(NodeId)];
//cout << NodeId << " " << evt << " : " << UTS << "<>" << altUTS << endl;
if(altUTS < UTS)
UTS = altUTS;//replace if lower
}
setNodeUpperBoundaryTS(NodeId,UTS);
}
//we can now recurse to the children
vector <int> SonsIds = getSonsId(NodeId);
int LTS = idXToLTS[getNodeSpecies(NodeId)];//start with a minimum value of the LTS
for(int i = 0; i < SonsIds.size(); i++)
{
setSubtreeBoundaryTS(SonsIds[i],idXToUTS, idXToLTS); //RECURSION TO THE CHILDREN
//getting the (now set) LTS of that child
int altLTS = getNodeLowerBoundaryTS(SonsIds[i]);
if(altLTS > LTS)//stocking it if it is the minimum
LTS = altLTS;
}
if(!isSpeciation)//setting LTS is the node isn't a speciation
setNodeLowerBoundaryTS(NodeId,LTS);
setNodeTimeSlice(NodeId, getNodeUpperBoundaryTS(NodeId));
}
/*
Takes:
- SpeciesTree (MySpeciesTree *): pointer to ultrametric species tree
Computes and set the bounded time slices for all nodes in the tree
The lower time slice are inherited from the children,
The upper time slices are inherited from the parent.
This also destroys the nodes with No Event (6) events
*/
void ReconciledTree::computeBoundedTimeSlices(MySpeciesTree * SpeciesTree)
{
// if( getTimeSliceStatus() == 0)//first check if the time slices exists
// cout << "ReconciledTree::computeBoundedTimeSlices : No time slices to draw from!" << endl;
//1. delete NoEvent nodes
removeNoEventNodes();
//2. build a map between species and maximum time slice (i.e. the time slice of the previous speciation -1)
map <int,int> idXToUTS;
map <int,int> idXToLTS;
vector <MySpeciesNode*> SpNodes = SpeciesTree->getNodes();
for(unsigned j=0; j < SpNodes.size(); j++)
{ //we want only speciation nodes: the ones whose real post order is != that of their children
if(SpNodes[j]->isLeaf())
continue;
int RPO = SpNodes[j]->getInfos().realPostOrder; // getting the real species name
int SonRPO = SpNodes[j]->getSon(0)->getInfos().realPostOrder; // species name of the (first) son
if(RPO != SonRPO)//speciation node
{
int nbson = SpNodes[j]->getNumberOfSons();
for(int i=0; i< nbson; i++)//setting time slice for all son
idXToUTS[SpNodes[j]->getSon(i)->getInfos().realPostOrder] = SpNodes[j]->getInfos().timeSlice - 1;
idXToLTS[RPO] = SpNodes[j]->getInfos().timeSlice;
}
}
//2.5 precomputes the TSs at leaves and speciations
PreComputeBoundedTimeSlices( idXToLTS);
//3. Recursively set the UTS and LTS of nodes
setSubtreeBoundaryTS(getRootId(), idXToUTS, idXToLTS);
//3.5 add null event nodes when there is one of several time slices missing in a branch
addIntermediaryNullBTS(getRootId());
//4. setting the TimeSliceStatus to notify of BTS
TimeSliceStatus = 2;
}
/*
Removes null event nodes and set to not time sliced
*/
void ReconciledTree::setToNonTimeSliced()
{
if( getTimeSliceStatus() == 0)//first check if the time slices exists
return
//1. delete NoEvent nodes
removeNoEventNodes();
//2. setting the TimeSliceStatus to notify of BTS
TimeSliceStatus = 0;
}
void ReconciledTree::SubdivideTree()
{
//expects that node already have an exact set time slice
if( getTimeSliceStatus() == 0)//first check if the time slices exists
throw Exception("ReconciledTree::SubdivideTree : No time slices to draw from!");
bool resetULTS = false;
if( getTimeSliceStatus() == 2)// setting upper and lower time slice boundaries as equal to the TS
resetULTS = true;
vector<int> NodesIds = getNodesId();
int NodeId;
for (unsigned j=0; j<NodesIds.size() ; j++)
{
NodeId= NodesIds[j];
Node * currentNode = getNode(NodeId);
int currentTS;
// cout << NodeId << " " << currentNode->hasNodeProperty(uts) << "->" ;
if(! currentNode->hasNodeProperty(uts) ) // special loss cases
{
Node * fatherNode = currentNode->getFather();
currentTS = getNodeTimeSlice(fatherNode->getId()) - 1;
if(currentTS < 0)
currentTS = 0;
//correcting the tree while we're at it
setNodeUpperBoundaryTS(NodeId, currentTS);//set them at the current time slice
setNodeLowerBoundaryTS(NodeId, currentTS);
}
else
currentTS = getNodeTimeSlice(currentNode->getId());
// cout << currentNode->hasNodeProperty(uts) <<endl;
if(resetULTS)//reset the upper and lower time slices
{
setNodeUpperBoundaryTS(NodeId, currentTS);//set them at the current time slice
setNodeLowerBoundaryTS(NodeId, currentTS);
}
if(!currentNode->hasFather())//this is the root node -> do nothing else
continue;
Node * fatherNode = currentNode->getFather();
int fatherTS = getNodeTimeSlice(fatherNode->getId());
int nbMissingNodes = fatherTS - currentTS - 1;
if(nbMissingNodes > 0 )
{
int sp = getNodeSpecies(NodeId);
if(getNodeEvent(NodeId) == R)
sp = -1;
int evt = N;
int cladenum = getNodeCladeNum(NodeId);
Node * newFatherNode = fatherNode;
for(int i = 0; i< nbMissingNodes;i++)//creating the missing nodes
{
int newId = MyNextId();// getNextId();
Node * newNode = new Node(newId);
nbNodes++;
//branching to the father
newFatherNode->addSon(newNode);
//setting the new node properties
setNodeSpecies(newNode,sp);
setNodeEvent(newNode,evt);
setNodeCladeNum(newNode,cladenum);
setNodeTimeSlice(newNode, fatherTS - i - 1);
setNodeUpperBoundaryTS(newNode, fatherTS - i - 1);
setNodeLowerBoundaryTS(newNode, fatherTS - i - 1);
//incrementing
newFatherNode = newNode;
}
fatherNode->removeSon(currentNode);
newFatherNode->addSon(currentNode);//branching current node to the Null node before it
}
}
//set time slice status to notify of TS
TimeSliceStatus = 1;
}
int ReconciledTree::getNumberOfDuplication()
{
return countAnyEvent(D);
}
int ReconciledTree::getNumberOfLoss()
{
return countAnyEvent(L);
}
int ReconciledTree::getNumberOfTransfer()
{
return countAnyEvent(R);
}
/*
Checks if the node have the same species
Takes:
- n1 (Node *): a node with at least the species property set
- n2 (Node * ): a node with at least the species property set
Returns:
(bool) : true if the two nodes have the same species; false otherwise
*/
bool ReconciledTree::haveSameSpecies(Node * n1, Node * n2)
{
//basic checks
if((!n1->hasNodeProperty(spe)) || (!n2->hasNodeProperty(spe)))
throw Exception("ReconciledTree::haveSameSpecies : given nodes don't have a species (S property)");
int n1s = dynamic_cast<BppInteger *> (n1->getNodeProperty(spe))->getValue();
int n2s = dynamic_cast<BppInteger *> (n2->getNodeProperty(spe))->getValue();
if(n1s != n2s)
return false;
return true;
}
/*
Checks if the node have compatible time slices
Takes:
- n1 (Node *): a node with at least the species property set
- n2 (Node * ): a node with at least the species property set
Returns:
(bool) : true if the two nodes have compatible time slices; false otherwise
*/
bool ReconciledTree::areTSCompatible(Node * n1, Node * n2)
{
if(TimeSliceStatus == 0) // no TS -> same species is sufficient
return true;
if(TimeSliceStatus == 1)
{
int n1ts = dynamic_cast<BppInteger *> (n1->getNodeProperty(uts))->getValue();
int n2ts = dynamic_cast<BppInteger *> (n2->getNodeProperty(uts))->getValue();
if(n1ts == n2ts)
return true;
return false;
}
int n1uts = dynamic_cast<BppInteger *> (n1->getNodeProperty(uts))->getValue();
int n2lts = dynamic_cast<BppInteger *> (n2->getNodeProperty(lts))->getValue();
//BTS case: TimeSliceStatus == 2
if(n1uts < n2lts)
return false;
int n1lts = dynamic_cast<BppInteger *> (n1->getNodeProperty(lts))->getValue();
int n2uts = dynamic_cast<BppInteger *> (n2->getNodeProperty(uts))->getValue();
if(n1lts > n2uts)
return false;
return true;
}
/*
Checks if the node are compatible (ie. same species and comparable timeslaice).
Presumes that both nodes have the same timeslice status as the tree
Takes:
- n1 (Node *): a node with at least the species property set
- n2 (Node *): a node with at least the species property set
Returns:
(bool) : true if the two nodes are compatible; false otherwise
*/
bool ReconciledTree::areCompatible(Node * n1, Node * n2)
{
//first species
if(!haveSameSpecies( n1, n2))
return false;
return areTSCompatible(n1, n2);
}
/*
Checks if the node are compatible (ie. same species and comparable timeslice).
Presumes that both nodes have the same timeslice status as the tree
Takes:
- id1 (int): a node id with at least the species property set
- id2 (int): a node id with at least the species property set
Returns:
(bool) : true if the two nodes are compatible; false otherwise
*/
bool ReconciledTree::areCompatible(int id1, int id2)
{
Node * n1 = getNode(id1);
Node * n2 = getNode(id2);
return areCompatible(n1, n2);
}
/*
Checks if AncId is the ancestor of SonId
Takes:
- AncId (int): id of the potential ancestor
- SonId (int): id of the potential descendant
Returns:
(bool): true if AncId is an ancestor of SonId
*/
bool ReconciledTree::isAncestor(int AncId, int SonId)
{
//solving the easiest cases
if(AncId == SonId)
return false;
int RootId = getRootId();
if(AncId == RootId) // the potential ancestor is the root so it is ancestor to SonId
return true;
if(SonId == RootId) // The descendant is the root -> impossible
return false;
Node * SonNode = getNode(SonId);
Node * FatherNode = SonNode->getFather();
int FatherId = FatherNode->getId();
bool ok= false; //storing result
while(FatherId != RootId)
{
if(FatherId == AncId) // found the Ancestor
{
ok = true;
break;
}
Node * SonNode = FatherNode;
FatherNode = SonNode->getFather();
FatherId = FatherNode->getId();
}
return ok;
}
/*
Get the path from ancestor to son. (If AncId is not an ancestor of SonId, will return the path to the root)
Takes:
- AncId (int): id of the potential ancestor
- SonId (int): id of the potential descendant
Returns:
(vector <Node *>): path including start and stop
*/
vector <Node *> ReconciledTree::pathFromAncestorToSon(int AncId, int SonId)
{
vector <Node *> path;
path.push_back(getNode(SonId));
int RootId = getRootId();
int currentId = SonId;
while((currentId != RootId)&&(currentId != AncId))
{
path.insert(path.begin(),path.front()->getFather());
currentId = path.front()->getId();
}
return path;
}
/*
Get the path from ancestor to son. (If AncId is not an ancestor of SonId, will return the path to the root)
Takes:
- AncId (int): id of the potential ancestor
- SonId (int): id of the potential descendant
Returns:
(vector <int >): path including start and stop
*/
vector <int> ReconciledTree::idPathFromAncestorToSon(int AncId, int SonId)
{
vector <Node *> path = pathFromAncestorToSon(AncId, SonId);
vector <int> idpath;
for(unsigned i = 0; i < path.size(); i++)
idpath.push_back(path[i]->getId());
return idpath;
}
int ReconciledTree::getIdWithName(const string &name)
{
//go through the whole tree. Does not throw error if a node has no name
int IdToReturn = -1;
vector <Node *> NodeToDo;
Node * currentNode;
NodeToDo.push_back(getRootNode());
while(NodeToDo.size() > 0)
{
currentNode = NodeToDo[0];
if(currentNode->hasName())
{
//cout << " " << currentNode->getId() << " " << currentNode->getName() << " <-> " << name << endl;
if(currentNode->getName() == name)
{
IdToReturn = currentNode->getId();
break;
}
}
//cout << "ReconciledTree::getIdWithName " << currentNode->getId() << " "<< currentNode->getNumberOfSons() <<endl;
for(unsigned i = 0 ; i < currentNode->getNumberOfSons() ; i++)
{
//cout << i << endl;
NodeToDo.push_back(currentNode->getSon(i));
}
NodeToDo.erase(NodeToDo.begin());
}
if(IdToReturn == -1)
throw Exception("ReconciledTree::getIdWithName: no nodes with name \"" + name + "\"");
return IdToReturn;
}
bool ReconciledTree::isRealLeaf(int id)
{
if(getNodeEvent(id) != C)
return false;
return true;
}
bool ReconciledTree::isExtant(int evtcode)
{
if(evtcode != C)
return false;
return true;
}
bool ReconciledTree::isSpeciation(int evtcode)
{
if(evtcode != S)
return false;
return true;
}
bool ReconciledTree::isLoss(int evtcode)
{
if(evtcode != L)
return false;
return true;
}
bool ReconciledTree::isDup(int evtcode)
{
if(evtcode != D)
return false;
return true;
}
bool ReconciledTree::isSout(int evtcode)
{
if(evtcode != Sout)
return false;
return true;
}
bool ReconciledTree::isRec(int evtcode)
{
if(evtcode != R)
return false;
return true;
}
bool ReconciledTree::isNull(int evtcode)
{
if(evtcode != N)
return false;
return true;
}
bool ReconciledTree::isBout(int evtcode)
{
if(evtcode != Bout)
return false;
return true;
}
ReconciledTree * ReconciledTree::cloneSubtree(int newRootId)
{
Node * newRoot = TreeTemplateTools::cloneSubtree<Node>(*this, newRootId);
return new ReconciledTree(newRoot, getTimeSliceStatus());
}
vector <string> ReconciledTree::getRealLeavesNames()
{
vector <string> names;
vector <int> LeavesId = getLeavesId();
for(size_t i = 0; i < LeavesId.size(); i++)
{
if( isRealLeaf(LeavesId[i]) )
names.push_back(getNodeName(LeavesId[i]));
}
return names;
}
/*
recursively extract a MyGeneTree instance copying the topology of the reconciled tree.
*/
MyGeneTree ReconciledTree::getMyGeneTreeTopology()
{
MyGeneNode * node = getMyGeneTreeTopologyAux(getRootNode());
return MyGeneTree( *node );
}
map <int, vector <string> > ReconciledTree::cladeToLeafListAssociation()
{
map <int, vector <string> > cladeToLeafList;
cladeToLeafListAssociationAux(getRootId(), cladeToLeafList );
return cladeToLeafList;
}
/*
Takes:
- int nodeId: the id of a node in the tree
Returns:
(vector <int> ) the list of the closest descendant of nodeId that are either leaves or speciations
*/
vector <int> ReconciledTree::getLeafOrSpeciationDescendants(int nodeId)
{
vector <int> descendants;
if(isLeaf(nodeId)) // leaf -> no descendant to report
return descendants;
vector <int> SonsId = getSonsId(nodeId);
for(unsigned i = 0 ; i < SonsId.size(); i++)
{
int ev = getNodeEvent(SonsId[i]);
if( (isSpeciation(ev)) || (isExtant(ev)) )
descendants.push_back(SonsId[i]); // speciation or leaf found -> no recursion
else
{ // not found -> recursion
vector <int> SonsDescendants = getLeafOrSpeciationDescendants(SonsId[i]);
for(unsigned j = 0 ; j < SonsDescendants.size(); j++) // adding the detected descendant to our list
descendants.push_back(SonsDescendants[j]);
}
}
return descendants;
}
/*
Takes:
- string name : name of the single leaf
- int speciesId : species id of the single leaf
*/
void ReconciledTree::makeSingleLeafTree( string name, int speciesId )
{
assert( nbNodes == 0 );
Node * newnode = new Node(0);
setRootNode(newnode);//setting as the new root
setNodeCladeNum(0, 0);//setting the new node cladenum property and updating the map
nbNodes++;
//setting NodeId as a leaf
setNodeSpecies(newnode,speciesId);
newnode->setName(name);
setNodeEvent(newnode,C);
setNodeUpperBoundaryTS(newnode,0);//the time slice of a leaf is 0
setNodeLowerBoundaryTS(newnode,0);
} | 26.008788 | 209 | 0.685218 | [
"vector"
] |
d0eb7e235d90691464d3f71bf51fb15295a57ebe | 184 | cpp | C++ | benchmarks/basic_arithmetic/Serial.cpp | irfanhamid/khyber | b6decef55ea199f884f2d77e049e979f1c7ba8bf | [
"Apache-2.0"
] | 1 | 2018-01-06T20:44:24.000Z | 2018-01-06T20:44:24.000Z | benchmarks/basic_arithmetic/Serial.cpp | irfanhamid/khyber | b6decef55ea199f884f2d77e049e979f1c7ba8bf | [
"Apache-2.0"
] | null | null | null | benchmarks/basic_arithmetic/Serial.cpp | irfanhamid/khyber | b6decef55ea199f884f2d77e049e979f1c7ba8bf | [
"Apache-2.0"
] | null | null | null | #include "Serial.hpp"
using namespace std;
void RunSerialImpl(vector<float>& dst, const vector<float>& src)
{
for ( auto i = 0; i < dst.size(); ++i ) {
dst[i] += src[i];
}
}
| 16.727273 | 64 | 0.592391 | [
"vector"
] |
d0f9778d46bec71c00acc8519574703ce7b440e1 | 9,420 | cpp | C++ | apps/lasblock.cpp | sebastic/libLAS | 59709b36d80bf48c5463c009e9c5ff251f398e33 | [
"BSD-3-Clause"
] | 1 | 2019-02-13T14:41:23.000Z | 2019-02-13T14:41:23.000Z | apps/lasblock.cpp | sebastic/libLAS | 59709b36d80bf48c5463c009e9c5ff251f398e33 | [
"BSD-3-Clause"
] | 1 | 2018-03-13T07:12:06.000Z | 2018-03-13T07:12:06.000Z | apps/lasblock.cpp | sebastic/libLAS | 59709b36d80bf48c5463c009e9c5ff251f398e33 | [
"BSD-3-Clause"
] | 2 | 2021-05-17T02:09:16.000Z | 2021-06-21T12:15:52.000Z | // $Id$
//
// lasblock generates block output for las2oci to store lidar data in OPC tables
//
//
// (C) Copyright Howard Butler 2010, hobu.inc@gmail.com
//
// Distributed under the BSD License
// (See accompanying file LICENSE.txt or copy at
// http://www.opensource.org/licenses/bsd-license.php)
//
#include <liblas/liblas.hpp>
#include <liblas/chipper.hpp>
#include "laskernel.hpp"
// std
#include <fstream>
#include <vector>
// boost
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4512)
#endif
#include <boost/program_options.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace po = boost::program_options;
#ifdef _WIN32
#define compare_no_case(a,b,n) _strnicmp( (a), (b), (n) )
#else
#define compare_no_case(a,b,n) strncasecmp( (a), (b), (n) )
#endif
typedef boost::shared_ptr<liblas::Writer> WriterPtr;
typedef boost::shared_ptr<liblas::CoordinateSummary> SummaryPtr;
typedef boost::shared_ptr<std::ofstream> OStreamPtr;
liblas::Writer* start_writer( std::ostream*& ofs,
std::string const& output,
liblas::Header const& header)
{
ofs = liblas::Create(output, std::ios::out | std::ios::binary);
if (!ofs)
{
std::ostringstream oss;
oss << "Cannot create " << output << "for write. Exiting...";
throw std::runtime_error(oss.str());
}
return new liblas::Writer(*ofs, header);
}
using namespace liblas;
void OutputHelp( std::ostream & oss, po::options_description const& options)
{
oss << "--------------------------------------------------------------------\n";
oss << " lasblock (" << GetFullVersion() << ")\n";
oss << "--------------------------------------------------------------------\n";
oss << options;
oss <<"\nFor more information, see the full documentation for lasblock at:\n";
oss << " http://liblas.org/utilities/block.html\n";
oss << "----------------------------------------------------------\n";
}
void write_tiles(std::string& output,
liblas::chipper::Chipper& c,
liblas::Reader& reader,
bool verbose,
bool bCompressed)
{
std::string out = output;
liblas::Header header = reader.GetHeader();
if (bCompressed)
header.SetCompressed(true);
std::string::size_type dot_pos = output.find_first_of(".");
out = output.substr(0, dot_pos);
if (verbose)
std::cout << "Writing " << c.GetBlockCount() << " blocks to " << output << std::endl;
boost::uint32_t prog = 0;
for ( boost::uint32_t i = 0; i < c.GetBlockCount(); ++i )
{
std::ostringstream name;
name << out << "-" << i;
if (bCompressed)
name << ".laz";
else
name << ".las";
SummaryPtr summary(new::liblas::CoordinateSummary);
{
std::ostream* ofs;
const liblas::chipper::Block& b = c.GetBlock(i);
header.SetExtent(b.GetBounds());
liblas::Writer* writer = start_writer(ofs, name.str(), header);
std::vector<boost::uint32_t> ids = b.GetIDs();
for ( boost::uint32_t pi = 0; pi < ids.size(); ++pi )
{
bool read = reader.ReadPointAt(ids[pi]);
if (read) {
liblas::Point const& p = reader.GetPoint();
summary->AddPoint(p);
writer->WritePoint(p);
}
}
if (writer != 0)
delete writer;
if (ofs != 0)
{
liblas::Cleanup(ofs);
}
}
liblas::Header hnew = FetchHeader(name.str());
RepairHeader(*summary, hnew);
RewriteHeader(hnew, name.str());
if (verbose)
term_progress(std::cout, (prog + 1) / static_cast<double>(c.GetBlockCount()));
prog++;
}
}
void write_index(std::string& output,
liblas::chipper::Chipper& c,
liblas::Reader& /*reader*/,
long precision,
bool verbose,
bool bUseStdout)
{
std::ostream* out;
if (bUseStdout)
{
out = &std::cout;
} else
{
out = static_cast<std::ostream*>(new std::ofstream(output.c_str()));
}
boost::uint32_t num_blocks = c.GetBlockCount();
if (verbose)
std::cout << "Writing " << c.GetBlockCount() << " blocks to " << output << std::endl;
boost::uint32_t prog = 0;
for ( boost::uint32_t i = 0; i < c.GetBlockCount(); ++i )
{
const liblas::chipper::Block& b = c.GetBlock(i);
std::vector<boost::uint32_t> ids = b.GetIDs();
*out << i << " " << ids.size() << " ";
out->setf(std::ios::fixed,std::ios::floatfield);
out->precision(precision);
liblas::Bounds<double> const& bnd = b.GetBounds();
*out << (bnd.min)(0) << " " << (bnd.min)(1) << " " << (bnd.max)(0) << " " << (bnd.max)(1) << " " ;
for ( boost::uint32_t pi = 0; pi < ids.size(); ++pi )
{
*out << ids[pi] << " ";
}
*out << std::endl;
// Set back to writing decimals
out->setf(std::ios::dec);
if (verbose)
term_progress(std::cout, (prog + 1) / static_cast<double>(num_blocks));
prog++;
}
if (out != 0 && !bUseStdout)
delete out;
}
int main(int argc, char* argv[])
{
std::string input;
std::string output;
long capacity = 3000;
long precision = 8;
bool verbose = false;
bool tiling = false;
bool bCompressed = false;
bool bUseStdout = false;
try
{
po::options_description desc("Allowed lasblock options");
po::positional_options_description p;
p.add("input", 1);
p.add("output", 1);
desc.add_options()
("help,h", "Produce this help message")
("capacity,c", po::value<long>(&capacity)->default_value(3000), "Number of points to nominally put into each block (note that this number will not be exact)")
("precision,p", po::value<long>(&precision)->default_value(8), "Number of decimal points to write for each bbox")
("stdout", po::value<bool>(&bUseStdout)->zero_tokens()->implicit_value(true), "Output data to stdout")
("write-points", po::value<bool>(&tiling)->zero_tokens()->implicit_value(true), "Write .las files for each block instead of an index file")
("compressed", po::value<bool>(&bCompressed)->zero_tokens()->implicit_value(true), "Produce .laz compressed data for --write-points tiles")
("input,i", po::value< std::string >(), "input LAS file")
("output,o", po::value< std::string >(&output)->default_value(""), "The output .kdx file (defaults to input filename + .kdx)")
("verbose,v", po::value<bool>(&verbose)->zero_tokens(), "Verbose message output")
;
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
std::cout <<"\nFor more information, see the full documentation for lasblock at:\n";
std::cout << " http://liblas.org/utilities/block.html\n";
std::cout << "----------------------------------------------------------\n";
return 1;
}
if (vm.count("input"))
{
input = vm["input"].as< std::string >();
std::ifstream ifs;
if (!liblas::Open(ifs, input.c_str()))
{
std::cerr << "Cannot open file '" << input << "'for read. Exiting...";
return 1;
}
}
else {
std::cerr << "Input LAS file not specified!\n";
OutputHelp(std::cout, desc);
return 1;
}
if (output.empty())
{
output = std::string(input) + ".kdx";
}
std::istream* ifs = liblas::Open(input, std::ios::in | std::ios::binary);
if (!ifs)
{
std::cerr << "Cannot open " << input << " for read. Exiting..." << std::endl;
return 1;
}
{
liblas::ReaderFactory f;
liblas::Reader reader = f.CreateWithStream(*ifs);
liblas::chipper::Chipper c(&reader, capacity);
if (verbose)
std::cout << "Chipping " << input<< " to " << output <<std::endl;
c.Chip();
if (!tiling)
{
write_index(output, c, reader, precision, verbose, bUseStdout);
} else
{
write_tiles(output, c, reader, verbose, bCompressed);
}
}
if (ifs != 0)
{
liblas::Cleanup(ifs);
ifs = 0;
}
}
catch(std::exception& e)
{
std::cerr << "error: " << e.what() << "\n";
return 1;
}
catch(...)
{
std::cerr << "Exception of unknown type!\n";
}
return 0;
}
| 28.895706 | 170 | 0.497346 | [
"vector"
] |
d0fe82c041c683ad7da21ac95ccebdb17079848b | 15,642 | cpp | C++ | c++/src/objmgr/tse_split_info.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/src/objmgr/tse_split_info.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/src/objmgr/tse_split_info.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: tse_split_info.cpp 390318 2013-02-26 21:04:57Z vasilche $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
* File Description:
* Split TSE info
*
*/
#include <ncbi_pch.hpp>
#include <objmgr/impl/tse_split_info.hpp>
#include <objmgr/impl/tse_info.hpp>
#include <objmgr/impl/tse_chunk_info.hpp>
#include <objmgr/impl/data_source.hpp>
#include <objmgr/impl/seq_annot_info.hpp>
//#include <objmgr/impl/bioseq_info.hpp>
//#include <objmgr/impl/bioseq_set_info.hpp>
#include <objmgr/impl/tse_assigner.hpp>
#include <objmgr/data_loader.hpp>
#include <objmgr/objmgr_exception.hpp>
#include <objmgr/seq_map.hpp>
#include <objmgr/prefetch_manager.hpp>
#include <objects/seq/Seq_literal.hpp>
#include <algorithm>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
/////////////////////////////////////////////////////////////////////////////
// CTSE_Chunk_Info
/////////////////////////////////////////////////////////////////////////////
CTSE_Split_Info::CTSE_Split_Info(void)
: m_BlobVersion(-1),
m_SplitVersion(-1),
m_BioseqChunkId(-1),
m_SeqIdToChunksSorted(false)
{
}
CTSE_Split_Info::CTSE_Split_Info(TBlobId blob_id, TBlobVersion blob_ver)
: m_BlobId(blob_id),
m_BlobVersion(blob_ver),
m_SplitVersion(-1),
m_BioseqChunkId(-1),
m_SeqIdToChunksSorted(false)
{
}
CTSE_Split_Info::~CTSE_Split_Info(void)
{
NON_CONST_ITERATE ( TChunks, it, m_Chunks ) {
it->second->x_DropAnnotObjects();
}
}
// TSE/DS attach
void CTSE_Split_Info::x_TSEAttach(CTSE_Info& tse, CRef<ITSE_Assigner>& lsnr)
{
m_TSE_Set.insert(TTSE_Set::value_type(&tse, lsnr));
NON_CONST_ITERATE ( TChunks, it, m_Chunks ) {
it->second->x_TSEAttach(tse, *lsnr);
}
}
void CTSE_Split_Info::x_TSEDetach(CTSE_Info& tse_info)
{
m_TSE_Set.erase(&tse_info);
}
CRef<ITSE_Assigner> CTSE_Split_Info::GetAssigner(const CTSE_Info& tse)
{
CRef<ITSE_Assigner> ret;
TTSE_Set::const_iterator it = m_TSE_Set.find(const_cast<CTSE_Info*>(&tse));
if( it != m_TSE_Set.end() )
return it->second;
return CRef<ITSE_Assigner>();
}
void CTSE_Split_Info::x_DSAttach(CDataSource& ds)
{
if ( !m_DataLoader ) {
m_DataLoader = ds.GetDataLoader();
_ASSERT(m_DataLoader);
}
}
// identification
CTSE_Split_Info::TBlobId CTSE_Split_Info::GetBlobId(void) const
{
_ASSERT(m_BlobId);
return m_BlobId;
}
CTSE_Split_Info::TBlobVersion CTSE_Split_Info::GetBlobVersion(void) const
{
return m_BlobVersion;
}
CTSE_Split_Info::TSplitVersion CTSE_Split_Info::GetSplitVersion(void) const
{
_ASSERT(m_SplitVersion >= 0);
return m_SplitVersion;
}
void CTSE_Split_Info::SetSplitVersion(TSplitVersion version)
{
_ASSERT(m_SplitVersion < 0);
_ASSERT(version >= 0);
m_SplitVersion = version;
}
CInitMutexPool& CTSE_Split_Info::GetMutexPool(void)
{
return m_MutexPool;
}
CDataLoader& CTSE_Split_Info::GetDataLoader(void) const
{
return m_DataLoader.GetNCObject();
}
bool CTSE_Split_Info::x_HasDelayedMainChunk(void) const
{
TChunks::const_iterator iter = m_Chunks.end(), begin = m_Chunks.begin();
return iter != begin && (--iter)->first == kMax_Int;
}
bool CTSE_Split_Info::x_NeedsDelayedMainChunk(void) const
{
TChunks::const_iterator iter = m_Chunks.end(), begin = m_Chunks.begin();
if ( iter == begin || (--iter)->first != kMax_Int ) {
return false;
}
return iter == begin || ((--iter)->first == kMax_Int-1 && iter == begin);
}
// chunk attach
void CTSE_Split_Info::AddChunk(CTSE_Chunk_Info& chunk_info)
{
CMutexGuard guard(m_SeqIdToChunksMutex);
_ASSERT(m_Chunks.find(chunk_info.GetChunkId()) == m_Chunks.end());
_ASSERT(m_Chunks.empty() || chunk_info.GetChunkId() != kMax_Int);
bool need_update = x_HasDelayedMainChunk();
m_Chunks[chunk_info.GetChunkId()].Reset(&chunk_info);
chunk_info.x_SplitAttach(*this);
if ( need_update ) {
chunk_info.x_EnableAnnotIndex();
}
}
CTSE_Chunk_Info& CTSE_Split_Info::GetChunk(TChunkId chunk_id)
{
TChunks::iterator iter = m_Chunks.find(chunk_id);
if ( iter == m_Chunks.end() ) {
NCBI_THROW(CObjMgrException, eAddDataError,
"invalid chunk id: "+NStr::IntToString(chunk_id));
}
return *iter->second;
}
const CTSE_Chunk_Info& CTSE_Split_Info::GetChunk(TChunkId chunk_id) const
{
TChunks::const_iterator iter = m_Chunks.find(chunk_id);
if ( iter == m_Chunks.end() ) {
NCBI_THROW(CObjMgrException, eAddDataError,
"invalid chunk id: "+NStr::IntToString(chunk_id));
}
return *iter->second;
}
CTSE_Chunk_Info& CTSE_Split_Info::GetSkeletonChunk(void)
{
TChunks::iterator iter = m_Chunks.find(0);
if ( iter != m_Chunks.end() ) {
return *iter->second;
}
CRef<CTSE_Chunk_Info> chunk(new CTSE_Chunk_Info(0));
AddChunk(*chunk);
_ASSERT(chunk == &GetChunk(0));
return *chunk;
}
// split info
void CTSE_Split_Info::x_AddDescInfo(const TDescInfo& info, TChunkId chunk_id)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.AddDescInfo(tse, info, chunk_id);
}
}
void CTSE_Split_Info::x_AddAssemblyInfo(const TAssemblyInfo& info,
TChunkId chunk_id)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.AddAssemblyInfo(tse, info, chunk_id);
}
}
void CTSE_Split_Info::x_AddAnnotPlace(const TPlace& place, TChunkId chunk_id)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.AddAnnotPlace(tse, place, chunk_id);
}
}
void CTSE_Split_Info::x_AddBioseqPlace(TBioseq_setId place_id,
TChunkId chunk_id)
{
if ( place_id == kTSE_Place_id ) {
_ASSERT(m_BioseqChunkId < 0);
_ASSERT(chunk_id >= 0);
m_BioseqChunkId = chunk_id;
}
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.AddBioseqPlace(tse, place_id, chunk_id);
}
}
void CTSE_Split_Info::x_AddSeq_data(const TLocationSet& location,
CTSE_Chunk_Info& chunk)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.AddSeq_data(tse, location, chunk);
}
}
void CTSE_Split_Info::x_SetContainedId(const TBioseqId& id,
TChunkId chunk_id)
{
m_SeqIdToChunksSorted = false;
m_SeqIdToChunks.push_back(pair<CSeq_id_Handle, TChunkId>(id, chunk_id));
}
bool CTSE_Split_Info::x_CanAddBioseq(const TBioseqId& id) const
{
ITERATE ( TTSE_Set, it, m_TSE_Set ) {
if ( it->first->ContainsBioseq(id) ) {
return false;
}
}
return true;
}
// annot index
void CTSE_Split_Info::x_UpdateFeatIdIndex(CSeqFeatData::E_Choice type,
EFeatIdType id_type)
{
NON_CONST_ITERATE ( TChunks, it, m_Chunks ) {
CTSE_Chunk_Info& chunk = *it->second;
if ( !chunk.IsLoaded() && !chunk.m_AnnotIndexEnabled &&
chunk.x_ContainsFeatIds(type, id_type) ) {
x_UpdateAnnotIndex(chunk);
}
}
}
void CTSE_Split_Info::x_UpdateFeatIdIndex(CSeqFeatData::ESubtype subtype,
EFeatIdType id_type)
{
NON_CONST_ITERATE ( TChunks, it, m_Chunks ) {
CTSE_Chunk_Info& chunk = *it->second;
if ( !chunk.IsLoaded() && !chunk.m_AnnotIndexEnabled &&
chunk.x_ContainsFeatIds(subtype, id_type) ) {
x_UpdateAnnotIndex(chunk);
}
}
}
void CTSE_Split_Info::x_UpdateAnnotIndex(void)
{
NON_CONST_ITERATE ( TChunks, it, m_Chunks ) {
x_UpdateAnnotIndex(*it->second);
}
}
void CTSE_Split_Info::x_UpdateAnnotIndex(CTSE_Chunk_Info& chunk)
{
if ( !chunk.IsLoaded() && !chunk.m_AnnotIndexEnabled ) {
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.UpdateAnnotIndex(tse, chunk);
}
chunk.m_AnnotIndexEnabled = true;
}
}
CTSE_Split_Info::TSeqIdToChunks::const_iterator
CTSE_Split_Info::x_FindChunk(const CSeq_id_Handle& id) const
{
if ( !m_SeqIdToChunksSorted ) {
TSeqIdToChunks(m_SeqIdToChunks).swap(m_SeqIdToChunks);
sort(m_SeqIdToChunks.begin(), m_SeqIdToChunks.end());
m_SeqIdToChunksSorted = true;
}
return lower_bound(m_SeqIdToChunks.begin(),
m_SeqIdToChunks.end(),
pair<CSeq_id_Handle, TChunkId>(id, -1));
}
// load requests
void CTSE_Split_Info::x_GetRecords(const CSeq_id_Handle& id, bool bioseq) const
{
vector< CConstRef<CTSE_Chunk_Info> > chunks;
{{
CMutexGuard guard(m_SeqIdToChunksMutex);
for ( TSeqIdToChunks::const_iterator iter = x_FindChunk(id);
iter != m_SeqIdToChunks.end() && iter->first == id; ++iter ) {
const CTSE_Chunk_Info& chunk = GetChunk(iter->second);
if ( !chunk.IsLoaded() ) {
chunks.push_back(ConstRef(&chunk));
}
}
}}
ITERATE ( vector< CConstRef<CTSE_Chunk_Info> >, it, chunks ) {
(*it)->x_GetRecords(id, bioseq);
}
}
void CTSE_Split_Info::GetBioseqsIds(TSeqIds& ids) const
{
ITERATE ( TChunks, it, m_Chunks ) {
it->second->GetBioseqsIds(ids);
}
}
bool CTSE_Split_Info::ContainsBioseq(const CSeq_id_Handle& id) const
{
CMutexGuard guard(m_SeqIdToChunksMutex);
for ( TSeqIdToChunks::const_iterator iter = x_FindChunk(id);
iter != m_SeqIdToChunks.end() && iter->first == id; ++iter ) {
if ( GetChunk(iter->second).ContainsBioseq(id) ) {
return true;
}
}
return false;
}
void CTSE_Split_Info::x_LoadChunk(TChunkId chunk_id) const
{
CPrefetchManager::IsActive();
GetChunk(chunk_id).Load();
}
void CTSE_Split_Info::x_LoadChunks(const TChunkIds& chunk_ids) const
{
if ( CPrefetchManager::IsActive() ) {
ITERATE ( TChunkIds, it, chunk_ids ) {
LoadChunk(*it);
}
return;
}
CTSE_Split_Info& info_nc = const_cast<CTSE_Split_Info&>(*this);
typedef vector< CRef<CTSE_Chunk_Info> > TChunkRefs;
typedef vector< AutoPtr<CInitGuard> > TInitGuards;
TChunkIds sorted_ids = chunk_ids;
sort(sorted_ids.begin(), sorted_ids.end());
sorted_ids.erase(unique(sorted_ids.begin(), sorted_ids.end()),
sorted_ids.end());
TChunkRefs chunks;
chunks.reserve(sorted_ids.size());
TInitGuards guards;
guards.reserve(sorted_ids.size());
// Collect and lock all chunks to be loaded
ITERATE(TChunkIds, id, sorted_ids) {
CRef<CTSE_Chunk_Info> chunk(&info_nc.GetChunk(*id));
AutoPtr<CInitGuard> guard(
new CInitGuard(chunk->m_LoadLock, info_nc.GetMutexPool()));
if ( !(*guard.get()) ) {
continue;
}
chunks.push_back(chunk);
guards.push_back(guard);
}
// Load chunks
info_nc.GetDataLoader().GetChunks(chunks);
}
void CTSE_Split_Info::x_UpdateCore(void)
{
if ( m_BioseqChunkId >= 0 ) {
GetChunk(m_BioseqChunkId).Load();
}
}
// load results
void CTSE_Split_Info::x_LoadDescr(const TPlace& place,
const CSeq_descr& descr)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.LoadDescr(tse, place, descr);
}
}
void CTSE_Split_Info::x_LoadAnnot(const TPlace& place,
const CSeq_annot& annot)
{
CRef<CSeq_annot> add;
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
if ( !add ) {
add.Reset(const_cast<CSeq_annot*>(&annot));
}
else {
CRef<CSeq_annot> tmp(add);
add.Reset(new CSeq_annot);
add->Assign(*tmp);
}
listener.LoadAnnot(tse, place, add);
}
}
void CTSE_Split_Info::x_LoadBioseq(const TPlace& place, const CBioseq& bioseq)
{
CRef<CSeq_entry> add;
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
if ( !add ) {
add = new CSeq_entry;
add->SetSeq(const_cast<CBioseq&>(bioseq));
}
else {
CRef<CSeq_entry> tmp(add);
add.Reset(new CSeq_entry);
add->Assign(*tmp);
}
listener.LoadBioseq(tse, place, add);
}
}
void CTSE_Split_Info::x_LoadSequence(const TPlace& place, TSeqPos pos,
const TSequence& sequence)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.LoadSequence(tse, place, pos, sequence);
}
}
void CTSE_Split_Info::x_LoadAssembly(const TBioseqId& seq_id,
const TAssembly& assembly)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
listener.LoadAssembly(tse, seq_id, assembly);
}
}
void CTSE_Split_Info::x_LoadSeq_entry(CSeq_entry& entry,
CTSE_SetObjectInfo* set_info)
{
CRef<CSeq_entry> add;
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
ITSE_Assigner& listener = *it->second;
if ( !add ) {
add = &entry;
}
else {
add = new CSeq_entry;
add->Assign(entry);
set_info = 0;
}
listener.LoadSeq_entry(tse, *add, set_info);
}
}
void CTSE_Split_Info::x_SetBioseqUpdater(CRef<CBioseqUpdater> updater)
{
NON_CONST_ITERATE ( TTSE_Set, it, m_TSE_Set ) {
CTSE_Info& tse = *it->first;
tse.SetBioseqUpdater(updater);
}
}
END_SCOPE(objects)
END_NCBI_SCOPE
| 27.783304 | 79 | 0.63029 | [
"vector"
] |
d0fe92edab62e13a6acb9195683993e3aeff9196 | 3,310 | cpp | C++ | SU2-Quantum/Common/src/geometry/primal_grid/CHexahedron.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/Common/src/geometry/primal_grid/CHexahedron.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/Common/src/geometry/primal_grid/CHexahedron.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | 1 | 2021-12-03T06:40:08.000Z | 2021-12-03T06:40:08.000Z | /*!
* \file CHexahedron.cpp
* \brief Main classes for defining the primal grid elements
* \author F. Palacios
* \version 7.0.6 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../../../include/geometry/primal_grid/CHexahedron.hpp"
unsigned short CHexahedron::Faces[6][4] = {{0,1,5,4},{1,2,6,5},{2,3,7,6},{3,0,4,7},{0,3,2,1},{4,5,6,7}};
unsigned short CHexahedron::Neighbor_Nodes[8][3] = {{1,3,4},{0,2,5},{1,3,6},{0,2,7},{0,5,7},{4,6,1},{2,5,7},{4,3,6}};
unsigned short CHexahedron::nNodesFace[6] = {4,4,4,4,4,4};
unsigned short CHexahedron::nNeighbor_Nodes[8] = {3,3,3,3,3,3,3,3};
unsigned short CHexahedron::nFaces = 6;
unsigned short CHexahedron::nNodes = 8;
unsigned short CHexahedron::nNeighbor_Elements = 6;
unsigned short CHexahedron::VTK_Type = 12;
unsigned short CHexahedron::maxNodesFace = 4;
CHexahedron::CHexahedron(unsigned long val_point_0, unsigned long val_point_1,
unsigned long val_point_2, unsigned long val_point_3,
unsigned long val_point_4, unsigned long val_point_5,
unsigned long val_point_6, unsigned long val_point_7) : CPrimalGrid() {
unsigned short iDim, iFace, iNeighbor_Elements;
/*--- Allocate center-of-gravity coordinates ---*/
nDim = 3;
Coord_CG = new su2double[nDim];
for (iDim = 0; iDim < nDim; iDim++)
Coord_CG[iDim] = 0.0;
Coord_FaceElems_CG = new su2double* [nFaces];
for (iFace = 0; iFace < nFaces; iFace++) {
Coord_FaceElems_CG[iFace] = new su2double [nDim];
for (iDim = 0; iDim < nDim; iDim++)
Coord_FaceElems_CG[iFace][iDim] = 0.0;
}
/*--- Allocate and define face structure of the element ---*/
Nodes = new unsigned long[nNodes];
Nodes[0] = val_point_0; Nodes[1] = val_point_1;
Nodes[2] = val_point_2; Nodes[3] = val_point_3;
Nodes[4] = val_point_4; Nodes[5] = val_point_5;
Nodes[6] = val_point_6; Nodes[7] = val_point_7;
/*--- Allocate and define neighbor elements to a element ---*/
nNeighbor_Elements = nFaces;
Neighbor_Elements = new long[nNeighbor_Elements];
for (iNeighbor_Elements = 0; iNeighbor_Elements<nNeighbor_Elements; iNeighbor_Elements++) {
Neighbor_Elements[iNeighbor_Elements]=-1;
}
}
CHexahedron::~CHexahedron() {
unsigned short iFaces;
for (iFaces = 0; iFaces < nFaces; iFaces++)
if (Coord_FaceElems_CG[iFaces] != nullptr) delete[] Coord_FaceElems_CG[iFaces];
delete[] Coord_FaceElems_CG;
}
void CHexahedron::Change_Orientation(void) {
swap(Nodes[1], Nodes[3]);
swap(Nodes[5], Nodes[7]);
}
| 34.842105 | 117 | 0.697281 | [
"geometry"
] |
cb9a07b64a09cc47d18bd2e928227de474ff68ad | 1,418 | cpp | C++ | src/measurement.cpp | zzchencn/SpotifyPuzzles | d0304da643935cc4b4952346b4ac6755515e1d8a | [
"Apache-2.0"
] | null | null | null | src/measurement.cpp | zzchencn/SpotifyPuzzles | d0304da643935cc4b4952346b4ac6755515e1d8a | [
"Apache-2.0"
] | null | null | null | src/measurement.cpp | zzchencn/SpotifyPuzzles | d0304da643935cc4b4952346b4ac6755515e1d8a | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <cstring>
#include <string>
using namespace std;
#define pairii pair<int, int>
#define llong long long
#define pb push_back
#define sortall(x) sort((x).begin(), (x).end())
#define INFI numeric_limits<int>::max()
#define INFLL numeric_limits<llong>::max()
#define INFD numeric_limits<double>::max()
#define FOR(i,s,n) for (int (i) = (s); (i) < (n); (i)++)
#define FORZ(i,n) FOR((i),0,(n))
char full[8][10] = {"thou","inch","foot","yard","chain","furlong","mile","league"};
char part[8][10] = {"th","in","ft","yd","ch","fur","mi","lea"};
double coef[8] = {1,1000,12,3,22,10,8,3};
void solve() {
double d;
char a[10],b[10],c[10];
scanf("%lf%s%s%s",&d,a,b,c);
int x,y;
FORZ(i,8) {
if (strcmp(full[i],a)==0 || strcmp(part[i],a)==0) x=i;
if (strcmp(full[i],c)==0 || strcmp(part[i],c)==0) y=i;
}
double f=1.0;
if (x<y) {
for (int i=x+1; i<=y; i++) f*=coef[i];
} else if (x>y) {
for (int i=x; i>=y+1; i--) f/=coef[i];
}
printf("%.12f",d/f);
}
int main() {
#ifdef DEBUG
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
solve();
return 0;
}
| 22.870968 | 83 | 0.594499 | [
"vector"
] |
cb9a2f23013c4adc684bc52d0b0de18dde4b4ba4 | 1,753 | cpp | C++ | Solution/Motor2D/j1Scene.cpp | rleonborras/DialogSystem | 16a0c4db516faf6d6dfa4985e49552b9738371a3 | [
"MIT"
] | null | null | null | Solution/Motor2D/j1Scene.cpp | rleonborras/DialogSystem | 16a0c4db516faf6d6dfa4985e49552b9738371a3 | [
"MIT"
] | null | null | null | Solution/Motor2D/j1Scene.cpp | rleonborras/DialogSystem | 16a0c4db516faf6d6dfa4985e49552b9738371a3 | [
"MIT"
] | null | null | null | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1Fonts.h"
#include "j1Scene.h"
#include "DialogSystem.h"
j1Scene::j1Scene() : j1Module()
{
name.assign("scene");
}
// Destructor
j1Scene::~j1Scene()
{}
// Called before render is available
bool j1Scene::Awake()
{
LOG("Loading Scene");
bool ret = true;
return ret;
}
// Called before the first frame
bool j1Scene::Start()
{
Background = App->tex->Load("textures/Background.png");
Character1 = { 78,0,34,54 };
Character1_Position.x = 320 ;
Character1_Position.y = 320 ;
//TexT_Test = App->fonts->Print("Hello");
Demo_ElementsAndCharacters_tex = App->tex->Load("textures/Demo_Chart.png");
return true;
}
// Called each loop iteration
bool j1Scene::PreUpdate()
{
return true;
}
// Called each loop iteration
bool j1Scene::Update(float dt)
{
int scale = 3;
App->render->Blit(Background, 0, 0, NULL, false);
App->render->Blit(Demo_ElementsAndCharacters_tex, Character1_Position.x, Character1_Position.y, &Character1, 1, scale);
int x, y;
App->input->GetMousePosition(x, y);
if (x > Character1_Position.x&&x<Character1_Position.x + Character1.w*scale && y>Character1_Position.y &&y < Character1_Position.y + Character1.h*scale)
if (App->input->GetMouseButtonDown(KEY_DOWN)) {
//TODO 8 start Your dialog!
App->dialog->StartDialogEvent(App->dialog->dialogA);
}
return true;
}
// Called each loop iteration
bool j1Scene::PostUpdate()
{
bool ret = true;
if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
ret = false;
return ret;
}
// Called before quitting
bool j1Scene::CleanUp()
{
LOG("Freeing scene");
return true;
}
| 19.054348 | 153 | 0.700513 | [
"render"
] |
cb9b834b5eb085147f28544318565d49c64bfaa7 | 4,592 | cpp | C++ | sim/sim.cpp | imichaelmiers/libforwardsec | e552e4a01d1776c9b61414e5f7a6011a68761ad2 | [
"BSD-2-Clause"
] | 56 | 2015-05-19T00:14:17.000Z | 2022-01-15T08:13:13.000Z | sim/sim.cpp | imichaelmiers/libforwardsec | e552e4a01d1776c9b61414e5f7a6011a68761ad2 | [
"BSD-2-Clause"
] | 1 | 2016-04-15T14:04:40.000Z | 2016-04-19T18:46:37.000Z | sim/sim.cpp | imichaelmiers/libforwardsec | e552e4a01d1776c9b61414e5f7a6011a68761ad2 | [
"BSD-2-Clause"
] | 6 | 2015-05-19T13:52:21.000Z | 2019-03-19T06:42:02.000Z | #include <iostream>
#include <vector>
#include <tuple>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include <algorithm> // std::max
#include <iostream>
#include <fstream>
#include "locale"
#include "gmpfse.h"
#include <fstream>
#include "sim.h"
using namespace std;
using namespace forwardsec;
using namespace relicxx;
bytes testVector = {{0x3a, 0x5d, 0x7a, 0x42, 0x44, 0xd3, 0xd8, 0xaf, 0xf5, 0xf3, 0xf1, 0x87, 0x81, 0x82, 0xb2,
0x53, 0x57, 0x30, 0x59, 0x75, 0x8d, 0xe6, 0x18, 0x17, 0x14, 0xdf, 0xa5, 0xa4, 0x0b,0x43,0xAD,0xBC}};
std::vector<string>makeTags(unsigned int n,unsigned int startintag){
std::vector<string> tags(n);
for(unsigned int i=0;i<n;i++){
tags[i] = "tag"+std::to_string(startintag+i);
}
return tags;
}
void sim(){
unsigned int windowsize;
unsigned int depth;
unsigned int numtags;
unsigned int iterations;
string dbgstr;
std::cin >> windowsize >> depth >> numtags >> iterations >> dbgstr;
// cerr << "window size: " << windowsize << " depth: " << depth << " numtags: "
// << numtags << " iterations: " << iterations << endl;
CPUTimeAndAvg dec,punc,derive;
GMPfse test(depth,numtags);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
bytes msg = {{0x3a, 0x5d, 0x7a, 0x42, 0x44, 0xd3, 0xd8, 0xaf, 0xf5, 0xf3, 0xf1, 0x87, 0x81, 0x82, 0xb2,
0x53, 0x57, 0x30, 0x59, 0x75, 0x8d, 0xe6, 0x18, 0x17, 0x14, 0xdf, 0xa5, 0xa4, 0x0b,0x43,0xAD,0xBC}};
int previnterval=0;
int msg_interval=0;
int tagctr = 42;
unsigned int skSize = 0;
unsigned int clockticks = 0;
int exceptionctr=0;
while(std::cin >> msg_interval){
tagctr++;
if(tagctr%10 == 0){
cout << "." << endl;
}
if(msg_interval>previnterval ){
//cerr << ".";
clockticks++;
stringstream ss;
{
cereal::PortableBinaryOutputArchive oarchive(ss);
oarchive(sk);
}
skSize = std::max<int>(skSize,(unsigned int)ss.tellp());
if(clockticks>windowsize){
for(unsigned int toDelete = clockticks - windowsize;toDelete<clockticks;toDelete++){
if(!sk.hasKey(toDelete)){
continue;
}
if(sk.needsChildKeys(toDelete)){
derive.start();
test.prepareIntervalAfter(pk,sk,toDelete);
derive.stop();
derive.reg();
}
sk.erase(toDelete);
}
}
}
previnterval = msg_interval;
auto tags = makeTags(numtags,tagctr);
GMPfseCiphertext ct = test.encrypt(pk,msg,msg_interval,tags);
if(!sk.hasKey(msg_interval)){
GMPfsePrivateKey skcpy;
try{
for(unsigned int i =0;i<iterations;i++){
skcpy = sk;
derive.start();
test.deriveKeyFor(pk,skcpy,msg_interval);
derive.stop();
derive.reg();
}
sk=skcpy;
} catch (std::invalid_argument e) {
exceptionctr++;
derive.reset();
string what = e.what();
ofstream errorfile;
errorfile.open("error_der_"+dbgstr,ios::binary|ios::out);
{
cereal::PortableBinaryOutputArchive oarchive(errorfile);
oarchive(what,msg_interval,pk,skcpy,ct);
cerr << "Exception during keyder on msg_interval" << msg_interval << " " <<what << endl;
}
errorfile.close();
continue;
}
}
try{
for(unsigned int i =0;i<iterations;i++){
dec.start();
bytes result = test.decrypt(pk,sk,ct);
dec.stop();
dec.reg();
}
} catch (std::invalid_argument e) {
exceptionctr++;
dec.reset();
string what = e.what();
ofstream errorfile;
errorfile.open("error_der_"+dbgstr,ios::binary|ios::out);
{
cereal::PortableBinaryOutputArchive oarchive(errorfile);
oarchive(what,msg_interval,pk,sk,ct);
cerr << "Exception during decrypt for interval " << msg_interval << " " << what << endl;
}
errorfile.close();
continue;
}
for(auto t: tags){
GMPfsePrivateKey skcpy;
for(unsigned int i =0;i<iterations;i++){
skcpy=sk;
if(skcpy.needsChildKeys(msg_interval)){
derive.start();
test.prepareIntervalAfter(pk,skcpy,msg_interval);
derive.stop();
derive.reg();
}
punc.start();
test.puncture(pk,skcpy,msg_interval,t);
punc.stop();
punc.reg();
}
sk=skcpy;
}
}
cerr << endl;
cout << "DeriveTime\n\t" << derive << endl;
cout << "DecTime\n\t" << dec << endl;
cout << "PunTime\n\t" << punc << endl;
cout << "MaxSize\t" << skSize << endl;
}
int main(){
relicResourceHandle h;
sim();
}
| 27.830303 | 110 | 0.611716 | [
"vector"
] |
cba00cf0a51df5f2b87d0c8932c3d68c3009101d | 2,967 | cpp | C++ | tsp.cpp | pantadeusz/simple-tsp | 696b7d396f516ba130250ba8d0d2568e1156516d | [
"MIT"
] | null | null | null | tsp.cpp | pantadeusz/simple-tsp | 696b7d396f516ba130250ba8d0d2568e1156516d | [
"MIT"
] | null | null | null | tsp.cpp | pantadeusz/simple-tsp | 696b7d396f516ba130250ba8d0d2568e1156516d | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <array>
#include <cmath>
namespace alo_tsp {
/**
* solucion contains vector of id-s of vertices to visit
* */
using solution_t = std::vector<int>;
/**
* coordinate
* */
class coordinate_t : public std::array<double,2> {};
using problem_t = std::vector<coordinate_t>;
using problem_with_solution_t = std::pair <problem_t, solution_t>;
double evaluate_tsp(const problem_with_solution_t pws);
solution_t tsp(const problem_t cities);
/**
* helper operator that calculates difference between two points
* */
coordinate_t operator-(const coordinate_t a, const coordinate_t b) {
auto ret = a;
for (size_t i = 0; i < b.size(); i++) ret[i] -= b[i];
return std::move(ret);
}
/**
* Calculate vector length
* */
double operator~(const coordinate_t a) {
return //std::sqrt(
std::accumulate(a.begin(), a.end(), 0.0, [](double s, auto e) {return s + e*e;})
//)
;
}
/**
* compare two solutions - are they identical?
* */
bool operator==(const solution_t &a, const solution_t &b) {
for (int i = 0; i < std::min(a.size(),b.size()); i++) if (a[i] != b[i]) return false;
return a.size() == b.size();
}
std::ostream &operator<<(std::ostream &o, const solution_t &s) {
using namespace std;
o << "[ ";
for (auto e : s) o << e << " ";
o << "]";
return o;
}
std::ostream &operator<<(std::ostream&o, const coordinate_t &c) {
using namespace std;
o << "[ ";
for (auto e : c) o << e << " ";
o << "]";
return o;
}
std::ostream &operator<<(std::ostream&o, const problem_with_solution_t &s) {
using namespace std;
o << evaluate_tsp(s) << "::[ ";
for (auto e : s.second) o << "{ #" << e << " : " << s.first[e] << "} ";
o << "]";
return o;
}
/**
* calculate how long is the path.
*
* do not go back.
*
* */
double evaluate_tsp(const problem_with_solution_t pws) {
using namespace std;
double dist = 0.0;
auto &[problem, solution] = pws;
for (size_t i = 0; i < solution.size(); i++) {
dist += ~(problem[solution[(i+1) % solution.size()]]-problem[solution[i]]);
}
return dist;
}
auto create_sol_sequence_vector = [](auto &cities){solution_t r; for (auto &c:cities) r.push_back(r.size()); return r;};
/**
* Brute force algorithm to calculate TSP
* */
solution_t tsp_brute_force(const problem_t cities) {
solution_t current,best;
// create vector of values 0, 1, 2, 3, ... based on argument
current = best = create_sol_sequence_vector(cities);
do if (evaluate_tsp({cities,current}) < evaluate_tsp({cities,best})) best = current;
while ( std::next_permutation(current.begin(),current.end()) );
return best;
}
} // namespace tsp
int main() {
using namespace alo_tsp;
problem_t problem = {
{-1, -1},
{0,-1}, {1, -1},
{-1, 1}, {0, 1},
{1, 1},
{-1, 0},{-1, 0}, {1, 0},
};
problem_with_solution_t pwsolution = {problem, tsp_brute_force(problem)};
std::cout << pwsolution << std::endl;
return 0;
}
| 24.121951 | 120 | 0.625548 | [
"vector"
] |
cba0e9dc3276b96194ad55d631ba2613563242f2 | 38,602 | cpp | C++ | msdf-atlas-gen/main.cpp | smolck/msdf-atlas-gen | 0f8d503803654d5c7c4ea2d58d4d7edda8705611 | [
"MIT"
] | null | null | null | msdf-atlas-gen/main.cpp | smolck/msdf-atlas-gen | 0f8d503803654d5c7c4ea2d58d4d7edda8705611 | [
"MIT"
] | null | null | null | msdf-atlas-gen/main.cpp | smolck/msdf-atlas-gen | 0f8d503803654d5c7c4ea2d58d4d7edda8705611 | [
"MIT"
] | null | null | null |
/*
* MULTI-CHANNEL SIGNED DISTANCE FIELD ATLAS GENERATOR v1.2 (2021-05-29) -
* standalone console program
* --------------------------------------------------------------------------------------------------
* A utility by Viktor Chlumsky, (c) 2020 - 2021
*
*/
#define _USE_MATH_DEFINES
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <thread>
#include <vector>
#include "msdf-atlas-gen.h"
using namespace msdf_atlas;
#define DEFAULT_ANGLE_THRESHOLD 3.0
#define DEFAULT_MITER_LIMIT 1.0
#define DEFAULT_PIXEL_RANGE 2.0
#define SDF_ERROR_ESTIMATE_PRECISION 19
#define GLYPH_FILL_RULE msdfgen::FILL_NONZERO
#define LCG_MULTIPLIER 6364136223846793005ull
#define LCG_INCREMENT 1442695040888963407ull
#ifdef MSDFGEN_USE_SKIA
#define TITLE_SUFFIX " & Skia"
#define EXTRA_UNDERLINE "-------"
#else
#define TITLE_SUFFIX
#define EXTRA_UNDERLINE
#endif
static const char *const helpText =
R"(
MSDF Atlas Generator by Viktor Chlumsky v)" MSDF_ATLAS_VERSION
R"( (with MSDFGEN v)" MSDFGEN_VERSION TITLE_SUFFIX R"()
----------------------------------------------------------------)" EXTRA_UNDERLINE
R"(
INPUT SPECIFICATION
-font <filename.ttf/otf>
Specifies the input TrueType / OpenType font file. This is required.
-charset <filename>
Specifies the input character set. Refer to the documentation for format of charset specification. Defaults to ASCII.
-glyphset <filename>
Specifies the set of input glyphs as glyph indices within the font file.
-fontscale <scale>
Specifies the scale to be applied to the glyph geometry of the font.
-fontname <name>
Specifies a name for the font that will be propagated into the output files as metadata.
-and
Separates multiple inputs to be combined into a single atlas.
ATLAS CONFIGURATION
-type <hardmask / softmask / sdf / psdf / msdf / mtsdf>
Selects the type of atlas to be generated.
-format <png / bmp / tiff / text / textfloat / bin / binfloat / binfloatbe>
Selects the format for the atlas image output. Some image formats may be incompatible with embedded output formats.
-dimensions <width> <height>
Sets the atlas to have fixed dimensions (width x height).
-pots / -potr / -square / -square2 / -square4
Picks the minimum atlas dimensions that fit all glyphs and satisfy the selected constraint:
power of two square / ... rectangle / any square / square with side divisible by 2 / ... 4
-yorigin <bottom / top>
Determines whether the Y-axis is oriented upwards (bottom origin, default) or downwards (top origin).
OUTPUT SPECIFICATION - one or more can be specified
-imageout <filename.*>
Saves the atlas as an image file with the specified format. Layout data must be stored separately.
-json <filename.json>
Writes the atlas's layout data, as well as other metrics into a structured JSON file.
GLYPH CONFIGURATION
-size <EM size>
Specifies the size of the glyphs in the atlas bitmap in pixels per EM.
-minsize <EM size>
Specifies the minimum size. The largest possible size that fits the same atlas dimensions will be used.
-emrange <EM range>
Specifies the SDF distance range in EM's.
-pxrange <pixel range>
Specifies the SDF distance range in output pixels. The default value is 2.
-nokerning
Disables inclusion of kerning pair table in output files.
DISTANCE FIELD GENERATOR SETTINGS
-angle <angle>
Specifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees. (msdf / mtsdf only)
-coloringstrategy <simple / inktrap / distance>
Selects the strategy of the edge coloring heuristic.
-errorcorrection <mode>
Changes the MSDF/MTSDF error correction mode. Use -errorcorrection help for a list of valid modes.
-errordeviationratio <ratio>
Sets the minimum ratio between the actual and maximum expected distance delta to be considered an error.
-errorimproveratio <ratio>
Sets the minimum ratio between the pre-correction distance error and the post-correction distance error.
-miterlimit <value>
Sets the miter limit that limits the extension of each glyph's bounding box due to very sharp corners. (psdf / msdf / mtsdf only))"
#ifdef MSDFGEN_USE_SKIA
R"(
-overlap
Switches to distance field generator with support for overlapping contours.
-nopreprocess
Disables path preprocessing which resolves self-intersections and overlapping contours.
-scanline
Performs an additional scanline pass to fix the signs of the distances.)"
#else
R"(
-nooverlap
Disables resolution of overlapping contours.
-noscanline
Disables the scanline pass, which corrects the distance field's signs according to the non-zero fill rule.)"
#endif
R"(
-seed <N>
Sets the initial seed for the edge coloring heuristic.
-threads <N>
Sets the number of threads for the parallel computation. (0 = auto)
)";
static const char *errorCorrectionHelpText = R"(
ERROR CORRECTION MODES
auto-fast
Detects inversion artifacts and distance errors that do not affect edges by range testing.
auto-full
Detects inversion artifacts and distance errors that do not affect edges by exact distance evaluation.
auto-mixed (default)
Detects inversions by distance evaluation and distance errors that do not affect edges by range testing.
disabled
Disables error correction.
distance-fast
Detects distance errors by range testing. Does not care if edges and corners are affected.
distance-full
Detects distance errors by exact distance evaluation. Does not care if edges and corners are affected, slow.
edge-fast
Detects inversion artifacts only by range testing.
edge-full
Detects inversion artifacts only by exact distance evaluation.
help
Displays this help.
)";
std::vector<unicode_t> getAsciiCharset() {
std::vector<unicode_t> charset;
charset.reserve(0x7f - 0x20); // TODO(smolck)
for (unicode_t cp = 0x20; cp < 0x7f; ++cp)
charset.push_back(cp);
return charset;
}
std::vector<char> readCharsetFromFile(const std::string &filename) {
// https://stackoverflow.com/a/195350 and https://stackoverflow.com/a/20053022
std::ifstream in(filename);
std::vector<char> contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
return contents;
}
static char toupper(char c) { return c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; }
static bool parseUnsigned(unsigned &value, const char *arg) {
static char c;
return sscanf(arg, "%u%c", &value, &c) == 1;
}
static bool parseUnsignedLL(unsigned long long &value, const char *arg) {
static char c;
return sscanf(arg, "%llu%c", &value, &c) == 1;
}
static bool parseDouble(double &value, const char *arg) {
static char c;
return sscanf(arg, "%lf%c", &value, &c) == 1;
}
static bool parseAngle(double &value, const char *arg) {
char c1, c2;
int result = sscanf(arg, "%lf%c%c", &value, &c1, &c2);
if (result == 1)
return true;
if (result == 2 && (c1 == 'd' || c1 == 'D')) {
value *= M_PI / 180;
return true;
}
return false;
}
static bool cmpExtension(const char *path, const char *ext) {
for (const char *a = path + strlen(path) - 1, *b = ext + strlen(ext) - 1;
b >= ext; --a, --b)
if (a < path || toupper(*a) != toupper(*b))
return false;
return true;
}
struct FontInput {
const char *fontFilename;
GlyphIdentifierType glyphIdentifierType;
const char *charsetFilename;
double fontScale;
const char *fontName;
};
struct Configuration {
ImageType imageType;
ImageFormat imageFormat;
YDirection yDirection;
int width, height;
double emSize;
double pxRange;
double angleThreshold;
double miterLimit;
void (*edgeColoring)(msdfgen::Shape &, double, unsigned long long);
bool expensiveColoring;
unsigned long long coloringSeed;
GeneratorAttributes generatorAttributes;
bool preprocessGeometry;
bool kerning;
int threadCount;
const char *imageFilename;
const char *jsonFilename;
};
template <typename T, typename S, int N, GeneratorFunction<S, N> GEN_FN>
static bool makeAtlas(const std::vector<GlyphGeometry> &glyphs,
const std::vector<FontGeometry> &fonts,
const Configuration &config) {
ImmediateAtlasGenerator<S, N, GEN_FN, BitmapAtlasStorage<T, N>> generator(
config.width, config.height);
generator.setAttributes(config.generatorAttributes);
generator.setThreadCount(config.threadCount);
generator.generate(glyphs.data(), glyphs.size());
msdfgen::BitmapConstRef<T, N> bitmap =
(msdfgen::BitmapConstRef<T, N>)generator.atlasStorage();
bool success = true;
if (config.imageFilename) {
if (saveImage(bitmap, config.imageFormat, config.imageFilename,
config.yDirection))
puts("Atlas image file saved.");
else {
success = false;
puts("Failed to save the atlas as an image file.");
}
}
return success;
}
int main(int argc, const char *const *argv) {
#define ABORT(msg) \
{ \
puts(msg); \
return 1; \
}
int result = 0;
std::vector<FontInput> fontInputs;
FontInput fontInput = {};
Configuration config = {};
fontInput.glyphIdentifierType = GlyphIdentifierType::UNICODE_CODEPOINT;
fontInput.fontScale = -1;
config.imageType = ImageType::MSDF;
config.imageFormat = ImageFormat::UNSPECIFIED;
config.yDirection = YDirection::BOTTOM_UP;
config.edgeColoring = msdfgen::edgeColoringInkTrap;
config.kerning = true;
const char *imageFormatName = nullptr;
int fixedWidth = -1, fixedHeight = -1;
config.preprocessGeometry = (
#ifdef MSDFGEN_USE_SKIA
true
#else
false
#endif
);
config.generatorAttributes.config.overlapSupport = !config.preprocessGeometry;
config.generatorAttributes.scanlinePass = !config.preprocessGeometry;
double minEmSize = 0;
enum {
/// Range specified in EMs
RANGE_EM,
/// Range specified in output pixels
RANGE_PIXEL,
} rangeMode = RANGE_PIXEL;
double rangeValue = 0;
TightAtlasPacker::DimensionsConstraint atlasSizeConstraint =
TightAtlasPacker::DimensionsConstraint::MULTIPLE_OF_FOUR_SQUARE;
config.angleThreshold = DEFAULT_ANGLE_THRESHOLD;
config.miterLimit = DEFAULT_MITER_LIMIT;
config.threadCount = 0;
// Parse command line
int argPos = 1;
bool suggestHelp = false;
bool explicitErrorCorrectionMode = false;
while (argPos < argc) {
const char *arg = argv[argPos];
#define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos + (p) < argc)
ARG_CASE("-type", 1) {
arg = argv[++argPos];
if (!strcmp(arg, "hardmask"))
config.imageType = ImageType::HARD_MASK;
else if (!strcmp(arg, "softmask"))
config.imageType = ImageType::SOFT_MASK;
else if (!strcmp(arg, "sdf"))
config.imageType = ImageType::SDF;
else if (!strcmp(arg, "psdf"))
config.imageType = ImageType::PSDF;
else if (!strcmp(arg, "msdf"))
config.imageType = ImageType::MSDF;
else if (!strcmp(arg, "mtsdf"))
config.imageType = ImageType::MTSDF;
else
ABORT("Invalid atlas type. Valid types are: hardmask, softmask, sdf, "
"psdf, msdf, mtsdf");
++argPos;
continue;
}
ARG_CASE("-format", 1) {
arg = argv[++argPos];
if (!strcmp(arg, "png"))
config.imageFormat = ImageFormat::PNG;
else if (!strcmp(arg, "bmp"))
config.imageFormat = ImageFormat::BMP;
else if (!strcmp(arg, "tiff"))
config.imageFormat = ImageFormat::TIFF;
else if (!strcmp(arg, "text"))
config.imageFormat = ImageFormat::TEXT;
else if (!strcmp(arg, "textfloat"))
config.imageFormat = ImageFormat::TEXT_FLOAT;
else if (!strcmp(arg, "bin"))
config.imageFormat = ImageFormat::BINARY;
else if (!strcmp(arg, "binfloat"))
config.imageFormat = ImageFormat::BINARY_FLOAT;
else if (!strcmp(arg, "binfloatbe"))
config.imageFormat = ImageFormat::BINARY_FLOAT_BE;
else
ABORT("Invalid image format. Valid formats are: png, bmp, tiff, text, "
"textfloat, bin, binfloat");
imageFormatName = arg;
++argPos;
continue;
}
ARG_CASE("-font", 1) {
fontInput.fontFilename = argv[++argPos];
++argPos;
continue;
}
ARG_CASE("-charset", 1) {
fontInput.charsetFilename = argv[++argPos];
fontInput.glyphIdentifierType = GlyphIdentifierType::UNICODE_CODEPOINT;
++argPos;
continue;
}
ARG_CASE("-glyphset", 1) {
fontInput.charsetFilename = argv[++argPos];
fontInput.glyphIdentifierType = GlyphIdentifierType::GLYPH_INDEX;
++argPos;
continue;
}
ARG_CASE("-fontscale", 1) {
double fs;
if (!(parseDouble(fs, argv[++argPos]) && fs > 0))
ABORT("Invalid font scale argument. Use -fontscale <font scale> with a "
"positive real number.");
fontInput.fontScale = fs;
++argPos;
continue;
}
ARG_CASE("-fontname", 1) {
fontInput.fontName = argv[++argPos];
++argPos;
continue;
}
ARG_CASE("-and", 0) {
if (!fontInput.fontFilename && !fontInput.charsetFilename &&
fontInput.fontScale < 0)
ABORT("No font, character set, or font scale specified before -and "
"separator.");
if (!fontInputs.empty() &&
!memcmp(&fontInputs.back(), &fontInput, sizeof(FontInput)))
ABORT(
"No changes between subsequent inputs. A different font, character "
"set, or font scale must be set inbetween -and separators.");
fontInputs.push_back(fontInput);
fontInput.fontName = nullptr;
++argPos;
continue;
}
ARG_CASE("-imageout", 1) {
config.imageFilename = argv[++argPos];
++argPos;
continue;
}
ARG_CASE("-json", 1) {
config.jsonFilename = argv[++argPos];
++argPos;
continue;
}
ARG_CASE("-dimensions", 2) {
unsigned w, h;
if (!(parseUnsigned(w, argv[argPos + 1]) &&
parseUnsigned(h, argv[argPos + 2]) && w && h))
ABORT("Invalid atlas dimensions. Use -dimensions <width> <height> with "
"two positive integers.");
fixedWidth = w, fixedHeight = h;
argPos += 3;
continue;
}
ARG_CASE("-pots", 0) {
atlasSizeConstraint =
TightAtlasPacker::DimensionsConstraint::POWER_OF_TWO_SQUARE;
fixedWidth = -1, fixedHeight = -1;
++argPos;
continue;
}
ARG_CASE("-potr", 0) {
atlasSizeConstraint =
TightAtlasPacker::DimensionsConstraint::POWER_OF_TWO_RECTANGLE;
fixedWidth = -1, fixedHeight = -1;
++argPos;
continue;
}
ARG_CASE("-square", 0) {
atlasSizeConstraint = TightAtlasPacker::DimensionsConstraint::SQUARE;
fixedWidth = -1, fixedHeight = -1;
++argPos;
continue;
}
ARG_CASE("-square2", 0) {
atlasSizeConstraint = TightAtlasPacker::DimensionsConstraint::EVEN_SQUARE;
fixedWidth = -1, fixedHeight = -1;
++argPos;
continue;
}
ARG_CASE("-square4", 0) {
atlasSizeConstraint =
TightAtlasPacker::DimensionsConstraint::MULTIPLE_OF_FOUR_SQUARE;
fixedWidth = -1, fixedHeight = -1;
++argPos;
continue;
}
ARG_CASE("-yorigin", 1) {
arg = argv[++argPos];
if (!strcmp(arg, "bottom"))
config.yDirection = YDirection::BOTTOM_UP;
else if (!strcmp(arg, "top"))
config.yDirection = YDirection::TOP_DOWN;
else
ABORT("Invalid Y-axis origin. Use bottom or top.");
++argPos;
continue;
}
ARG_CASE("-size", 1) {
double s;
if (!(parseDouble(s, argv[++argPos]) && s > 0))
ABORT("Invalid EM size argument. Use -size <EM size> with a positive "
"real number.");
config.emSize = s;
++argPos;
continue;
}
ARG_CASE("-minsize", 1) {
double s;
if (!(parseDouble(s, argv[++argPos]) && s > 0))
ABORT("Invalid minimum EM size argument. Use -minsize <EM size> with a "
"positive real number.");
minEmSize = s;
++argPos;
continue;
}
ARG_CASE("-emrange", 1) {
double r;
if (!(parseDouble(r, argv[++argPos]) && r >= 0))
ABORT("Invalid range argument. Use -emrange <EM range> with a positive "
"real number.");
rangeMode = RANGE_EM;
rangeValue = r;
++argPos;
continue;
}
ARG_CASE("-pxrange", 1) {
double r;
if (!(parseDouble(r, argv[++argPos]) && r >= 0))
ABORT("Invalid range argument. Use -pxrange <pixel range> with a "
"positive real number.");
rangeMode = RANGE_PIXEL;
rangeValue = r;
++argPos;
continue;
}
ARG_CASE("-angle", 1) {
double at;
if (!parseAngle(at, argv[argPos + 1]))
ABORT("Invalid angle threshold. Use -angle <min angle> with a positive "
"real number less than PI or a value in degrees followed by 'd' "
"below 180d.");
config.angleThreshold = at;
argPos += 2;
continue;
}
ARG_CASE("-errorcorrection", 1) {
msdfgen::ErrorCorrectionConfig &ec =
config.generatorAttributes.config.errorCorrection;
if (!strcmp(argv[argPos + 1], "disabled") ||
!strcmp(argv[argPos + 1], "0") || !strcmp(argv[argPos + 1], "none")) {
ec.mode = msdfgen::ErrorCorrectionConfig::DISABLED;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (!strcmp(argv[argPos + 1], "default") ||
!strcmp(argv[argPos + 1], "auto") ||
!strcmp(argv[argPos + 1], "auto-mixed") ||
!strcmp(argv[argPos + 1], "mixed")) {
ec.mode = msdfgen::ErrorCorrectionConfig::EDGE_PRIORITY;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE;
} else if (!strcmp(argv[argPos + 1], "auto-fast") ||
!strcmp(argv[argPos + 1], "fast")) {
ec.mode = msdfgen::ErrorCorrectionConfig::EDGE_PRIORITY;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (!strcmp(argv[argPos + 1], "auto-full") ||
!strcmp(argv[argPos + 1], "full")) {
ec.mode = msdfgen::ErrorCorrectionConfig::EDGE_PRIORITY;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
} else if (!strcmp(argv[argPos + 1], "distance") ||
!strcmp(argv[argPos + 1], "distance-fast") ||
!strcmp(argv[argPos + 1], "indiscriminate") ||
!strcmp(argv[argPos + 1], "indiscriminate-fast")) {
ec.mode = msdfgen::ErrorCorrectionConfig::INDISCRIMINATE;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (!strcmp(argv[argPos + 1], "distance-full") ||
!strcmp(argv[argPos + 1], "indiscriminate-full")) {
ec.mode = msdfgen::ErrorCorrectionConfig::INDISCRIMINATE;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
} else if (!strcmp(argv[argPos + 1], "edge-fast")) {
ec.mode = msdfgen::ErrorCorrectionConfig::EDGE_ONLY;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (!strcmp(argv[argPos + 1], "edge") ||
!strcmp(argv[argPos + 1], "edge-full")) {
ec.mode = msdfgen::ErrorCorrectionConfig::EDGE_ONLY;
ec.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
} else if (!strcmp(argv[argPos + 1], "help")) {
puts(errorCorrectionHelpText);
return 0;
} else
ABORT("Unknown error correction mode. Use -errorcorrection help for "
"more information.");
explicitErrorCorrectionMode = true;
argPos += 2;
continue;
}
ARG_CASE("-errordeviationratio", 1) {
double edr;
if (!(parseDouble(edr, argv[argPos + 1]) && edr > 0))
ABORT("Invalid error deviation ratio. Use -errordeviationratio <ratio> "
"with a positive real number.");
config.generatorAttributes.config.errorCorrection.minDeviationRatio = edr;
argPos += 2;
continue;
}
ARG_CASE("-errorimproveratio", 1) {
double eir;
if (!(parseDouble(eir, argv[argPos + 1]) && eir > 0))
ABORT("Invalid error improvement ratio. Use -errorimproveratio <ratio> "
"with a positive real number.");
config.generatorAttributes.config.errorCorrection.minImproveRatio = eir;
argPos += 2;
continue;
}
ARG_CASE("-coloringstrategy", 1) {
if (!strcmp(argv[argPos + 1], "simple"))
config.edgeColoring = msdfgen::edgeColoringSimple,
config.expensiveColoring = false;
else if (!strcmp(argv[argPos + 1], "inktrap"))
config.edgeColoring = msdfgen::edgeColoringInkTrap,
config.expensiveColoring = false;
else if (!strcmp(argv[argPos + 1], "distance"))
config.edgeColoring = msdfgen::edgeColoringByDistance,
config.expensiveColoring = true;
else
puts("Unknown coloring strategy specified.");
argPos += 2;
continue;
}
ARG_CASE("-miterlimit", 1) {
double m;
if (!(parseDouble(m, argv[++argPos]) && m >= 0))
ABORT("Invalid miter limit argument. Use -miterlimit <limit> with a "
"positive real number.");
config.miterLimit = m;
++argPos;
continue;
}
ARG_CASE("-nokerning", 0) {
config.kerning = false;
++argPos;
continue;
}
ARG_CASE("-kerning", 0) {
config.kerning = true;
++argPos;
continue;
}
ARG_CASE("-nopreprocess", 0) {
config.preprocessGeometry = false;
++argPos;
continue;
}
ARG_CASE("-preprocess", 0) {
config.preprocessGeometry = true;
++argPos;
continue;
}
ARG_CASE("-nooverlap", 0) {
config.generatorAttributes.config.overlapSupport = false;
++argPos;
continue;
}
ARG_CASE("-overlap", 0) {
config.generatorAttributes.config.overlapSupport = true;
++argPos;
continue;
}
ARG_CASE("-noscanline", 0) {
config.generatorAttributes.scanlinePass = false;
++argPos;
continue;
}
ARG_CASE("-scanline", 0) {
config.generatorAttributes.scanlinePass = true;
++argPos;
continue;
}
ARG_CASE("-seed", 1) {
if (!parseUnsignedLL(config.coloringSeed, argv[argPos + 1]))
ABORT(
"Invalid seed. Use -seed <N> with N being a non-negative integer.");
argPos += 2;
continue;
}
ARG_CASE("-threads", 1) {
unsigned tc;
if (!parseUnsigned(tc, argv[argPos + 1]) || (int)tc < 0)
ABORT("Invalid thread count. Use -threads <N> with N being a "
"non-negative integer.");
config.threadCount = (int)tc;
argPos += 2;
continue;
}
ARG_CASE("-help", 0) {
puts(helpText);
return 0;
}
printf("Unknown setting or insufficient parameters: %s\n", arg);
suggestHelp = true;
++argPos;
}
if (suggestHelp)
printf("Use -help for more information.\n");
// Nothing to do?
if (argc == 1) {
printf("Usage: msdf-atlas-gen"
#ifdef _WIN32
".exe"
#endif
" -font <filename.ttf/otf> -charset <charset> <output "
"specification> <options>\n"
"Use -help for more information.\n");
return 0;
}
if (!fontInput.fontFilename)
ABORT("No font specified.");
if (!(config.imageFilename || config.jsonFilename)) {
puts("No output specified.");
return 0;
}
bool layoutOnly = !config.imageFilename;
// Finalize font inputs
const FontInput *nextFontInput = &fontInput;
for (std::vector<FontInput>::reverse_iterator it = fontInputs.rbegin();
it != fontInputs.rend(); ++it) {
if (!it->fontFilename && nextFontInput->fontFilename)
it->fontFilename = nextFontInput->fontFilename;
if (!it->charsetFilename && nextFontInput->charsetFilename) {
it->charsetFilename = nextFontInput->charsetFilename;
it->glyphIdentifierType = nextFontInput->glyphIdentifierType;
}
if (it->fontScale < 0 && nextFontInput->fontScale >= 0)
it->fontScale = nextFontInput->fontScale;
nextFontInput = &*it;
}
if (fontInputs.empty() ||
memcmp(&fontInputs.back(), &fontInput, sizeof(FontInput)))
fontInputs.push_back(fontInput);
// Fix up configuration based on related values
if (!(config.imageType == ImageType::PSDF ||
config.imageType == ImageType::MSDF ||
config.imageType == ImageType::MTSDF))
config.miterLimit = 0;
if (config.emSize > minEmSize)
minEmSize = config.emSize;
if (!(fixedWidth > 0 && fixedHeight > 0) && !(minEmSize > 0)) {
puts("Neither atlas size nor glyph size selected, using default...");
minEmSize = MSDF_ATLAS_DEFAULT_EM_SIZE;
}
if (!(config.imageType == ImageType::SDF ||
config.imageType == ImageType::PSDF ||
config.imageType == ImageType::MSDF ||
config.imageType == ImageType::MTSDF)) {
rangeMode = RANGE_PIXEL;
rangeValue = (double)(config.imageType == ImageType::SOFT_MASK);
} else if (rangeValue <= 0) {
rangeMode = RANGE_PIXEL;
rangeValue = DEFAULT_PIXEL_RANGE;
}
if (config.kerning && !config.jsonFilename)
config.kerning = false;
if (config.threadCount <= 0)
config.threadCount = std::max((int)std::thread::hardware_concurrency(), 1);
if (config.generatorAttributes.scanlinePass) {
if (explicitErrorCorrectionMode &&
config.generatorAttributes.config.errorCorrection.distanceCheckMode !=
msdfgen::ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE) {
const char *fallbackModeName = "unknown";
switch (config.generatorAttributes.config.errorCorrection.mode) {
case msdfgen::ErrorCorrectionConfig::DISABLED:
fallbackModeName = "disabled";
break;
case msdfgen::ErrorCorrectionConfig::INDISCRIMINATE:
fallbackModeName = "distance-fast";
break;
case msdfgen::ErrorCorrectionConfig::EDGE_PRIORITY:
fallbackModeName = "auto-fast";
break;
case msdfgen::ErrorCorrectionConfig::EDGE_ONLY:
fallbackModeName = "edge-fast";
break;
}
printf("Selected error correction mode not compatible with scanline "
"mode, falling back to %s.\n",
fallbackModeName);
}
config.generatorAttributes.config.errorCorrection.distanceCheckMode =
msdfgen::ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
}
// Finalize image format
ImageFormat imageExtension = ImageFormat::UNSPECIFIED;
if (config.imageFilename) {
if (cmpExtension(config.imageFilename, ".png"))
imageExtension = ImageFormat::PNG;
else if (cmpExtension(config.imageFilename, ".bmp"))
imageExtension = ImageFormat::BMP;
else if (cmpExtension(config.imageFilename, ".tif") ||
cmpExtension(config.imageFilename, ".tiff"))
imageExtension = ImageFormat::TIFF;
else if (cmpExtension(config.imageFilename, ".txt"))
imageExtension = ImageFormat::TEXT;
else if (cmpExtension(config.imageFilename, ".bin"))
imageExtension = ImageFormat::BINARY;
}
if (config.imageFormat == ImageFormat::UNSPECIFIED) {
config.imageFormat = ImageFormat::PNG;
imageFormatName = "png";
// If image format is not specified and -imageout is the only image output,
// infer format from its extension
if (imageExtension != ImageFormat::UNSPECIFIED)
config.imageFormat = imageExtension;
}
if (config.imageType == ImageType::MTSDF &&
config.imageFormat == ImageFormat::BMP)
ABORT("Atlas type not compatible with image format. MTSDF requires a "
"format with alpha channel.");
if (imageExtension != ImageFormat::UNSPECIFIED) {
// Warn if image format mismatches -imageout extension
bool mismatch = false;
switch (config.imageFormat) {
case ImageFormat::TEXT:
case ImageFormat::TEXT_FLOAT:
mismatch = imageExtension != ImageFormat::TEXT;
break;
case ImageFormat::BINARY:
case ImageFormat::BINARY_FLOAT:
case ImageFormat::BINARY_FLOAT_BE:
mismatch = imageExtension != ImageFormat::BINARY;
break;
default:
mismatch = imageExtension != config.imageFormat;
}
if (mismatch)
printf("Warning: Output image file extension does not match the image's "
"actual format (%s)!\n",
imageFormatName);
}
imageFormatName = nullptr; // No longer consistent with imageFormat
bool floatingPointFormat =
(config.imageFormat == ImageFormat::TIFF ||
config.imageFormat == ImageFormat::TEXT_FLOAT ||
config.imageFormat == ImageFormat::BINARY_FLOAT ||
config.imageFormat == ImageFormat::BINARY_FLOAT_BE);
// Load fonts
std::vector<GlyphGeometry> glyphs;
std::vector<FontGeometry> fonts;
bool anyCodepointsAvailable = false;
{
class FontHolder {
msdfgen::FreetypeHandle *ft;
msdfgen::FontHandle *font;
const char *fontFilename;
public:
FontHolder()
: ft(msdfgen::initializeFreetype()), font(nullptr),
fontFilename(nullptr) {}
~FontHolder() {
if (ft) {
if (font)
msdfgen::destroyFont(font);
msdfgen::deinitializeFreetype(ft);
}
}
bool load(const char *fontFilename) {
if (ft && fontFilename) {
if (this->fontFilename && !strcmp(this->fontFilename, fontFilename))
return true;
if (font)
msdfgen::destroyFont(font);
if ((font = msdfgen::loadFont(ft, fontFilename))) {
this->fontFilename = fontFilename;
return true;
}
this->fontFilename = nullptr;
}
return false;
}
operator msdfgen::FontHandle *() const { return font; }
} font;
for (FontInput &fontInput : fontInputs) {
if (!font.load(fontInput.fontFilename))
ABORT("Failed to load specified font file.");
if (fontInput.fontScale <= 0)
fontInput.fontScale = 1;
// Load character set
std::vector<unicode_t> charset;
if (fontInput.charsetFilename) {
ABORT("I broke the charset filename thing");
// charset = reinterpret_cast<unsigned int>(readCharsetFromFile(fontInput.charsetFilename));
// if (!charset.load(fontInput.charsetFilename,
// fontInput.glyphIdentifierType !=
// GlyphIdentifierType::UNICODE_CODEPOINT))
// ABORT(fontInput.glyphIdentifierType ==
// GlyphIdentifierType::GLYPH_INDEX ? "Failed to load glyph set
// specification." : "Failed to load character set specification.");
} else {
charset = getAsciiCharset();
fontInput.glyphIdentifierType = GlyphIdentifierType::UNICODE_CODEPOINT;
}
// Load glyphs
FontGeometry fontGeometry(&glyphs);
int glyphsLoaded = -1;
switch (fontInput.glyphIdentifierType) {
case GlyphIdentifierType::GLYPH_INDEX:
glyphsLoaded = fontGeometry.loadGlyphset(
font, fontInput.fontScale, charset, config.preprocessGeometry,
config.kerning);
break;
case GlyphIdentifierType::UNICODE_CODEPOINT:
glyphsLoaded =
fontGeometry.loadCharset(font, fontInput.fontScale, charset,
config.preprocessGeometry, config.kerning);
anyCodepointsAvailable |= glyphsLoaded > 0;
break;
}
if (glyphsLoaded < 0)
ABORT("Failed to load glyphs from font.");
printf("Loaded geometry of %d out of %d glyphs", glyphsLoaded,
(int)charset.size());
if (fontInputs.size() > 1)
printf(" from font \"%s\"", fontInput.fontFilename);
printf(".\n");
// List missing glyphs
if (glyphsLoaded < (int)charset.size()) {
printf("Missing %d %s", (int)charset.size() - glyphsLoaded,
fontInput.glyphIdentifierType ==
GlyphIdentifierType::UNICODE_CODEPOINT
? "codepoints"
: "glyphs");
bool first = true;
switch (fontInput.glyphIdentifierType) {
case GlyphIdentifierType::GLYPH_INDEX:
for (unicode_t cp : charset)
if (!fontGeometry.getGlyph(msdfgen::GlyphIndex(cp)))
printf("%c 0x%02X", first ? ((first = false), ':') : ',', cp);
break;
case GlyphIdentifierType::UNICODE_CODEPOINT:
for (unicode_t cp : charset)
if (!fontGeometry.getGlyph(cp))
printf("%c 0x%02X", first ? ((first = false), ':') : ',', cp);
break;
}
printf("\n");
}
if (fontInput.fontName)
fontGeometry.setName(fontInput.fontName);
fonts.push_back((FontGeometry &&) fontGeometry);
}
}
if (glyphs.empty())
ABORT("No glyphs loaded.");
// Determine final atlas dimensions, scale and range, pack glyphs
{
double unitRange = 0, pxRange = 0;
switch (rangeMode) {
case RANGE_EM:
unitRange = rangeValue;
break;
case RANGE_PIXEL:
pxRange = rangeValue;
break;
}
bool fixedDimensions = fixedWidth >= 0 && fixedHeight >= 0;
bool fixedScale = config.emSize > 0;
TightAtlasPacker atlasPacker;
if (fixedDimensions)
atlasPacker.setDimensions(fixedWidth, fixedHeight);
else
atlasPacker.setDimensionsConstraint(atlasSizeConstraint);
atlasPacker.setPadding(config.imageType == ImageType::MSDF ||
config.imageType == ImageType::MTSDF
? 0
: -1);
// TODO: In this case (if padding is -1), the border pixels of each glyph
// are black, but still computed. For floating-point output, this may play a
// role.
if (fixedScale)
atlasPacker.setScale(config.emSize);
else
atlasPacker.setMinimumScale(minEmSize);
atlasPacker.setPixelRange(pxRange);
atlasPacker.setUnitRange(unitRange);
atlasPacker.setMiterLimit(config.miterLimit);
if (int remaining = atlasPacker.pack(glyphs.data(), glyphs.size())) {
if (remaining < 0) {
ABORT("Failed to pack glyphs into atlas.");
} else {
printf("Error: Could not fit %d out of %d glyphs into the atlas.\n",
remaining, (int)glyphs.size());
return 1;
}
}
atlasPacker.getDimensions(config.width, config.height);
if (!(config.width > 0 && config.height > 0))
ABORT("Unable to determine atlas size.");
config.emSize = atlasPacker.getScale();
config.pxRange = atlasPacker.getPixelRange();
if (!fixedScale)
printf("Glyph size: %.9g pixels/EM\n", config.emSize);
if (!fixedDimensions)
printf("Atlas dimensions: %d x %d\n", config.width, config.height);
}
// Generate atlas bitmap
if (!layoutOnly) {
// Edge coloring
if (config.imageType == ImageType::MSDF ||
config.imageType == ImageType::MTSDF) {
if (config.expensiveColoring) {
Workload(
[&glyphs, &config](int i, int threadNo) -> bool {
unsigned long long glyphSeed =
(LCG_MULTIPLIER * (config.coloringSeed ^ i) + LCG_INCREMENT) *
!!config.coloringSeed;
glyphs[i].edgeColoring(config.edgeColoring, config.angleThreshold,
glyphSeed);
return true;
},
glyphs.size())
.finish(config.threadCount);
} else {
unsigned long long glyphSeed = config.coloringSeed;
for (GlyphGeometry &glyph : glyphs) {
glyphSeed *= LCG_MULTIPLIER;
glyph.edgeColoring(config.edgeColoring, config.angleThreshold,
glyphSeed);
}
}
}
bool success = false;
switch (config.imageType) {
case ImageType::HARD_MASK:
if (floatingPointFormat)
success = makeAtlas<float, float, 1, scanlineGenerator>(glyphs, fonts,
config);
else
success =
makeAtlas<byte, float, 1, scanlineGenerator>(glyphs, fonts, config);
break;
case ImageType::SOFT_MASK:
case ImageType::SDF:
if (floatingPointFormat)
success =
makeAtlas<float, float, 1, sdfGenerator>(glyphs, fonts, config);
else
success =
makeAtlas<byte, float, 1, sdfGenerator>(glyphs, fonts, config);
break;
case ImageType::PSDF:
if (floatingPointFormat)
success =
makeAtlas<float, float, 1, psdfGenerator>(glyphs, fonts, config);
else
success =
makeAtlas<byte, float, 1, psdfGenerator>(glyphs, fonts, config);
break;
case ImageType::MSDF:
if (floatingPointFormat)
success =
makeAtlas<float, float, 3, msdfGenerator>(glyphs, fonts, config);
else
success =
makeAtlas<byte, float, 3, msdfGenerator>(glyphs, fonts, config);
break;
case ImageType::MTSDF:
if (floatingPointFormat)
success =
makeAtlas<float, float, 4, mtsdfGenerator>(glyphs, fonts, config);
else
success =
makeAtlas<byte, float, 4, mtsdfGenerator>(glyphs, fonts, config);
break;
}
if (!success)
result = 1;
}
if (config.jsonFilename) {
if (exportJSON(fonts.data(), fonts.size(), config.emSize, config.pxRange,
config.width, config.height, config.imageType,
config.yDirection, config.jsonFilename, config.kerning))
puts("Glyph layout and metadata written into JSON file.");
else {
result = 1;
puts("Failed to write JSON output file.");
}
}
return result;
}
| 35.775718 | 137 | 0.625071 | [
"geometry",
"shape",
"vector"
] |
cba13d5dff33009fe5991596aea18b898d7bef42 | 1,111 | cpp | C++ | 202204/0422_spiralOrder.cpp | talentwill/CardCoding | 1fcd20f3a76cec85845552a8917847971d9aeeb1 | [
"MIT"
] | null | null | null | 202204/0422_spiralOrder.cpp | talentwill/CardCoding | 1fcd20f3a76cec85845552a8917847971d9aeeb1 | [
"MIT"
] | null | null | null | 202204/0422_spiralOrder.cpp | talentwill/CardCoding | 1fcd20f3a76cec85845552a8917847971d9aeeb1 | [
"MIT"
] | 1 | 2022-03-10T05:28:19.000Z | 2022-03-10T05:28:19.000Z | class Solution
{
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty() or matrix[0].empty()) {
return {};
}
vector<int> ans;
int top = 0;
int bottom = matrix.size() - 1;
int left = 0;
int right = matrix[0].size() - 1;
while (top <= bottom and left <= right) {
for (int col = left; col <= right; col++) {
ans.emplace_back(matrix[top][col]);
}
top++;
for (int row = top; row <= bottom; row++) {
ans.emplace_back(matrix[row][right]);
}
right--;
// 注意点:行或列大于2的情况
if (left < right and top < bottom) {
for (int col = right; col >= left; col--) {
ans.emplace_back(matrix[bottom][col]);
}
bottom--;
for (int row = bottom; row >= top; row--) {
ans.emplace_back(matrix[row][left])
}
left++;
}
}
return ans;
}
}; | 26.452381 | 59 | 0.412241 | [
"vector"
] |
cba5b8ba1625db3d7df854769c53b104d1d34b45 | 7,807 | cc | C++ | IO/rings.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | IO/rings.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | IO/rings.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <string>
#include "ace/FILE_Connector.h"
#include "IO/MessageManager.h"
#include "IO/Writers.h"
#include "Messages/RadarConfig.h"
#include "Messages/Video.h"
#include "Utils/CmdLineArgs.h"
#include "Utils/Utils.h"
using namespace SideCar;
const std::string about = "Simple PRI pattern generator.";
const Utils::CmdLineArgs::OptionDef options[] = {{'a', "arc", "number of radials on/off in ring", "ARC"},
{'c', "count", "number of rings to generate", "RINGS"},
{'f', "frequency", "rate at which the timmestamps change ", "FREQ"},
{'g', "gates", "number of samples per radial", "GATES"},
{'m', "minrange", "minimum range", "MIN"},
{'M', "maxrange", "maximum range", "MAX"},
{'n', "noise", "noise amplitude (0-32767)", "NOISE"},
{'p', "power", "value to use for ON", "POWER"},
{'r', "radials", "number of radials in a scan", "RADS"},
{'s', "scans", "number of scans to generate", "SCANS"},
{'P', "spacing", "spacing between rings", "WIDTH"},
{'w', "width", "width of ring in samples", "WIDTH"}};
const Utils::CmdLineArgs::ArgumentDef args[] = {{"FILE", "path to output file"}};
int
makeNoise(int level)
{
return int(::drand48() * level - level / 2);
}
int
main(int argc, char** argv)
{
size_t numScans = 1;
size_t numGates = Messages::RadarConfig::GetGateCountMax();
size_t numRadials = Messages::RadarConfig::GetRadialCount();
double minRange = Messages::RadarConfig::GetRangeMin_deprecated();
double maxRange = Messages::RadarConfig::GetRangeMax();
size_t numRings = 10;
size_t ringWidth = 5;
size_t arcWidth = numRadials;
double frequency = 360.0;
int noise = 1024;
int power = 8192;
Utils::CmdLineArgs cla(argc, argv, about, options, sizeof(options), args, sizeof(args));
std::string value;
if (cla.hasOpt("frequency", value))
if (!(value >> frequency) || frequency <= 0.0) cla.usage("invalid 'frequency' value");
if (cla.hasOpt("minrange", value))
if (!(value >> minRange) || minRange < 0.0) cla.usage("invalid 'minrange' value");
if (cla.hasOpt("maxrange", value))
if (!(value >> maxRange) || maxRange < 1.0) cla.usage("invalid 'maxrange' value");
if (minRange >= maxRange) cla.usage("min range must be less than max range");
if (cla.hasOpt("scans", value))
if (!(value >> numScans) || numScans < 1) cla.usage("invalid 'scans' value");
if (cla.hasOpt("gates", value))
if (!(value >> numGates) || numGates < 1) cla.usage("invalid 'samples' value");
if (cla.hasOpt("radials", value)) {
if (!(value >> numRadials) || numRadials < 360) cla.usage("invalid 'radials' value");
arcWidth = numRadials;
}
if (cla.hasOpt("count", value))
if (!(value >> numRings) || numRings < 1 || numRings > numGates) cla.usage("invalid 'count' value");
if (cla.hasOpt("width", value))
if (!(value >> ringWidth) || ringWidth < 1 || ringWidth > 100) cla.usage("invalid 'width' value");
if (cla.hasOpt("arc", value))
if (!(value >> arcWidth) || arcWidth < 1 || arcWidth > numRadials) cla.usage("invalid 'arc' value");
if (cla.hasOpt("power", value)) {
if (!(value >> power) || power < 1 || power > 32767) {
std::ostringstream os;
os << "invalid 'power' value - " << value;
cla.usage(os.str());
}
}
if (cla.hasOpt("noise", value)) {
if (!(value >> noise)) cla.usage("invalid 'noise' value");
power -= noise;
}
double timeRate = 1.0 / frequency;
double beamWidth = (M_PI * 2.0) / numRadials;
double shaftChange = double(Messages::RadarConfig::GetShaftEncodingMax()) / numRadials;
double ringSpacing = double(numGates) / double(numRings);
if (cla.hasOpt("spacing", value))
if (!(value >> ringSpacing)) cla.usage("invalid 'spacing' value");
std::clog << "numRadials: " << numRadials << " beamWidth: " << Utils::radiansToDegrees(beamWidth) << " degrees "
<< beamWidth << " radians\n";
std::clog << "shaft change: " << shaftChange << '\n';
std::clog << "numGates: " << numGates << " minRange: " << minRange << " maxRange: " << maxRange << '\n';
std::clog << "numRings: " << numRings << " width: " << ringWidth << " arc: " << arcWidth
<< " spacing: " << ringSpacing << '\n';
std::clog << "time change: " << timeRate << " frequency: " << frequency << std::endl;
// Create a new FileWriter object, and then 'connect' it to the file path given on the command line -- this
// opens the file.
//
::unlink(cla.arg(0).c_str());
IO::FileWriter::Ref writer(IO::FileWriter::Make());
ACE_FILE_Addr address(cla.arg(0).c_str());
ACE_FILE_Connector fd(writer->getDevice(), address);
double clock = 0.0;
bool arcVisible = true;
size_t arcCounter = arcWidth;
Messages::VMEDataMessage vme;
vme.header.msgDesc = ((Messages::VMEHeader::kPackedReal << 16) | Messages::VMEHeader::kAzimuthValidMask |
Messages::VMEHeader::kIRIGValidMask | Messages::VMEHeader::kPRIValidMask);
vme.header.pri = 0;
vme.header.timeStamp = 0;
vme.rangeMin = minRange;
vme.rangeFactor = (maxRange - minRange) / numGates;
// Generate the requested number of scans
//
double shaftSim = 0.0;
for (size_t scan = 0; scan < numScans; ++scan) {
// Generate the requested number of radials
//
for (size_t radial = 0; radial < numRadials; ++radial) {
++vme.header.pri;
vme.header.azimuth = uint32_t(::rint(shaftSim));
shaftSim += shaftChange;
if (shaftSim > Messages::RadarConfig::GetShaftEncodingMax())
shaftSim -= Messages::RadarConfig::GetShaftEncodingMax();
Messages::Video::Ref msg(Messages::Video::Make("rings", vme, numGates));
msg->setCreatedTimeStamp(clock);
clock += timeRate;
vme.header.irigTime = clock;
if (!arcVisible) {
// This gate is hidden, so just write noise
//
for (size_t gate = 0; gate < numGates; ++gate) msg->push_back(makeNoise(noise));
} else {
// The gate is potentially visible. See if it should be for this radial.
//
size_t onCounter = 0;
double nextRing = ringSpacing - ringWidth;
if (nextRing < 0.0) nextRing = 0.0;
for (size_t gate = 0; gate < numGates; ++gate) {
if (gate >= nextRing) {
nextRing += ringSpacing;
onCounter = ringWidth;
}
msg->push_back(makeNoise(noise) + (onCounter ? power : 0));
if (onCounter) --onCounter;
}
}
if (--arcCounter == 0) {
arcVisible = !arcVisible;
arcCounter = arcWidth;
}
// Done creating the PRI mesage. Write its CDR representation out to disk.
//
IO::MessageManager mgr(msg);
writer->writeEncoded(1, mgr.getEncoded());
}
}
return 0;
}
| 40.242268 | 117 | 0.5399 | [
"object"
] |
cba652b16d03af7d68fbdaa3805590751ce6f6ad | 13,158 | cc | C++ | src/scheduler.cc | sunnyxhuang/weaver | 7c27062e190f3a49b3be3f591233c549871747f0 | [
"Apache-2.0"
] | null | null | null | src/scheduler.cc | sunnyxhuang/weaver | 7c27062e190f3a49b3be3f591233c549871747f0 | [
"Apache-2.0"
] | null | null | null | src/scheduler.cc | sunnyxhuang/weaver | 7c27062e190f3a49b3be3f591233c549871747f0 | [
"Apache-2.0"
] | null | null | null | //
// scheduler.cc
// Ximulator
//
// Created by Xin Sunny Huang on 9/21/14.
// Copyright (c) 2014 Xin Sunny Huang. All rights reserved.
//
#include <iomanip>
#include <cfloat>
#include <sys/time.h>
#include <string.h>
#include "coflow.h"
#include "events.h"
#include "global.h"
#include "scheduler.h"
#include "util.h"
#define MWM_RANGE 100000000 //2147483647 = 2,147,483,647
using namespace std;
///////////////////////////////////////////////////////
////////////// Code for base class Scheduler
///////////////////////////////////////////////////////
int Scheduler::instance_count_ = 0;
const double Scheduler::INVALID_RATE_ = DBL_MAX;
Scheduler::Scheduler(long scheduler_link_rate) :
SCHEDULER_LINK_RATE_BPS_(scheduler_link_rate) {
instance_count_++;
m_simPtr = NULL;
m_currentTime = 0;
m_myTimeLine = new SchedulerTimeLine();
m_coflowPtrVector = vector<Coflow *>();
m_nextElecRate = map<long, long>();
m_nextOptcRate = map<long, long>();
}
Scheduler::~Scheduler() {
delete m_myTimeLine;
}
void
Scheduler::UpdateAlarm() {
// update alarm for scheduler on simulator
if (!m_myTimeLine->isEmpty()) {
Event *nextEvent = m_myTimeLine->PeekNext();
double nextTime = nextEvent->GetEventTime();
// Event *schedulerAlarm = new Event(ALARM_SCHEDULER, nextTime);
m_simPtr->UpdateSchedulerAlarm(new EventNotifyScheduler(nextTime, this));
}
}
void
Scheduler::NotifySimEnd() {
return;
cout << "[Scheduler::NotifySimEnd()] is called." << endl;
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end(); cfIt++) {
vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows();
for (vector<Flow *>::iterator fpIt = flowVecPtr->begin();
fpIt != flowVecPtr->end(); fpIt++) {
if ((*fpIt)->GetBitsLeft() <= 0) {
// such flow has finished
continue;
}
cout << "[Scheduler::NotifySimEnd()] flow [" << (*fpIt)->GetFlowId()
<< "] "
<< "(" << (*fpIt)->GetSrc() << "=>" << (*fpIt)->GetDest() << ") "
<< (*fpIt)->GetSizeInBit() << " bytes "
<< (*fpIt)->GetBitsLeft() << " bytes left "
<< (*fpIt)->GetElecRate() << " bps" << endl;
}
}
}
bool Scheduler::Transmit(double startTime, double endTime,
bool basic, bool local, bool salvage) {
// cout << "[Scheduler::Transmit] TX " << startTime << "->" << endTime << endl;
bool hasCoflowFinish = false;
bool hasFlowFinish = false;
bool hasFakeCoflowFinish = false;
vector<Coflow *> finished_coflows;
vector<Flow *> finished_flows;
map<int, long> validate_tx_src_bits, validate_tx_dst_bits;
map<int, int> validate_src_flow_num, validate_dst_flow_num;
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end();) {
for (Flow *flow : *((*cfIt)->GetFlows())) {
if (flow->GetBitsLeft() <= 0) {
// such flow has finished
continue;
}
// tx rate verification debug
long validate_tx_this_flow_bits = flow->GetBitsLeft();
// ********* begin tx ****************
if (basic) {
flow->Transmit(startTime, endTime);
}
// tx rate verification debug // only consider non-local, major tx
validate_tx_this_flow_bits -= flow->GetBitsLeft();
if (local) {
flow->TxLocal();
}
if (salvage) {
flow->TxSalvage();
}
// ********* end tx ********************
validate_tx_src_bits[flow->GetSrc()] += validate_tx_this_flow_bits;
validate_tx_dst_bits[flow->GetDest()] += validate_tx_this_flow_bits;
if (validate_tx_this_flow_bits > 0) {
validate_src_flow_num[flow->GetSrc()]++;
validate_dst_flow_num[flow->GetDest()]++;
}
if (flow->GetBitsLeft() == 0) {
hasFlowFinish = true;
(*cfIt)->NumFlowFinishInc();
flow->SetEndTime(endTime);
finished_flows.push_back(flow);
// debug for coflow progress
if (DEBUG_LEVEL >= 4) {
cout << fixed << setw(FLOAT_TIME_WIDTH) << endTime << "s Finished "
<< (*cfIt)->GetName() << " " << flow->toString()
<< (*cfIt)->NumFlowsLeft() << " flows left in coflow\n";
}
}
// update coflow account on bytes sent.
(*cfIt)->AddTxBit(validate_tx_this_flow_bits);
}
if ((*cfIt)->IsComplete()) {
Coflow *finished_coflow = (*cfIt)->GetRootCoflow();
finished_coflows.push_back(finished_coflow);
finished_coflow->SetEndTime(endTime);
hasCoflowFinish = true;
//cout << string(FLOAT_TIME_WIDTH+2, ' ')
cout << fixed << setw(FLOAT_TIME_WIDTH) << endTime << "s "
<< "[Scheduler::Transmit] coflow finish! "
<< "Name " << (*cfIt)->GetName() << ", "
<< "root Coflow #" << finished_coflow->GetJobId() << endl;
}
if ((*cfIt)->IsComplete()
|| ((*cfIt)->IsFake() && (*cfIt)->IsFakeCompleted())) {
if ((*cfIt)->IsFake() && (*cfIt)->IsFakeCompleted()) {
// This fake coflow has done. We can delete it here and the parent
// coflow will be handled back as finishd coflow.
hasFakeCoflowFinish = true;
// cout << "Deleting Fake Coflow #" << (*cfIt)->GetJobId() << endl;
delete (*cfIt);
}
// advance coflow iterator.
cfIt = m_coflowPtrVector.erase(cfIt);
} else {
// jump to next coflow
cfIt++;
}
} // for coflow iterator
ScheduleToNotifyTrafficFinish(endTime, finished_coflows, finished_flows);
if (hasCoflowFinish || hasFakeCoflowFinish) {
CoflowFinishCallBack(endTime);
} else if (hasFlowFinish) {
FlowFinishCallBack(endTime);
}
if (hasCoflowFinish || hasFlowFinish || hasFakeCoflowFinish) {
Scheduler::UpdateFlowFinishEvent(endTime);
}
// Validate bits transmitted meet constraints.
// in packet switched network, there might bee 100s of concurrent flows
// to/from the same port, and each flow tx possibly comes with 1 bit error.
// Therefore we allow a larger slack for tx constraint check, based on the
// number of concurrent flows at a port . In optical net, the number of
// concurrent flows are less. So a smaller slack is sufficient.
long bound =
10 + SCHEDULER_LINK_RATE_BPS_ * NUM_LINK_PER_RACK * (endTime - startTime);
if (!ValidateLastTxMeetConstraints(
bound, validate_tx_src_bits, validate_tx_dst_bits,
validate_src_flow_num, validate_dst_flow_num)) {
cerr << startTime << " Warming: Fail to meet tx bound!!!" <<
endl;
exit(-1);
}
if (hasCoflowFinish || hasFlowFinish || hasFakeCoflowFinish) {
return true;
}
return false;
}
void
Scheduler::ScheduleToNotifyTrafficFinish(double end_time,
vector<Coflow *> &coflows_done,
vector<Flow *> &flows_done) {
if (coflows_done.empty() && flows_done.empty()) {
return;
}
// if (coflows_done.empty()
// && SPEEDUP_1BY1_TRAFFIC_IN_SCHEDULER
// && m_coflowPtrVector.size() == 1) {
// // no FCT for hacking mode.
// return;
// }
//notify traffic generator of coflow / flow finish
vector<Coflow *> *finishedCf = new vector<Coflow *>(coflows_done);
vector<Flow *> *finishedF = new vector<Flow *>(flows_done);
MsgEventTrafficFinish *msgEventPtr =
new MsgEventTrafficFinish(end_time, finishedCf, finishedF);
m_simPtr->AddEvent(msgEventPtr);
}
//returns negative if all flows has finished
//return DBL_MAX if all flows are waiting indefinitely
double
Scheduler::CalcTime2FirstFlowEnd() {
double time2FirstFinish = DBL_MAX;
bool hasUnfinishedFlow = false;
bool finishTimeValid = false;
for (Coflow *coflow :m_coflowPtrVector) {
for (Flow *flow : *coflow->GetFlows()) {
if (flow->GetBitsLeft() <= 0) {
//such flow has completed
continue;
}
hasUnfinishedFlow = true;
// calc the min finishing time
double flowCompleteTime = DBL_MAX;
if (flow->isThruOptic() && flow->GetOptcRate() > 0) {
flowCompleteTime = SecureFinishTime(flow->GetBitsLeft(),
flow->GetOptcRate());
} else if (!flow->isThruOptic() && flow->GetElecRate() > 0) {
flowCompleteTime = SecureFinishTime(flow->GetBitsLeft(),
flow->GetElecRate());
}
if (time2FirstFinish > flowCompleteTime) {
finishTimeValid = true;
time2FirstFinish = flowCompleteTime;
}
}
}
if (hasUnfinishedFlow) {
if (finishTimeValid) {
return time2FirstFinish;
} else {
//all flows are waiting indefinitely
return DBL_MAX;
}
} else {
// all flows are finished
return -DBL_MAX;
}
}
double Scheduler::UpdateFlowFinishEvent(double baseTime) {
double time2FirstFinish = CalcTime2FirstFlowEnd();
if (time2FirstFinish == DBL_MAX) {
// all flows are waiting indefinitely
m_myTimeLine->RemoveSingularEvent(FLOW_FINISH);
} else if (time2FirstFinish == -DBL_MAX) {
// all flows are done
} else {
// valid finishing time
m_myTimeLine->RemoveSingularEvent(FLOW_FINISH);
double firstFinishTime = baseTime + time2FirstFinish;
Event *flowFinishEventPtr = new Event(FLOW_FINISH, firstFinishTime);
m_myTimeLine->AddEvent(flowFinishEventPtr);
}
return time2FirstFinish;
}
void
Scheduler::UpdateRescheduleEvent(double reScheduleTime) {
m_myTimeLine->RemoveSingularEvent(RESCHEDULE);
Event *rescheduleEventPtr = new Event(RESCHEDULE, reScheduleTime);
m_myTimeLine->AddEvent(rescheduleEventPtr);
}
void
Scheduler::NotifyAddFlows(double alarmTime) {
//FlowArrive(alarmTime);
EventFlowArrive *msgEp = new EventFlowArrive(alarmTime);
m_myTimeLine->AddEvent(msgEp);
UpdateAlarm();
}
void
Scheduler::NotifyAddCoflows(double alarmTime, vector<Coflow *> *cfVecPtr) {
//CoflowArrive(alarmTime,cfVecPtr);
EventCoflowArrive *msgEp = new EventCoflowArrive(alarmTime, cfVecPtr);
m_myTimeLine->AddEvent(msgEp);
UpdateAlarm();
}
double
Scheduler::SecureFinishTime(long bits, long rate) {
if (rate == 0) {
return DBL_MAX;
}
double timeLen = (double) bits / (double) rate;
// more complicated impl below *********
long bitsleft = 1;
int delta = 0;
while (bitsleft > 0) {
timeLen = (double) (delta + bits) / (double) rate;
bitsleft = bits - rate * timeLen;
delta++;
}
// more complicated impl above *****
//if (timeLen < 0.0000000001) return 0.0000000001;
return timeLen;
}
void
Scheduler::Print(void) {
return;
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end(); cfIt++) {
if (cfIt == m_coflowPtrVector.begin()) {
cout << fixed << setw(FLOAT_TIME_WIDTH)
<< m_currentTime << "s ";
} else {
cout << string(FLOAT_TIME_WIDTH + 2, ' ');
}
cout << "[Scheduler::Print] "
<< "Coflow ID " << (*cfIt)->GetCoflowId() << endl;
(*cfIt)->Print();
}
}
// copy flow rate from m_nextElecRate & m_nextOptcRate
// and reflect the rate on flow record.
void
Scheduler::SetFlowRate() {
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end(); cfIt++) {
vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows();
for (vector<Flow *>::iterator fpIt = flowVecPtr->begin();
fpIt != flowVecPtr->end(); fpIt++) {
//set flow rate
long flowId = (*fpIt)->GetFlowId();
long elecBps = MapWithDef(m_nextElecRate, flowId, (long) 0);
long optcBps = MapWithDef(m_nextOptcRate, flowId, (long) 0);
(*fpIt)->SetRate(elecBps, optcBps);
}
}
}
bool Scheduler::ValidateLastTxMeetConstraints(
long port_bound_bits,
const map<int, long> &src_tx_bits, const map<int, long> &dst_tx_bits,
const map<int, int> &src_flow_num, const map<int, int> &dst_flow_num) {
for (const auto &src_kv_pair : src_tx_bits) {
long buget = port_bound_bits
+ FindWithDef(src_flow_num, src_kv_pair.first, 0);
if (src_kv_pair.second > buget) {
cerr << "Error in validating TX constraints!!! \n"
<< "src " << src_kv_pair.first << " tx " << src_kv_pair.second
<< " and flows over bound = " << buget << endl;
return false;
} else if (DEBUG_LEVEL >= 5) {
cout << "Valid: src " << src_kv_pair.first
<< " tx " << src_kv_pair.second
<< " < budget = " << buget << endl;
}
}
for (const auto &dst_kv_pair : dst_tx_bits) {
long buget = port_bound_bits
+ FindWithDef(dst_flow_num, dst_kv_pair.first, 0);
if (dst_kv_pair.second > buget) {
cerr << "Error in validating TX constraints!!! \n"
<< "dst " << dst_kv_pair.first << " tx " << dst_kv_pair.second
<< " and flows over bound = " << buget << endl;
return false;
} else if (DEBUG_LEVEL >= 5) {
cout << "Valid: dst " << dst_kv_pair.first
<< " tx " << dst_kv_pair.second
<< " < budget = " << buget << endl;
}
}
// cout << "TX budget is valid." << endl;
return true;
}
| 31.328571 | 81 | 0.615975 | [
"vector"
] |
cbade2234dce65143ba1939c9945c85de88c9944 | 1,798 | cpp | C++ | client/client.cpp | utevo/Multiprocess-filesystem | 38ce2c53bd18a8946c1d01c071e5d1c0b6c1f348 | [
"MIT"
] | null | null | null | client/client.cpp | utevo/Multiprocess-filesystem | 38ce2c53bd18a8946c1d01c071e5d1c0b6c1f348 | [
"MIT"
] | null | null | null | client/client.cpp | utevo/Multiprocess-filesystem | 38ce2c53bd18a8946c1d01c071e5d1c0b6c1f348 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include "../libraries/client/lib.hpp"
#include "../libraries/core/utils.hpp"
// void printInode(const Inode&);
int main() {
MFSClient client;
client.mfs_mount("./mfs");
client.mfs_creat("/plik1.txt", FileStatus::RDWR);
client.mfs_creat("/plik2.txt", FileStatus::RDWR);
client.mfs_creat("/plik3.txt", FileStatus::RDWR);
client.mfs_creat("/plik4.txt", FileStatus::RDWR);
// client.mfs_mkdir("/folder");
// client.mfs_mkdir("/folder2");
// client.mfs_mkdir("/folder2");
//
// client.mfs_creat("/folder/plik4.txt", FileStatus::RDWR);
client.mfs_creat("/plik5.txt", FileStatus::RDWR);
client.mfs_unlink("/plik3.txt");
int fd = client.mfs_creat("/plik6.txt", FileStatus::RDWR);
int fd1 = client.mfs_open("/plik6.txt", FileStatus::RDWR);
client.mfs_creat("/plik6.txt", FileStatus::RDWR);
char buff[17000];
for(int i = 0; i < 17000; ++i)
buff[i] = 'a';
client.mfs_write(fd, buff, 17000);
char buff2[4100];
for(int i = 0; i < 4100; ++i)
buff2[i] = 'b';
//client.mfs_write(fd1, buff2, 4100);
// int filefd = client.openAndSeek(client.blocksOffset + 2 * client.blockSize);
char tmp[4096];
char tmp2[4096];
// read(filefd, &tmp, 4096);
// lseek(filefd, client.blocksOffset + 6 * client.blockSize, SEEK_SET);
// read(filefd, &tmp2, 4096);
client.mfs_read(fd1, tmp, 4096);
for(auto s : client.mfs_ls("/"))
std::cout << s.first << "\t" << s.second << std::endl;
std::cout << " " << std::endl;
// for(auto s : client.mfs_ls("/folder"))
// std::cout << s.first << "\t" << s.second << std::endl;
}
| 32.107143 | 82 | 0.611791 | [
"vector"
] |
cbb1bf48270b5c37c1acd1b4eef289622254f9f8 | 1,147 | cpp | C++ | Engine/src/Object/Object.cpp | vimontgames/supervimontbros | d589e42628e549273878d3db1298dd8c7525036a | [
"MIT"
] | 1 | 2021-01-21T19:37:57.000Z | 2021-01-21T19:37:57.000Z | Engine/src/Object/Object.cpp | vimontgames/supervimontbros | d589e42628e549273878d3db1298dd8c7525036a | [
"MIT"
] | null | null | null | Engine/src/Object/Object.cpp | vimontgames/supervimontbros | d589e42628e549273878d3db1298dd8c7525036a | [
"MIT"
] | null | null | null | #include "Precomp.h"
#include "Object.h"
using namespace sf;
#if 0
#define DBG_REFCOUNT(fmt, ...) debugPrint(fmt, __VA_ARGS__)
#else
#define DBG_REFCOUNT(fmt, ...)
#endif
uint Object::s_count = 0;
//--------------------------------------------------------------------------
Object::Object(const sf::String & _name) :
m_name(_name)
{
DBG_REFCOUNT("Create Object \"%s\"\n", m_name.toAnsiString().c_str());
s_count++;
}
//--------------------------------------------------------------------------
Object::~Object()
{
DBG_REFCOUNT("Delete Object \"%s\"\n", m_name.toAnsiString().c_str());
s_count--;
}
//--------------------------------------------------------------------------
uint Object::increaseRefCount()
{
DBG_REFCOUNT("Increase RefCount of Object \"%s\" (RefCount %u => %u)\n", m_name.toAnsiString().c_str(), m_refCount, m_refCount+1);
return ++m_refCount;
}
//--------------------------------------------------------------------------
void Object::release()
{
DBG_REFCOUNT("Release Object \"%s\" (RefCount %u => %u)\n", m_name.toAnsiString().c_str(), m_refCount, m_refCount - 1);
if (--m_refCount == 0)
{
delete this;
}
} | 26.068182 | 131 | 0.489102 | [
"object"
] |
cbb3646c3e855e66c4b4866a47809f2717592405 | 1,975 | cpp | C++ | Tree/BinaryTreeInorderTraversal/BinaryTreeInorderTraversal.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | 2 | 2015-08-28T03:52:05.000Z | 2015-09-03T09:54:40.000Z | Tree/BinaryTreeInorderTraversal/BinaryTreeInorderTraversal.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | Tree/BinaryTreeInorderTraversal/BinaryTreeInorderTraversal.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | // Source : https://leetcode.com/problems/binary-tree-inorder-traversal/
// Author : Yijing Bai
// Date : 2016-01-03
/**********************************************************************************
*
* Given a binary tree, return the inorder traversal of its nodes' values.
*
* For example:
* Given binary tree {1,#,2,3},
*
* 1
* \
* 2
* /
* 3
*
* return [1,3,2].
*
* Note: Recursive solution is trivial, could you do it iteratively?
*
* confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
*
* OJ's Binary Tree Serialization:
*
* The serialization of a binary tree follows a level order traversal, where '#'
* signifies a path terminator where no node exists below.
*
* Here's an example:
*
* 1
* / \
* 2 3
* /
* 4
* \
* 5
*
* The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*
*
*
*
*
*
*
*
**********************************************************************************/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
vector<TreeNode*> node_stack;
if (!root) return result;
TreeNode* current = root;
while (current) {
node_stack.push_back(current);
current = current->left;
}
while (!node_stack.empty()) {
TreeNode* node = node_stack.back();
node_stack.pop_back();
result.push_back(node->val);
if (node->right) {
current = node->right;
while (current) {
node_stack.push_back(current);
current = current->left;
}
}
}
return result;
}
};
| 22.701149 | 87 | 0.484051 | [
"vector"
] |
cbb73ff982c73780203b6a527a67117ebe6f2964 | 5,720 | cpp | C++ | Server.cpp | evgezoh/SDLGame | 50cf2c600b3d5031f761220498704c945a1b5c44 | [
"MIT"
] | null | null | null | Server.cpp | evgezoh/SDLGame | 50cf2c600b3d5031f761220498704c945a1b5c44 | [
"MIT"
] | null | null | null | Server.cpp | evgezoh/SDLGame | 50cf2c600b3d5031f761220498704c945a1b5c44 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <sdkddkver.h>
#include <fstream>
#include <thread>
//#include <mutex>
#include <vector>
#include <string>
SOCKET Connect;
SOCKET *Connections;
SOCKET Listen;
int ClientCount = 0;
const int MaxCountOfThreads = 64;
#define S_WIDTH 440
#define S_HEIGHT 680
#define BALL_SIZE 20
#define BALL_STEP 10
std::vector <std::pair <SOCKET, SOCKET>> players(MaxCountOfThreads / 2, std::pair <SOCKET, SOCKET>(-1, -1));
std::vector <std::pair <int, int>> ballposition(MaxCountOfThreads / 2, std::pair <int, int>(S_HEIGHT / 2 - BALL_SIZE / 2, S_HEIGHT / 2 - BALL_SIZE / 2));
std::vector <int> distance(MaxCountOfThreads, 0);
//void clientThread(int ID);
void clientThread();
void findClients();
void changeBallPosition(int angel, int &BallPosY, int id)
{
if (!(id % 2))
{
if (angel >= 0)
{
if (BallPosY >= 0)
BallPosY-=2;
}
if (BallPosY <= 0)
{
BallPosY = 0;
}
if (angel < 0)
{
if (BallPosY <= S_HEIGHT)
BallPosY+=2;
}
if (BallPosY >= S_HEIGHT)
{
BallPosY = S_HEIGHT;
}
//std::cout << "position has been changed 1" << std::endl;
ballposition[id / 2].second = S_HEIGHT - BALL_SIZE - BallPosY;
}
else
{
if (angel >= 0)
{
if (BallPosY < S_HEIGHT)
BallPosY+=2;
}
if (BallPosY <= 0)
{
BallPosY = 0;
}
if (angel < 0)
{
if (BallPosY > 0)
BallPosY-=2;
}
if (BallPosY >= S_HEIGHT)
{
BallPosY = S_HEIGHT;
}
//std::cout << "position has been changed 2" << std::endl;
ballposition[id / 2].second = S_HEIGHT - BALL_SIZE - BallPosY;
}
}
struct sendData
{
int EnemyX;
int EnemyY;
int BallX;
int BallY;
};
int main()
{
setlocale(LC_ALL, "Russian");
WSAData data;
WORD version = MAKEWORD(2, 2);
int res = WSAStartup(version, &data);
if (res)
{
return 0;
}
struct addrinfo hints;
struct addrinfo *result;
Connections = new SOCKET(MaxCountOfThreads);
//Connections = (SOCKET*)calloc(64, sizeof(SOCKET));
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo(NULL, "777", &hints, &result);
Listen = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
bind(Listen, result->ai_addr, result->ai_addrlen);
listen(Listen, SOMAXCONN);
freeaddrinfo(result);
std::cout << "Server start" << std::endl;
char m_connect[] = "I'm Server";
std::thread* Th = new std::thread(clientThread);
std::thread* Th1 = new std::thread(findClients);
Th->join();
Th1->join();
system("Pause");
return 0;
}
void findClients()
{
for (;;Sleep(75))
{
if (Connect = accept(Listen, NULL, NULL))
{
std::cout << "Client " << Connect << " connect... (" << ClientCount << ")" << std::endl;
Connections[ClientCount] = Connect;
if (players[ClientCount / 2].first != -1)
{
players[ClientCount / 2].second = Connect;
}
else
{
players[ClientCount / 2].first = Connect;
}
ClientCount++;
}
}
}
void clientThread()
{
while (true)
{
for (int ID = 0; ID < ClientCount; ID++)
{
int BallPosX = S_WIDTH / 2 - BALL_SIZE / 2;
//int BallPosY = S_HEIGHT / 2 - BALL_SIZE / 2;
int angel;
bool collision;
char ch[1024];
bool inLoop = true;
if (recv(Connections[ID], ch, 1024, NULL) > 0)
{
Sleep(10);
std::string str1 = std::string(ch);
angel = 0;
int minus = 1;
int number = 1;
sendData senddata = { 0,0,0,0 };
for (int i = 0; i < str1.length(); ++i)
{
if (int(str1[i]) == 32)
{
number++;
}
else
{
switch (number)
{
case 1: senddata.EnemyX *= 10; senddata.EnemyX += (int(str1[i]) - 48); break;
case 2: senddata.EnemyY *= 10; senddata.EnemyY += (int(str1[i]) - 48); break;
case 3: if (int(str1[i]) == 45) { minus = -1; }
else { angel *= 10; angel += (int(str1[i]) - 48); } break;
case 4: collision = int(str1[i]) - 48; break;
}
}
}
angel *= minus;
if (collision)
{
if (ID % 2)
{
distance[ID - 1] = 0;
}
else
{
distance[ID + 1] = 0;
}
distance[ID] = 1000;
collision = false;
}
if (distance[ID] > 0)
{
distance[ID]--;
changeBallPosition(angel, ballposition[ID / 2].first, ID);
}
if (ID % 2)
{
//std::cout << "Second client sent to first" << std::endl;
std::string toclient = std::to_string(senddata.EnemyX) + " " + std::to_string(senddata.EnemyY) + " "
+ std::to_string(BallPosX) + " " + std::to_string(ballposition[ID / 2].first);
std::string toclient1 = std::to_string(1000) + " " + std::to_string(1000) + " "
+ std::to_string(S_WIDTH - BALL_SIZE - BallPosX) + " " + std::to_string(ballposition[ID / 2].second);
send(players[ID / 2].first, toclient.c_str(), 25, NULL);
send(players[ID / 2].second, toclient1.c_str(), 25, NULL);
}
else
{
//std::cout << "First client sent to second" << std::endl;
std::string toclient = std::to_string(senddata.EnemyX) + " " + std::to_string(senddata.EnemyY) + " "
+ std::to_string(S_WIDTH - BALL_SIZE - BallPosX) + " " + std::to_string(ballposition[ID / 2].second);
std::string toclient1 = std::to_string(1000) + " " + std::to_string(1000) + " "
+ std::to_string(BallPosX) + " " + std::to_string(ballposition[ID / 2].first);
if (players[ID / 2].second != -1)
{
send(players[ID / 2].second, toclient.c_str(), 25, NULL);
}
send(players[ID / 2].first, toclient1.c_str(), 25, NULL);
}
}
}
}
}
| 21.107011 | 153 | 0.593531 | [
"vector"
] |
cbc16826b95f11f31ac7ccafb5e8e1053c873400 | 2,568 | cpp | C++ | aws-cpp-sdk-glue/source/model/JoinColumn.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-glue/source/model/JoinColumn.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-glue/source/model/JoinColumn.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/glue/model/JoinColumn.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
{
JoinColumn::JoinColumn() :
m_fromHasBeenSet(false),
m_keysHasBeenSet(false)
{
}
JoinColumn::JoinColumn(JsonView jsonValue) :
m_fromHasBeenSet(false),
m_keysHasBeenSet(false)
{
*this = jsonValue;
}
JoinColumn& JoinColumn::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("From"))
{
m_from = jsonValue.GetString("From");
m_fromHasBeenSet = true;
}
if(jsonValue.ValueExists("Keys"))
{
Array<JsonView> keysJsonList = jsonValue.GetArray("Keys");
for(unsigned keysIndex = 0; keysIndex < keysJsonList.GetLength(); ++keysIndex)
{
Array<JsonView> enclosedInStringPropertiesJsonList = keysJsonList[keysIndex].AsArray();
Aws::Vector<Aws::String> enclosedInStringPropertiesList;
enclosedInStringPropertiesList.reserve((size_t)enclosedInStringPropertiesJsonList.GetLength());
for(unsigned enclosedInStringPropertiesIndex = 0; enclosedInStringPropertiesIndex < enclosedInStringPropertiesJsonList.GetLength(); ++enclosedInStringPropertiesIndex)
{
enclosedInStringPropertiesList.push_back(enclosedInStringPropertiesJsonList[enclosedInStringPropertiesIndex].AsString());
}
m_keys.push_back(std::move(enclosedInStringPropertiesList));
}
m_keysHasBeenSet = true;
}
return *this;
}
JsonValue JoinColumn::Jsonize() const
{
JsonValue payload;
if(m_fromHasBeenSet)
{
payload.WithString("From", m_from);
}
if(m_keysHasBeenSet)
{
Array<JsonValue> keysJsonList(m_keys.size());
for(unsigned keysIndex = 0; keysIndex < keysJsonList.GetLength(); ++keysIndex)
{
Array<JsonValue> enclosedInStringPropertiesJsonList(m_keys[keysIndex].size());
for(unsigned enclosedInStringPropertiesIndex = 0; enclosedInStringPropertiesIndex < enclosedInStringPropertiesJsonList.GetLength(); ++enclosedInStringPropertiesIndex)
{
enclosedInStringPropertiesJsonList[enclosedInStringPropertiesIndex].AsString(m_keys[keysIndex][enclosedInStringPropertiesIndex]);
}
keysJsonList[keysIndex].AsArray(std::move(enclosedInStringPropertiesJsonList));
}
payload.WithArray("Keys", std::move(keysJsonList));
}
return payload;
}
} // namespace Model
} // namespace Glue
} // namespace Aws
| 27.031579 | 172 | 0.742601 | [
"vector",
"model"
] |
cbcf252219915ed9d865e254ca47a3f99f1ee840 | 2,195 | cpp | C++ | 701_c.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 701_c.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 701_c.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | //Does Not Work
// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
bool poss(int sz,vector<int>&s, string st)
{
//slding window of size sz and check if all the char are present or nor
//cout<<sz<<endl;
vector<int>freq(128,0);
for(int i=0;i<sz;i++)
freq[int(st[i])]++;
int l=0;
int r=sz;
while(r<int(st.size()))
{
bool ok=true;
for(int i=0;i<128;i++)
{
if(s[i]>0 && freq[i]==0)
{
ok=false;
break;
}
}
if(ok)
return true;
--freq[int(st[l])];
l++;
++freq[int(st[r])];
r++;
}
bool ok=true;
for(int i=0;i<128;i++)
if(s[i]>0 && freq[i]==0)
ok=false;
if(!ok)
return false;
else
return true;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int t;
cin>>t;
string st;
cin>>st;
//Binary search answer works Time :O(nlogn), but we can do better
// vector<int>s(128,0);
// for(int i=0;i<t;i++)
// s[int(st[i])]++;
// int l=0;
// int h=t;
// int ans=-1;
// while(l<=h)
// {
// int mid=l+(h-l)/2;
// if(poss(mid,s,st))
// {
// ans=mid;
// h=mid-1;
// }
// else
// l=mid+1;
// }
// cout<<ans;
// return 0;
set<char>freq;
for(int i=0;i<t;i++)
freq.insert(st[i]);
int l=0;
//map for runnig chars
map<char,int>temp;
set<char>comp;
int ans=INT_MAX;
for(int r=0;r<t;r++)
{
temp[st[r]]++;
comp.insert(st[r]);
//try to shirnk the size if we got all the chars
if(comp==freq)
{
//for(auto it:temp)
// cout<<it.first<<" "<<it.second<<endl;
//cout<<st[l]<<" "<<temp[st[l]]<<endl;
while(temp[st[l]]>1)
{
if(temp[st[l]]>1)
--temp[st[l]];
l++;
}
ans=min(ans,r-l+1);
}
}
cout<<ans;
return 0;
}
| 18.601695 | 106 | 0.542597 | [
"vector"
] |
cbd50479c24e640687ab8df05ed550451052c655 | 2,419 | hpp | C++ | src/state.hpp | przemekBielak/HSM | df9397ab80d366a4524e3d708485d231741f62dc | [
"MIT"
] | null | null | null | src/state.hpp | przemekBielak/HSM | df9397ab80d366a4524e3d708485d231741f62dc | [
"MIT"
] | null | null | null | src/state.hpp | przemekBielak/HSM | df9397ab80d366a4524e3d708485d231741f62dc | [
"MIT"
] | null | null | null | /**
* @file state.hpp
* @author Przemyslaw Bielak (przemyslaw.bielak@protonmail.com)
* @brief Describes a single state in a state machine.
* @version 0.1
* @date 2019-02-01
*
* @copyright Copyright (c) 2019
*
*/
#ifndef STATE_H
#define STATE_H
#include <vector>
#include "state_cfg.hpp"
/** @brief Pointer to a handler function */
typedef void (*handler)();
typedef struct transition_t_ transition_t;
/** @brief State class error codes */
typedef enum stateError_t_ {
NO_ERROR = 0u,
TRANSITION_QUEUE_FULL,
TRANSITION_ALREADY_EXISTS
}stateError_t;
/**
* @brief State is a node in linked list of states
* @details Each state has exactly one parent and 0-* transitions
*/
class State {
public:
/**
* @brief Construct a new State object
*
* @param parent pointer to a parent state
* @param handler function which is called when state is active
*/
State(State * const parent, handler);
~State();
/**
* @brief Get the Parent object
*
* @return State*
*/
State *getParent();
/**
* @brief Get the handler function
*
* @return handler
*/
handler getHandler();
/**
* @brief Get the list of all transitions
*
* @return std::vector<transition_t>
*/
std::vector<transition_t> getTransition(void);
/**
* @brief Add new transition
*
* @param tr transition
* @return stateError_t
*/
stateError_t addTransition(const transition_t transition);
private:
/** @brief Pointer to a parent state */
State *m_parent;
/** @brief Handler function */
void(*m_handler)();
/**
* @brief Transition list
* @details Vector is used because of forward declaration of transition_t (impossible to define array this way).
* Size of vector is restricted to MAX_NUM_OF_TRANSITIONS, so dynamic resizing is not possible.
*
*/
std::vector<transition_t> m_transition;
};
/**
* @brief Describes state transition data
*
*/
typedef struct transition_t_ {
event_t event; /**< Event which starts the transition */
State *nextState; /**< Pointer to the next state */
}transition_t;
#endif // #ifndef STATE_H | 23.715686 | 120 | 0.590327 | [
"object",
"vector"
] |
cbdc04b60bf2e588a6dfcd279e65a3252eb9bdce | 10,138 | cpp | C++ | src/data_reader.cpp | Loop3D/map2model_cpp | 9c280f386e656837570e755859ccc0f4b8163761 | [
"MIT"
] | null | null | null | src/data_reader.cpp | Loop3D/map2model_cpp | 9c280f386e656837570e755859ccc0f4b8163761 | [
"MIT"
] | null | null | null | src/data_reader.cpp | Loop3D/map2model_cpp | 9c280f386e656837570e755859ccc0f4b8163761 | [
"MIT"
] | null | null | null | /******************************************************************************
* A class for reading input data.
*
* Author: Vitaliy Ogarko, vogarko@gmail.com
*******************************************************************************/
#include <fstream>
#include <iostream>
#include "clipper.h"
#include "converter_types.h"
#include "data_reader.h"
#include "parameters_utils.h"
namespace ConverterLib {
// Reads coordinates of an object from a string in WKT format.
static Paths ReadCoordinates(const std::string &__line,
const std::string keyword) {
std::string line = __line;
std::size_t pos = line.find(keyword);
if (pos == std::string::npos) {
std::cout << "Error: not found keyword " << keyword << "\n"
<< "line =" << line << std::endl;
exit(0);
}
Paths paths;
// Extract line part followed by "keyword".
line = line.substr(pos + keyword.length());
Path path;
while (true) {
// Remove leading brackets and spaces.
while (line[0] == '(' || line[0] == ' ') {
line.erase(0, 1);
}
std::istringstream iss(line);
double x, y;
cInt ix, iy;
// Reading next pair of coordinates (separated by a space).
if (!(iss >> x >> y)) {
std::cout << "Error in reading a pair of coordinates!" << std::endl;
break;
}
// Converting coordinates to integers (since the Clipper lib works with
// integers).
ix = ConverterUtils::CoordToInteger(x);
iy = ConverterUtils::CoordToInteger(y);
// if (ix < 4076981032068774 || ix > 6796680558010894 ||
// iy < 74358400408943136 || iy > 75861207033895728) {
// std::cout << "ix: " << ix << " iy:" << iy << std::endl;
// }
path.push_back(IntPoint(ix, iy));
// Getting positions of the following comma and closing bracket.
std::size_t pos_comma = line.find(',');
std::size_t pos_close_bracket = line.find(')');
if (pos_comma < pos_close_bracket) {
// There is one more pair of coordinates (separated by a comma).
// Remove from the line a processed part.
line.erase(0, pos_comma + 1);
} else {
// End of polygon, i.e., found closing bracket ")".
// Adding next path.
paths.push_back(path);
path.clear();
// Search if there are more polygons at this line.
std::size_t pos_open_bracket = line.find('(');
if (pos_open_bracket != std::string::npos) {
// Move to the beginning of the next polygon.
line.erase(0, pos_open_bracket + 1);
// Will be adding a new path for this object.
} else {
// No more paths.
break;
}
}
}
return paths;
}
static std::string RemoveQuotations(const std::string &line) {
std::string res = line;
res.erase(std::remove(res.begin(), res.end(), '\"'), res.end());
return res;
}
static int String2Int(const std::string str) {
int res;
std::istringstream(str) >> res;
return res;
}
static double String2Double(const std::string str) {
double res;
std::istringstream(str) >> res;
return res;
}
std::string ReadField(const std::string &__line, size_t column,
const char delimiter) {
std::string line = __line;
for (size_t i = 1; i < column; i++) {
std::size_t pos = line.find(delimiter);
line = line.substr(pos + 1);
}
std::size_t pos = line.find(delimiter);
std::string field = line.substr(0, pos);
// Removing quotes if any.
field = RemoveQuotations(field);
return field;
}
std::map<std::string, size_t> ReadHeader(const std::string &__line,
const char delimiter) {
std::map<std::string, size_t> headerFields;
std::string line = __line;
std::size_t pos = line.find(delimiter);
size_t column = 1;
while (pos != std::string::npos) {
std::string field = line.substr(0, pos);
line = line.substr(pos + 1);
// Store the field.
headerFields[field] = column;
column++;
pos = line.find(delimiter);
}
// Store the last field.
std::string field = line;
headerFields[field] = column;
return headerFields;
}
int ReadIntField(const std::string &__line, size_t column,
const char delimiter) {
return String2Int(ReadField(__line, column, delimiter));
}
// Trim a string from left.
static inline std::string ltrim(std::string s, const char *t = " \t\n\r\f\v") {
s.erase(0, s.find_first_not_of(t));
return s;
}
// Trim a string from right.
static inline std::string rtrim(std::string s, const char *t = " \t\n\r\f\v") {
s.erase(s.find_last_not_of(t) + 1);
return s;
}
// Trim a string from left and right.
static inline std::string trim(std::string s, const char *t = " \t\n\r\f\v") {
return ltrim(rtrim(s, t), t);
}
static size_t getFieldColumn(const std::map<std::string, size_t> &headerFields,
const std::string &fieldName) {
const std::map<std::string, size_t>::const_iterator it =
headerFields.find(fieldName);
if (it != headerFields.end()) {
return it->second;
} else {
std::cout << "Unknown field name: " << fieldName << std::endl;
exit(0);
}
}
int ReadDataObj(const std::string &filename, const std::string &keyword,
const std::map<std::string, std::string> &constNames,
Objects &objects, const std::vector<int> &idsToRead,
const std::vector<std::string> &idsToReadString) {
std::ifstream myfile(filename.c_str());
if (!myfile.good()) {
std::cout << "Error in opening the file " << filename << "\n";
exit(0);
} else {
std::cout << "Reading data from the file " << filename << "\n";
}
std::string line;
// Reading the header.
std::getline(myfile, line);
std::map<std::string, size_t> headerFields = ReadHeader(line);
// Loop over the file lines.
while (std::getline(myfile, line).good()) {
// Skip lines without the keyword.
std::size_t pos = line.find(keyword);
if (pos == std::string::npos)
continue;
std::string fieldName;
// Extracting ID.
int id;
if (keyword == "LINESTRING") {
fieldName = getConstName(constNames, "FIELD_FAULT_ID");
id = ReadIntField(line, getFieldColumn(headerFields, fieldName));
} else if (keyword == "POLYGON") {
fieldName = getConstName(constNames, "FIELD_POLYGON_ID");
id = ReadIntField(line, getFieldColumn(headerFields, fieldName));
} else if (keyword == "POINT") {
// Currently deposits have not integer id, so assign id here.
id = objects.size();
} else {
std::cout << "Unknown object type: " << keyword << "\n";
exit(0);
}
// Processing only IDs form the input list, if it is not empty.
if (!idsToRead.empty() &&
std::find(idsToRead.begin(), idsToRead.end(), id) == idsToRead.end()) {
continue;
}
if (keyword == "LINESTRING") {
// Ignore faults with features of this type.
fieldName = getConstName(constNames, "FIELD_FAULT_FEATURE");
std::string feature =
trim(ReadField(line, getFieldColumn(headerFields, fieldName)));
if (feature == getConstName(constNames, "FAULT_AXIAL_FEATURE_NAME")) {
continue;
}
}
if (keyword == "POINT") {
// Ignore deposits of this site type.
fieldName = getConstName(constNames, "FIELD_SITE_TYPE");
std::string site_type =
trim(ReadField(line, getFieldColumn(headerFields, fieldName)));
if (site_type == getConstName(constNames, "IGNORE_DEPOSITS_SITE_TYPE")) {
continue;
}
}
Object object;
object.id = id;
if (keyword == "POINT") {
fieldName = getConstName(constNames, "FIELD_SITE_CODE");
object.site_code =
trim(ReadField(line, getFieldColumn(headerFields, fieldName)));
fieldName = getConstName(constNames, "FIELD_SITE_COMMO");
object.site_commo =
trim(ReadField(line, getFieldColumn(headerFields, fieldName)));
// Processing only codes form the input list, if it is not empty.
if (!idsToReadString.empty() &&
std::find(idsToReadString.begin(), idsToReadString.end(),
object.site_code) == idsToReadString.end()) {
continue;
}
} else if (keyword == "POLYGON") {
fieldName = getConstName(constNames, "FIELD_POLYGON_LEVEL1_NAME");
object.name =
trim(ReadField(line, getFieldColumn(headerFields, fieldName)));
fieldName = getConstName(constNames, "FIELD_POLYGON_LEVEL2_NAME");
object.group =
trim(ReadField(line, getFieldColumn(headerFields, fieldName)));
fieldName = getConstName(constNames, "FIELD_POLYGON_MIN_AGE");
object.min_age = String2Double(
ReadField(line, getFieldColumn(headerFields, fieldName)));
fieldName = getConstName(constNames, "FIELD_POLYGON_MAX_AGE");
object.max_age = String2Double(
ReadField(line, getFieldColumn(headerFields, fieldName)));
fieldName = getConstName(constNames, "FIELD_POLYGON_CODE");
object.code = ReadField(line, getFieldColumn(headerFields, fieldName));
fieldName = getConstName(constNames, "FIELD_POLYGON_DESCRIPTION");
object.description =
ReadField(line, getFieldColumn(headerFields, fieldName));
fieldName = getConstName(constNames, "FIELD_POLYGON_ROCKTYPE1");
object.rocktype1 =
ReadField(line, getFieldColumn(headerFields, fieldName));
fieldName = getConstName(constNames, "FIELD_POLYGON_ROCKTYPE2");
object.rocktype2 =
ReadField(line, getFieldColumn(headerFields, fieldName));
}
// Reading coordinates.
fieldName = getConstName(constNames, "FIELD_COORDINATES");
line = ReadField(line, getFieldColumn(headerFields, fieldName));
object.paths = ReadCoordinates(line, keyword);
// Adding next object.
objects.push_back(object);
}
myfile.close();
std::cout << "Objects read: " << objects.size() << std::endl;
return (int)(objects.size());
}
//========================================================================================
}; // namespace ConverterLib
| 30.721212 | 90 | 0.613336 | [
"object",
"vector"
] |
cbe55f215e95088c3765e218a03234e1afec0a6b | 3,483 | cpp | C++ | src/RcppExports.cpp | tnagler/wdm-r | a6452c388addc415b47f920970a2de490728182d | [
"MIT"
] | 2 | 2018-06-24T15:18:56.000Z | 2022-03-29T10:50:39.000Z | src/RcppExports.cpp | tnagler/wdm-r | a6452c388addc415b47f920970a2de490728182d | [
"MIT"
] | null | null | null | src/RcppExports.cpp | tnagler/wdm-r | a6452c388addc415b47f920970a2de490728182d | [
"MIT"
] | null | null | null | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <Rcpp.h>
using namespace Rcpp;
#ifdef RCPP_USE_GLOBAL_ROSTREAM
Rcpp::Rostream<true>& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
Rcpp::Rostream<false>& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
#endif
// wdm_cpp
double wdm_cpp(const std::vector<double>& x, const std::vector<double>& y, std::string method, const std::vector<double>& weights, bool remove_missing);
RcppExport SEXP _wdm_wdm_cpp(SEXP xSEXP, SEXP ySEXP, SEXP methodSEXP, SEXP weightsSEXP, SEXP remove_missingSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const std::vector<double>& >::type x(xSEXP);
Rcpp::traits::input_parameter< const std::vector<double>& >::type y(ySEXP);
Rcpp::traits::input_parameter< std::string >::type method(methodSEXP);
Rcpp::traits::input_parameter< const std::vector<double>& >::type weights(weightsSEXP);
Rcpp::traits::input_parameter< bool >::type remove_missing(remove_missingSEXP);
rcpp_result_gen = Rcpp::wrap(wdm_cpp(x, y, method, weights, remove_missing));
return rcpp_result_gen;
END_RCPP
}
// wdm_mat_cpp
Rcpp::NumericMatrix wdm_mat_cpp(const Rcpp::NumericMatrix& x, std::string method, const std::vector<double>& weights, bool remove_missing);
RcppExport SEXP _wdm_wdm_mat_cpp(SEXP xSEXP, SEXP methodSEXP, SEXP weightsSEXP, SEXP remove_missingSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const Rcpp::NumericMatrix& >::type x(xSEXP);
Rcpp::traits::input_parameter< std::string >::type method(methodSEXP);
Rcpp::traits::input_parameter< const std::vector<double>& >::type weights(weightsSEXP);
Rcpp::traits::input_parameter< bool >::type remove_missing(remove_missingSEXP);
rcpp_result_gen = Rcpp::wrap(wdm_mat_cpp(x, method, weights, remove_missing));
return rcpp_result_gen;
END_RCPP
}
// indep_test_cpp
Rcpp::List indep_test_cpp(const std::vector<double>& x, const std::vector<double>& y, std::string method, const std::vector<double>& weights, bool remove_missing, std::string alternative);
RcppExport SEXP _wdm_indep_test_cpp(SEXP xSEXP, SEXP ySEXP, SEXP methodSEXP, SEXP weightsSEXP, SEXP remove_missingSEXP, SEXP alternativeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const std::vector<double>& >::type x(xSEXP);
Rcpp::traits::input_parameter< const std::vector<double>& >::type y(ySEXP);
Rcpp::traits::input_parameter< std::string >::type method(methodSEXP);
Rcpp::traits::input_parameter< const std::vector<double>& >::type weights(weightsSEXP);
Rcpp::traits::input_parameter< bool >::type remove_missing(remove_missingSEXP);
Rcpp::traits::input_parameter< std::string >::type alternative(alternativeSEXP);
rcpp_result_gen = Rcpp::wrap(indep_test_cpp(x, y, method, weights, remove_missing, alternative));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_wdm_wdm_cpp", (DL_FUNC) &_wdm_wdm_cpp, 5},
{"_wdm_wdm_mat_cpp", (DL_FUNC) &_wdm_wdm_mat_cpp, 4},
{"_wdm_indep_test_cpp", (DL_FUNC) &_wdm_indep_test_cpp, 6},
{NULL, NULL, 0}
};
RcppExport void R_init_wdm(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| 49.757143 | 188 | 0.747344 | [
"vector"
] |
cbe64698551beca1c6a401721901b254a5645e77 | 32,408 | cpp | C++ | src/AsyncWebServerMaintainer.cpp | Suicyc1e/Sequoia | 7a31bde385673e5522373eb7a2ee33c4042c3b8d | [
"MIT"
] | null | null | null | src/AsyncWebServerMaintainer.cpp | Suicyc1e/Sequoia | 7a31bde385673e5522373eb7a2ee33c4042c3b8d | [
"MIT"
] | null | null | null | src/AsyncWebServerMaintainer.cpp | Suicyc1e/Sequoia | 7a31bde385673e5522373eb7a2ee33c4042c3b8d | [
"MIT"
] | null | null | null | #include <AsyncWebServerMaintainer.h>
#include <SmartDoorBell.h>
#include <SDCardMaintainer.h>
#include <SmartPlantCarer.h>
#include <SpeakerMaintainer.h>
#include <TesterOfTheFeatures.h>
#include <ClampMaintainer.h>
#include <ScalesMaintainer.h>
#include <SmartPetFeeder.h>
const char* UI_CONTROL_ELEMENT_ID = "output";
const char* UI_CONTROL_ELEMNT_STATE = "state";
const char* UI_CONTROL_CONNECT_BUTTON_CONNECT = "connect";
AsyncWebServerMaintainer::AsyncWebServerMaintainer() : _asyncWebServer(AsyncWebServer(80)),
_processor([this](const String &data) -> String
{ return VariablesProcessor(data); })
{
//InitializeMainStageWebServer();
//InitializeInitialWebServer();
//_asyncWebServer.begin();
Serial.println("Starting Async WebServer.");
InitializeInitialWebServer();
_asyncWebServer.begin();
}
void AsyncWebServerMaintainer::StartWebServer(WebServerPhase phase)
{
switch (phase)
{
case WebServerPhase::INIT_PHASE:
{
_asyncWebServer.reset();
InitializeInitialWebServer();
//_asyncWebServer.begin();
}
break;
case WebServerPhase::READY_PHASE:
{
_asyncWebServer.reset();
InitializeMainStageWebServer();
//_asyncWebServer.begin();
}
break;
}
}
AsyncWebServerMaintainer::~AsyncWebServerMaintainer()
{
}
String AsyncWebServerMaintainer::VariablesProcessor(const String &data)
{
//TODO::Implement these variables regarding to the current state of things...
//Callbacks...
// date
// ZConnect
// ip_video_stream
// fire_s_state
// vibro_s_state
// mat_s_state
// mot_s_state
Serial.println(data);
if (data == "fire_s_state")
{
return "no alarm";
}
if (data == "date")
{
return "19/10/2021";
}
if (data == "ZConnect")
{
return "Connected!";
}
if (data == "ip_video_stream")
{
// String address = SmartDoorBell::GetInstance()->GetOwnIPAddress().toString();
// return address;
return "/"; //yeah, baby.
}
if (data == "mat_s_state")
{
return "no alaram";
}
if (data == "water_level")
{
return "100";
}
if (data == "vibro_s_state")
{
return "no alaram";
}
if (data == "mot_s_state")
{
return "no alaram";
}
if (data == "current_weight")
{
return String(SmartPetFeeder::GetInstance()->GetCurrentWeight() * 1000, 2);
}
return String();
}
String AsyncWebServerMaintainer::ButtonsProcessor(const String &data)
{
Serial.println("Entering ButtonsProcessor");
Serial.println(data);
if (data == "ZigBeeConnect")
{
Serial.println("ZigBeeConnect ---> OK");
return String();
}
return String();
}
void AsyncWebServerMaintainer::PlantCarerZigBeeStart(AsyncWebServerRequest *request)
{
SmartPlantCarer::GetInstance()->StartZigBee();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PlantCarerWaterPumpControl(AsyncWebServerRequest *request)
{
if(!request->hasArg("value"))
{
request->send(404);
return;
}
String var = request->arg("value");
int val = atoi(request->arg("value").c_str());
SmartPlantCarer::GetInstance()->EnableWaterPump(val);
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PlantCarerWaterLockerControl(AsyncWebServerRequest *request)
{
if(!request->hasArg("value") || !request->hasArg("id"))
{
request->send(404);
return;
}
int id = atoi(request->arg("id").c_str());
int val = atoi(request->arg("value").c_str());
SmartPlantCarer::GetInstance()->EnableWaterLocker(id, val);
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PlantCarerLedBulbControl(AsyncWebServerRequest *request)
{
if(!request->hasArg("value"))
{
request->send(404);
return;
}
int val = atoi(request->arg("value").c_str());
SmartPlantCarer::GetInstance()->EnableLedBulbRelay(val);
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PlantCarerWaterLevelCheck(AsyncWebServerRequest *request)
{
Serial.println("DEBUG: Check WATER LEVEL!");
//1 ---> HIGH
//0 ---> LOW
if(!request->hasArg("level"))
{
request->send(404);
return;
}
int level = atoi(request->arg("level").c_str());
if (level == 0)
{
Serial.println("Check LOW side water level: " + SmartPlantCarer::GetInstance()->GetLowWaterLevelState());
}
if (level == 1)
{
Serial.println("Check HIGH side water level: " + SmartPlantCarer::GetInstance()->GetHightWaterLevelState());
}
else
{
Serial.printf("WARNING: Unknown level parameter: %d. HIGH side water level: %d \n", level, SmartPlantCarer::GetInstance()->GetHightWaterLevelState());
}
int currentLevel = level ? SmartPlantCarer::GetInstance()->GetHightWaterLevelState() : SmartPlantCarer::GetInstance()->GetLowWaterLevelState();
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"waterLevel\":%d,", currentLevel);
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(200, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PlantCarerSoilHumidityLevelCheck(AsyncWebServerRequest *request)
{
if(!request->hasArg("id"))
{
request->send(404);
return;
}
int id = atoi(request->arg("id").c_str());
int currentLevel = SmartPlantCarer::GetInstance()->GetSoilHumididtyState(id);
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"soilHumidityLevel\":%d,", currentLevel);
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(200, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellZigBeeStart(AsyncWebServerRequest *request)
{
#ifndef DEBUG_MOBILE_APPLICATION_DEVELOPMENT
SmartDoorBell::GetInstance()->StartZigBee();
#endif
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellSetControl(AsyncWebServerRequest *request)
{
if(!request->hasArg("value") || !request->hasArg("controlId"))
{
request->send(404);
return;
}
int id = atoi(request->arg("controlId").c_str());
int val = atoi(request->arg("value").c_str());
if (!IsValidDoorBellAttribute(id))
{
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"errorDescription\": unhandled attribute id!");
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(404, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
#ifndef DEBUG_MOBILE_APPLICATION_DEVELOPMENT
SmartDoorBell::GetInstance()->AttributeChangedProcessor(id, val, AttributeChangeSource::SYSTEM_INTERNAL);
#endif
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellCheckButtonAlarm(AsyncWebServerRequest *request)
{
bool alarm = SmartDoorBell::GetInstance()->GetButtonTriggered();
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"buttonTriggered\":%d,", alarm);
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(200, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellCheckMicrophoneAlarm(AsyncWebServerRequest *request)
{
bool alarm = SmartDoorBell::GetInstance()->GetMicrophoneTriggered();
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"microPhoneTriggered\":%d,", alarm);
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(200, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellCheckBoxVibrationAlarm(AsyncWebServerRequest *request)
{
bool alarm = SmartDoorBell::GetInstance()->GetBoxVibrationTriggered();
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"boxVibrationTriggered\":%d,", alarm);
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(200, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellCheckAdditionalSensorsMapper(AsyncWebServerRequest *request)
{
uint32_t sensorsMapper = SmartDoorBell::GetInstance()->GetAdditionalSensorMaper();
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"sensorsMapper\":%d,", sensorsMapper);
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(200, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellGetDeviceStatus(AsyncWebServerRequest *request)
{
//TODO:: Implement it!
}
void AsyncWebServerMaintainer::DoorBellGetSoundTrack(AsyncWebServerRequest *request)
{
//TODO:: Implement it!
}
bool isValidSpeakerCommand(int commandId)
{
return (commandId == static_cast<int>(SPEAKER_COMMANDS::STOP_RESUME) ||
commandId == static_cast<int>(SPEAKER_COMMANDS::SET_LEVEL) ||
commandId == static_cast<int>(SPEAKER_COMMANDS::PLAY_NEXT_SONG));
}
void AsyncSetSoundControl(void *parameter)
{
SoundControlCommand *command = (SoundControlCommand*) parameter;
if (command->_id == static_cast<int>(SPEAKER_COMMANDS::STOP_RESUME)) //sound control
{
SpeakerMaintainer::GetInstance()->MusicFlowControl(command->_val);
}
else if (command->_id == static_cast<int>(SPEAKER_COMMANDS::SET_LEVEL)) //sound resume
{
SpeakerMaintainer::GetInstance()->SetLevel(command->_val);
}
else if (command->_id == static_cast<int>(SPEAKER_COMMANDS::PLAY_NEXT_SONG)) //sound resume
{
//Under TEST!
SpeakerMaintainer::GetInstance()->SetNextSong(NEXT_SONG, true);
}
vTaskDelete(NULL);
};
void AsyncWebServerMaintainer::DoorBellSoundControl(AsyncWebServerRequest *request)
{
if(!request->hasArg("value") || !request->hasArg("controlId"))
{
request->send(404);
return;
}
int id = atoi(request->arg("controlId").c_str());
int val = atoi(request->arg("value").c_str());
if(!isValidSpeakerCommand(id))
{
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"errorDescription\": unhandled controlId!");
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(404, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
SpeakerMaintainer::GetInstance()->AsyncSoundControl(SoundControlCommand{id, val});
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::NetworkSetupControl(AsyncWebServerRequest *request)
{
Serial.println("Nothing to do");
}
void AsyncWebServerMaintainer::DoorBellLedTest(AsyncWebServerRequest *request)
{
TesterOfTheFeatures::GetInstance()->IncrementLedTestPhase();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellScalesTare(AsyncWebServerRequest *request)
{
ScalesMaintainer::GetInstance()->AsyncTare();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellScalesMeasure(AsyncWebServerRequest *request)
{
ScalesMaintainer::GetInstance()->AsyncGetWeight();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellToggleClamp(AsyncWebServerRequest *request)
{
//DEBUG!!!!
bool currentState = digitalRead(CLAMP_PIO);
Serial.printf("Current state: %d", currentState);
digitalWrite(CLAMP_PIO, !currentState);
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::DoorBellToggleClampTimed(AsyncWebServerRequest *request)
{
if(!request->hasArg("timeMs"))
{
request->send(404);
return;
}
int msToBeOpened = atoi(request->arg("timeMs").c_str());
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
ClampMaintainer::GetInstance()->Feed(msToBeOpened);
}
void AsyncWebServerMaintainer::PetFeederScalesTare(AsyncWebServerRequest *request)
{
ScalesMaintainer::GetInstance()->AsyncTare();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PetFeederScalesMeasure(AsyncWebServerRequest *request)
{
ScalesMaintainer::GetInstance()->AsyncGetWeight();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PetFeederToggleClamp(AsyncWebServerRequest *request)
{
//DEBUG!!!!
bool currentState = digitalRead(CLAMP_PIO);
Serial.printf("Current state: %d", currentState);
digitalWrite(CLAMP_PIO, !currentState);
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PetFeederToggleClampTimed(AsyncWebServerRequest *request)
{
if(!request->hasArg("timeMs"))
{
request->send(404);
return;
}
int msToBeOpened = atoi(request->arg("timeMs").c_str());
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
ClampMaintainer::GetInstance()->Feed(msToBeOpened);
}
void AsyncWebServerMaintainer::PetFeederScalesCalibrate(AsyncWebServerRequest *request)
{
ScalesMaintainer::GetInstance()->AsyncCalibrateMeasure();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PetFeederSetScale(AsyncWebServerRequest *request)
{
if(!request->hasArg("scalesFactor"))
{
request->send(404);
return;
}
int32_t scalesFactor = atoi(request->arg("scalesFactor").c_str());
ScalesMaintainer::GetInstance()->AsyncSetScalesFactor(scalesFactor);
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PetFeederDirectMeasure(AsyncWebServerRequest *request)
{
if(!request->hasArg("iterationsNumber"))
{
request->send(404);
return;
}
int32_t iterationsNumber = atoi(request->arg("iterationsNumber").c_str());
float result = ScalesMaintainer::GetInstance()->DirectGetWeight(iterationsNumber);
SmartPetFeeder::GetInstance()->SetCurrentWeight(result);
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"weight\":%f,", result);
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(200, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PetFeederFeedThePet(AsyncWebServerRequest *request)
{
if(!request->hasArg("foodWeightGramms"))
{
request->send(404);
return;
}
int32_t foodWeight = atoi(request->arg("foodWeightGramms").c_str());
SmartPetFeeder::GetInstance()->FeedThePetAsync(foodWeight);
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::PetFeederSoundControl(AsyncWebServerRequest *request)
{
if(!request->hasArg("value") || !request->hasArg("controlId"))
{
request->send(404);
return;
}
int id = atoi(request->arg("controlId").c_str());
int val = atoi(request->arg("value").c_str());
if(!isValidSpeakerCommand(id))
{
static char json_response[1024];
char * p = json_response;
*p++ = '{';
p+=sprintf(p, "\"errorDescription\": unhandled controlId!");
*p++ = '}';
*p++ = 0;
AsyncWebServerResponse * response = request->beginResponse(404, "application/json", json_response);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
SoundControlCommand command{id, val};
request->send(response);
#ifndef DEBUG_MOBILE_APPLICATION_DEVELOPMENT
if (id == static_cast<int>(SPEAKER_COMMANDS::STOP_RESUME)) //sound control
{
SpeakerMaintainer::GetInstance()->MusicFlowControl(val);
}
else if (id == static_cast<int>(SPEAKER_COMMANDS::SET_LEVEL)) //sound resume
{
SpeakerMaintainer::GetInstance()->SetLevel(val);
}
else if (id == static_cast<int>(SPEAKER_COMMANDS::PLAY_NEXT_SONG)) //sound resume
{
//Under TEST!
SpeakerMaintainer::GetInstance()->SetNextSong(NEXT_SONG, true);
}
#endif
}
void AsyncWebServerMaintainer::PetFeederGetSoundTrack(AsyncWebServerRequest *request)
{
//TODO:: Implement it!
}
void AsyncWebServerMaintainer::PetFeederLedTest(AsyncWebServerRequest *request)
{
TesterOfTheFeatures::GetInstance()->IncrementLedTestPhase();
AsyncWebServerResponse * response = request->beginResponse(200);
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
}
void AsyncWebServerMaintainer::InitializeInitialWebServer()
{
//Main
_asyncWebServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
//request->send(SD, "/index.html", String(), false, std::bind(&AsyncWebServerMaintainer::Processor, this, std::placeholders::_1));
request->send(SD, "/AccessPointInterface/index.html", String(), false, VariablesProcessor);
});
// Route to load style.css file
_asyncWebServer.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(SD, "/AccessPointInterface/style.css", "text/css"); });
//_asyncWebServer.on("/networkCredentials/formData", HTTP_POST, PlantCarerWaterLockerControl);
_networkCredentialsHandler =
new AsyncCallbackJsonWebHandler("/networkCredentials/formData", [&](AsyncWebServerRequest *request, JsonVariant &json)
{
StaticJsonDocument<200> data;
Serial.println("Entering FormHandler.");
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
//parse json here
const char *ssid = data["ssid"];
const char *password = data["password"];
Serial.printf("Network Credentials. SSID: %s PASSWORD: %s\n", ssid, password);
String response;
serializeJson(data, response);
request->send(200, "application/json", response);
Serial.println(response);
//CONTINUE HERE!
//Create ASYNC Call to the Handler ---> Since Handler is not Async And may block the server.
_networkSelectedCallBack(ssid, password);
});
_asyncWebServer.addHandler(_networkCredentialsHandler);
}
void AsyncWebServerMaintainer::InitializeMainStageWebServer()
{
//AwsTemplateProcessor pr = [this](const String& data) -> String { return Processor(data);};
//Plant Carer
_asyncWebServer.on("/plantCarer/waterPumpState", HTTP_POST, PlantCarerWaterPumpControl);
_asyncWebServer.on("/plantCarer/waterLocker", HTTP_POST, PlantCarerWaterLockerControl);
_asyncWebServer.on("/plantCarer/ledBulb", HTTP_POST, PlantCarerLedBulbControl);
_asyncWebServer.on("/plantCarer/waterLevel", HTTP_GET, PlantCarerWaterLevelCheck);
_asyncWebServer.on("/plantCarer/soilHumidityLevel", HTTP_GET, PlantCarerSoilHumidityLevelCheck);
_asyncWebServer.on("/plantCarer/startZigBee", HTTP_POST, PlantCarerZigBeeStart);
//Smart-Door-Bell
_asyncWebServer.on("/doorBell/deviceStatus", HTTP_GET, DoorBellGetDeviceStatus);
_asyncWebServer.on("/doorBell/startZigBee", HTTP_POST, DoorBellZigBeeStart);
_asyncWebServer.on("/doorBell/setControl", HTTP_POST, DoorBellSetControl);
_asyncWebServer.on("/doorBell/checkButtonAlaram", HTTP_GET, DoorBellCheckButtonAlarm);
_asyncWebServer.on("/doorBell/checkMicroPhoneAlaram", HTTP_GET, DoorBellCheckMicrophoneAlarm);
_asyncWebServer.on("/doorBell/checkBoxVibrationAlarm", HTTP_GET, DoorBellCheckBoxVibrationAlarm);
_asyncWebServer.on("/doorBell/getAdditionalSensorsMapper", HTTP_GET, DoorBellCheckAdditionalSensorsMapper);
_asyncWebServer.on("/doorBell/soundControl", HTTP_POST, DoorBellSoundControl);
_asyncWebServer.on("/doorBell/getCurrentTrack", HTTP_GET, DoorBellGetSoundTrack);
_asyncWebServer.on("/doorBell/ledTest", HTTP_GET, DoorBellLedTest);
#ifdef BUILD_FOR_DOOR_BELL
_asyncWebServer.on("/doorBell/scalesTare", HTTP_GET, DoorBellScalesTare);
_asyncWebServer.on("/doorBell/scalesMeasure", HTTP_GET, DoorBellScalesMeasure);
#endif
_asyncWebServer.on("/doorBell/toggleClamp", HTTP_GET, DoorBellToggleClamp);
_asyncWebServer.on("/doorBell/toggleClampTimed", HTTP_GET, DoorBellToggleClampTimed);
//Pet Feeder
_asyncWebServer.on("/petFeeder/scalesTare", HTTP_GET, PetFeederScalesTare);
_asyncWebServer.on("/petFeeder/scalesMeasure", HTTP_GET, PetFeederScalesMeasure);
_asyncWebServer.on("/petFeeder/toggleClamp", HTTP_GET, PetFeederToggleClamp);
_asyncWebServer.on("/petFeeder/toggleClampTimed", HTTP_GET, PetFeederToggleClampTimed);
_asyncWebServer.on("/petFeeder/scalesCalibrate", HTTP_GET, PetFeederScalesCalibrate);
_asyncWebServer.on("/petFeeder/setScale", HTTP_GET, PetFeederSetScale);
_asyncWebServer.on("/petFeeder/scalesDirectMeasure", HTTP_GET, PetFeederDirectMeasure);
_asyncWebServer.on("/petFeeder/feedThePet", HTTP_GET, PetFeederFeedThePet);
_asyncWebServer.on("/petFeeder/soundControl", HTTP_POST, PetFeederSoundControl);
_asyncWebServer.on("/petFeeder/getCurrentTrack", HTTP_GET, PetFeederGetSoundTrack);
_asyncWebServer.on("/petFeeder/ledTest", HTTP_GET, PetFeederLedTest);
//TODO:: Add Web GUI Enable-Disable.
#ifndef DEBUG_MOBILE_APPLICATION_DEVELOPMENT
// _asyncWebServer.serveStatic("/", SD, "index.html").setCacheControl("max-age=600").setTemplateProcessor(VariablesProcessor);
// _asyncWebServer.serveStatic("/style.css", SD, "style.css").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/MainLogo.png", SD, "/Assets/MainLogo.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/CornerRounder.png", SD, "/Assets/CornerRounder.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/play.png", SD, "/Assets/play.png").setCacheControl("max-age=600");
//Main
_asyncWebServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
//request->send(SD, "/index.html", String(), false, std::bind(&AsyncWebServerMaintainer::Processor, this, std::placeholders::_1));
request->send(SD, "/index.html", String(), false, VariablesProcessor);
});
// Route to load style.css file
_asyncWebServer.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(SD, "/style.css", "text/css"); });
// //Images Web (Common)
// _asyncWebServer.on("/MainLogo.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/MainLogo.png", "image/png"); });
// _asyncWebServer.on("/CornerRounder.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/CornerRounder.png", "image/png"); });
// _asyncWebServer.on("/play.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/play.png", "image/png"); });
//Images Web (Plant Carer)
#ifdef BUILD_FOR_PLANT_CARER
_asyncWebServer.serveStatic("/bulbs.png", SD, "/Assets/bulbs.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/custom.png", SD, "/Assets/custom.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/ferns.png", SD, "/Assets/ferns.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/fruit.png", SD, "/Assets/fruit.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/gorsh013.png", SD, "/Assets/gorsh013.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/modebl.png", SD, "/Assets/modebl.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/model.png", SD, "/Assets/model.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/palm.png", SD, "/Assets/palm.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/succulents.png", SD, "/Assets/succulents.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/tropl.png", SD, "/Assets/tropl.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/tropbl.png", SD, "/Assets/tropbl.png").setCacheControl("max-age=600");
_asyncWebServer.serveStatic("/100.png", SD, "/Assets/100.png").setCacheControl("max-age=600");
// _asyncWebServer.on("/bulbs.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/bulbs.png", "image/png"); });
// _asyncWebServer.on("/custom.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/custom.png", "image/png"); });
// _asyncWebServer.on("/ferns.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/ferns.png", "image/png"); });
// _asyncWebServer.on("/fruit.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/fruit.png", "image/png"); });
// _asyncWebServer.on("/gorsh013.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/gorsh013.png", "image/png"); });
// _asyncWebServer.on("/modebl.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/modebl.png", "image/png"); });
// _asyncWebServer.on("/model.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/model.png", "image/png"); });
// _asyncWebServer.on("/palm.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/palm.png", "image/png"); });
// _asyncWebServer.on("/succulents.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/succulents.png", "image/png"); });
// _asyncWebServer.on("/tropbl.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/tropbl.png", "image/png"); });
// _asyncWebServer.on("/tropbl.png", HTTP_GET, [](AsyncWebServerRequest *request)
// { request->send(SD, "/Assets/tropbl.png", "image/png"); });
#endif
//Buttons (Smart Door Bell Main Control)
_asyncWebServer.on("/buttonUpdateState", HTTP_GET, [] (AsyncWebServerRequest *request)
{
String inputMessage1;
String inputMessage2;
// GET input1 value on <ESP_IP>/buttonUpdateState?output=<inputMessage1>&state=<inputMessage2>
if (request->hasParam(UI_CONTROL_ELEMENT_ID) && request->hasParam(UI_CONTROL_ELEMNT_STATE))
{
inputMessage1 = request->getParam(UI_CONTROL_ELEMENT_ID)->value();
inputMessage2 = request->getParam(UI_CONTROL_ELEMNT_STATE)->value();
//digitalWrite(inputMessage1.toInt(), inputMessage2.toInt());
}
else
{
inputMessage1 = "No message sent";
inputMessage2 = "No message sent";
}
Serial.print("Button: ");
Serial.print(inputMessage1);
Serial.print(" - Set to: ");
Serial.println(inputMessage2);
if (inputMessage1.toInt() == 1)
{
//ScalesMaintainer::GetInstance()->AsyncCalibrateMeasure();
}
request->send(200, "text/plain", "OK");
});
_asyncWebServer.on("/ZigBeeConnect", HTTP_GET, [] (AsyncWebServerRequest *request)
{
String inputMessage1;
// GET input1 value on <ESP_IP>/buttonUpdateState?connect=<inputMessage1>
if (request->hasParam(UI_CONTROL_ELEMENT_ID))
{
inputMessage1 = request->getParam(UI_CONTROL_CONNECT_BUTTON_CONNECT)->value();
}
else
{
inputMessage1 = "No message sent";
}
Serial.print("Connect Set to: ");
Serial.println(inputMessage1);
//ScalesMaintainer::GetInstance()->AsyncCalibrateMeasure();
request->send(200, "text/plain", "OK");
});
#endif
}
AsyncWebServerMaintainer *AsyncWebServerMaintainer::GetInstance()
{
xSemaphoreTake(mutex_, portMAX_DELAY);
if (pinstance_ == nullptr)
{
pinstance_ = new AsyncWebServerMaintainer();
}
xSemaphoreGive(mutex_);
return pinstance_;
}
AsyncWebServerMaintainer *AsyncWebServerMaintainer::pinstance_{nullptr};
SemaphoreHandle_t AsyncWebServerMaintainer::mutex_{xSemaphoreCreateMutex()}; | 32.44044 | 158 | 0.662522 | [
"model"
] |
cbea19374d5896f6427ab3d089386c88f9f7a093 | 1,617 | cpp | C++ | dijkstra/bellman ford.cpp | vijayshankarrealdeal/Algorithms | 973a4ccbc9d0d49216ecddce40355fab1e6b8178 | [
"MIT"
] | 1 | 2021-03-22T07:41:14.000Z | 2021-03-22T07:41:14.000Z | dijkstra/bellman ford.cpp | vijayshankarrealdeal/Algorithms | 973a4ccbc9d0d49216ecddce40355fab1e6b8178 | [
"MIT"
] | null | null | null | dijkstra/bellman ford.cpp | vijayshankarrealdeal/Algorithms | 973a4ccbc9d0d49216ecddce40355fab1e6b8178 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <fstream>
using namespace std;
vector<int> x;
class Graph
{
public:
char i;
char f;
int w;
Graph(char i, char f, int w);
};
Graph::Graph(char i, char f, int w)
{
this->i = i;
this->f = f;
this->w = w;
}
int dist[128];
void printArr(int arr[])
{
int i;
for (i = 0; i < 128; i++)
{
if (arr[i] == 9999)
{
continue;
}
else
{
cout << arr[i] << endl;
}
}
printf("\n");
}
void bell(vector<Graph> &t, char src)
{
for (int i = 0; i < 128; i++)
{
dist[i] = 9999;
}
int min_node = src;
dist[src] = 0;
x.push_back(dist[src]);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < t.size(); j++)
{
char u = t[j].i;
char f = t[j].f;
int w = t[j].w;
if (dist[u] != 9999 && dist[u] + w < dist[f])
{
dist[f] = dist[u] + w;
x.push_back(dist[f]);
break;
}
}
}
}
main()
{
ofstream outfile;
outfile.open("bellman.txt");
vector<Graph> t;
t.push_back(Graph('s', 't', 6));
t.push_back(Graph('s', 'y', 7));
t.push_back(Graph('t', 'x', 5));
t.push_back(Graph('t', 'y', 8));
t.push_back(Graph('x', 't', -2));
t.push_back(Graph('y', 'z', 9));
t.push_back(Graph('z', 's', 2));
t.push_back(Graph('t', 'z', -4));
t.push_back(Graph('y', 'x', -3));
bell(t, 's');
for(auto k:x)
{
cout<<k<<endl;
outfile<<k<<endl;
}
}
| 18.802326 | 57 | 0.422387 | [
"vector"
] |
cbee3ee0bdb27903cde214baa34edd597f167e7b | 574 | hpp | C++ | include/saci/tree/model/tree.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | 1 | 2020-07-29T20:42:58.000Z | 2020-07-29T20:42:58.000Z | include/saci/tree/model/tree.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | null | null | null | include/saci/tree/model/tree.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | null | null | null |
// Copyright Ricardo Calheiros de Miranda Cosme 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "saci/tree/model/branch.hpp"
#include "saci/tree/model/branch_impl.hpp"
#include "saci/tree/model/branches.hpp"
#include "saci/tree/model/leaf.hpp"
#include "saci/tree/model/leaf_impl.hpp"
#include "saci/tree/model/leaves.hpp"
#include "saci/tree/model/leaves_impl.hpp"
#include "saci/tree/model/root.hpp"
#include "saci/tree/model/with_ctx.hpp"
| 31.888889 | 61 | 0.763066 | [
"model"
] |
cbf30aee2a077ebbedbc97e0f91565d0480299cb | 7,772 | cpp | C++ | benchmarks/benchmarks.cpp | appelmar/RcppThread | be8884b8e206b97ef151868b546f5730dfc09f49 | [
"MIT"
] | null | null | null | benchmarks/benchmarks.cpp | appelmar/RcppThread | be8884b8e206b97ef151868b546f5730dfc09f49 | [
"MIT"
] | null | null | null | benchmarks/benchmarks.cpp | appelmar/RcppThread | be8884b8e206b97ef151868b546f5730dfc09f49 | [
"MIT"
] | null | null | null | // [[Rcpp::plugins(cpp11)]]
// [[Rcpp::plugins(openmp)]]
// [[Rcpp::depends(RcppThread)]]
// [[Rcpp::depends(RcppParallel)]]
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(wdm)]]
#include <Eigen/Dense>
#include <wdm/eigen.hpp>
#include <Rcpp.h>
// #include <RcppParallel.h>
#include <RcppThread.h>
#include <omp.h>
#include <tbb/tbb.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <functional>
#include <vector>
namespace bench {
double
time_one(const std::function<void()>& f)
{
auto t0 = std::chrono::steady_clock::now();
f();
auto t1 = std::chrono::steady_clock::now();
return std::chrono::duration<double>(t1 - t0).count();
}
void
time_once(const std::vector<std::function<void()>>& funcs,
std::vector<double>& times)
{
for (size_t k = 0; k < funcs.size(); k++) {
times[k] += time_one(funcs[k]);
}
}
std::vector<double>
mark(std::vector<std::function<void()>> funcs, double min_sec = 1)
{
size_t min_time = 0;
std::vector<double> times(funcs.size(), 0);
while (min_time < min_sec) {
time_once(funcs, times);
min_time = *std::max_element(times.begin(), times.end());
}
return times;
}
} // end namespace bench
class BenchMethods
{
size_t n_;
std::function<void(int)> func_;
public:
BenchMethods(size_t n, std::function<void(int)> func)
: n_{ n }
, func_(func)
{}
void singleThreaded(int n)
{
for (size_t i = 0; i < n; ++i)
func_(i);
}
void ThreadPool(int n)
{
for (size_t i = 0; i < n; ++i)
quickpool::push(func_, i);
quickpool::wait();
}
void parallelFor(int n)
{
quickpool::parallel_for(0, n, func_);
}
void OpenMP_static(int n)
{
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < n; ++i)
func_(i);
}
void OpenMP_dynamic(int n)
{
#pragma omp parallel for schedule(dynamic, 1)
for (size_t i = 0; i < n; ++i)
func_(i);
}
// void RcppParallelFor(int n)
// {
// struct Job : public RcppParallel::Worker
// {
// std::function<void(int)> f;
// void operator()(std::size_t begin, std::size_t end)
// {
// for (size_t i = begin; i < end; i++)
// f(i);
// }
// } job;
// job.f = func_;
// RcppParallel::parallelFor(0, n, job);
// }
void IntelTBB(int n)
{
tbb::parallel_for(
tbb::blocked_range<int>(0, n),
[&](tbb::blocked_range<int> r) {
for (int i = r.begin(); i < r.end(); ++i) {
func_(i);
}
}
);
}
};
Rcpp::NumericVector
benchMark(std::function<void(int i)> task, size_t n, double min_sec = 10)
{
BenchMethods methods(n, task);
auto times = bench::mark({
[&] { methods.singleThreaded(n); },
[&] { methods.IntelTBB(n); },
[&] { methods.parallelFor(n); },
[&] { methods.ThreadPool(n); },
[&] { methods.OpenMP_static(n); },
[&] { methods.OpenMP_dynamic(n); }
},
min_sec);
// // compute speed up over single threaded
// const auto t0 = times[0];
// for (auto& t : times)
// t = t0 / t;
return Rcpp::wrap(times);
}
void set_colnames(Rcpp::NumericMatrix& times)
{
colnames(times) = Rcpp::CharacterVector{
"single",
"Intel TBB",
"quickpool::parallel_for", "quickpool::push",
"OpenMP static", "OpenMP dynamic",
};
}
// [[Rcpp::export]]
Rcpp::NumericMatrix
benchEmpty(Rcpp::IntegerVector ns, double min_sec = 10)
{
Rcpp::NumericMatrix times(ns.size(), 6);
for (int i = 0; i < ns.size(); i++) {
times(i, Rcpp::_) = benchMark([](int i) {}, ns[i], min_sec);
}
set_colnames(times);
return times;
}
// [[Rcpp::export]]
Rcpp::NumericMatrix
benchSqrt(Rcpp::IntegerVector ns, double min_sec = 10)
{
auto op = [](double x) {
double xx = x;
for (int j = 0; j != 1000; j++) {
xx = std::sqrt(xx);
}
};
Rcpp::NumericMatrix times(ns.size(), 6);
for (int i = 0; i < ns.size(); i++) {
std::vector<double> x(ns[i], 3.14);
times(i, Rcpp::_) = benchMark([&](int i) { op(x[i]); }, ns[i], min_sec);
}
set_colnames(times);
return times;
}
// [[Rcpp::export]]
Rcpp::NumericMatrix
benchSqrtWrite(std::vector<int> ns, double min_sec = 10)
{
auto op = [](double& x) {
for (int j = 0; j != 1000; j++) {
x = std::sqrt(x);
}
};
Rcpp::NumericMatrix times(ns.size(), 6);
for (int i = 0; i < ns.size(); i++) {
std::vector<double> x(ns[i], 3.14);
times(i, Rcpp::_) = benchMark([&](int i) { op(x[i]); }, ns[i], min_sec);
}
set_colnames(times);
return times;
}
// [[Rcpp::export]]
Rcpp::NumericMatrix
benchSqrtImbalanced(Rcpp::IntegerVector ns, double min_sec = 10)
{
auto op = [](double x, size_t i) {
double xx = x;
for (int j = 0; j < i; j++) {
xx = std::sqrt(xx);
}
};
Rcpp::NumericMatrix times(ns.size(), 6);
for (int i = 0; i < ns.size(); i++) {
std::vector<double> x(ns[i], 3.14);
times(i, Rcpp::_) = benchMark([&](int i) { op(x[i], i); }, ns[i], min_sec);
}
set_colnames(times);
return times;
}
// [[Rcpp::export]]
Rcpp::NumericMatrix
benchSqrtWriteImbalanced(std::vector<int> ns, double min_sec = 10)
{
auto op = [](double& x, size_t i) {
for (int j = 0; j < i; j++) {
x = std::sqrt(x);
}
};
Rcpp::NumericMatrix times(ns.size(), 6);
for (int i = 0; i < ns.size(); i++) {
std::vector<double> x(ns[i], 3.14);
times(i, Rcpp::_) = benchMark([&](int i) { op(x[i], i); }, ns[i], min_sec);
}
set_colnames(times);
return times;
}
// [[Rcpp::export]]
Rcpp::NumericMatrix
benchKDE(std::vector<int> ns, size_t d, double min_sec = 10)
{
using namespace Eigen;
auto kernel = [](const VectorXd& x) {
return (-x.array().pow(2) / 2).exp() / std::sqrt(3.14159 * 2);
};
auto kde = [=](const VectorXd& x) {
double n = x.size();
double sd = std::sqrt((x.array() - x.mean()).square().sum() / (n - 1));
double bw = 1.06 * sd * std::pow(n, -0.2);
VectorXd grid = VectorXd::LinSpaced(500, -1, 1);
VectorXd fhat(grid.size());
for (size_t i = 0; i < grid.size(); ++i) {
fhat(i) = kernel((x.array() - grid(i)) / bw).mean() / bw;
}
return fhat;
};
Rcpp::NumericMatrix times(ns.size(), 6);
for (int i = 0; i < ns.size(); i++) {
MatrixXd x = MatrixXd(ns[i], d).setRandom();
times(i, Rcpp::_) =
benchMark([&](int i) { kde(x.col(i)); }, d, min_sec);
}
set_colnames(times);
return times;
}
// [[Rcpp::export]]
Rcpp::NumericMatrix
benchKendall(std::vector<int> ns, size_t d, double min_sec = 10)
{
using namespace Eigen;
Rcpp::NumericMatrix times(ns.size(), 6);
for (int i = 0; i < ns.size(); i++) {
MatrixXd x = MatrixXd(ns[i], d).setRandom();
MatrixXd res = MatrixXd::Identity(d, d);
auto ktau = [&](size_t i, size_t j) {
res(i, j) = wdm::wdm(x.col(i), x.col(j), "kendall");
res(j, i) = res(i, j);
};
auto task = [&](int i) {
for (size_t j = i + 1; j < d; ++j) {
ktau(i, j);
}
};
times(i, Rcpp::_) = benchMark(task, ns[i], min_sec);
}
set_colnames(times);
return times;
}
| 24.673016 | 81 | 0.508621 | [
"vector"
] |
cbff9cc866d27cdae7195676234a733d3c8ea473 | 2,175 | cc | C++ | numerics/functions/piecewise_linear.cc | jpanikulam/experiments | be36319a89f8baee54d7fa7618b885edb7025478 | [
"MIT"
] | 1 | 2019-04-14T11:40:28.000Z | 2019-04-14T11:40:28.000Z | numerics/functions/piecewise_linear.cc | jpanikulam/experiments | be36319a89f8baee54d7fa7618b885edb7025478 | [
"MIT"
] | 5 | 2018-04-18T13:54:29.000Z | 2019-08-22T20:04:17.000Z | numerics/functions/piecewise_linear.cc | jpanikulam/experiments | be36319a89f8baee54d7fa7618b885edb7025478 | [
"MIT"
] | 1 | 2018-12-24T03:45:47.000Z | 2018-12-24T03:45:47.000Z | #include "numerics/functions/piecewise_linear.hh"
#include "logging/assert.hh"
namespace numerics {
IncreasingPiecewiseLinearFunction1d::IncreasingPiecewiseLinearFunction1d(
const std::vector<IncreasingPiecewiseLinearFunction1d::ControlPoint>& points) {
JASSERT_GE(points.size(), 2u, "Must have at least 2 points");
for (std::size_t k = 1; k < points.size(); ++k) {
JASSERT_LT(points[k - 1].x, points[k].x,
"Points must be monotonically increasing in X coordinate");
JASSERT_LT(points[k - 1].y, points[k].y,
"Points must be monotonically increasing in Y coordinate");
const double slope =
(points[k].y - points[k - 1].y) / (points[k].x - points[k - 1].x);
augmented_points_.push_back({points[k - 1].x, points[k - 1].y, slope});
}
{
const double last_slope = augmented_points_.back().slope;
augmented_points_.push_back({points.back().x, points.back().y, last_slope});
}
}
IncreasingPiecewiseLinearFunction1d IncreasingPiecewiseLinearFunction1d::inverse() const {
std::vector<IncreasingPiecewiseLinearFunction1d::ControlPoint> control_points;
for (const auto& point : augmented_points_) {
control_points.push_back({point.y, point.x});
}
return IncreasingPiecewiseLinearFunction1d(control_points);
}
double IncreasingPiecewiseLinearFunction1d::at(const double x) const {
JASSERT_GE(x, augmented_points_.front().x,
"x must be after the first point in the list");
JASSERT_LE(x, augmented_points_.back().x,
"x must be before the last point in the list");
return (*this)(x);
}
// TODO: Use binary search
double IncreasingPiecewiseLinearFunction1d::operator()(const double x) const {
for (std::size_t k = 0u; k < augmented_points_.size() - 1; ++k) {
const auto& next_pt = augmented_points_[k + 1];
if (next_pt.x >= x) {
const auto& cur_pt = augmented_points_[k];
const double x_offset = x - cur_pt.x;
const double value = (cur_pt.slope * x_offset) + cur_pt.y;
return value;
}
}
const auto& first_pt = augmented_points_.front();
return first_pt.slope * (x - first_pt.x) + first_pt.y;
}
} // namespace numerics | 36.864407 | 90 | 0.690115 | [
"vector"
] |
cbffc9d276105564020c48ae0254f3c4e5736dd0 | 2,863 | cpp | C++ | source/Player.cpp | daniel2643/Go-Fish | 9acca717d7d527aa250867fc45cae0ee48cf84f7 | [
"MIT"
] | null | null | null | source/Player.cpp | daniel2643/Go-Fish | 9acca717d7d527aa250867fc45cae0ee48cf84f7 | [
"MIT"
] | null | null | null | source/Player.cpp | daniel2643/Go-Fish | 9acca717d7d527aa250867fc45cae0ee48cf84f7 | [
"MIT"
] | null | null | null | //
// Player.cpp
// FIT1048-AA2-28306848
//
// Created by Daniel on 07/09/2017.
// Copyright © 2017 Daniel. All rights reserved.
//
#include "Player.h"
int Player::player_count = 0;
//Constructors
Player::Player(){
name = "Player" + to_string(player_count+1);
player_count++;
}
Player::Player(string init_name){
name = init_name;
player_count++;
}
//Destructor
Player::~Player(){
player_count--;
}
//Mutators
bool Player::setName(string new_name){
bool is_valid = false;
name = new_name;
is_valid = true;
return is_valid;
}
void Player::addCard(Card new_card){
bool is_insert = false;
int n = hand_cards.size();
int i = 0;
if (n==0){
hand_cards.push_back(new_card);
is_insert = true;
}
while (n==hand_cards.size() && i<n){
if (hand_cards[i].getValue() > new_card.getValue() || (hand_cards[i].getValue() == new_card.getValue() && hand_cards[i].getSuit() >= new_card.getSuit())){
hand_cards.insert(hand_cards.begin()+i, new_card);
is_insert = true;
}
i++;
}
if (!is_insert)
hand_cards.push_back(new_card);
}
//toString method
string Player::toString(){
stringstream ss;
ss << name << " ***** Cards in Hand:" << endl;
for (int i = 0; i<hand_cards.size(); i++){
ss << hand_cards[i].toString() << " ";
}
ss << endl;
return ss.str();
}
//Other methods
void Player::sortHandCards(){
int n = hand_cards.size();
for (int i=1; i<n; i++){
int j = i;
while (j>0 && ((hand_cards[j].getValue()<hand_cards[j-1].getValue()) || (hand_cards[j].getValue() == hand_cards[j-1].getValue() && hand_cards[j].getSuit()<hand_cards[j-1].getSuit()))){
hand_cards[j], hand_cards[j-1] = hand_cards[j-1], hand_cards[j];
j--;
}
}
}
bool Player::isCardIn(int new_card_value){
bool in = false;
int n = getHandCards().size();
for (int i=0; i<n; i++){
if(new_card_value==getHandCards()[i].getValue()){
in = true;
break;
}
}
return in;
}
bool Player::isFull(int card_value){
bool full = false;
int count = 0;
for (int i=0; i<getHandCards().size(); i++){
if (getHandCards()[i].getValue()==card_value)
count++;
}
if (count==4)
full = true;
return full;
}
bool Player::isEmpty(){
bool empty = false;
if (getHandCards().size() == 0)
empty = true;
return empty;
}
vector<Card> Player::removePassCard(int card_value){
vector<Card> tmp;
int i = 0;
while(i<getHandCards().size()){
if (getHandCards()[i].getValue() == card_value){
tmp.push_back(getHandCards()[i]);
hand_cards.erase(hand_cards.begin()+i);
i--;
}
i++;
}
return tmp;
}
| 22.193798 | 192 | 0.559204 | [
"vector"
] |
0204cbb92ef86681163d5f08417b7903afc8d4c1 | 4,327 | cc | C++ | components/safe_browsing/db/v4_embedded_test_server_util.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/safe_browsing/db/v4_embedded_test_server_util.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/safe_browsing/db/v4_embedded_test_server_util.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/safe_browsing/db/v4_embedded_test_server_util.h"
#include <memory>
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/base64url.h"
#include "base/bind.h"
#include "base/logging.h"
#include "components/safe_browsing/db/util.h"
#include "components/safe_browsing/db/v4_test_util.h"
#include "net/base/url_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/embedded_test_server/request_handler_util.h"
namespace safe_browsing {
namespace {
// This method parses a request URL and returns a vector of HashPrefixes that
// were being requested. It does this by:
// 1. Finding the "req" query param.
// 2. Base64 decoding it.
// 3. Parsing the FindFullHashesRequest from the decoded string.
std::vector<HashPrefix> GetPrefixesForRequest(const GURL& url) {
// Find the "req" query param.
std::string req;
bool success = net::GetValueForKeyInQuery(url, "$req", &req);
DCHECK(success) << "Requests to fullHashes:find should include the req param";
// Base64 decode it.
std::string decoded_output;
success = base::Base64UrlDecode(
req, base::Base64UrlDecodePolicy::REQUIRE_PADDING, &decoded_output);
DCHECK(success);
// Parse the FindFullHashRequest from the decoded output.
FindFullHashesRequest full_hash_req;
success = full_hash_req.ParseFromString(decoded_output);
DCHECK(success);
// Extract HashPrefixes from the request proto.
const ThreatInfo& info = full_hash_req.threat_info();
std::vector<HashPrefix> prefixes;
for (int i = 0; i < info.threat_entries_size(); ++i) {
prefixes.push_back(info.threat_entries(i).hash());
}
return prefixes;
}
// This function listens for requests to /v4/fullHashes:find, and responds with
// predetermined responses.
std::unique_ptr<net::test_server::HttpResponse> HandleFullHashRequest(
const std::map<GURL, ThreatMatch>& response_map,
const std::map<GURL, base::TimeDelta>& delay_map,
const net::test_server::HttpRequest& request) {
if (!(net::test_server::ShouldHandle(request, "/v4/fullHashes:find")))
return nullptr;
FindFullHashesResponse find_full_hashes_response;
find_full_hashes_response.mutable_negative_cache_duration()->set_seconds(600);
// Mock a response based on |response_map| and the prefixes scraped from the
// request URL.
//
// This loops through all prefixes requested, and finds all of the full hashes
// that match the prefix.
std::vector<HashPrefix> request_prefixes =
GetPrefixesForRequest(request.GetURL());
const base::TimeDelta* delay = nullptr;
for (const HashPrefix& prefix : request_prefixes) {
for (const auto& response : response_map) {
FullHash full_hash = GetFullHash(response.first);
if (V4ProtocolManagerUtil::FullHashMatchesHashPrefix(full_hash, prefix)) {
ThreatMatch* match = find_full_hashes_response.add_matches();
*match = response.second;
auto it = delay_map.find(response.first);
if (it != delay_map.end()) {
delay = &(it->second);
}
}
}
}
std::string serialized_response;
find_full_hashes_response.SerializeToString(&serialized_response);
auto http_response =
(delay ? std::make_unique<net::test_server::DelayedHttpResponse>(*delay)
: std::make_unique<net::test_server::BasicHttpResponse>());
http_response->set_content(serialized_response);
return http_response;
}
} // namespace
void StartRedirectingV4RequestsForTesting(
const std::map<GURL, ThreatMatch>& response_map,
net::test_server::EmbeddedTestServer* embedded_test_server,
const std::map<GURL, base::TimeDelta>& delay_map) {
// Static so accessing the underlying buffer won't cause use-after-free.
static std::string url_prefix;
url_prefix = embedded_test_server->GetURL("/v4").spec();
SetSbV4UrlPrefixForTesting(url_prefix.c_str());
embedded_test_server->RegisterRequestHandler(
base::BindRepeating(&HandleFullHashRequest, response_map, delay_map));
}
} // namespace safe_browsing
| 37.301724 | 80 | 0.742778 | [
"vector"
] |
0207a4a6ae0834c8f0a6d88401739575bf1d6978 | 26,086 | cpp | C++ | my_windows_test_exec/example_3.cpp | Chaojimengnan/my-windows | 85fc5c205cea0820c090ea2b46fee62c0bba552a | [
"MIT"
] | null | null | null | my_windows_test_exec/example_3.cpp | Chaojimengnan/my-windows | 85fc5c205cea0820c090ea2b46fee62c0bba552a | [
"MIT"
] | null | null | null | my_windows_test_exec/example_3.cpp | Chaojimengnan/my-windows | 85fc5c205cea0820c090ea2b46fee62c0bba552a | [
"MIT"
] | null | null | null | #include "example_3.h"
#include "stdafx.h"
DWORD WINAPI ThreadFunc(PVOID param)
{
std::tcout << _T("这是另一个线程,正在执行中~\n");
return 0;
}
void example_3()
{
/*auto thread_handle = CreateThread(NULL, 0, ThreadFunc, nullptr, CREATE_SUSPENDED, nullptr);
SetThreadPriority(thread_handle, THREAD_PRIORITY_IDLE);
ResumeThread(thread_handle);
CloseHandle(thread_handle);*/
std::tcout << _T("这是主线程,正在执行~\n");
auto thread_handle = mw::safe_handle(mw::c_create_thread(ThreadFunc));
std::tcout << _T("新线程创建完毕~\n");
// 等待线程返回
WaitForSingleObject(*thread_handle, INFINITE);
std::tcout << _T("新线程返回了~\n");
}
/////////////////////////////////////////////////////////
long g_x = 0;
DWORD WINAPI ThreadFunc1(PVOID param)
{
mw::sync::interlocked_exchange_add(g_x, 1);
return 0;
}
DWORD WINAPI ThreadFunc2(PVOID param)
{
mw::sync::interlocked_exchange_add(g_x, 1);
return 0;
}
class MyClass
{
public:
MyClass(int a)
{
this->a = a;
std::cout << a << ",进入构造函数"
<< "\n";
}
MyClass(MyClass&& t) noexcept
{
a = t.a;
std::cout << a << ",进入移动构造函数"
<< "\n";
}
MyClass(const MyClass& t) noexcept
{
a = t.a;
std::cout << a << ",进入拷贝构造函数"
<< "\n";
}
MyClass& operator=(const MyClass& t)
{
a = t.a;
return *this;
}
MyClass& operator=(MyClass&& t) noexcept
{
a = t.a;
return *this;
}
~MyClass()
{
std::cout << a << ",进入析构函数"
<< "\n";
}
int a;
private:
};
void example_3_1()
{
/*auto thread_handle1 = mw::safe_handle(mw::c_create_thread(ThreadFunc1));
auto thread_handle2 = mw::safe_handle(mw::c_create_thread(ThreadFunc2));
WaitForSingleObject(*thread_handle1, INFINITE);
WaitForSingleObject(*thread_handle2, INFINITE);
auto* my_ptr1 = (int*)malloc(sizeof(int));
auto* my_ptr2 = (int*)_aligned_malloc(sizeof(int), 2);
auto* my_ptr3 = (int*)_aligned_malloc(sizeof(int), 4);
auto* my_ptr4 = (int*)_aligned_malloc(sizeof(int), 8);
std::cout << g_x << ",完成\n";
std::cout << &g_x << "\n";
std::cout << my_ptr1 << "\n";
std::cout << my_ptr2 << "\n";
std::cout << my_ptr3 << "\n";
std::cout << my_ptr4 << "\n";*/
/*using my_type = MyClass;
mw::interlocked_list<my_type> mymy;
mymy.push(1);
mymy.push(2);
mymy.push(3);
my_type temp(0);
while (mymy.pop(temp))
{
std::cout << temp.a << "\n";
}
std::cout << mymy.size() << ",aaa\n";*/
// 申请原始内存
auto mymy = (MyClass*)_aligned_malloc(sizeof(MyClass), MEMORY_ALLOCATION_ALIGNMENT);
// 构造MyClass
new (mymy) MyClass(3);
std::cout << mymy->a << "\n";
// 调用析构函数
mymy->~MyClass();
// 释放内存
_aligned_free(mymy);
}
/////////////////////////////////////////////////////////
//mw::interlocked_list<std::string> my_list;
//mw::interlocked_list<std::string> my_out_list;
std::vector<std::string> vec_list;
std::vector<std::string> vec_out_list;
mw::sync::critical_section my_cs_input;
mw::sync::critical_section my_cs_output;
DWORD WINAPI input_thread(PVOID param)
{
for (size_t i = 0; i < 3; i++)
{
std::ostringstream s;
s << (const char*)param << ":" << i;
//my_list.push(s.str());
my_cs_input.enter();
vec_list.push_back(s.str());
my_cs_input.leave();
}
return 0;
}
DWORD WINAPI consume_thread(PVOID param)
{
std::string temp;
mw::sleep(5);
/*while (my_list.pop(temp))
{
std::ostringstream s;
s << (const char*)param << "获取到: " << temp << "\n";
my_out_list.push(s.str());
}*/
while (true)
{
//my_cs_input.enter();
if (my_cs_input.into_section_return([&temp]() {
if (vec_list.size() == 0)
return 1;
temp = vec_list.back();
vec_list.pop_back();
return 0;
}))
break;
//my_cs_input.leave();
std::ostringstream s;
s << (const char*)param << "获取到: " << temp << "\n";
my_cs_output.enter();
vec_out_list.push_back(s.str());
my_cs_output.leave();
}
return 0;
}
#include <vector>
void example_3_2()
{
std::tcout << _T("正在执行~\n");
std::shared_ptr<HANDLE> my_handles[6];
my_handles[0] = mw::safe_handle(mw::c_create_thread(input_thread, (LPVOID) "input_1", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[1] = mw::safe_handle(mw::c_create_thread(input_thread, (LPVOID) "input_2", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[2] = mw::safe_handle(mw::c_create_thread(input_thread, (LPVOID) "input_3", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[3] = mw::safe_handle(mw::c_create_thread(consume_thread, (LPVOID) "consume_1", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[4] = mw::safe_handle(mw::c_create_thread(consume_thread, (LPVOID) "consume_2", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[5] = mw::safe_handle(mw::c_create_thread(consume_thread, (LPVOID) "consume_3", nullptr, nullptr, CREATE_SUSPENDED));
HANDLE my_handles2[6] = { *my_handles[0].get(), *my_handles[1].get(), *my_handles[2].get(), *my_handles[3].get(), *my_handles[4].get(), *my_handles[5].get() };
//HANDLE my_handles2[3] = { *my_handles[0].get(),*my_handles[1].get() ,*my_handles[3].get()};
for (size_t i = 0; i < 6; i++)
{
mw::resume_thread(my_handles2[i]);
}
// 等待线程返回
WaitForMultipleObjects(6, my_handles2, true, INFINITE);
std::string temp;
/*while (my_out_list.pop(temp))
{
std::cout << temp << "\n";
}*/
for (auto&& i : vec_out_list)
{
std::cout << i << "\n";
}
}
#define CACHE_ALIGN 64
// 强制每个结构体在不同的高速缓存行
struct __declspec(align(CACHE_ALIGN)) CUSTINFO1
{
DWORD dwCustomerID; // 大部分时间只读
wchar_t szName[100]; // 大部分时间只读
// 强制下面的成员在不同的高速缓存行
__declspec(align(CACHE_ALIGN)) int nBalcanceDuw; // 读写
FILETIME ftLastOrderDate; // 读写
};
// 强制每个结构体在不同的高速缓存行
struct alignas(CACHE_ALIGN) CUSTINFO2
{
DWORD a; // 大部分时间只读
wchar_t b[100]; // 大部分时间只读
// 强制下面的成员在不同的高速缓存行
alignas(CACHE_ALIGN) int c; // 读写
FILETIME d; // 读写
};
void example_3_3()
{
std::cout << alignof(CUSTINFO1) << "\n";
std::cout << alignof(CUSTINFO2) << "\n";
std::cout << sizeof(CUSTINFO1) << "\n";
std::cout << sizeof(CUSTINFO2) << "\n";
//CUSTINFO1 a = { 0 };
CUSTINFO2 b = { 0 };
b.a = 1;
for (size_t i = 0; i < 100; i++)
{
b.b[i] = L'a';
}
b.c = 8;
b.d.dwLowDateTime = 5;
b.d.dwHighDateTime = 6;
}
void example_3_4()
{
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION mymy = nullptr;
DWORD nums = 0;
mw::get_logical_processor_information(mymy, nums);
for (size_t i = 0; i < nums; i++)
{
if (mymy[i].Relationship == RelationCache)
{
std::cout << mymy[i].Cache.LineSize << "\n";
std::cout << "\n";
}
}
free(mymy);
}
const int COUNT = 1000;
int sum = 0;
DWORD WINAPI the_first_thread(PVOID pvParam)
{
sum = 0;
for (size_t i = 1; i <= COUNT; ++i)
{
sum += i;
}
std::cout << "线程1结束\n";
return sum;
}
DWORD WINAPI the_second_thread(PVOID pvParam)
{
sum = 0;
for (size_t i = 1; i <= COUNT; ++i)
{
sum += i;
}
std::cout << "线程2结束\n";
return sum;
}
CRITICAL_SECTION cs;
DWORD WINAPI the_first_thread_safe(PVOID pvParam)
{
EnterCriticalSection(&cs);
sum = 0;
for (size_t i = 1; i <= COUNT; ++i)
{
sum += i;
}
std::cout << "线程1结束\n";
LeaveCriticalSection(&cs);
return sum;
}
DWORD WINAPI the_second_thread_safe(PVOID pvParam)
{
EnterCriticalSection(&cs);
sum = 0;
for (size_t i = 1; i <= COUNT; ++i)
{
sum += i;
}
std::cout << "线程2结束\n";
LeaveCriticalSection(&cs);
return sum;
}
void example_3_5()
{
std::vector<HANDLE> my_thread_handles;
InitializeCriticalSection(&cs);
my_thread_handles.push_back(mw::c_create_thread(the_first_thread_safe));
my_thread_handles.push_back(mw::c_create_thread(the_second_thread_safe));
WaitForMultipleObjects(my_thread_handles.size(), my_thread_handles.data(), true, INFINITE);
std::cout << "结束!\n";
std::cout << "sum = " << sum << "\n";
for (auto&& i : my_thread_handles)
{
CloseHandle(i);
}
}
DWORD WINAPI first_thread_safe(PVOID pvParam)
{
auto cs = static_cast<mw::sync::critical_section*>(pvParam);
cs->enter();
sum = 0;
for (size_t i = 1; i <= COUNT; ++i)
{
sum += i;
}
std::cout << "线程1结束\n";
cs->leave();
return sum;
}
DWORD WINAPI second_thread_safe(PVOID pvParam)
{
auto cs = static_cast<mw::sync::critical_section*>(pvParam);
cs->into_section([]() {
sum = 0;
for (size_t i = 1; i <= COUNT; ++i)
{
sum += i;
}
std::cout << "线程2结束\n";
});
return sum;
}
void example_3_6()
{
std::vector<HANDLE> my_thread_handles;
mw::sync::critical_section mymy;
my_thread_handles.push_back(mw::c_create_thread(first_thread_safe, &mymy));
my_thread_handles.push_back(mw::c_create_thread(second_thread_safe, &mymy));
WaitForMultipleObjects(my_thread_handles.size(), my_thread_handles.data(), true, INFINITE);
std::cout << "结束!\n";
std::cout << "sum = " << sum << "\n";
for (auto&& i : my_thread_handles)
{
CloseHandle(i);
}
}
mw::sync::slimrw_lock my_slim_input;
mw::sync::slimrw_lock my_slim_output;
DWORD WINAPI input_thread_slim(PVOID param)
{
for (size_t i = 0; i < 3; i++)
{
std::ostringstream s;
s << (const char*)param << ":" << i;
// 进入独占锁
my_slim_input.acquire_exclusive();
vec_list.push_back(s.str());
my_slim_input.release_exclusive();
}
return 0;
}
DWORD WINAPI consume_thread_slim(PVOID param)
{
std::string temp;
mw::sleep(5);
while (true)
{
// 进入共享锁(只读)
if (my_slim_input.into_shared_return([&temp]() {
if (vec_list.size() == 0)
return 1;
temp = vec_list.back();
return 0;
}))
break;
// 进入独占锁(写)
my_slim_input.into_exclusive([] {
vec_list.pop_back();
});
std::ostringstream s;
s << (const char*)param << "获取到: " << temp << "\n";
// 进入输出独占锁
my_slim_output.acquire_exclusive();
vec_out_list.push_back(s.str());
my_slim_output.release_exclusive();
}
return 0;
}
void example_3_7()
{
std::tcout << _T("正在执行~\n");
std::shared_ptr<HANDLE> my_handles[6];
my_handles[0] = mw::safe_handle(mw::c_create_thread(input_thread, (LPVOID) "input_1", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[1] = mw::safe_handle(mw::c_create_thread(input_thread, (LPVOID) "input_2", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[2] = mw::safe_handle(mw::c_create_thread(input_thread, (LPVOID) "input_3", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[3] = mw::safe_handle(mw::c_create_thread(consume_thread, (LPVOID) "consume_1", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[4] = mw::safe_handle(mw::c_create_thread(consume_thread, (LPVOID) "consume_2", nullptr, nullptr, CREATE_SUSPENDED));
my_handles[5] = mw::safe_handle(mw::c_create_thread(consume_thread, (LPVOID) "consume_3", nullptr, nullptr, CREATE_SUSPENDED));
HANDLE my_handles2[6] = { *my_handles[0].get(), *my_handles[1].get(), *my_handles[2].get(), *my_handles[3].get(), *my_handles[4].get(), *my_handles[5].get() };
for (size_t i = 0; i < 6; i++)
{
mw::resume_thread(my_handles2[i]);
}
// 等待线程返回
WaitForMultipleObjects(6, my_handles2, true, INFINITE);
std::string temp;
for (auto&& i : vec_out_list)
{
std::cout << i << "\n";
}
}
// 用于生产者写入和消费者读入的中介数据结构
std::vector<std::string> cv_vec_list;
// 用于输出流的读写锁
mw::sync::slimrw_lock output_stream_lock;
// 用于中介数据结构的读写锁
mw::sync::slimrw_lock cv_vec_list_lock;
// 中介数据结构最大值
constexpr int MAX_LIST_SIZE = 20;
// 用于指示中介数据结构已满的条件变量
mw::sync::condition_variable cv_vec_list_full;
// 用于指示中间数据结构已空的条件变量
mw::sync::condition_variable cv_vec_list_empty;
/// <summary>
/// 生产者线程
/// </summary>
DWORD WINAPI input_thread_slim_cv(PVOID param)
{
while (true)
{
// 进入独占模式的slim锁
cv_vec_list_lock.into_exclusive([] {
// 判断是否已满
while (cv_vec_list.size() == MAX_LIST_SIZE)
{
// 唤醒消费者,即:中介数据满啦!!
cv_vec_list_full.wake_all();
// 然后睡眠,等待消费者调用cv_vec_list_empty.wake_all
output_stream_lock.into_exclusive([] {
std::cout << "\n生产者睡了\n\n";
});
cv_vec_list_empty.sleep_slimrw(cv_vec_list_lock);
output_stream_lock.into_exclusive([] {
std::cout << "\n生产者醒了\n\n";
});
}
output_stream_lock.into_exclusive([] {
std::cout << "生产者生产了一个数据\n";
});
cv_vec_list.push_back("一份数据"); // 模拟生产一个数据
});
}
return 0;
}
/// <summary>
/// 消费者线程
/// </summary>
DWORD WINAPI consume_thread_slim_cv(PVOID param)
{
while (true)
{
// 进入独占模式的slim锁
cv_vec_list_lock.into_exclusive([] {
// 判断是否已空
while (cv_vec_list.size() == 0)
{
// 唤醒生产者,即:中介数据空啦!!
cv_vec_list_empty.wake_all();
// 然后睡眠,等待消费者调用cv_vec_list_full.wake_all
output_stream_lock.into_exclusive([] {
std::cout << "\n消费者睡了\n\n";
});
cv_vec_list_full.sleep_slimrw(cv_vec_list_lock);
output_stream_lock.into_exclusive([] {
std::cout << "\n消费者醒了\n\n";
});
}
output_stream_lock.into_exclusive([] {
std::cout << "消费者消费了一个数据\n";
});
cv_vec_list.pop_back(); // 模拟消费一个数据
});
}
return 0;
}
/// <summary>
/// 该例子展示使用条件变量和读写锁,当生产者线程将中介数据结构写入到最大值时,唤醒消费者,然后自己进入睡眠。
/// 当消费者将中介数据结构读完之后,唤醒生产者,然后自己进入睡眠
/// </summary>
void example_3_8()
{
std::vector<HANDLE> my_thread_handles;
my_thread_handles.push_back(mw::c_create_thread(input_thread_slim_cv));
my_thread_handles.push_back(mw::c_create_thread(consume_thread_slim_cv));
my_thread_handles.push_back(mw::c_create_thread(input_thread_slim_cv));
my_thread_handles.push_back(mw::c_create_thread(consume_thread_slim_cv));
my_thread_handles.push_back(mw::c_create_thread(input_thread_slim_cv));
my_thread_handles.push_back(mw::c_create_thread(consume_thread_slim_cv));
std::cin.get();
for (auto& i : my_thread_handles)
{
CloseHandle(i);
}
}
void example_3_9()
{
//auto my_handle = mw::safe_handle(mw::c_create_thread(ThreadFunc));
//
//DWORD dw = mw::sync::wait_for_single_object(*my_handle, 500);
//switch (dw)
//{
//case WAIT_OBJECT_0:
// // 线程已终止
// break;
//case WAIT_TIMEOUT:
// // 在500毫秒内,指定线程并未终止
// break;
//case WAIT_FAILED:
// // 调用失败(不合法的句柄?)
// break;
//default:
// break;
//}
std::vector<HANDLE> handles_vec;
for (size_t i = 0; i < 3; i++)
handles_vec.push_back(mw::c_create_thread(ThreadFunc));
DWORD dw = mw::sync::wait_for_multiple_object(handles_vec.size(), handles_vec.data(), false, 500);
switch (dw)
{
case WAIT_FAILED:
// 调用失败(不合法的句柄?)
break;
case WAIT_TIMEOUT:
// 在500毫秒内,没有一个指定线程并未终止
break;
case WAIT_OBJECT_0 + 0:
// 线程[0]终止
break;
case WAIT_OBJECT_0 + 1:
// 线程[1]终止
break;
case WAIT_OBJECT_0 + 2:
// 线程[2]终止
break;
}
for (auto& i : handles_vec)
CloseHandle(i);
}
DWORD WINAPI word_count(PVOID pvParam);
DWORD WINAPI spell_check(PVOID pvParam);
DWORD WINAPI grammar_check(PVOID pvParam);
HANDLE event_file_ready = nullptr;
void example_3_10()
{
// 创建一个手动重置,初始未触发的事件
event_file_ready = mw::sync::create_event();
if (!event_file_ready)
return;
// 生成三个新线程
std::vector<HANDLE> handle_list;
handle_list.push_back(mw::c_create_thread(word_count));
handle_list.push_back(mw::c_create_thread(spell_check));
handle_list.push_back(mw::c_create_thread(grammar_check));
// 打开文件,并将内容读入内存
std::cout << "正在读入文件\n";
// 触发事件,表示文件内容已经读入内存,使得三个线程能够行动
std::cout << "文件读入完成,触发事件!\n";
mw::sync::set_event(event_file_ready);
mw::sync::wait_for_multiple_object(handle_list.size(), handle_list.data());
std::cout << "所有进程执行完成!\n";
CloseHandle(event_file_ready);
for (auto&& i : handle_list)
{
CloseHandle(i);
}
}
DWORD WINAPI word_count(PVOID pvParam)
{
// 等待文件数据进入内存
mw::sync::wait_for_single_object(event_file_ready);
std::cout << "word_count访问内存块\n";
mw::sync::set_event(event_file_ready);
return 0;
}
DWORD WINAPI spell_check(PVOID pvParam)
{
// 等待文件数据进入内存
mw::sync::wait_for_single_object(event_file_ready);
// 访问内存块
std::cout << "spell_check访问内存块\n";
mw::sync::set_event(event_file_ready);
return 0;
}
DWORD WINAPI grammar_check(PVOID pvParam)
{
// 等待文件数据进入内存
mw::sync::wait_for_single_object(event_file_ready);
// 访问内存块
std::cout << "grammar_check访问内存块\n";
mw::sync::set_event(event_file_ready);
return 0;
}
HANDLE waitable_timer = nullptr;
DWORD WINAPI another_thread_wait_timer(PVOID pvParam)
{
while (true)
{
// 等待计时器触发
mw::sync::wait_for_single_object(waitable_timer);
// 访问内存块
std::cout << "线程被计时器激活!\n";
}
return 0;
}
/// <summary>
/// 将秒数转换为对应的百纳秒数,即1秒为10'000'000百纳秒,计时器以百纳秒为基本单位
/// </summary>
/// <param name="val">对应的秒数</param>
/// <returns>返回对应的纳秒数</returns>
constexpr long long operator"" _second_units(unsigned long long val)
{
return long long(val * 10'000'000);
}
void APIENTRY TimerAPCRoutine(
LPVOID lpArgToCompletionRoutine,
DWORD dwTimerLowValue,
DWORD dwTimerHighValue)
{
std::cout << "mother funker~\n";
}
/// <summary>
/// 测试可等待计时器内核对象
/// </summary>
void example_3_11()
{
SYSTEMTIME st = { 0 };
FILETIME local_time = { 0 }, utc_time = { 0 };
LARGE_INTEGER larget_utc_time = { 0 };
waitable_timer = mw::sync::create_waitable_timer(0, TIMER_ALL_ACCESS);
//st.wYear = 2021; // 年份
//st.wMonth = 12; // 十二月
//st.wDayOfWeek = 0; // 忽略
//st.wDay = 6; // 十二月第六天
//st.wHour = 10; // 上午10点
//st.wMinute = 16;
//st.wSecond = 0;
//st.wMilliseconds = 0;
//SystemTimeToFileTime(&st, &local_time);
//LocalFileTimeToFileTime(&local_time, &utc_time);
//larget_utc_time.LowPart = utc_time.dwLowDateTime;
//larget_utc_time.HighPart = utc_time.dwHighDateTime;
//auto thread_handle = mw::safe_handle(mw::c_create_thread(another_thread_wait_timer));
larget_utc_time.QuadPart = -1_second_units;
if (waitable_timer) // 第三个参数是6小时循环触发一次
mw::sync::set_waitable_timer(waitable_timer, &larget_utc_time, 5000, TimerAPCRoutine);
mw::sync::sleep_alertable();
if (waitable_timer)
CloseHandle(waitable_timer);
//std::cin.get();
}
volatile LONG index = 0;
VOID CALLBACK work_callback(
PTP_CALLBACK_INSTANCE Instance,
PVOID Context,
PTP_WORK Work)
{
auto _index = mw::sync::interlocked_increment(index);
//std::cout << "猛男归来!" << _index << "\n";
printf_s("猛男归来!%d,thread_id = %d\n", _index, mw::get_current_thread_id());
mw::sleep(1000 * _index);
//std::cout << "完成!" << _index << "\n";
printf_s("完成!%d\n", _index);
}
/// <summary>
/// 测试线程池工作项,即异步调用函数
/// </summary>
void example_3_12()
{
// 创建工作项
auto work_item = mw::create_threadpool_work(work_callback);
// 提交工作项
mw::submit_threadpool_work(work_item);
mw::submit_threadpool_work(work_item);
mw::submit_threadpool_work(work_item);
mw::submit_threadpool_work(work_item);
// 等待完成
mw::wait_for_threadpool_work_callbacks(work_item);
//std::cout << "所有提交工作项已经完成!\n";
printf_s("所有提交工作项已经完成!\n");
// 释放工作项资源
mw::close_threadpool_work(work_item);
}
VOID CALLBACK timer_callback(
PTP_CALLBACK_INSTANCE Instance,
PVOID Context,
PTP_TIMER timer)
{
printf_s("大咩德斯!\n");
Sleep(1000);
}
/// <summary>
/// 测试线程池计时器,即隔一段时间调用函数
/// </summary>
void example_3_13()
{
auto timer = mw::create_threadpool_timer(timer_callback);
FILETIME ft = { 0 };
ft.dwLowDateTime = -10000000;
mw::set_threadpool_timer(timer, &ft, 1000);
std::cout << "main_thread:" << mw::is_threadpool_timer_set(timer) << "\n";
Sleep(5000);
// 暂停计时器,然后等待当前还在执行的计时器回调,然后释放计时器结构体
mw::set_threadpool_timer(timer, nullptr);
mw::wait_for_threadpool_timer_callbacks(timer, true);
mw::close_threadpool_timer(timer);
}
VOID CALLBACK wait_callback(
PTP_CALLBACK_INSTANCE Instance,
PVOID Context,
PTP_WAIT Wait,
TP_WAIT_RESULT itResult)
{
switch (itResult)
{
case WAIT_TIMEOUT:
std::cout << "回调函数:侦测到超时!\n";
break;
case WAIT_OBJECT_0:
std::cout << "回调函数:指定内核对象激活!\n";
break;
case WAIT_ABANDONED_0:
std::cout << "回调函数:内核对象被遗弃!\n";
break;
default:
std::cout << "回调函数:BUG,进入了奇怪的地方\n";
break;
}
}
/// <summary>
/// 测试线程池等待,即等待内核对象触发,然后调用函数
/// </summary>
void example_3_14()
{
auto wait = mw::create_threadpool_wait(wait_callback);
auto test_event = mw::sync::create_event();
mw::set_threadpool_wait(wait, test_event);
Sleep(1000);
mw::sync::set_event(test_event);
Sleep(1000);
mw::wait_for_threadpool_wait_callbakcs(wait, 0);
mw::close_threadpool_wait(wait);
}
VOID CALLBACK io_callback(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_Inout_opt_ PVOID Context,
_Inout_opt_ PVOID Overlapped,
_In_ ULONG IoResult,
_In_ ULONG_PTR NumberOfBytesTransferred,
_Inout_ PTP_IO Io)
{
std::cout << IoResult << "\n";
std::cout << NumberOfBytesTransferred << "\n\n";
}
/// <summary>
/// 测试线程池io,即在异步I/O完成时调用一个函数
/// </summary>
void example_3_15()
{
auto file_handle = mw::create_file(_T("../temp/123.txt"), GENERIC_WRITE, OPEN_EXISTING, 0);
auto io_handle = mw::create_threadpool_io(file_handle, io_callback);
OVERLAPPED op1 = { 0 }, op2 = { 0 }, op3 = { 0 };
op1.Offset = -1;
op1.OffsetHigh = -1;
op2.Offset = -1;
op2.OffsetHigh = -1;
op3.Offset = -1;
op3.OffsetHigh = -1;
// 每次异步IO之前就要调用该函数
mw::start_threadpool_io(io_handle);
// 除此之外,你还需要检查返回值和GetLastError,如果不是997,那么需要调用cancle将线程池等待取消掉
mw::write_file(file_handle, "asdhausdhasud", 13, nullptr, &op1);
// 每次异步IO之前就要调用该函数
mw::start_threadpool_io(io_handle);
mw::write_file(file_handle, "___1231241231234", 16, nullptr, &op2);
// 每次异步IO之前就要调用该函数
mw::start_threadpool_io(io_handle);
mw::write_file(file_handle, "@@@@@@@", 7, nullptr, &op3);
mw::wait_for_threadpool_io_callbacks(io_handle);
CloseHandle(file_handle);
mw::close_threadpool_io(io_handle);
}
/// <summary>
/// 创建一个线程池(而不是使用默认线程池),并创建一个回调环境与其关联,最后创建一个清理组与回调环境关联。
/// </summary>
void example_3_16()
{
// 创建线程池,并指定最大线程和最小线程数量
auto threadpool = mw::create_threadpool();
mw::set_threadpool_thread_maximum(threadpool, 8);
mw::set_threadpool_thread_minimum(threadpool, 1);
// 创建回调环境,并将其与线程池关联
TP_CALLBACK_ENVIRON pcbe = { 0 };
mw::initialize_threadpool_environment(&pcbe);
// 若没有这句,则回调环境与默认线程池关联
mw::set_threadpool_callback_pool(&pcbe, threadpool);
// 创建清理组,并将其与回调环境关联,其作用是得体地销毁线程池
auto cleanup_group = mw::create_threadpool_cleanup_group();
mw::set_threadpool_callback_cleanup_group(&pcbe, cleanup_group);
// 创建工作项,不要忘记与回调环境关联
auto work_item = mw::create_threadpool_work(work_callback, nullptr, &pcbe);
// 提交工作项
mw::submit_threadpool_work(work_item);
mw::submit_threadpool_work(work_item);
mw::submit_threadpool_work(work_item);
mw::submit_threadpool_work(work_item);
// 关闭所有成员,在之前等待所有回调完成
// (在这里只有work_item一个成员),如果有多个不同类型的项,则只需这个函数就能Close所有项,不用分别调用不同的Close函数
mw::close_threadpool_cleanup_group_members(cleanup_group);
// 然后关闭清理组本身(调用之前必须确认清理组没有成员)
mw::close_threadpool_cleanup_group(cleanup_group);
// 最后关闭和释放线程池和回调环境
mw::destroy_threadpool_environment(&pcbe);
mw::close_threadpool(threadpool);
}
void* main_fiber = nullptr;
void* work_fiber = nullptr;
VOID WINAPI my_work_fiber(
LPVOID lpFiberParameter)
{
std::cout << "工作纤程:我很好哦~\n";
mw::switch_to_fiber(main_fiber);
std::cout << "工作纤程:我觉得你很幼稚,主纤程\n";
mw::switch_to_fiber(main_fiber);
std::cout << "工作纤程:纳尼!NO~~~~~\n";
}
/// <summary>
/// 纤程初步
/// </summary>
void example_3_17()
{
// 将当前线程转换为纤程
main_fiber = mw::convert_thread_to_fiber();
work_fiber = mw::create_fiber(my_work_fiber);
std::cout << "主纤程:你好吗,工作纤程?\n";
mw::switch_to_fiber(work_fiber);
std::cout << "主纤程:是吗,我也很好。\n";
mw::switch_to_fiber(work_fiber);
std::cout << "主纤程:那你去死吧(调用DeleteFiber)\n";
mw::delete_fiber(work_fiber);
std::cout << "完毕\n";
mw::convert_fiber_to_thread();
}
DWORD WINAPI thread_tls_getter(PVOID param)
{
auto index = reinterpret_cast<DWORD>(param);
mw::tls_set_value(index, (LPVOID)10);
std::cout << mw::get_current_thread_id() << ":" << (int)mw::tls_get_value(index);
return 0;
}
/// <summary>
/// TLS尝试
/// </summary>
void example_3_18()
{
auto index = mw::tls_alloc();
auto thread_handle = mw::c_create_thread(thread_tls_getter, (LPVOID)index);
mw::tls_set_value(index, (LPVOID)5);
std::cout << mw::get_current_thread_id() << ":" << (int)mw::tls_get_value(index);
mw::sync::wait_for_single_object(thread_handle);
mw::tls_free(index);
CloseHandle(thread_handle);
} | 24.086796 | 163 | 0.614813 | [
"vector"
] |
0209c6435b094f43716f3f329466d78ab225ae9d | 8,012 | cpp | C++ | clove/src/measure_chain.cpp | msmania/procjack | a8e7a48208d776235c2808f5f60ff1bd754c1279 | [
"MIT"
] | 12 | 2017-09-26T01:27:55.000Z | 2022-03-27T12:13:09.000Z | clove/src/measure_chain.cpp | msmania/procjack | a8e7a48208d776235c2808f5f60ff1bd754c1279 | [
"MIT"
] | null | null | null | clove/src/measure_chain.cpp | msmania/procjack | a8e7a48208d776235c2808f5f60ff1bd754c1279 | [
"MIT"
] | 5 | 2019-12-12T06:19:30.000Z | 2022-03-27T10:53:43.000Z | #include <windows.h>
#include <vector>
#include <memory>
#include <numeric>
#include "../../common.h"
#include "pack.h"
#include "page.h"
void Log(LPCWSTR format, ...);
std::vector<uint64_t> address_chain(const char *str);
void WaitAndThenCleanup();
extern "C" {
extern uint8_t MeasurementChain_Start;
extern uint8_t MeasurementChain_Checkpoint;
extern uint8_t MeasurementChain_End;
}
extern ExecutablePages g_exec_pages;
extern std::vector<std::unique_ptr<CodePack>> g_packs;
extern SRWLOCK g_shim_lock;
/*
void M_Start() {
++(*reinterpret_cast<uint32_t*>(0x8ffffffffffffff0));
*reinterpret_cast<uint64_t*>(0x8ffffffffffffff8) = __rdtsc();
}
void M_Checkpoint() {
auto t = __rdtsc();
reinterpret_cast<uint64_t*>(0x8fffffffffffffe0)[0x0] +=
(t - *reinterpret_cast<uint64_t*>(0x8ffffffffffffff8));
*reinterpret_cast<uint64_t*>(0x8ffffffffffffff8) = t;
++(*reinterpret_cast<uint32_t*>(0x8ffffffffffffff0));
}
*/
struct MeasurementChainPack final : public CodePack {
class Template_Start : public CodeTemplate {
#ifdef _WIN64
static constexpr uint32_t offset_CallCount = 0x04;
static constexpr uint32_t offset_Checkpoint = 0x19;
#else
static constexpr uint32_t offset_CallCount = 0x03;
static constexpr uint32_t offset_Checkpoint_L = 0x0c;
static constexpr uint32_t offset_Checkpoint_H = 0x12;
#endif
public:
size_t Size() const {
return &MeasurementChain_Checkpoint - &MeasurementChain_Start;
}
void CopyTo(void *destination) const {
std::memcpy(destination, &MeasurementChain_Start, Size());
}
bool Fill(void *start_address,
const void *call_count,
const void *checkpoint,
const void *final_jump_to) const {
*at<const void*>(start_address, offset_CallCount) = call_count;
#ifdef _WIN64
*at<const void*>(start_address, offset_Checkpoint) = checkpoint;
#else
*at<const void*>(start_address, offset_Checkpoint_L) = checkpoint;
*at<const void*>(start_address, offset_Checkpoint_H)
= at<const void>(checkpoint, 4);
#endif
return PutImmediateNearJump(
at<void>(start_address, static_cast<uint32_t>(Size() - 5)),
final_jump_to);
}
};
class Template_Checkpoint : public CodeTemplate {
#ifdef _WIN64
static constexpr uint32_t offset_Total1 = 0x05;
static constexpr uint32_t offset_Checkpoint1 = 0x12;
static constexpr uint32_t offset_Total2 = 0x2b;
static constexpr uint32_t offset_Checkpoint2 = 0x38;
static constexpr uint32_t offset_CallCount = 0x45;
#else
static constexpr uint32_t offset_Total1_L = 0x06;
static constexpr uint32_t offset_Total1_H = 0x0c;
static constexpr uint32_t offset_Checkpoint1_L = 0x12;
static constexpr uint32_t offset_Checkpoint1_H = 0x18;
static constexpr uint32_t offset_Total2_L = 0x22;
static constexpr uint32_t offset_Total2_H = 0x2a;
static constexpr uint32_t offset_Checkpoint2_L = 0x2f;
static constexpr uint32_t offset_Checkpoint2_H = 0x35;
static constexpr uint32_t offset_CallCount = 0x3a;
#endif
public:
size_t Size() const {
return &MeasurementChain_End - &MeasurementChain_Checkpoint;
}
void CopyTo(void *destination) const {
std::memcpy(destination, &MeasurementChain_Checkpoint, Size());
}
bool Fill(void *start_address,
const void *call_count,
const void *checkpoint,
const void *total_ticks,
const void *final_jump_to) const {
#ifdef _WIN64
*at<const void*>(start_address, offset_Total1)
= *at<const void*>(start_address, offset_Total2)
= total_ticks;
*at<const void*>(start_address, offset_Checkpoint1)
= *at<const void*>(start_address, offset_Checkpoint2)
= checkpoint;
#else
*at<const void*>(start_address, offset_Total1_L)
= *at<const void*>(start_address, offset_Total2_L)
= total_ticks;
*at<const void*>(start_address, offset_Total1_H)
= *at<const void*>(start_address, offset_Total2_H)
= at<const void>(total_ticks, 4);
*at<const void*>(start_address, offset_Checkpoint1_L)
= *at<const void*>(start_address, offset_Checkpoint2_L)
= checkpoint;
*at<const void*>(start_address, offset_Checkpoint1_H)
= *at<const void*>(start_address, offset_Checkpoint2_H)
= at<const void>(checkpoint, 4);
#endif
*at<const void*>(start_address, offset_CallCount) = call_count;
return PutImmediateNearJump(
at<void>(start_address, static_cast<uint32_t>(Size() - 5)),
final_jump_to);
}
};
const Template_Start template_start_;
const Template_Checkpoint template_checkpoint_;
uint64_t checkpoint_;
const uint32_t n_;
std::vector<uint32_t> call_count_;
std::vector<uint64_t> ticks_;
std::vector<void*> function_target_;
std::vector<void*> function_trampoline_;
std::vector<void*> function_detour_;
MeasurementChainPack(const std::vector<uint64_t> &address_chain)
: checkpoint_(0),
n_(static_cast<uint32_t>(address_chain.size())),
call_count_(n_, 0),
ticks_(n_, 0),
function_target_(n_, 0),
function_trampoline_(n_, 0),
function_detour_(n_, 0) {
for (uint32_t i = 0; i < n_; ++i) {
function_target_[i]
= function_trampoline_[i]
= reinterpret_cast<void*>(address_chain[i]);
}
}
bool ActivateDetourInternal(ExecutablePages &exec_pages) {
if (n_ < 2) return false;
function_detour_[0] = exec_pages.Push(template_start_,
function_target_[0]);
if (!DetourAttachHelper(function_trampoline_[0],
function_detour_[0])
|| !template_start_.Fill(function_detour_[0],
&call_count_[0],
&checkpoint_,
function_trampoline_[0]))
goto revert;
for (uint32_t i = 1; i < n_; ++i) {
function_detour_[i] = exec_pages.Push(template_checkpoint_,
function_target_[i]);
if (!DetourAttachHelper(function_trampoline_[i],
function_detour_[i])
|| !template_checkpoint_.Fill(function_detour_[i],
&call_count_[i],
&checkpoint_,
&ticks_[i],
function_trampoline_[i]))
goto revert;
}
return true;
revert:
for (uint32_t i = 0; i < n_; ++i) {
// Need to revert in the reverse order because only the last-pushed
// page is revertable.
if (function_detour_[n_ - 1 - i]
&& !exec_pages.Revert(function_detour_[n_ - 1 - i])) {
Log(L"Failed to revert %p\n", function_detour_[n_ - 1 - i]);
}
}
return false;
}
bool DeactivateDetourInternal(ExecutablePages&) {
bool ret = true;
for (uint32_t i = 0; i < n_; ++i) {
ret &= DetourDetachHelper(function_trampoline_[i],
function_detour_[i]);
}
return ret;
}
void Print() const {
Log(L"[MeasurementChain] total ticks: %llu\n",
std::accumulate(ticks_.begin(), ticks_.end(), 0I64));
for (uint32_t i = 1; i < n_; ++i) {
Log(L" %p-%p: %llu (callcount: %d %d)\n",
function_target_[i - 1],
function_target_[i],
ticks_[i],
call_count_[i - 1],
call_count_[i]);
}
}
};
void MeasurementChain(Package *package) {
auto chain = address_chain(package->nw.args);
if (chain.size() < 2) {
Log(L"Invalid parameter!\n");
return;
}
if (auto new_pack = std::make_unique<MeasurementChainPack>(chain)) {
AcquireSRWLockExclusive(&g_shim_lock);
if (new_pack->ActivateDetour(g_exec_pages)) {
g_packs.emplace_back(std::move(new_pack));
}
ReleaseSRWLockExclusive(&g_shim_lock);
}
WaitAndThenCleanup();
}
| 33.805907 | 73 | 0.644284 | [
"vector"
] |
0211dadd461d1b26440f4e3059fd829d365cc2ce | 16,845 | hpp | C++ | blast/include/util/format_guess.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/util/format_guess.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/util/format_guess.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | #ifndef FORMATGUESS__HPP
#define FORMATGUESS__HPP
/* $Id: format_guess.hpp 629211 2021-04-12 18:52:01Z ivanov $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Anatoliy Kuznetsov
*
* File Description: Different "fuzzy-logic" methods to identify file formats.
*
*/
#include <corelib/ncbistd.hpp>
#include <bitset>
BEGIN_NCBI_SCOPE
class CFormatGuessHints;
//////////////////////////////////////////////////////////////////
///
/// Class implements different ad-hoc unreliable file format
/// identifications.
///
class NCBI_XUTIL_EXPORT CFormatGuess
{
public:
/// The formats are checked in the same order as declared here.
enum EFormat {
// WARNING! Never change numeric values of these enumerators!
// E.g. these values are hard-coded in the Local Data Storage (LDS)
// index databases.
eUnknown = 0, ///< unknown format
eBinaryASN = 1, ///< Binary ASN.1
eRmo = 2, ///< RepeatMasker Output
eGtf_POISENED = 3, ///< Old and Dead GFF/GTF style annotations
eGlimmer3 = 4, ///< Glimmer3 predictions
eAgp = 5, ///< AGP format assembly, AgpRead
eXml = 6, ///< XML
eWiggle = 7, ///< UCSC WIGGLE file format
eBed = 8, ///< UCSC BED file format, CBedReader
eBed15 = 9, ///< UCSC BED15 or microarray format
eNewick = 10, ///< Newick file
eAlignment = 11, ///< Text alignment
eDistanceMatrix = 12, ///< Distance matrix file
eFlatFileSequence = 13, ///< GenBank/GenPept/DDBJ/EMBL flat-file
///< sequence portion
eFiveColFeatureTable = 14, ///< Five-column feature table
eSnpMarkers = 15, ///< SNP Marker flat file
eFasta = 16, ///< FASTA format sequence record, CFastaReader
eTextASN = 17, ///< Text ASN.1
eTaxplot = 18, ///< Taxplot file
ePhrapAce = 19, ///< Phrap ACE assembly file
eTable = 20, ///< Generic table
eGtf = 21, ///< New GTF, CGtfReader
eGff3 = 22, ///< GFF3, CGff3Reader
eGff2 = 23, ///< GFF2, CGff2Reader, any GFF-like that doesn't fit the others
eHgvs = 24, ///< HGVS, CHgvsParser
eGvf = 25, ///< GVF, CGvfReader
eZip = 26, ///< zip compressed file
eGZip = 27, ///< GNU zip compressed file
eBZip2 = 28, ///< bzip2 compressed file
eLzo = 29, ///< lzo compressed file
eSra = 30, ///< INSDC Sequence Read Archive file
eBam = 31, ///< Binary alignment/map file
eVcf = 32, ///< VCF, CVcfReader
eUCSCRegion = 33, ///< USCS Region file format
eGffAugustus = 34, ///< GFFish output of Augustus Gene Prediction
eJSON = 35, ///< JSON
ePsl = 36, ///< PSL alignment format
// The following formats are not yet recognized by CFormatGuess - CXX-10039
eAltGraphX = 37,
eBed5FloatScore = 38,
eBedGraph = 39,
eBedRnaElements = 40,
eBigBarChart = 41,
eBigBed = 42,
eBigPsl = 43,
eBigChain = 44,
eBigMaf = 45,
eBigWig = 46,
eBroadPeak = 47,
eChain = 48,
eClonePos = 49,
eColoredExon = 50,
eCtgPos = 51,
eDownloadsOnly = 52,
eEncodeFiveC = 53,
eExpRatio = 54,
eFactorSource = 55,
eGenePred = 56,
eLd2 = 57,
eNarrowPeak = 58,
eNetAlign = 59,
ePeptideMapping = 60,
eRmsk = 61,
eSnake = 62,
eVcfTabix = 63,
eWigMaf = 64,
// The following formats *are* recognized by CFormatGuess:
eFlatFileGenbank = 65,
eFlatFileEna = 66,
eFlatFileUniProt = 67,
// *** Adding new format codes? ***
// (1) A sanity check in the implementation depends on the format codes being
// consecutive. Hence no gaps allowed!
// (2) Heed the warning above about never changing an already existing
// format code!
// (3) You must provide a display name for the new format. Do that in
// sm_FormatNames.
// (4) You must add your new format to sm_CheckOrder (unless you don't want your
// format actually being checked and recognized.
/// Max value of EFormat
eFormat_max
};
enum ESequenceType {
eUndefined,
eNucleotide,
eProtein
};
enum EMode {
eQuick,
eThorough
};
enum ESTStrictness {
eST_Lax, ///< Implement historic behavior, risking false positives.
eST_Default, ///< Be relatively strict, but still allow for typos.
eST_Strict ///< Require 100% encodability of printable non-digits.
};
enum EOnError {
eDefault = 0, ///< Return eUnknown
eThrowOnBadSource, ///< Throw an exception if the data source (stream, file) can't be read
};
static bool IsSupportedFormat(EFormat format);
/// Hints for guessing formats. Two hint types can be used: preferred and
/// disabled. Preferred are checked before any other formats. Disabled
/// formats are not checked at all.
class CFormatHints
{
public:
typedef CFormatGuess::EFormat TFormat;
CFormatHints(void) {}
/// Mark the format as preferred.
CFormatHints& AddPreferredFormat(TFormat fmt);
/// Mark the format as disabled.
CFormatHints& AddDisabledFormat(TFormat fmt);
/// Disable all formats not marked as preferred
CFormatHints& DisableAllNonpreferred(void);
/// Remove format hint.
void RemoveFormat(TFormat fmt);
/// Remove all hints
CFormatHints& Reset(void);
/// Check if there are any hints are set at all.
bool IsEmpty(void) const;
/// Check if the format is listed as preferred.
bool IsPreferred(TFormat fmt) const;
/// Check if the format is listed as disabled.
bool IsDisabled(TFormat fmt) const;
private:
typedef bitset<CFormatGuess::eFormat_max> THints;
THints m_Preferred;
THints m_Disabled;
};
/// Guess sequence type. Function calculates sequence alphabet and
/// identifies if the source belongs to nucleotide or protein sequence
static ESequenceType SequenceType(const char* str, unsigned length = 0,
ESTStrictness strictness = eST_Default);
static const char* GetFormatName(EFormat format);
// ----------------------------------------------------------------------
// "Stateless" interface:
// Useful for checking for all formats in one simple call.
// May go away; use object interface instead.
// ----------------------------------------------------------------------
/// Guess file format
static
EFormat Format(const string& path, EOnError onerror = eDefault);
/// Format prediction based on an input stream
/// @note On completion, the function pushes whatever data it had to read
/// (in order to detect data format) back to the stream -- using
/// CStreamUtils::Stepback()
static
EFormat Format(CNcbiIstream& input, EOnError onerror = eDefault);
// ----------------------------------------------------------------------
// "Object" interface:
// Use when interested only in a limited number of formats, in excluding
// certain tests, a specific order in which formats are tested, ...
// ----------------------------------------------------------------------
CFormatGuess();
CFormatGuess(const string& fname);
/// @note Data format detection methods GuessFormat() and TestFormat()
/// take care to push whatever data they read back to the stream
/// using CStreamUtils::Stepback()
CFormatGuess(CNcbiIstream& input);
~CFormatGuess();
NCBI_DEPRECATED EFormat GuessFormat(EMode);
NCBI_DEPRECATED bool TestFormat(EFormat, EMode);
/// @note If the instance of the class is built upon std::istream, then
/// on completion this function pushes whatever data it had to read
/// (in order to detect data format) back to the stream -- using
/// CStreamUtils::Stepback()
EFormat GuessFormat(EOnError onerror = eDefault);
/// @note If the instance of the class is built upon std::istream, then
/// on completion this function pushes whatever data it had to read
/// (in order to detect data format) back to the stream -- using
/// CStreamUtils::Stepback()
bool TestFormat(EFormat, EOnError onerror = eDefault);
/// Get format hints
CFormatHints& GetFormatHints(void) { return m_Hints; }
/// Check whether testing is enabled for given format
bool IsEnabled(EFormat format) const { return !m_Hints.IsDisabled(format); };
protected:
void Initialize();
bool EnsureTestBuffer();
bool EnsureStats();
bool EnsureSplitLines();
bool IsAllComment();
bool IsAsciiText();
bool TestFormatRepeatMasker(EMode);
bool TestFormatPhrapAce(EMode);
bool TestFormatGtf(EMode);
bool TestFormatGvf(EMode);
bool TestFormatGff3(EMode);
bool TestFormatGff2(EMode);
bool TestFormatGlimmer3(EMode);
bool TestFormatAgp(EMode);
bool TestFormatNewick(EMode);
bool TestFormatXml(EMode);
bool TestFormatAlignment(EMode);
bool TestFormatCLUSTAL(void);
bool TestFormatBinaryAsn(EMode);
bool TestFormatDistanceMatrix(EMode);
bool TestFormatTaxplot(EMode);
bool TestFormatFlatFileSequence(EMode);
bool TestFormatFiveColFeatureTable(EMode);
bool TestFormatTable(EMode);
bool TestFormatFasta(EMode);
bool TestFormatTextAsn(EMode);
bool TestFormatSnpMarkers(EMode);
bool TestFormatBed(EMode);
bool TestFormatBed15(EMode);
bool TestFormatWiggle(EMode);
bool TestFormatHgvs(EMode);
bool TestFormatZip(EMode);
bool TestFormatGZip(EMode);
bool TestFormatBZip2(EMode);
bool TestFormatLzo(EMode);
bool TestFormatSra(EMode);
bool TestFormatBam(EMode);
bool TestFormatVcf(EMode);
bool TestFormatAugustus(EMode);
bool TestFormatJson(EMode);
bool TestFormatPsl(EMode);
bool TestFormatFlatFileGenbank(EMode);
bool TestFormatFlatFileEna(EMode);
bool TestFormatFlatFileUniProt(EMode);
bool IsInputRepeatMaskerWithoutHeader();
bool IsInputRepeatMaskerWithHeader();
static bool IsLineFlatFileSequence(const std::string&);
static bool IsSampleNewick(const std::string&);
static bool IsLabelNewick(const std::string&);
static bool IsLineAgp(const std::string&);
static bool IsLineGlimmer3(const std::string&);
static bool IsLineGtf(const std::string&);
static bool IsLineGvf(const std::string&);
static bool IsLineGff3(const std::string&);
static bool IsLineGff2(const std::string&);
static bool IsLineAugustus(const std::string&);
static bool IsLinePhrapId(const std::string&);
static bool IsLineRmo(const std::string&);
static bool IsAsnComment(const vector<string>&);
static bool IsLineHgvs(const std::string&);
static bool IsLinePsl(const std::string&, bool ignoreFirstColumn);
private:
static bool x_TestInput( CNcbiIstream& input, EOnError onerror );
bool x_TestFormat(EFormat format, EMode mode);
// to test for a table we check each of the most common delimiter combitions,
// ' ' ' \t' '\t' ',' '|'
bool x_TestTableDelimiter(const string& delims);
// Check that the beginning of testString looks like JSON
bool x_CheckJsonStart(const string& testString) const;
// In-place deletion of JSON strings
void x_StripJsonStrings(string& testString) const;
// Starting at from_pos, find the next set of double quotes
// indicating the end of a JSON string
size_t x_FindNextJsonStringStop(const string& input, const size_t from_pos) const;
void x_FindJsonStringLimits(const string& testString, list<size_t>& limits) const;
// Checks and removes punctuation from testString
bool x_CheckStripJsonPunctuation(string& testString) const;
// In-place deletion of JSON punctuation
// Returns the number of characters deleted.
size_t x_StripJsonPunctuation(string& testString) const;
// In-place deletion of JSON keywords: true, false, null
void x_StripJsonKeywords(string& testString) const;
bool x_CheckStripJsonNumbers(string& testString) const;
bool x_IsTruncatedJsonNumber(const string& testString) const;
// Is a truncation of true, false, or null
bool x_IsTruncatedJsonKeyword(const string& testString) const;
bool x_IsNumber(const string& testString) const;
// Return true if the string is blank or a list of space-delimited numbers
bool x_IsBlankOrNumbers(const string& testString) const;
// data:
using NAME_MAP = map<EFormat, const char*>;
static const NAME_MAP sm_FormatNames;
bool x_TryProcessCLUSTALSeqData(const string& line, string& id, size_t& seg_length) const;
bool x_LooksLikeCLUSTALConservedInfo(const string& line) const;
protected:
static vector<int> sm_CheckOrder;
static const streamsize s_iTestBufferGranularity = 8096;
CNcbiIstream& m_Stream;
bool m_bOwnsStream;
char* m_pTestBuffer;
streamsize m_iTestBufferSize;
streamsize m_iTestDataSize;
bool m_bStatsAreValid;
bool m_bSplitDone;
unsigned int m_iStatsCountData;
unsigned int m_iStatsCountAlNumChars;
unsigned int m_iStatsCountDnaChars;
unsigned int m_iStatsCountAaChars;
unsigned int m_iStatsCountBraces;
std::list<std::string> m_TestLines;
CFormatHints m_Hints;
};
inline CFormatGuess::CFormatHints&
CFormatGuess::CFormatHints::AddPreferredFormat(TFormat fmt)
{
m_Disabled.reset(fmt);
m_Preferred.set(fmt);
return *this;
}
inline CFormatGuess::CFormatHints&
CFormatGuess::CFormatHints::AddDisabledFormat(TFormat fmt)
{
m_Preferred.reset(fmt);
m_Disabled.set(fmt);
return *this;
}
inline CFormatGuess::CFormatHints&
CFormatGuess::CFormatHints::DisableAllNonpreferred(void)
{
m_Disabled = ~m_Preferred;
return *this;
}
inline void CFormatGuess::CFormatHints::RemoveFormat(TFormat fmt)
{
m_Disabled.reset(fmt);
m_Preferred.reset(fmt);
}
inline CFormatGuess::CFormatHints&
CFormatGuess::CFormatHints::Reset(void)
{
m_Preferred.reset();
m_Disabled.reset();
return *this;
}
inline bool CFormatGuess::CFormatHints::IsEmpty(void) const
{
return m_Preferred.count() == 0 && m_Disabled.count() == 0;
}
inline bool CFormatGuess::CFormatHints::IsPreferred(TFormat fmt) const
{
return m_Preferred.test(fmt);
}
inline bool CFormatGuess::CFormatHints::IsDisabled(TFormat fmt) const
{
return m_Disabled.test(fmt);
}
END_NCBI_SCOPE
#endif
| 36.070664 | 99 | 0.615732 | [
"object",
"vector"
] |
0215cbf587c84fe4aee2b9a8633d1023200b92bd | 4,994 | cpp | C++ | externals/browser/externals/browser/externals/libutility/utility/procstat.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2021-09-02T08:42:59.000Z | 2021-09-02T08:42:59.000Z | externals/browser/externals/browser/externals/libutility/utility/procstat.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | null | null | null | externals/browser/externals/browser/externals/libutility/utility/procstat.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <unistd.h>
#include <sys/types.h>
#include <cerrno>
#include <system_error>
#include <proc/readproc.h>
#include "procstat.hpp"
#include "dbglog/dbglog.hpp"
namespace utility {
namespace {
std::size_t pageSize(::sysconf(_SC_PAGESIZE));
std::size_t pageSizeKb(pageSize >> 10);
inline int flags(const ::pid_t *pids) {
int flags(PROC_FILLSTATUS | PROC_FILLMEM);
if (pids) { flags |= PROC_PID; }
return flags;
}
struct PidTag {};
struct UidTag {};
typedef std::vector< ::pid_t> Pids;
Pids makePidList(const PidList &pids)
{
if (pids.empty()) { return {}; }
std::vector< ::pid_t> pidList(pids.begin(), pids.end());
pidList.push_back(0);
return pidList;
}
PROCTAB* openPids(const Pids &pids)
{
int flags(PROC_FILLSTATUS | PROC_FILLMEM);
if (!pids.empty()) { flags |= PROC_PID; }
auto p(::openproc(flags, pids.data()));
if (!p) {
std::system_error e(errno, std::system_category());
LOG(err3) << "Cannot open /proc: <"
<< e.code() << ", " << e.what() << ">.";
throw e;
}
return p;
}
PROCTAB* openUids(const UidList &uids)
{
int flags(PROC_FILLSTATUS | PROC_FILLMEM | PROC_UID);
std::vector< ::uid_t> uidList(uids.begin(), uids.end());
auto p(::openproc(flags, uids.data(), int(uids.size())));
if (!p) {
std::system_error e(errno, std::system_category());
LOG(err3) << "Cannot open /proc: <"
<< e.code() << ", " << e.what() << ">.";
throw e;
}
return p;
}
class Table {
public:
Table(const PidList &pids, const PidTag&)
: pidList(makePidList(pids))
, p(openPids(pidList)), proc()
{}
Table(const UidList &uids, const UidTag&)
: p(openUids(uids)), proc()
{}
~Table() {
if (proc) { ::freeproc(proc); }
if (p) { ::closeproc(p); }
}
const ::proc_t* next() {
auto item(::readproc(p, proc));
if (item && !proc) { proc = item; }
return item;
}
private:
Pids pidList;
::PROCTAB *p;
::proc_t *proc;
};
void fill(ProcStat &ps, const ::proc_t *proc)
{
ps.pid = proc->tid;
ps.ppid = proc->ppid;
ps.rss = proc->vm_rss;
ps.swap = proc->vm_swap;
ps.virt = proc->size / pageSizeKb;
ps.shared = proc->share / pageSizeKb;
}
} // namespace
ProcStat::list getProcStat(const PidList &pids)
{
Table table(pids, PidTag{});
ProcStat::list stat;
auto ipids(pids.begin());
auto epids(pids.end());
while (const auto *proc = table.next()) {
if (ipids != epids) {
const auto pid(*ipids++);
if (pid != proc->tid) {
std::system_error e(ESRCH, std::system_category());
LOG(err3) << "Cannot get process " << pid << " information.";
throw e;
}
}
stat.emplace_back();
fill(stat.back(), proc);
}
if (ipids != epids) {
std::system_error e(ESRCH, std::system_category());
LOG(err3) << "Not all processes found.";
throw e;
}
return stat;
}
ProcStat::list getUserProcStat(const UidList &uids)
{
Table table(uids, UidTag{});
ProcStat::list stat;
while (const auto *proc = table.next()) {
stat.emplace_back();
fill(stat.back(), proc);
}
return stat;
}
ProcStat::list getUserProcStat(ProcStat::Uid uid)
{
return getUserProcStat(UidList{uid});
}
ProcStat::list getUserProcStat()
{
return getUserProcStat(UidList{::getuid()});
}
ProcStat getProcStat()
{
return getProcStat(PidList{::getpid()}).front();
}
} // namespace utility
| 25.742268 | 78 | 0.622347 | [
"vector"
] |
0227877432ff3d6c347a6191087fcb2d649565af | 891 | cpp | C++ | acmicpc/1884.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/1884.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/1884.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
#include <vector>
#include <cstring>
#include <tuple>
using namespace std;
#define MAX 101
typedef tuple<int, int, int> tp;
const int INF = 1e9+7;
int k, n, r, s, d, l, t;
vector<tp> graph[MAX];
int dp[MAX][10001];
int solve(int cur, int cost)
{
if (cur == n)
return 0;
if (~dp[cur][cost])
return dp[cur][cost];
dp[cur][cost] = INF;
for (int i=0; i<graph[cur].size(); ++i) {
auto [len, time, next] = graph[cur][i];
if (cost - time >= 0)
dp[cur][cost] = min(dp[cur][cost], solve(next, cost - time) + len);
}
return dp[cur][cost];
}
int main()
{
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
cin >> k >> n >> r;
for (int i=0; i<r; ++i) {
cin >> s >> d >> l >> t;
graph[s].push_back({l, t, d});
}
memset(dp, -1, sizeof(dp));
int ans = solve(1, k);
if (ans == INF)
cout << "-1\n";
else
cout << ans << '\n';
return 0;
}
| 16.2 | 70 | 0.556678 | [
"vector"
] |
0234febc0306ca9837bc18f75191ee4eadb6e574 | 3,859 | cpp | C++ | core/sph/solvers/StandardSets.cpp | grische/OpenSPH | 74a8fff865157ae94e8d7ed249b116fbadf6ad20 | [
"MIT"
] | null | null | null | core/sph/solvers/StandardSets.cpp | grische/OpenSPH | 74a8fff865157ae94e8d7ed249b116fbadf6ad20 | [
"MIT"
] | 1 | 2022-01-27T21:25:34.000Z | 2022-01-27T21:25:34.000Z | core/sph/solvers/StandardSets.cpp | grische/OpenSPH | 74a8fff865157ae94e8d7ed249b116fbadf6ad20 | [
"MIT"
] | null | null | null | #include "sph/solvers/StandardSets.h"
#include "sph/equations/DeltaSph.h"
#include "sph/equations/Fluids.h"
#include "sph/equations/Friction.h"
#include "sph/equations/HelperTerms.h"
#include "sph/equations/Potentials.h"
#include "sph/equations/XSph.h"
#include "sph/equations/av/Conductivity.h"
#include "sph/equations/av/Stress.h"
#include "system/Factory.h"
NAMESPACE_SPH_BEGIN
EquationHolder getStandardEquations(const RunSettings& settings, const EquationHolder& other) {
EquationHolder equations;
if (settings.get<bool>(RunSettingsId::SPH_USE_XSPH)) {
// add XSPH as the very first term (it modifies velocities used by other terms)
equations += makeTerm<XSph>();
}
/// \todo test that all possible combination (pressure, stress, AV, ...) work and dont assert
Flags<ForceEnum> forces = settings.getFlags<ForceEnum>(RunSettingsId::SPH_SOLVER_FORCES);
if (forces.has(ForceEnum::PRESSURE)) {
equations += makeTerm<PressureForce>();
if (forces.has(ForceEnum::NAVIER_STOKES)) {
equations += makeTerm<NavierStokesForce>();
} else if (forces.has(ForceEnum::SOLID_STRESS)) {
equations += makeTerm<SolidStressForce>(settings);
}
}
if (forces.has(ForceEnum::INTERNAL_FRICTION)) {
/// \todo this term (and also AV) do not depend on particular equation set, so it could be moved
/// outside to reduce code duplication, but this also provides a way to get all necessary terms by
/// calling a single function ...
equations += makeTerm<ViscousStress>();
}
if (forces.has(ForceEnum::SURFACE_TENSION)) {
equations += makeTerm<CohesionTerm>();
}
if (forces.has(ForceEnum::INERTIAL)) {
const Vector omega = settings.get<Vector>(RunSettingsId::FRAME_ANGULAR_FREQUENCY);
equations += makeTerm<InertialForce>(omega);
}
const Vector g = settings.get<Vector>(RunSettingsId::FRAME_CONSTANT_ACCELERATION);
if (g != Vector(0._f)) {
equations += makeExternalForce([g](const Vector& UNUSED(r), const Float UNUSED(t)) { return g; });
}
if (settings.get<bool>(RunSettingsId::SPH_SCRIPT_ENABLE)) {
const Path scriptPath(settings.get<String>(RunSettingsId::SPH_SCRIPT_FILE));
const Float period = settings.get<Float>(RunSettingsId::SPH_SCRIPT_PERIOD);
const bool oneshot = settings.get<bool>(RunSettingsId::SPH_SCRIPT_ONESHOT);
equations += makeTerm<ChaiScriptTerm>(scriptPath, period, oneshot);
}
equations += makeTerm<ContinuityEquation>(settings);
if (settings.get<bool>(RunSettingsId::SPH_USE_DELTASPH)) {
equations += makeTerm<DeltaSph::DensityDiffusion>();
equations += makeTerm<DeltaSph::VelocityDiffusion>();
}
// artificial viscosity
equations += EquationHolder(Factory::getArtificialViscosity(settings));
if (settings.get<bool>(RunSettingsId::SPH_AV_USE_STRESS)) {
equations += makeTerm<StressAV>(settings);
}
if (settings.get<bool>(RunSettingsId::SPH_USE_AC)) {
equations += makeTerm<ArtificialConductivity>(settings);
}
// add all the additional equations
equations += other;
// adaptivity of smoothing length should be last as it sets 4th component of velocities (and
// accelerations), this should be improved (similarly to derivatives - equation phases)
Flags<SmoothingLengthEnum> hflags =
settings.getFlags<SmoothingLengthEnum>(RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH);
if (hflags.has(SmoothingLengthEnum::CONTINUITY_EQUATION)) {
equations += makeTerm<AdaptiveSmoothingLength>(settings);
} else {
/// \todo add test checking that with ConstSmoothingLength the h will indeed be const
equations += makeTerm<ConstSmoothingLength>();
}
return equations;
}
NAMESPACE_SPH_END
| 39.377551 | 106 | 0.69759 | [
"vector"
] |
02350613d616d940b868c0fb5bb1a0e77c2cde5e | 19,056 | cpp | C++ | Modules/ContourModel/DataManagement/mitkContourModel.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | null | null | null | Modules/ContourModel/DataManagement/mitkContourModel.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Modules/ContourModel/DataManagement/mitkContourModel.cpp | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | null | null | null | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkContourModel.h>
#include <mitkPlaneGeometry.h>
mitk::ContourModel::ContourModel() : m_UpdateBoundingBox(true)
{
// set to initial state
this->InitializeEmpty();
}
mitk::ContourModel::ContourModel(const ContourModel &other)
: BaseData(other), m_ContourSeries(other.m_ContourSeries), m_lineInterpolation(other.m_lineInterpolation)
{
m_SelectedVertex = nullptr;
}
mitk::ContourModel::~ContourModel()
{
m_SelectedVertex = nullptr;
this->m_ContourSeries.clear(); // TODO check destruction
}
void mitk::ContourModel::AddVertex(const Point3D &vertex, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->AddVertex(vertex, false, timestep);
}
}
void mitk::ContourModel::AddVertex(const Point3D &vertex, bool isControlPoint, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->AddVertex(vertex, isControlPoint);
this->InvokeEvent(ContourModelSizeChangeEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
void mitk::ContourModel::AddVertex(const VertexType &vertex, TimeStepType timestep)
{
this->AddVertex(vertex.Coordinates, vertex.IsControlPoint, timestep);
}
void mitk::ContourModel::AddVertexAtFront(const Point3D &vertex, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->AddVertexAtFront(vertex, false, timestep);
}
}
void mitk::ContourModel::AddVertexAtFront(const Point3D &vertex, bool isControlPoint, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->AddVertexAtFront(vertex, isControlPoint);
this->InvokeEvent(ContourModelSizeChangeEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
void mitk::ContourModel::AddVertexAtFront(const VertexType &vertex, TimeStepType timestep)
{
this->AddVertexAtFront(vertex.Coordinates, vertex.IsControlPoint, timestep);
}
bool mitk::ContourModel::SetVertexAt(int pointId, const Point3D &point, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
if (pointId >= 0 && this->m_ContourSeries[timestep]->GetSize() > ContourElement::VertexSizeType(pointId))
{
this->m_ContourSeries[timestep]->SetVertexAt(pointId, point);
this->Modified();
this->m_UpdateBoundingBox = true;
return true;
}
return false;
}
return false;
}
bool mitk::ContourModel::SetVertexAt(int pointId, const VertexType *vertex, TimeStepType timestep)
{
if (vertex == nullptr)
return false;
if (!this->IsEmptyTimeStep(timestep))
{
if (pointId >= 0 && this->m_ContourSeries[timestep]->GetSize() > ContourElement::VertexSizeType(pointId))
{
this->m_ContourSeries[timestep]->SetVertexAt(pointId, vertex);
this->Modified();
this->m_UpdateBoundingBox = true;
return true;
}
return false;
}
return false;
}
void mitk::ContourModel::InsertVertexAtIndex(const Point3D &vertex, int index, bool isControlPoint, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
if (index >= 0 && this->m_ContourSeries[timestep]->GetSize() > ContourElement::VertexSizeType(index))
{
this->m_ContourSeries[timestep]->InsertVertexAtIndex(vertex, isControlPoint, index);
this->InvokeEvent(ContourModelSizeChangeEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
}
void mitk::ContourModel::UpdateContour(const ContourModel* sourceModel, TimeStepType destinationTimeStep, TimeStepType sourceTimeStep)
{
if (nullptr == sourceModel)
{
mitkThrow() << "Cannot update contour. Passed source model is invalid.";
}
if (!sourceModel->GetTimeGeometry()->IsValidTimeStep(sourceTimeStep))
{
mitkThrow() << "Cannot update contour. Source contour time geometry does not support passed time step. Invalid time step: " << sourceTimeStep;
}
if (!this->GetTimeGeometry()->IsValidTimeStep(destinationTimeStep))
{
MITK_WARN << "Cannot update contour. Contour time geometry does not support passed time step. Invalid time step: " << destinationTimeStep;
return;
}
this->Clear(destinationTimeStep);
std::for_each(sourceModel->Begin(sourceTimeStep), sourceModel->End(sourceTimeStep), [this, destinationTimeStep](ContourElement::VertexType* vertex) {
this->m_ContourSeries[destinationTimeStep]->AddVertex(vertex->Coordinates, vertex->IsControlPoint);
});
this->InvokeEvent(ContourModelSizeChangeEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
bool mitk::ContourModel::IsEmpty(TimeStepType timestep) const
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->IsEmpty();
}
return true;
}
bool mitk::ContourModel::IsEmpty() const
{
return this->IsEmpty(0);
}
int mitk::ContourModel::GetNumberOfVertices(TimeStepType timestep) const
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetSize();
}
return -1;
}
const mitk::ContourModel::VertexType *mitk::ContourModel::GetVertexAt(int index, TimeStepType timestep) const
{
if (!this->IsEmptyTimeStep(timestep) && this->m_ContourSeries[timestep]->GetSize() > mitk::ContourElement::VertexSizeType(index))
{
return this->m_ContourSeries[timestep]->GetVertexAt(index);
}
return nullptr;
}
const mitk::ContourModel::VertexType *mitk::ContourModel::GetNextControlVertexAt(mitk::Point3D &point,
float eps,
TimeStepType timestep) const
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetNextControlVertexAt(point, eps);
}
return nullptr;
}
const mitk::ContourModel::VertexType *mitk::ContourModel::GetPreviousControlVertexAt(mitk::Point3D &point,
float eps,
TimeStepType timestep) const
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetPreviousControlVertexAt(point, eps);
}
return nullptr;
}
int mitk::ContourModel::GetIndex(const VertexType *vertex, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->GetIndex(vertex);
}
return -1;
}
void mitk::ContourModel::Close(TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->Close();
this->InvokeEvent(ContourModelClosedEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
void mitk::ContourModel::Open(TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->Open();
this->InvokeEvent(ContourModelClosedEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
void mitk::ContourModel::SetClosed(bool isClosed, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->SetClosed(isClosed);
this->InvokeEvent(ContourModelClosedEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
bool mitk::ContourModel::IsEmptyTimeStep(unsigned int t) const
{
return (this->m_ContourSeries.size() <= t);
}
bool mitk::ContourModel::IsNearContour(Point3D &point, float eps, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->IsNearContour(point, eps);
}
return false;
}
void mitk::ContourModel::Concatenate(ContourModel *other, TimeStepType timestep, bool check)
{
if (!this->IsEmptyTimeStep(timestep))
{
if (!this->m_ContourSeries[timestep]->IsClosed())
{
this->m_ContourSeries[timestep]->Concatenate(other->m_ContourSeries[timestep], check);
this->InvokeEvent(ContourModelSizeChangeEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
}
mitk::ContourModel::VertexIterator mitk::ContourModel::Begin(TimeStepType timestep) const
{
return this->IteratorBegin(timestep);
}
mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorBegin(TimeStepType timestep) const
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->IteratorBegin();
}
else
{
mitkThrow() << "No iterator at invalid timestep " << timestep << ". There are only " << this->GetTimeSteps()
<< " timesteps available.";
}
}
mitk::ContourModel::VertexIterator mitk::ContourModel::End(TimeStepType timestep) const
{
return this->IteratorEnd(timestep);
}
mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorEnd(TimeStepType timestep) const
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->IteratorEnd();
}
else
{
mitkThrow() << "No iterator at invalid timestep " << timestep << ". There are only " << this->GetTimeSteps()
<< " timesteps available.";
}
}
bool mitk::ContourModel::IsClosed(int timestep) const
{
if (!this->IsEmptyTimeStep(timestep))
{
return this->m_ContourSeries[timestep]->IsClosed();
}
return false;
}
bool mitk::ContourModel::SelectControlVertexAt(Point3D &point, float eps, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetControlVertexAt(point, eps);
}
return this->m_SelectedVertex != nullptr;
}
bool mitk::ContourModel::SelectVertexAt(Point3D &point, float eps, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(point, eps);
}
return this->m_SelectedVertex != nullptr;
}
bool mitk::ContourModel::SelectVertexAt(int index, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep) && index >= 0)
{
return (this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(index));
}
return false;
}
bool mitk::ContourModel::SetControlVertexAt(Point3D &point, float eps, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
VertexType *vertex = this->m_ContourSeries[timestep]->GetVertexAt(point, eps);
if (vertex != nullptr)
{
vertex->IsControlPoint = true;
return true;
}
}
return false;
}
bool mitk::ContourModel::SetControlVertexAt(int index, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep) && index >= 0)
{
VertexType *vertex = this->m_ContourSeries[timestep]->GetVertexAt(index);
if (vertex != nullptr)
{
vertex->IsControlPoint = true;
return true;
}
}
return false;
}
bool mitk::ContourModel::RemoveVertex(const VertexType *vertex, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
if (this->m_ContourSeries[timestep]->RemoveVertex(vertex))
{
this->Modified();
this->m_UpdateBoundingBox = true;
this->InvokeEvent(ContourModelSizeChangeEvent());
return true;
}
}
return false;
}
bool mitk::ContourModel::RemoveVertexAt(int index, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
if (this->m_ContourSeries[timestep]->RemoveVertexAt(index))
{
this->Modified();
this->m_UpdateBoundingBox = true;
this->InvokeEvent(ContourModelSizeChangeEvent());
return true;
}
}
return false;
}
bool mitk::ContourModel::RemoveVertexAt(Point3D &point, float eps, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
if (this->m_ContourSeries[timestep]->RemoveVertexAt(point, eps))
{
this->Modified();
this->m_UpdateBoundingBox = true;
this->InvokeEvent(ContourModelSizeChangeEvent());
return true;
}
}
return false;
}
void mitk::ContourModel::ShiftSelectedVertex(Vector3D &translate)
{
if (this->m_SelectedVertex)
{
this->ShiftVertex(this->m_SelectedVertex, translate);
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
void mitk::ContourModel::ShiftContour(Vector3D &translate, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
// shift all vertices
for (auto vertex : *(this->m_ContourSeries[timestep]))
{
this->ShiftVertex(vertex, translate);
}
this->Modified();
this->m_UpdateBoundingBox = true;
this->InvokeEvent(ContourModelShiftEvent());
}
}
void mitk::ContourModel::ShiftVertex(VertexType *vertex, Vector3D &vector)
{
vertex->Coordinates[0] += vector[0];
vertex->Coordinates[1] += vector[1];
vertex->Coordinates[2] += vector[2];
}
void mitk::ContourModel::Clear(TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
// clear data at timestep
this->m_ContourSeries[timestep]->Clear();
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
void mitk::ContourModel::Expand(unsigned int timeSteps)
{
std::size_t oldSize = this->m_ContourSeries.size();
if (static_cast<std::size_t>(timeSteps) > oldSize)
{
Superclass::Expand(timeSteps);
// insert contours for each new timestep
for (std::size_t i = oldSize; i < static_cast<std::size_t>(timeSteps); i++)
{
m_ContourSeries.push_back(ContourElement::New());
}
this->InvokeEvent(ContourModelExpandTimeBoundsEvent());
}
}
void mitk::ContourModel::SetRequestedRegionToLargestPossibleRegion()
{
// no support for regions
}
bool mitk::ContourModel::RequestedRegionIsOutsideOfTheBufferedRegion()
{
// no support for regions
return false;
}
bool mitk::ContourModel::VerifyRequestedRegion()
{
// no support for regions
return true;
}
void mitk::ContourModel::SetRequestedRegion(const itk::DataObject * /*data*/)
{
// no support for regions
}
void mitk::ContourModel::Clear()
{
// clear data and set to initial state again
this->ClearData();
this->InitializeEmpty();
this->Modified();
this->m_UpdateBoundingBox = true;
}
void mitk::ContourModel::RedistributeControlVertices(int period, TimeStepType timestep)
{
if (!this->IsEmptyTimeStep(timestep))
{
this->m_ContourSeries[timestep]->RedistributeControlVertices(this->GetSelectedVertex(), period);
this->InvokeEvent(ContourModelClosedEvent());
this->Modified();
this->m_UpdateBoundingBox = true;
}
}
mitk::ContourModel::VertexListType mitk::ContourModel::GetControlVertices(TimeStepType timestep)
{
VertexListType controlVertices;
if (!this->IsEmptyTimeStep(timestep))
{
controlVertices = this->m_ContourSeries[timestep]->GetControlVertices();
}
return controlVertices;
}
mitk::ContourModel::VertexListType mitk::ContourModel::GetVertexList(TimeStepType timestep)
{
VertexListType controlVertices;
if (!this->IsEmptyTimeStep(timestep))
{
controlVertices = *this->m_ContourSeries[timestep]->GetVertexList();
}
return controlVertices;
}
void mitk::ContourModel::ClearData()
{
// call the superclass, this releases the data of BaseData
Superclass::ClearData();
// clear out the time resolved contours
this->m_ContourSeries.clear();
}
void mitk::ContourModel::Initialize()
{
this->InitializeEmpty();
this->Modified();
this->m_UpdateBoundingBox = true;
}
void mitk::ContourModel::Initialize(const ContourModel &other)
{
TimeStepType numberOfTimesteps = other.GetTimeGeometry()->CountTimeSteps();
this->InitializeTimeGeometry(numberOfTimesteps);
for (TimeStepType currentTimestep = 0; currentTimestep < numberOfTimesteps; currentTimestep++)
{
this->m_ContourSeries.push_back(ContourElement::New());
this->SetClosed(other.IsClosed(currentTimestep), currentTimestep);
}
m_SelectedVertex = nullptr;
this->m_lineInterpolation = other.m_lineInterpolation;
this->Modified();
this->m_UpdateBoundingBox = true;
}
void mitk::ContourModel::InitializeEmpty()
{
// clear data at timesteps
this->m_ContourSeries.resize(0);
this->m_ContourSeries.push_back(ContourElement::New());
// set number of timesteps to one
this->InitializeTimeGeometry(1);
m_SelectedVertex = nullptr;
this->m_lineInterpolation = ContourModel::LINEAR;
}
void mitk::ContourModel::UpdateOutputInformation()
{
if (this->GetSource())
{
this->GetSource()->UpdateOutputInformation();
}
if (this->m_UpdateBoundingBox)
{
// update the bounds of the geometry according to the stored vertices
ScalarType mitkBounds[6];
// calculate the boundingbox at each timestep
typedef itk::BoundingBox<unsigned long, 3, ScalarType> BoundingBoxType;
typedef BoundingBoxType::PointsContainer PointsContainer;
int timesteps = this->GetTimeSteps();
// iterate over the timesteps
for (int currenTimeStep = 0; currenTimeStep < timesteps; currenTimeStep++)
{
if (dynamic_cast<PlaneGeometry *>(this->GetGeometry(currenTimeStep)))
{
// do not update bounds for 2D geometries, as they are unfortunately defined with min bounds 0!
return;
}
else
{ // we have a 3D geometry -> let's update bounds
// only update bounds if the contour was modified
if (this->GetMTime() > this->GetGeometry(currenTimeStep)->GetBoundingBox()->GetMTime())
{
mitkBounds[0] = 0.0;
mitkBounds[1] = 0.0;
mitkBounds[2] = 0.0;
mitkBounds[3] = 0.0;
mitkBounds[4] = 0.0;
mitkBounds[5] = 0.0;
BoundingBoxType::Pointer boundingBox = BoundingBoxType::New();
PointsContainer::Pointer points = PointsContainer::New();
auto it = this->IteratorBegin(currenTimeStep);
auto end = this->IteratorEnd(currenTimeStep);
// fill the boundingbox with the points
while (it != end)
{
Point3D currentP = (*it)->Coordinates;
BoundingBoxType::PointType p;
p.CastFrom(currentP);
points->InsertElement(points->Size(), p);
it++;
}
// construct the new boundingBox
boundingBox->SetPoints(points);
boundingBox->ComputeBoundingBox();
BoundingBoxType::BoundsArrayType tmp = boundingBox->GetBounds();
mitkBounds[0] = tmp[0];
mitkBounds[1] = tmp[1];
mitkBounds[2] = tmp[2];
mitkBounds[3] = tmp[3];
mitkBounds[4] = tmp[4];
mitkBounds[5] = tmp[5];
// set boundingBox at current timestep
BaseGeometry *geometry3d = this->GetGeometry(currenTimeStep);
geometry3d->SetBounds(mitkBounds);
}
}
}
this->m_UpdateBoundingBox = false;
}
GetTimeGeometry()->Update();
}
void mitk::ContourModel::ExecuteOperation(Operation * /*operation*/)
{
// not supported yet
}
| 28.023529 | 151 | 0.687028 | [
"geometry",
"vector",
"model",
"3d"
] |
023c0b582ab0cf444de28bb8e2b8a6014e057b58 | 4,196 | cpp | C++ | src/execution/operator/aggregate/physical_simple_aggregate.cpp | xhochy/duckdb | 20ba65f96794ab53f7a66e22d9bc58d59d8bc623 | [
"MIT"
] | null | null | null | src/execution/operator/aggregate/physical_simple_aggregate.cpp | xhochy/duckdb | 20ba65f96794ab53f7a66e22d9bc58d59d8bc623 | [
"MIT"
] | null | null | null | src/execution/operator/aggregate/physical_simple_aggregate.cpp | xhochy/duckdb | 20ba65f96794ab53f7a66e22d9bc58d59d8bc623 | [
"MIT"
] | 1 | 2019-09-06T09:58:14.000Z | 2019-09-06T09:58:14.000Z | #include "execution/operator/aggregate/physical_simple_aggregate.hpp"
#include "common/vector_operations/vector_operations.hpp"
#include "execution/expression_executor.hpp"
#include "planner/expression/bound_aggregate_expression.hpp"
using namespace duckdb;
using namespace std;
PhysicalSimpleAggregate::PhysicalSimpleAggregate(vector<TypeId> types, vector<unique_ptr<Expression>> expressions) :
PhysicalOperator(PhysicalOperatorType::SIMPLE_AGGREGATE, types), aggregates(move(expressions)) {
}
void PhysicalSimpleAggregate::GetChunkInternal(ClientContext &context, DataChunk &chunk, PhysicalOperatorState *state_) {
auto state = reinterpret_cast<PhysicalSimpleAggregateOperatorState *>(state_);
while(true) {
// iterate over the child
children[0]->GetChunk(context, state->child_chunk, state->child_state.get());
if (state->child_chunk.size() == 0) {
break;
}
ExpressionExecutor executor(state->child_chunk);
// now resolve the aggregates for each of the children
state->payload_chunk.Reset();
for(index_t aggr_idx = 0; aggr_idx < aggregates.size(); aggr_idx++) {
auto &aggregate = (BoundAggregateExpression&) *aggregates[aggr_idx];
auto &payload_vector = state->payload_chunk.data[aggr_idx];
// resolve the child expression of the aggregate (if any)
if (aggregate.child) {
executor.ExecuteExpression(*aggregate.child, payload_vector);
} else {
payload_vector.count = state->child_chunk.size();
}
// perform the actual aggregation
switch (aggregate.type) {
case ExpressionType::AGGREGATE_COUNT_STAR:
state->aggregates[aggr_idx] = state->aggregates[aggr_idx] + Value::BIGINT(payload_vector.count);
break;
case ExpressionType::AGGREGATE_COUNT: {
Value count = VectorOperations::Count(payload_vector);
state->aggregates[aggr_idx] = state->aggregates[aggr_idx] + count;
break;
}
case ExpressionType::AGGREGATE_SUM: {
Value sum = VectorOperations::Sum(payload_vector);
if (sum.is_null) {
break;
}
if (state->aggregates[aggr_idx].is_null) {
state->aggregates[aggr_idx] = sum;
} else {
state->aggregates[aggr_idx] = state->aggregates[aggr_idx] + sum;
}
break;
}
case ExpressionType::AGGREGATE_MIN: {
Value min = VectorOperations::Min(payload_vector);
if (min.is_null) {
break;
}
if (state->aggregates[aggr_idx].is_null || state->aggregates[aggr_idx] > min) {
state->aggregates[aggr_idx] = min;
}
break;
}
case ExpressionType::AGGREGATE_MAX: {
Value max = VectorOperations::Max(payload_vector);
if (max.is_null) {
break;
}
if (state->aggregates[aggr_idx].is_null || state->aggregates[aggr_idx] < max) {
state->aggregates[aggr_idx] = max;
}
break;
}
default:
throw Exception("Unsupported aggregate for simple aggregation");
}
}
}
// initialize the result chunk with the aggregate values
for(index_t aggr_idx = 0; aggr_idx < aggregates.size(); aggr_idx++) {
chunk.data[aggr_idx].count = 1;
chunk.data[aggr_idx].SetValue(0, state->aggregates[aggr_idx]);
}
state->finished = true;
}
unique_ptr<PhysicalOperatorState> PhysicalSimpleAggregate::GetOperatorState() {
return make_unique<PhysicalSimpleAggregateOperatorState>(this, children[0].get());
}
PhysicalSimpleAggregateOperatorState::PhysicalSimpleAggregateOperatorState(PhysicalSimpleAggregate *parent, PhysicalOperator *child)
: PhysicalOperatorState(child) {
vector<TypeId> payload_types;
for (auto &aggregate : parent->aggregates) {
assert(aggregate->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE);
auto &aggr = (BoundAggregateExpression &)*aggregate;
// initialize the payload chunk
if (aggr.child) {
payload_types.push_back(aggr.child->return_type);
} else {
// COUNT(*)
payload_types.push_back(TypeId::BIGINT);
}
// initialize the aggregate values
switch (aggregate->type) {
case ExpressionType::AGGREGATE_COUNT_STAR:
case ExpressionType::AGGREGATE_COUNT:
case ExpressionType::AGGREGATE_COUNT_DISTINCT:
aggregates.push_back(Value::BIGINT(0));
break;
default:
aggregates.push_back(Value());
break;
}
}
payload_chunk.Initialize(payload_types);
}
| 34.966667 | 132 | 0.730458 | [
"vector"
] |
0243e801a72c0f212a3a90406cfb3114bf1724df | 1,029 | cpp | C++ | SPOJ/Random/PERMUT1/permut1.cpp | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | SPOJ/Random/PERMUT1/permut1.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | SPOJ/Random/PERMUT1/permut1.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<stdio.h>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<set>
#include<vector>
#include<utility>
#define sd(x) scanf("%d",&x);
#define sd2(x,y) scanf("%d %d",&x,&y);
#define sd3(x,y,z) scanf("%d %d %d",&x,&y,&z);
#define sull(x) scanf("%ull",&x);
#define print(x) printf("%d\n",x);
#define print2(x,y) printf("%d %d\n",x,y);
#define print3(x,y,z) printf("%d %d %d\n",x,y,z);
#define printull(x) printf("%ull\n",x);
using namespace std;
int main(){
int d, n, k, i, j;
sd(d);
long long dp[13][99];
memset(dp, 0, sizeof(dp));
for(i = 1; i < 13; i++)
dp[i][0] = 1;
for(i = 1; i <= 98; i++)
dp[1][i] = 0;
for(i = 2; i<= 12; i++){
for(j = 0; j <= 98; j++)
if(j - + 1 < 0)
dp[i][j] = dp[i][j-1] + dp[i-1][j];
else
for(k = j - i + 1; k <= j; k++)
dp[i][j] += dp[i-1][k];
}
/*for(i = 1; i <=5; i++){
for(j = 0; j <= 10; j++)
cout<<dp[i][j]<<" ";
cout<<endl;}*/
while(d--){
sd2(n,k);
cout<<dp[n][k]<<endl;
}
return 0;
}
| 20.176471 | 49 | 0.498542 | [
"vector"
] |
024acdf4025277fddd118eb4ec756a7345a77460 | 1,605 | cpp | C++ | solutions/LeetCode/C++/1014.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/1014.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/1014.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 24 ms submission
static const auto io_sync_off = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return 0;
}();
class Solution {
public:
int maxScoreSightseeingPair(vector<int>& A) {
int n = A.size();
int m = 0, ans = 0;
for(int i = 0; i < n; ++i) {
int tmp = m + A[i] - i; // 24 ms
if(ans < tmp)
ans = tmp;
tmp = A[i] + i;
if(m < tmp)
m = tmp;
// ans = max(ans, m + A[i] - i); // 28 ms
// m = max(m, A[i] + i);
}
return ans;
}
};
__________________________________________________________________________________________________
sample 28 ms submission
static int _ = [](){std::ios::sync_with_stdio(false);cin.tie(NULL);return 0;}();
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
template<class K,class V> using umap = unordered_map<K,V>;
template<class T> using uset = unordered_set<T>;
#define F(i,l,r) for(int i=(l);i<(r);i++)
#define RF(i,l,r) for(int i=(r)-1;i>=l;i--)
#define FILL(a,v) memset(a,v,sizeof(a))
#define LOG(arg) cout << ""#arg" = " << (arg) << endl
const int MOD = 1e9+7;
class Solution {
public:
int maxScoreSightseeingPair(vector<int>& a) {
int mx = a[0]+a[1]-1;
int lmx = max(a[0] - 1, a[1]);
int n = a.size();
F(i,2,n){
lmx--;
mx = max(mx, lmx + a[i]);
lmx = max(lmx, a[i]);
}
return mx;
}
};
__________________________________________________________________________________________________
| 26.311475 | 98 | 0.621807 | [
"vector"
] |
024ba13ff0eab60c41a9a8a4478ed1fef32c7078 | 2,948 | cpp | C++ | core/src/main/cpp/util/MslContext.cpp | sghill/msl | 97f53d685389bab496df889d87ccdbd1e9728032 | [
"Apache-2.0"
] | 559 | 2015-01-01T14:47:49.000Z | 2022-03-05T02:33:53.000Z | core/src/main/cpp/util/MslContext.cpp | sghill/msl | 97f53d685389bab496df889d87ccdbd1e9728032 | [
"Apache-2.0"
] | 141 | 2015-01-06T18:43:22.000Z | 2020-09-27T02:21:21.000Z | core/src/main/cpp/util/MslContext.cpp | sghill/msl | 97f53d685389bab496df889d87ccdbd1e9728032 | [
"Apache-2.0"
] | 85 | 2015-03-04T19:10:35.000Z | 2022-02-15T10:34:40.000Z | /**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <util/MslContext.h>
#include <IllegalArgumentException.h>
#include <numerics/safe_math.h>
#include <util/StaticMslMutex.h>
using namespace std;
using base::internal::CheckedNumeric;
namespace netflix {
namespace msl {
namespace util {
namespace {
const int64_t MILLISECONDS_PER_SECOND = 1000;
StaticMslMutex staticMutex;
uint32_t nextId() {
LockGuard lock(staticMutex);
static CheckedNumeric<uint32_t> id = 0;
if (!(id++.IsValid())) {
assert(false);
}
return id.ValueOrDie();
}
} // namespace anonymous
// NOTE: Static initialization of MslContext::ReauthCode::ENTITY_REAUTH,
// MslContext::ReauthCode::ENTITYDATA_REAUTH, and MslContext::ReauthCode::INVALID
// is done in MslContants.cpp.
// static
const std::vector<MslContext::ReauthCode>& MslContext::ReauthCode::getValues() {
static std::vector<MslContext::ReauthCode> gValues;
if (gValues.empty()) {
gValues.push_back(ENTITY_REAUTH);
gValues.push_back(ENTITYDATA_REAUTH);
gValues.push_back(INVALID);
}
return gValues;
}
// static
MslContext::ReauthCode MslContext::ReauthCode::valueOf(const MslConstants::ResponseCode& code)
{
const std::vector<MslContext::ReauthCode>& values = getValues();
std::vector<MslContext::ReauthCode>::const_iterator it;
for (it = values.begin(); it != values.end(); ++it)
{
if (it->responseCode_ == code)
return *it;
}
std::ostringstream sstream;
sstream << "Unknown value " << code << ".";
throw IllegalArgumentException(sstream.str());
}
MslContext::MslContext() : id_(nextId())
{
}
void MslContext::updateRemoteTime(shared_ptr<Date> time)
{
const int64_t localSeconds = getTime() / MILLISECONDS_PER_SECOND;
const int64_t remoteSeconds = time->getTime() / MILLISECONDS_PER_SECOND;
offset_ = remoteSeconds - localSeconds;
synced_ = true;
}
shared_ptr<Date> MslContext::getRemoteTime()
{
if (!synced_) return shared_ptr<Date>();
const int64_t localSeconds = getTime() / MILLISECONDS_PER_SECOND;
const int64_t remoteSeconds = localSeconds + offset_;
return make_shared<Date>(remoteSeconds * MILLISECONDS_PER_SECOND);
}
bool MslContext::equals(std::shared_ptr<const MslContext> other) const
{
return id_ == other->id_;
}
}}} // namespace netflix::msl::util
| 28.901961 | 94 | 0.712687 | [
"vector"
] |
025167a28fe55ceb82ed28ddd713e7206c0dc076 | 6,348 | cpp | C++ | jogo-da-forca/src/JogoForca.cpp | danihenrif/jogo-da-forca-maze | 684f5819891298aa9fea2c1dcaa21af8b60ef4e7 | [
"MIT"
] | null | null | null | jogo-da-forca/src/JogoForca.cpp | danihenrif/jogo-da-forca-maze | 684f5819891298aa9fea2c1dcaa21af8b60ef4e7 | [
"MIT"
] | null | null | null | jogo-da-forca/src/JogoForca.cpp | danihenrif/jogo-da-forca-maze | 684f5819891298aa9fea2c1dcaa21af8b60ef4e7 | [
"MIT"
] | null | null | null | #include "../include/JogoForca.h"
#include "../include/util.h"
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>//sleep
#include <thread>//sleep
#include <random>//random number
#include <ctime>//random number
using namespace std;
JogoForca::JogoForca(int argc, string nomeArquivo){
letra = '\0';
pontos = 0;
erros = 0;
initialize_game(argc,nomeArquivo);
}
JogoForca::~JogoForca(){}
void JogoForca::initialize_game(int argc, string nomeArquivo){
//Carrega as palavras
if(argc==1){
cout << "ERROR000: Nenhum arquivo foi indicado" << endl;
state = GAME_OVER;
return;
}
ifstream levelFile("data/" + nomeArquivo);//carrega o arquivo
lineCount = 0;
string line;
if(levelFile.is_open()){
while (getline(levelFile,line)){ //pega cada linha do arquivo
if(lineCount > 50){
cout << "ERROR0001: Quantidade de palavras excedidas" << endl;
state = GAME_OVER;
return;
}
if(line == "\0"){
cout << "ERROR002: Há ao menos uma linha vazia" << endl;
state = GAME_OVER;
return;
}
palavras.push_back(line);
lineCount++;
}
}
else{
cout << "ERROR0003: Falha ao abrir o arquivo" << endl;
state = GAME_OVER;
return;
}
state = FIRST_TIME;
}
void JogoForca::loop(){
if(state==GAME_OVER){return;}//Finaliza antes de mostrar a tela em caso de erro no arquivo
//Iniciar o jogo ou listar
cout << "Você deseja jogar ou listar os scores anteriores (1/0)? ";
int op;
cin >> op;
cin.ignore();
if(op == 0){//Lista os scores anteriores
ifstream arq("data/scores.txt");//abre o arquivo scpres.txt
if(arq.is_open()){
cout << arq.rdbuf();//printa o conteudo do arquivo scores.txt
}
}
else{//Loop para o jogo
while(state != GAME_OVER){ //Loop de realização do jogo
process_actions();
}
}
}
void JogoForca::process_actions(){
if(state == RUNNING || state == FIRST_TIME){
if (state == FIRST_TIME){
palavra = sortWord(); //sorteia a palavra
tamanhoPalavra = palavra.length();
//Acrescenta os underlines na palavra da forca
for(int i = 0 ; i < tamanhoPalavra ; i++){
palavraForca.push_back('_');
}
}
geraTela();
}
}
void JogoForca::geraTela(){
if(state == FIRST_TIME){//Primeira interação
cout << "Pontos: " << pontos << endl;
printaForca(erros);
//Printa underlines
for(int i = 0 ; i < tamanhoPalavra ; i++){
if(i == 0){cout << palavraForca[0];}
else{
cout << " " << palavraForca[i];
}
}
cout << endl;
state = RUNNING;
}
else{
//Entrada do usuário
cout << "Digite uma letra: ";
cin >> letra;
cin.ignore();
bool acerto = 0;
//Busca letra na string e muda caso acerte
for(int i = 0 ; i < tamanhoPalavra ; i++){
if(letra == palavra[i]){
acerto = 1;
palavraForca[i] = letra; //Muda o caractere da posição em que a letra foi acertada
pontos++;
}
}
if(acerto == 0){
erros++;//Resgistra o erro para não ganhar pontuação extra
pontos--; //se não acertou perde ponto
}
clearScreen();
cout << "Pontos: " << pontos << endl;
printaForca(erros);
printaPalavraForca();
if(acerto == 0){
cout << "ESSA LETRA NÂO ESTÀ NA PALAVRA :D" << endl;
}
resolveWINORLOSE();
}
}
string JogoForca::sortWord(){
srand(time(NULL));
int random = rand() % lineCount;
return palavras[random];
}
void JogoForca::printaPalavraForca(){
for(int i = 0 ; i < tamanhoPalavra ; i++){
if(i == 0){cout << palavraForca[0];}
else{
cout << " " << palavraForca[i];
}
}
cout << endl;
}
void JogoForca::resolveWINORLOSE(){
if(erros == 6){
cout << "GAMEOVER :C, a palavra era " << palavra << endl;
arquivo();//Grava no arquivo
return;
}
if(palavraForca == palavra){
palavrasAcertadas.push_back(palavra);//Adiciona a palavra na lista de palavras acertadas
/*Checa se venceu sem errar*/
if (erros == 0){
cout << "Parabéns, você acertou a palavra inteira sem erros, isso te dá 1 ponto adicional !!" << endl;
pontos++;
cout << "Pontos: " << pontos << endl;
}
else{
cout << "Parabéns, você acertou a palavra e ganhará mais 2 pontos" << endl;
pontos+=2;
cout << "Pontos: " << pontos << endl;
}
/* */
cout << "Você deseja continuar jogando ? (1/0)(Sim/Não): ";
int resposta;
cin >> resposta;
wait(1000);
clearScreen();
// Se quer continuar, zera as variáveis de controle para a próxima rodada
if(resposta == 1){
state=FIRST_TIME;
erros = 0;
palavraForca = "\0";
}
else{//Se não grava no arquivo
arquivo();
}
}
}
void JogoForca::arquivo(){
state=GAME_OVER;
cout << "Informe o seu nome: ";
cin >> nomeJogador;
//Adiciona os dados da rodada no arquivo
ofstream f_out;
f_out.open("data/scores.txt",ios::app);//Abre o arquivo
if(f_out.is_open()){
f_out << nomeJogador << "; "; //Adiciona o nome do jogador no arquivo
for(vector<string>::iterator it = palavrasAcertadas.begin(); it != palavrasAcertadas.end() ; it++){//Palavras acertadas
f_out << *it << ", ";
}
f_out << pontos << ";" << endl; //Adiciona a pontuação no arquivo
cout << "Seus dados foram gravados em data/scores.txt" << endl;
}
else{
cout << "Erro ao abrir o arquivo scores.txt" << endl;
}
}
| 26.78481 | 127 | 0.514335 | [
"vector"
] |
025ac63e954163f74ab58cb920e0bd641065ff65 | 51,611 | cpp | C++ | applications/incompressible_fluid_application/custom_elements/fluid_2dGLS.cpp | lcirrott/Kratos | 8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea | [
"BSD-4-Clause"
] | 2 | 2020-04-30T19:13:08.000Z | 2021-04-14T19:40:47.000Z | applications/incompressible_fluid_application/custom_elements/fluid_2dGLS.cpp | lcirrott/Kratos | 8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea | [
"BSD-4-Clause"
] | 13 | 2019-10-07T12:06:51.000Z | 2020-02-18T08:48:33.000Z | applications/incompressible_fluid_application/custom_elements/fluid_2dGLS.cpp | lcirrott/Kratos | 8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea | [
"BSD-4-Clause"
] | 1 | 2020-06-12T08:51:24.000Z | 2020-06-12T08:51:24.000Z | /*
==============================================================================
KratosR1IncompressibleFluidApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).
Copyright 2007
Pooyan Dadvand, Riccardo Rossi
pooyan@cimne.upc.edu
rrossi@cimne.upc.edu
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain
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 condition:
Distribution of this code for any commercial purpose is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.
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.
==============================================================================
*/
//
// Project Name: Kratos
// Last modified by: $Author: jmarti $
// Date: $Date: 2008-11-26 08:17:41 $
// Revision: $Revision: 1.0 $
//
//
//#define GRADPN_FORM
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "includes/cfd_variables.h"
#include "custom_elements/fluid_2dGLS.h"
#include "utilities/math_utils.h"
#include "incompressible_fluid_application.h"
#include "utilities/geometry_utilities.h"
namespace Kratos
{
//************************************************************************************
//************************************************************************************
Fluid2DGLS::Fluid2DGLS(IndexType NewId, GeometryType::Pointer pGeometry)
: Element(NewId, pGeometry)
{
//DO NOT ADD DOFS HERE!!!
}
//************************************************************************************
//************************************************************************************
Fluid2DGLS::Fluid2DGLS(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties)
: Element(NewId, pGeometry, pProperties)
{
}
Element::Pointer Fluid2DGLS::Create(IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties) const
{
KRATOS_TRY
return Element::Pointer(new Fluid2DGLS(NewId, GetGeometry().Create(ThisNodes), pProperties));
KRATOS_CATCH("");
}
Fluid2DGLS::~Fluid2DGLS()
{
}
//************************************************************************************
//************************************************************************************
void Fluid2DGLS::CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
int FractionalStepNumber = rCurrentProcessInfo[FRACTIONAL_STEP];
if (FractionalStepNumber < 3) //first step of the fractional step solution
{
// int ComponentIndex = FractionalStepNumber - 1;
}
else if (FractionalStepNumber == 4) //second step of the fractional step solution
{
Stage2(rLeftHandSideMatrix, rRightHandSideVector, rCurrentProcessInfo);
}
KRATOS_CATCH("")
}
//************************************************************************************
//************************************************************************************
void Fluid2DGLS::CalculateRightHandSide(VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
///////////////////////NECESSARY LOCALS///////////////////////////////////////////
boost::numeric::ublas::bounded_matrix<double,3,3> msWorkMatrix = ZeroMatrix(3,3);
boost::numeric::ublas::bounded_matrix<double,3,2> msDN_DX = ZeroMatrix(3,2);
array_1d<double,3> msN = ZeroVector(3); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,2> msShapeFunc = ZeroMatrix(6,2);
boost::numeric::ublas::bounded_matrix<double,2,6> msConvOp = ZeroMatrix(2,6);
boost::numeric::ublas::bounded_matrix<double,6,6> msAuxMat = ZeroMatrix(6,6);
array_1d<double,6> msAuxVec = ZeroVector(6); //dimension = number of nodes
array_1d<double,2> ms_adv_vel = ZeroVector(2); //dimesion coincides with space dimension
array_1d<double,2> ms_vel_gauss = ZeroVector(2); //dimesion coincides with space dimension
array_1d<double,3> ms_temp_vec_np = ZeroVector(3); //dimension = number of nodes
array_1d<double,3> ms_aux0 = ZeroVector(3); //dimension = number of nodes
array_1d<double,3> ms_aux1 = ZeroVector(3); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,6> msAuxMat1 = ZeroMatrix(6,6);
boost::numeric::ublas::bounded_matrix<double,6,3> msAuxMat2 = ZeroMatrix(6,3);
boost::numeric::ublas::bounded_matrix<double,2,2> msGrad_ug = ZeroMatrix(2,2);
array_1d<double,6> msStabMomRes = ZeroVector(6); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,3> msGradOp = ZeroMatrix(6,3);
boost::numeric::ublas::bounded_matrix<double,3,3> msWorkMatrix1 = ZeroMatrix(3,3);
///////////////////////////////////////////////////////////////////////////////////
if(rRightHandSideVector.size() != 3)
{
rRightHandSideVector.resize(3,false);
}
double dt = rCurrentProcessInfo[DELTA_TIME];
//fract. vel, that is calculated in the first Fractional Step.. but is saved inside the "VELOCITY" VARIABLE
//so, u_n os VELOCITY, 1 and u_n-1 VELOCITY,2
const array_1d<double,3>& fv0 = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY);
const array_1d<double,3>& fv0_old = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY,1);
//const array_1d<double,3>& fv0_n_1 = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY,2);
const double nu0 = GetGeometry()[0].FastGetSolutionStepValue(VISCOSITY);
const double rho0 = GetGeometry()[0].FastGetSolutionStepValue(DENSITY);
double p0 = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE);
//double p0_old = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE_OLD_IT);
double p0_old = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE,1);
const array_1d<double,3>& ff0 = GetGeometry()[0].FastGetSolutionStepValue(BODY_FORCE);
const array_1d<double,3>& fv1 = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY);
const array_1d<double,3>& fv1_old = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY,1);
//const array_1d<double,3>& fv1_n_1 = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY,2);
const double nu1 = GetGeometry()[1].FastGetSolutionStepValue(VISCOSITY);
const double rho1 = GetGeometry()[1].FastGetSolutionStepValue(DENSITY);
double p1 = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE);
//double p1_old = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE_OLD_IT);
double p1_old = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE,1);
const array_1d<double,3>& ff1 = GetGeometry()[1].FastGetSolutionStepValue(BODY_FORCE);
const array_1d<double,3>& fv2 = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY);
const array_1d<double,3>& fv2_old = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY,1);
//const array_1d<double,3>& fv2_n_1 = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY,2);
const double nu2 = GetGeometry()[2].FastGetSolutionStepValue(VISCOSITY);
const double rho2 = GetGeometry()[2].FastGetSolutionStepValue(DENSITY);
double p2 = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE);
double p2_old = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE,1);
//old iteration can be used if we want to iterate between 1st and 2nd fractional steps
//double p2_old = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE_OLD_IT);
const array_1d<double,3>& ff2 = GetGeometry()[2].FastGetSolutionStepValue(BODY_FORCE);
//in msAuxVec we store the velocity, (not the frac step vel, but u_n, the one that enters the stabilization)
msAuxVec[0]=fv0[0];
msAuxVec[1]=fv0[1];
msAuxVec[2]=fv1[0];
msAuxVec[3]=fv1[1];
msAuxVec[4]=fv2[0];
msAuxVec[5]=fv2[1];
//getting data for the given geometry
double Area;
GeometryUtils::CalculateGeometryData(GetGeometry(),msDN_DX,msN,Area);
//calculating average density and viscosity
double nu = 0.33333333333333*(nu0 + nu1 + nu2 );
double density = 0.33333333333333*(rho0 + rho1 + rho2 );
//ms_vel_gauss[i] = msN[0]*(fv0[i]) + msN[1]*(fv1[i]) + msN[2]*(fv2[i]);
//but with one integration N=0.333333333
ms_vel_gauss[0] = 0.33333333333333*(fv0[0]+fv1[0]+fv2[0]);
ms_vel_gauss[1] = 0.33333333333333*(fv0[1]+fv1[1]+fv2[1]);
//calculating parameter tau (saved internally to each element)
double h = sqrt(2.00*Area);
double norm_u = ms_vel_gauss[0]*ms_vel_gauss[0] + ms_vel_gauss[1]*ms_vel_gauss[1];
norm_u = sqrt(norm_u);
double tau = 1.00 / ( 4.00*nu/(h*h) +2.00*norm_u/h + 1.0/dt);
//tau=0.0;
noalias(msWorkMatrix)=prod(msDN_DX,trans(msDN_DX));
noalias(msWorkMatrix1) = (dt/2.0 + tau) * Area*msWorkMatrix;
//////////////////////////////////////////////////////////
//////////// AND NOW RHS //////////////////
//////////////////////////////////////////////////////////
//Dirichlet contribution (that is: LHS*p_new)
ms_temp_vec_np[0] = p0;
ms_temp_vec_np[1] = p1;
ms_temp_vec_np[2] = p2;
//LHS is already multiplied by AREA
noalias(rRightHandSideVector) = -prod(msWorkMatrix1,ms_temp_vec_np);
//NOW RHS-=dt L p_old
//changing the meaning of temp_vec_np
ms_temp_vec_np[0] = p0_old;
ms_temp_vec_np[1] = p1_old;
ms_temp_vec_np[2] = p2_old;
noalias(rRightHandSideVector) += Area* dt/2.0 * (prod(msWorkMatrix,ms_temp_vec_np)) ;
//***************************************************************************
//here we have the Du_tila term
double Gaux;
Gaux = msDN_DX(0,0)*fv0[0] + msDN_DX(0,1)*fv0[1];
Gaux += msDN_DX(1,0)*fv1[0] + msDN_DX(1,1)*fv1[1];
Gaux += msDN_DX(2,0)*fv2[0] + msDN_DX(2,1)*fv2[1];
rRightHandSideVector[0] -= density*Area*Gaux * msN[0];
rRightHandSideVector[1] -= density*Area*Gaux * msN[1];
rRightHandSideVector[2] -= density*Area*Gaux * msN[2];
ms_aux0=0.33333333333333333*(ff0+ff1+ff2);
//ms_aux1 - is the product of: (nabla q, f)
ms_aux1[0]=msDN_DX(0,0)*ms_aux0[0]+msDN_DX(0,1)*ms_aux0[1];
ms_aux1[1]=msDN_DX(1,0)*ms_aux0[0]+msDN_DX(1,1)*ms_aux0[1];
ms_aux1[2]=msDN_DX(2,0)*ms_aux0[0]+msDN_DX(2,1)*ms_aux0[1];
//KRATOS_WATCH(temp)
//rRightHandSideVector += tau*density*Area*ms_aux1;
//RHS += -tau*nablaN*du_gausspoint/dt
//we reuse ms_vel_gauss to store the accelerations( (u_n - u_n-1)/dt)
ms_vel_gauss[0]=0.33333333333*(fv0[0]+fv1[0]+fv2[0]-fv0_old[0]-fv1_old[0]-fv2_old[0])/dt;
ms_vel_gauss[1]=0.33333333333*(fv0[1]+fv1[1]+fv2[1]-fv0_old[1]-fv1_old[1]-fv2_old[1])/dt;
//and now we reuse ms_aux1
ms_aux1=prod(msDN_DX,ms_vel_gauss);
noalias(rRightHandSideVector) -= tau*density*Area*ms_aux1;
//and now the stabilization term referring to the convective operator
//RHS+=nablaq*convop (convetcion of the Gauss point vel)
//contains d_ug/dx
//x-component of u derived with resp to x, remember msAuxVec stores velocity
msGrad_ug(0,0)=msDN_DX(0,0)*msAuxVec[0]+msDN_DX(1,0)*msAuxVec[2]+msDN_DX(2,0)*msAuxVec[4];
//x-component of u derived with resp to y
msGrad_ug(0,1)=msDN_DX(0,1)*msAuxVec[0]+msDN_DX(1,1)*msAuxVec[2]+msDN_DX(2,1)*msAuxVec[4];
//y-component of u derived with resp to x
msGrad_ug(1,0)=msDN_DX(0,0)*msAuxVec[1]+msDN_DX(1,0)*msAuxVec[3]+msDN_DX(2,0)*msAuxVec[5];
//y-component of u derived with resp to y
msGrad_ug(1,1)=msDN_DX(0,1)*msAuxVec[1]+msDN_DX(1,1)*msAuxVec[3]+msDN_DX(2,1)*msAuxVec[5];
array_1d<double,2> a;
a[0]=0.33333333333333*(msAuxVec[0]+msAuxVec[2]+msAuxVec[4])*msGrad_ug(0,0)+0.33333333333333*(msAuxVec[1]+msAuxVec[3]+msAuxVec[5])*msGrad_ug(0,1);
a[1]=0.33333333333333*(msAuxVec[0]+msAuxVec[2]+msAuxVec[4])*msGrad_ug(1,0)+0.33333333333333*(msAuxVec[1]+msAuxVec[3]+msAuxVec[5])*msGrad_ug(1,1);
//we again reuse ms_aux0
//noalias(ms_aux0) = prod(msDN_DX,a);
//noalias(rRightHandSideVector) -double rho_gauss=0.0;
KRATOS_CATCH("")
}
//************************************************************************************
//************************************************************************************
//calculation by component of the fractional step velocity corresponding to the first stage
void Fluid2DGLS::Stage2(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
///////////////////////NECESSARY LOCALS///////////////////////////////////////////
boost::numeric::ublas::bounded_matrix<double,3,3> msWorkMatrix = ZeroMatrix(3,3);
boost::numeric::ublas::bounded_matrix<double,3,2> msDN_DX = ZeroMatrix(3,2);
array_1d<double,3> msN = ZeroVector(3); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,2> msShapeFunc = ZeroMatrix(6,2);
boost::numeric::ublas::bounded_matrix<double,2,6> msConvOp = ZeroMatrix(2,6);
boost::numeric::ublas::bounded_matrix<double,6,6> msAuxMat = ZeroMatrix(6,6);
array_1d<double,6> msAuxVec = ZeroVector(6); //dimension = number of nodes
array_1d<double,2> ms_adv_vel = ZeroVector(2); //dimesion coincides with space dimension
array_1d<double,2> ms_vel_gauss = ZeroVector(2); //dimesion coincides with space dimension
array_1d<double,3> ms_temp_vec_np = ZeroVector(3); //dimension = number of nodes
array_1d<double,3> ms_aux0 = ZeroVector(3); //dimension = number of nodes
array_1d<double,3> ms_aux1 = ZeroVector(3); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,6> msAuxMat1 = ZeroMatrix(6,6);
boost::numeric::ublas::bounded_matrix<double,6,3> msAuxMat2 = ZeroMatrix(6,3);
boost::numeric::ublas::bounded_matrix<double,2,2> msGrad_ug = ZeroMatrix(2,2);
array_1d<double,6> msStabMomRes = ZeroVector(6); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,3> msGradOp = ZeroMatrix(6,3);
array_1d<double, 2 > vel_gauss;
boost::numeric::ublas::bounded_matrix<double,3,3> Tres = ZeroMatrix(3,3);
boost::numeric::ublas::bounded_matrix<double,3,3> msResta = IdentityMatrix(3,3);
//unsigned int TDim = 2;
//const double Cs = this->GetValue(C_SMAGORINSKY);
//KRATOS_WATCH(Cs);
//KRATOS_THROW_ERROR(std::logic_error, "method not implemented", "");
mThisIntegrationMethod= GeometryData::GI_GAUSS_1;
//const GeometryType::IntegrationPointsArrayType& integration_points = GetGeometry().IntegrationPoints(mThisIntegrationMethod);
//const Matrix& Ncontainer = GetGeometry().ShapeFunctionsValues(mThisIntegrationMethod);//GetGeometry().CalculateShapeFunctionsIntegrationPointsValues(GeometryData::GI_GAUSS_1);
///////////////////////////////////////////////////////////////////////////////////
if(rRightHandSideVector.size() != 3)
{
rLeftHandSideMatrix.resize(3,3,false);
rRightHandSideVector.resize(3,false);
}
double dt = rCurrentProcessInfo[DELTA_TIME];
//fract. vel, that is calculated in the first Fractional Step.. but is saved inside the "VELOCITY" VARIABLE
//so, u_n os VELOCITY, 1 and u_n-1 VELOCITY,2
const array_1d<double,3>& fv0 = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY);
//const array_1d<double,3>& fv0_old = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY,1);
//const array_1d<double,3>& fv0_n_1 = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY,2);
const array_1d<double, 3 > & proj0 = GetGeometry()[0].FastGetSolutionStepValue(PRESS_PROJ);
const double nu0 = GetGeometry()[0].FastGetSolutionStepValue(VISCOSITY);
const double rho0 = GetGeometry()[0].FastGetSolutionStepValue(DENSITY);
double p0 = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE);
//double p0_old = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE_OLD_IT);
double p0_old = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE,1);
//const array_1d<double,3>& ff0 = GetGeometry()[0].FastGetSolutionStepValue(BODY_FORCE);
const array_1d<double,3>& fv1 = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY);
//const array_1d<double,3>& fv1_old = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY,1);
//const array_1d<double,3>& fv1_n_1 = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY,2);
const array_1d<double, 3 > & proj1 = GetGeometry()[1].FastGetSolutionStepValue(PRESS_PROJ);
const double nu1 = GetGeometry()[1].FastGetSolutionStepValue(VISCOSITY);
const double rho1 = GetGeometry()[1].FastGetSolutionStepValue(DENSITY);
double p1 = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE);
//double p1_old = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE_OLD_IT);
double p1_old = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE,1);
//const array_1d<double,3>& ff1 = GetGeometry()[1].FastGetSolutionStepValue(BODY_FORCE);
const array_1d<double,3>& fv2 = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY);
//const array_1d<double,3>& fv2_old = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY,1);
//const array_1d<double,3>& fv2_n_1 = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY,2);
const array_1d<double, 3 > & proj2 = GetGeometry()[2].FastGetSolutionStepValue(PRESS_PROJ);
const double nu2 = GetGeometry()[2].FastGetSolutionStepValue(VISCOSITY);
const double rho2 = GetGeometry()[2].FastGetSolutionStepValue(DENSITY);
double p2 = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE);
double p2_old = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE,1);
//old iteration can be used if we want to iterate between 1st and 2nd fractional steps
//double p2_old = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE_OLD_IT);
//const array_1d<double,3>& ff2 = GetGeometry()[2].FastGetSolutionStepValue(BODY_FORCE);
//int counti=0.0;
// double density = 0.0;
//const unsigned int number_of_points = GetGeometry().size();
//KRATOS_WATCH(counti);
//in msAuxVec we store the velocity, (not the frac step vel, but u_n, the one that enters the stabilization)
msAuxVec[0]=fv0[0];
msAuxVec[1]=fv0[1];
msAuxVec[2]=fv1[0];
msAuxVec[3]=fv1[1];
msAuxVec[4]=fv2[0];
msAuxVec[5]=fv2[1];
//getting data for the given geometry
double Area;
GeometryUtils::CalculateGeometryData(GetGeometry(),msDN_DX,msN,Area);
//KRATOS_WATCH("AREA");
//KRATOS_WATCH(Area);
//calculating average density and viscosity
double nu = 0.33333333333333*(nu0 + nu1 + nu2 );
double density = 0.33333333333333*(rho0 + rho1 + rho2 );
//ms_vel_gauss[i] = msN[0]*(fv0[i]) + msN[1]*(fv1[i]) + msN[2]*(fv2[i]);
//but with one integration N=0.333333333
ms_vel_gauss[0] = 0.33333333333333*(fv0[0]+fv1[0]+fv2[0]);
ms_vel_gauss[1] = 0.33333333333333*(fv0[1]+fv1[1]+fv2[1]);
//calculating parameter tau (saved internally to each element)
double h = sqrt(2.00*Area);
double norm_u = ms_vel_gauss[0]*ms_vel_gauss[0] + ms_vel_gauss[1]*ms_vel_gauss[1];
norm_u = sqrt(norm_u);
//double rho_gauss=0.0;
//int countip=0.0;
//int countipp=0.0;
//for(unsigned int i = 0; i < 3.0 ; i++)
//{
// if(GetGeometry()[i].FastGetSolutionStepValue(FLAG_VARIABLE)==1.0) counti++;
//}
//for(unsigned int i = 0; i < 3.0 ; i++)
//{
// if(GetGeometry()[i].FastGetSolutionStepValue(FLAG_VARIABLE)==10.0) countip++;
//}
//if(countip==3.0) {density=10.0;}
//else density=1.0;
//for(unsigned int i = 0; i < 3.0 ; i++)
//{
// if(GetGeometry()[i].FastGetSolutionStepValue(FLAG_VARIABLE)==6.0) countipp++;
//}
//if(countipp==3.0) {density=6.0;}
//if(countip==3.0) {density=1000.0;}
//else density=1.0;
//tau=0.0;
//AND NOW WE ADD THE RESPECTIVE CONTRIBUTIONS TO THE RHS AND LHS of THE SECOND FRAC STEP
//we use Backward Euler for this step, therefore stab. contribution no RHS +=Tau1*(gradQ, residual)
// and LHS +=Tau1*(gradQ, gradP)
//laplacian term L = Dt * gradN * trans(gradN);
//stabilization term Spp = tau * gradN * trans(gradN);
//WATCH OUT for DIVISION with RHO - check if it changes or not in case of Momentum being the primary Variable
//
// msWorkMatrix stores the element laplacian
//
//noalias(msWorkMatrix)=prod(msDN_DX,trans(msDN_DX));
//noalias(rLeftHandSideMatrix) = (dt/(2.0*density) + tau/density) * Area*msWorkMatrix;
//rhs consists of D*u_tilda (divergence of the Fractional velocity) and the term: Tau1*(nabla_q, residual_gausspoint)
//fv is u_tilda
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//Dirichlet contribution (that is: LHS*p_new)
//ms_temp_vec_np[0] = p0;
//ms_temp_vec_np[1] = p1;
//ms_temp_vec_np[2] = p2;
//LHS is already multiplied by AREA
//noalias(rRightHandSideVector) = -prod(rLeftHandSideMatrix,ms_temp_vec_np);
//NOW RHS-=dt L p_old
//changing the meaning of temp_vec_np
//ms_temp_vec_np[0] = p0_old;
//ms_temp_vec_np[1] = p1_old;
//ms_temp_vec_np[2] = p2_old;
//noalias(rRightHandSideVector) += Area* dt/(2.0 * density ) * (prod(msWorkMatrix,ms_temp_vec_np)) ;
//***************************************************************************
/*vel_gauss[0] = msN[0] * proj0[0] + msN[1] * proj1[0] + msN[2] * proj2[0];
vel_gauss[1] = msN[0] * proj0[1] + msN[1] * proj1[1] + msN[2] * proj2[1];
vel_gauss *= tau;
noalias(rRightHandSideVector) += prod(msDN_DX, vel_gauss)*Area;*/// *density;
/*if(countip>0.0) {density=10.0;}
if(counti>0.0) {density=1.0;}*/
//density = 0.33333333333333*(rho0 + rho1 + rho2 );
//double Gaux;
//Gaux = msDN_DX(0,0)*fv0[0] + msDN_DX(0,1)*fv0[1];
//Gaux += msDN_DX(1,0)*fv1[0] + msDN_DX(1,1)*fv1[1];
//Gaux += msDN_DX(2,0)*fv2[0] + msDN_DX(2,1)*fv2[1];
//rRightHandSideVector[0] -= Area*Gaux * msN[0];
//rRightHandSideVector[1] -= Area*Gaux * msN[1];
//rRightHandSideVector[2] -= Area*Gaux * msN[2];
//vel_gauss[0] = msN[0] * proj0[0] + msN[1] * proj1[0] + msN[2] * proj2[0];
//vel_gauss[1] = msN[0] * proj0[1] + msN[1] * proj1[1] + msN[2] * proj2[1];
//vel_gauss *= tau;
//noalias(rRightHandSideVector) += prod(msDN_DX, vel_gauss) * Area ;
///////////////////////////////////////
///////////////////////////////////////
//mInvJ0.resize(integration_points.size());
//mDetJ0.resize(integration_points.size(),false);
//KRATOS_WATCH("ACAAAAAAAAAAA");
//double total_density=0.0;
//const GeometryType::ShapeFunctionsGradientsType& DN_De = GetGeometry().ShapeFunctionsLocalGradients(mThisIntegrationMethod);
//GeometryType::JacobiansType J0;
//J0 = GetGeometry().Jacobian(J0, mThisIntegrationMethod);
//density = this->GetValue(DENSITY);
//KRATOS_WATCH(density);
density = this->GetValue(DENSITY);
KRATOS_WATCH(density);
//density = 0.33333333333333*(rho0 + rho1 + rho2 );
//if(density>1.01 and density<999.0) density=500.0;
/*noalias(rLeftHandSideMatrix) = ZeroMatrix(TDim + 1, TDim + 1);
noalias(rRightHandSideVector) = ZeroVector(TDim + 1);*/
double tau = 1.00 / ( 4.00* nu/(density * h*h) + 2.00*norm_u/h + 1.0/dt);
noalias(msWorkMatrix)=prod(msDN_DX,trans(msDN_DX));
noalias(rLeftHandSideMatrix) = (dt/(2.0*density) + tau/density) * msWorkMatrix * Area;
ms_temp_vec_np[0] = p0;
ms_temp_vec_np[1] = p1;
ms_temp_vec_np[2] = p2;
//LHS is already multiplied by AREA
noalias(rRightHandSideVector) = -prod(rLeftHandSideMatrix,ms_temp_vec_np);
ms_temp_vec_np[0] = p0_old;
ms_temp_vec_np[1] = p1_old;
ms_temp_vec_np[2] = p2_old;
noalias(rRightHandSideVector) += dt/(2.0 * density ) * (prod(msWorkMatrix,ms_temp_vec_np)) * Area;
double nodal_1 = 0.333333333333 * Area * density ;
double nodal_2 = 0.333333333333 * Area * density ;
double nodal_3 = 0.333333333333 * Area * density ;
GetGeometry()[0].SetLock();
GetGeometry()[0].FastGetSolutionStepValue(NODAL_AREA) += nodal_1;
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
GetGeometry()[1].FastGetSolutionStepValue(NODAL_AREA) += nodal_2;
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
GetGeometry()[2].FastGetSolutionStepValue(NODAL_AREA) += nodal_3;
GetGeometry()[2].UnSetLock();
double Gaux;
Gaux = msDN_DX(0,0)*fv0[0] + msDN_DX(0,1)*fv0[1];
Gaux += msDN_DX(1,0)*fv1[0] + msDN_DX(1,1)*fv1[1];
Gaux += msDN_DX(2,0)*fv2[0] + msDN_DX(2,1)*fv2[1];
rRightHandSideVector[0] -= Area * Gaux * msN[0];
rRightHandSideVector[1] -= Area * Gaux * msN[1];
rRightHandSideVector[2] -= Area * Gaux * msN[2];
vel_gauss[0] = msN[0] * proj0[0] + msN[1] * proj1[0] + msN[2] * proj2[0];
vel_gauss[1] = msN[0] * proj0[1] + msN[1] * proj1[1] + msN[2] * proj2[1];
vel_gauss *= tau;
noalias(rRightHandSideVector) += prod(msDN_DX, vel_gauss) * Area;
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/* for(unsigned int PointNumber = 0; PointNumber<integration_points.size(); PointNumber++)
{
//KRATOS_WATCH(integration_points.size());
//KRATOS_WATCH(PointNumber);
unsigned int number_of_nodes = GetGeometry().PointsNumber();
unsigned int dimension = GetGeometry().WorkingSpaceDimension();
const Vector& N=row(Ncontainer,PointNumber);
MathUtils<double>::InvertMatrix(J0[PointNumber],mInvJ0[PointNumber],mDetJ0[PointNumber]);
double Weight = integration_points[PointNumber].Weight()* mDetJ0[PointNumber];
noalias(msDN_DX) = prod(DN_De[PointNumber],mInvJ0[PointNumber]);
//KRATOS_WATCH(msDN_DX);
//double rho_gauss=0.0;
//density =0.0;
//for (unsigned int i=0;i<number_of_nodes;i++) density += N[i]*GetGeometry()[i].FastGetSolutionStepValue(DENSITY);
density = N[0]*GetGeometry()[0].FastGetSolutionStepValue(DENSITY) + N[1]*GetGeometry()[1].FastGetSolutionStepValue(DENSITY) +N[2]*GetGeometry()[2].FastGetSolutionStepValue(DENSITY);
density = this->GetValue(DENSITY);
double tau = 1.00 / ( 4.00* nu/(density * h*h) + 2.00*norm_u/h + 1.0/dt);
noalias(msWorkMatrix)=prod(msDN_DX,trans(msDN_DX));
noalias(rLeftHandSideMatrix) += (dt/(2.0*density) + tau/density) * msWorkMatrix * Weight;
//NOW RHS-=dt L p_old
//changing the meaning of temp_vec_np
ms_temp_vec_np[0] = p0_old;
ms_temp_vec_np[1] = p1_old;
ms_temp_vec_np[2] = p2_old;
noalias(rRightHandSideVector) += dt/(2.0 * density ) * (prod(msWorkMatrix,ms_temp_vec_np)) * Weight;
Tres(0,0)=N[0]*N[0];
Tres(0,1)=N[0]*N[1];
Tres(0,2)=N[0]*N[2];
Tres(1,0)=N[1]*N[0];
Tres(1,1)=N[1]*N[1];
Tres(1,2)=N[1]*N[2];
Tres(2,0)=N[2]*N[0];
Tres(2,1)=N[2]*N[1];
Tres(2,2)=N[2]*N[2];
//KRATOS_WATCH(Tres);
double nodal_1 = (N[0]*N[0] + N[0]*N[1] + N[0]*N[2]) * Weight * density ;
double nodal_2 = (N[1]*N[0] + N[1]*N[1] + N[1]*N[2]) * Weight * density ;
double nodal_3 = (N[2]*N[0] + N[2]*N[1] + N[2]*N[2]) * Weight * density ;
GetGeometry()[0].SetLock();
GetGeometry()[0].FastGetSolutionStepValue(NODAL_AREA) += nodal_1;
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
GetGeometry()[1].FastGetSolutionStepValue(NODAL_AREA) += nodal_2;
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
GetGeometry()[2].FastGetSolutionStepValue(NODAL_AREA) += nodal_3;
GetGeometry()[2].UnSetLock();
//density=1.0;
double Gaux;
Gaux = msDN_DX(0,0)*fv0[0] + msDN_DX(0,1)*fv0[1];
Gaux += msDN_DX(1,0)*fv1[0] + msDN_DX(1,1)*fv1[1];
Gaux += msDN_DX(2,0)*fv2[0] + msDN_DX(2,1)*fv2[1];
rRightHandSideVector[0] -= Weight * Gaux * N[0];
rRightHandSideVector[1] -= Weight * Gaux * N[1];
rRightHandSideVector[2] -= Weight * Gaux * N[2];
vel_gauss[0] = N[0] * proj0[0] + N[1] * proj1[0] + N[2] * proj2[0];
vel_gauss[1] = N[0] * proj0[1] + N[1] * proj1[1] + N[2] * proj2[1];
vel_gauss *= tau;
noalias(rRightHandSideVector) += prod(msDN_DX, vel_gauss) * Weight;
}
//Dirichlet contribution (that is: LHS*p_new)
ms_temp_vec_np[0] = -p0;
ms_temp_vec_np[1] = -p1;
ms_temp_vec_np[2] = -p2;
//LHS is already multiplied by AREA
noalias(rRightHandSideVector) += prod(rLeftHandSideMatrix,ms_temp_vec_np);
*/
KRATOS_CATCH("")
}
//************************************************************************************
//************************************************************************************
// this subroutine calculates the nodal contributions for the explicit steps of the
// fractional step procedure
void Fluid2DGLS::InitializeSolutionStep(ProcessInfo& CurrentProcessInfo)
{
KRATOS_TRY
int FractionalStepNumber = CurrentProcessInfo[FRACTIONAL_STEP];
boost::numeric::ublas::bounded_matrix<double, 3, 3 > MassFactors = 1.0 / 3.0 * IdentityMatrix(3, 3);
boost::numeric::ublas::bounded_matrix<double, 3, 3 > WorkMatrix;
boost::numeric::ublas::bounded_matrix<double, 3, 2 > DN_DX;
array_1d<double, 3 > N;
array_1d<double, 2 > vel_gauss;
array_1d<double, 3 > temp_vec_np;
array_1d<double, 3 > u_DN;
array_1d<double, 3 > aux0;
array_1d<double, 3 > aux1;
array_1d<double, 3 > aux2;
//getting data for the given geometry
double Area;
GeometryUtils::CalculateGeometryData(GetGeometry(), DN_DX, N, Area);
//KRATOS_THROW_ERROR(std::logic_error, "method not implemented", "");
if (FractionalStepNumber == 5) //calculation of stabilization terms
{
//KRATOS_THROW_ERROR(std::logic_error, "method not implemented", "");
///////////////////////NECESSARY LOCALS///////////////////////////////////////////
boost::numeric::ublas::bounded_matrix<double,3,3> msWorkMatrix = ZeroMatrix(3,3);
array_1d<double,6> GalerkinRHS = ZeroVector(6); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,3,2> msDN_DX = ZeroMatrix(3,2);
array_1d<double,3> msN = ZeroVector(3); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,2> msShapeFunc = ZeroMatrix(6,2);
boost::numeric::ublas::bounded_matrix<double,2,6> msConvOp = ZeroMatrix(2,6);
boost::numeric::ublas::bounded_matrix<double,6,6> msAuxMat = ZeroMatrix(6,6);
array_1d<double,6> msAuxVec = ZeroVector(6); //dimension = number of nodes
array_1d<double,2> ms_adv_vel = ZeroVector(2); //dimesion coincides with space dimension
array_1d<double,2> ms_vel_gauss = ZeroVector(2); //dimesion coincides with space dimension
///////////////////////////////////////////////////////////////////////////////////
//first we compute the force term and pressure gradient terms:
//getting data for the given geometry
double Area;
GeometryUtils::CalculateGeometryData(GetGeometry(),msDN_DX,msN,Area);
//getting the velocity on the nodes and other necessary variabless
const array_1d<double,3> vel0 = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY,1);
double p_n0 = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE,1);
const double nu0 = GetGeometry()[0].FastGetSolutionStepValue(VISCOSITY);
const double rho0 = GetGeometry()[0].FastGetSolutionStepValue(DENSITY);
const array_1d<double,3> vel1 = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY,1);
double p_n1 = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE,1);
const double nu1 = GetGeometry()[1].FastGetSolutionStepValue(VISCOSITY);
const double rho1 = GetGeometry()[1].FastGetSolutionStepValue(DENSITY);
const array_1d<double,3>& vel2 = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY,1);
double p_n2 = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE,1);
const double nu2 = GetGeometry()[2].FastGetSolutionStepValue(VISCOSITY);
const double rho2 = GetGeometry()[2].FastGetSolutionStepValue(DENSITY);
//====================================================================
//calculating viscosity and density
double nu = 0.333333333333333333333333*(nu0 + nu1 + nu2 );
double density = 0.3333333333333333333333*(rho0 + rho1 + rho2 );
//int counti=0.0;
int countip=0.0;
//int countipp=0.0;
//for(unsigned int i = 0; i < 3.0 ; i++)
//{
// if(GetGeometry()[i].FastGetSolutionStepValue(FLAG_VARIABLE)==1.0) counti++;
//}
for(unsigned int i = 0; i < 3.0 ; i++)
{
if(GetGeometry()[i].FastGetSolutionStepValue(FLAG_VARIABLE)==10.0) countip++;
}
//for(unsigned int i = 0; i < 3.0 ; i++)
//{
// if(GetGeometry()[i].FastGetSolutionStepValue(FLAG_VARIABLE)==6.0) countipp++;
//}
//if(countipp==3.0) {density=6.0;}
//if(countip==3.0) {density=1000.0;}
//else density=1.0;
/* if(countip>0.0) {density=10.0;}
if(counti>0.0) {density=1.0;}*/
//density = 0.33333333333333*(rho0 + rho1 + rho2 );
//density = 0.3333333333333333333333*(rho0 + rho1 + rho2 );
//density = this->GetValue(DENSITY);
//KRATOS_WATCH(density);
density = this->GetValue(DENSITY);
//density = 0.33333333333333*(rho0 + rho1 + rho2 );
//if(density>1.01 and density<999.0) density=500.0;
//density = 0.33333333333333*(rho0 + rho1 + rho2 );
//if(density>1.01 and density<900.0) density=500.0;
//KRATOS_WATCH(density);
noalias(msWorkMatrix) = Area* /*density **/ nu * prod(msDN_DX,trans(msDN_DX));
//x comp
GalerkinRHS[0]=-1.0*(msWorkMatrix(0,0)*vel0[0]+msWorkMatrix(0,1)*vel1[0]+msWorkMatrix(0,2)*vel2[0]);
//y comp
GalerkinRHS[1]=-1.0*(msWorkMatrix(0,0)*vel0[1]+msWorkMatrix(0,1)*vel1[1]+msWorkMatrix(0,2)*vel2[1]);
//x comp
GalerkinRHS[2]=-1.0*(msWorkMatrix(1,0)*vel0[0]+msWorkMatrix(1,1)*vel1[0]+msWorkMatrix(1,2)*vel2[0]);
//y comp
GalerkinRHS[3]=-1.0*(msWorkMatrix(1,0)*vel0[1]+msWorkMatrix(1,1)*vel1[1]+msWorkMatrix(1,2)*vel2[1]);
//x comp
GalerkinRHS[4]=-1.0*(msWorkMatrix(2,0)*vel0[0]+msWorkMatrix(2,1)*vel1[0]+msWorkMatrix(2,2)*vel2[0]);
//y comp
GalerkinRHS[5]=-1.0*(msWorkMatrix(2,0)*vel0[1]+msWorkMatrix(2,1)*vel1[1]+msWorkMatrix(2,2)*vel2[1]);
//////////////////////////////////////
//////////////////////////////////////
/*GetGeometry()[0].SetLock();
array_1d<double,3>& rmu0 = GetGeometry()[0].FastGetSolutionStepValue(ANGULAR_VELOCITY);
rmu0[0] += GalerkinRHS[0];
rmu0[1] += GalerkinRHS[1];
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
array_1d<double,3>& rmu1 = GetGeometry()[1].FastGetSolutionStepValue(ANGULAR_VELOCITY);
rmu1[0] += GalerkinRHS[2];
rmu1[1] += GalerkinRHS[3];
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
array_1d<double,3>& rmu2 = GetGeometry()[2].FastGetSolutionStepValue(ANGULAR_VELOCITY);
rmu2[0] += GalerkinRHS[4];
rmu2[1] += GalerkinRHS[5];
GetGeometry()[2].UnSetLock();*/
//////////////////////////////////////
//////////////////////////////////////
//density=1.0;
ms_adv_vel[0] = msN[0]*(vel0[0])+msN[1]*(vel1[0])+msN[2]*(vel2[0]);
ms_adv_vel[1] = msN[0]*(vel0[1])+msN[1]*(vel1[1])+msN[2]*(vel2[1]);
const array_1d<double,3> body_force = 0.333333333333333*(GetGeometry()[0].FastGetSolutionStepValue(BODY_FORCE)+ GetGeometry()[1].FastGetSolutionStepValue(BODY_FORCE) + GetGeometry()[2].FastGetSolutionStepValue(BODY_FORCE));
unsigned int number_of_nodes=3;
for(unsigned int i = 0; i<number_of_nodes; i++)
{
GalerkinRHS[i*2] += body_force[0]* density * Area * 0.3333333333333;
GalerkinRHS[i*2+1] += body_force[1] * density * Area * 0.3333333333333;
}
double p_avg=0.333333333333*(p_n0+p_n1+p_n2)*Area;
GalerkinRHS[0]+=msDN_DX(0,0)*p_avg;
GalerkinRHS[1]+=msDN_DX(0,1)*p_avg;
GalerkinRHS[2]+=msDN_DX(1,0)*p_avg;
GalerkinRHS[3]+=msDN_DX(1,1)*p_avg;
GalerkinRHS[4]+=msDN_DX(2,0)*p_avg;
GalerkinRHS[5]+=msDN_DX(2,1)*p_avg;
//////////////////////////////////////
//////////////////////////////////////
/*GetGeometry()[0].SetLock();
array_1d<double,3>& rmp0 = GetGeometry()[0].FastGetSolutionStepValue(ANGULAR_ACCELERATION);
rmp0[0] += msDN_DX(0,0)*p_avg;
rmp0[1] += msDN_DX(0,1)*p_avg;
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
array_1d<double,3>& rmp1 = GetGeometry()[1].FastGetSolutionStepValue(ANGULAR_ACCELERATION);
rmp1[0] += msDN_DX(1,0)*p_avg;
rmp1[1] += msDN_DX(1,1)*p_avg;
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
array_1d<double,3>& rmp2 = GetGeometry()[2].FastGetSolutionStepValue(ANGULAR_ACCELERATION);
rmp2[0] += msDN_DX(2,0)*p_avg;
rmp2[1] += msDN_DX(2,1)*p_avg;
GetGeometry()[2].UnSetLock();*/
//////////////////////////////////////
//////////////////////////////////////
GetGeometry()[0].SetLock();
//array_1d<double,3>& rhsg0 = GetGeometry()[0].FastGetSolutionStepValue(ANGULAR_ACCELERATION);
//rhsg0[0] += body_force[0]* Area * 0.3333333333333;// *density ;
//rhsg0[1] += body_force[1]* Area * 0.3333333333333;// *density ;
array_1d<double,3>& rhs0 = GetGeometry()[0].FastGetSolutionStepValue(FORCE);
rhs0[0] += GalerkinRHS[0];
rhs0[1] += GalerkinRHS[1];
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
//array_1d<double,3>& rhsg1 = GetGeometry()[1].FastGetSolutionStepValue(ANGULAR_ACCELERATION);
//rhsg1[0] += body_force[0]* Area * 0.3333333333333;// *density ;
//rhsg1[1] += body_force[1]* Area * 0.3333333333333;// *density;
array_1d<double,3>& rhs1 = GetGeometry()[1].FastGetSolutionStepValue(FORCE);
rhs1[0] += GalerkinRHS[2];
rhs1[1] += GalerkinRHS[3];
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
//array_1d<double,3>& rhsg2 = GetGeometry()[2].FastGetSolutionStepValue(ANGULAR_ACCELERATION);
//rhsg2[0] += body_force[0]* Area * 0.3333333333333;//*density;
//rhsg2[1] += body_force[1]* Area * 0.3333333333333;//*density;
array_1d<double,3>& rhs2 = GetGeometry()[2].FastGetSolutionStepValue(FORCE);
rhs2[0] += GalerkinRHS[4];
rhs2[1] += GalerkinRHS[5];
GetGeometry()[2].UnSetLock();
/*GetGeometry()[0].SetLock();
array_1d<double,3>& rhs0 = GetGeometry()[0].FastGetSolutionStepValue(FORCE);
rhs0[0] += GalerkinRHS[0];
rhs0[1] += GalerkinRHS[1];
GetGeometry()[0].UnSetLock();*/
/* GetGeometry()[1].SetLock();
array_1d<double,3>& rhs1 = GetGeometry()[1].FastGetSolutionStepValue(FORCE);
rhs1[0] += GalerkinRHS[2];
rhs1[1] += GalerkinRHS[3];
GetGeometry()[1].UnSetLock();*/
/*GetGeometry()[2].SetLock();
array_1d<double,3>& rhs2 = GetGeometry()[2].FastGetSolutionStepValue(FORCE);
rhs2[0] += GalerkinRHS[4];
rhs2[1] += GalerkinRHS[5];
GetGeometry()[2].UnSetLock();*/
double nodal_contrib = 0.333333333333333333333333333 * Area;
GetGeometry()[0].SetLock();
GetGeometry()[0].FastGetSolutionStepValue(NODAL_MASS) += nodal_contrib * density;
GetGeometry()[0].FastGetSolutionStepValue(PARTICLE_MASS) += nodal_contrib ;
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
GetGeometry()[1].FastGetSolutionStepValue(NODAL_MASS) += nodal_contrib * density;
GetGeometry()[1].FastGetSolutionStepValue(PARTICLE_MASS) += nodal_contrib ;
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
GetGeometry()[2].FastGetSolutionStepValue(NODAL_MASS) += nodal_contrib * density;
GetGeometry()[2].FastGetSolutionStepValue(PARTICLE_MASS) += nodal_contrib;
GetGeometry()[2].UnSetLock();
}
else if (FractionalStepNumber == 6) //calculation of velocities
{
//KRATOS_THROW_ERROR(std::logic_error, "method not implemented", "");
///////////////////////NECESSARY LOCALS///////////////////////////////////////////
boost::numeric::ublas::bounded_matrix<double,3,3> msWorkMatrix = ZeroMatrix(3,3);
array_1d<double,6> GalerkinRHS = ZeroVector(6); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,3,2> msDN_DX = ZeroMatrix(3,2);
array_1d<double,3> msN = ZeroVector(3); //dimension = number of nodes
boost::numeric::ublas::bounded_matrix<double,6,2> msShapeFunc = ZeroMatrix(6,2);
boost::numeric::ublas::bounded_matrix<double,2,6> msConvOp = ZeroMatrix(2,6);
boost::numeric::ublas::bounded_matrix<double,6,6> msAuxMat = ZeroMatrix(6,6);
array_1d<double,6> msAuxVec = ZeroVector(6); //dimension = number of nodes
array_1d<double,2> ms_adv_vel = ZeroVector(2); //dimesion coincides with space dimension
array_1d<double,2> ms_vel_gauss = ZeroVector(2); //dimesion coincides with space dimension
///////////////////////////////////////////////////////////////////////////////////
//first we compute the force term and pressure gradient terms:
//getting data for the given geometry
double Area;
GeometryUtils::CalculateGeometryData(GetGeometry(),msDN_DX,msN,Area);
//getting the velocity on the nodes and other necessary variabless
const array_1d<double,3> vel0 = GetGeometry()[0].FastGetSolutionStepValue(VELOCITY);
double p_n0 = GetGeometry()[0].FastGetSolutionStepValue(PRESSURE);
const double nu0 = GetGeometry()[0].FastGetSolutionStepValue(VISCOSITY);
const double rho0 = GetGeometry()[0].FastGetSolutionStepValue(DENSITY);
const array_1d<double,3> vel1 = GetGeometry()[1].FastGetSolutionStepValue(VELOCITY);
double p_n1 = GetGeometry()[1].FastGetSolutionStepValue(PRESSURE);
const double nu1 = GetGeometry()[1].FastGetSolutionStepValue(VISCOSITY);
const double rho1 = GetGeometry()[1].FastGetSolutionStepValue(DENSITY);
const array_1d<double,3>& vel2 = GetGeometry()[2].FastGetSolutionStepValue(VELOCITY);
double p_n2 = GetGeometry()[2].FastGetSolutionStepValue(PRESSURE);
const double nu2 = GetGeometry()[2].FastGetSolutionStepValue(VISCOSITY);
const double rho2 = GetGeometry()[2].FastGetSolutionStepValue(DENSITY);
//====================================================================
//calculating viscosity and density
double nu = 0.333333333333333333333333*(nu0 + nu1 + nu2 );
double density = 0.3333333333333333333333*(rho0 + rho1 + rho2 );
noalias(msWorkMatrix) = Area*density*nu * prod(msDN_DX,trans(msDN_DX));
//x comp
GalerkinRHS[0]=-1.0*(msWorkMatrix(0,0)*vel0[0]+msWorkMatrix(0,1)*vel1[0]+msWorkMatrix(0,2)*vel2[0]);
//y comp
GalerkinRHS[1]=-1.0*(msWorkMatrix(0,0)*vel0[1]+msWorkMatrix(0,1)*vel1[1]+msWorkMatrix(0,2)*vel2[1]);
//x comp
GalerkinRHS[2]=-1.0*(msWorkMatrix(1,0)*vel0[0]+msWorkMatrix(1,1)*vel1[0]+msWorkMatrix(1,2)*vel2[0]);
//y comp
GalerkinRHS[3]=-1.0*(msWorkMatrix(1,0)*vel0[1]+msWorkMatrix(1,1)*vel1[1]+msWorkMatrix(1,2)*vel2[1]);
//x comp
GalerkinRHS[4]=-1.0*(msWorkMatrix(2,0)*vel0[0]+msWorkMatrix(2,1)*vel1[0]+msWorkMatrix(2,2)*vel2[0]);
//y comp
GalerkinRHS[5]=-1.0*(msWorkMatrix(2,0)*vel0[1]+msWorkMatrix(2,1)*vel1[1]+msWorkMatrix(2,2)*vel2[1]);
ms_adv_vel[0] = msN[0]*(vel0[0])+msN[1]*(vel1[0])+msN[2]*(vel2[0]);
ms_adv_vel[1] = msN[0]*(vel0[1])+msN[1]*(vel1[1])+msN[2]*(vel2[1]);
const array_1d<double,3> body_force = 0.333333333333333*(GetGeometry()[0].FastGetSolutionStepValue(BODY_FORCE)+ GetGeometry()[1].FastGetSolutionStepValue(BODY_FORCE) + GetGeometry()[2].FastGetSolutionStepValue(BODY_FORCE));
unsigned int number_of_nodes=3;
for(unsigned int i = 0; i<number_of_nodes; i++)
{
GalerkinRHS[i*2] += body_force[0]* density * Area * 0.3333333333333;
GalerkinRHS[i*2+1] += body_force[1] * density * Area * 0.3333333333333;
}
double p_avg=0.333333333333*(p_n0+p_n1+p_n2)*Area;
GalerkinRHS[0]+=msDN_DX(0,0)*p_avg;
GalerkinRHS[1]+=msDN_DX(0,1)*p_avg;
GalerkinRHS[2]+=msDN_DX(1,0)*p_avg;
GalerkinRHS[3]+=msDN_DX(1,1)*p_avg;
GalerkinRHS[4]+=msDN_DX(2,0)*p_avg;
GalerkinRHS[5]+=msDN_DX(2,1)*p_avg;
GetGeometry()[0].SetLock();
array_1d<double,3>& rhs0 = GetGeometry()[0].FastGetSolutionStepValue(FORCE);
rhs0[0] += GalerkinRHS[0];
rhs0[1] += GalerkinRHS[1];
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
array_1d<double,3>& rhs1 = GetGeometry()[1].FastGetSolutionStepValue(FORCE);
rhs1[0] += GalerkinRHS[2];
rhs1[1] += GalerkinRHS[3];
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
array_1d<double,3>& rhs2 = GetGeometry()[2].FastGetSolutionStepValue(FORCE);
rhs2[0] += GalerkinRHS[4];
rhs2[1] += GalerkinRHS[5];
GetGeometry()[2].UnSetLock();
double nodal_contrib = 0.333333333333333333333333333 * Area*density;
GetGeometry()[0].SetLock();
GetGeometry()[0].FastGetSolutionStepValue(NODAL_MASS) += nodal_contrib;
GetGeometry()[0].UnSetLock();
GetGeometry()[1].SetLock();
GetGeometry()[1].FastGetSolutionStepValue(NODAL_MASS) += nodal_contrib;
GetGeometry()[1].UnSetLock();
GetGeometry()[2].SetLock();
GetGeometry()[2].FastGetSolutionStepValue(NODAL_MASS) += nodal_contrib;
GetGeometry()[2].UnSetLock();
}
KRATOS_CATCH("");
}
//************************************************************************************
//************************************************************************************
void Fluid2DGLS::EquationIdVector(EquationIdVectorType& rResult, ProcessInfo& CurrentProcessInfo)
{
unsigned int number_of_nodes = GetGeometry().PointsNumber();
if (rResult.size() != number_of_nodes)
rResult.resize(number_of_nodes, false);
unsigned int FractionalStepNumber = CurrentProcessInfo[FRACTIONAL_STEP];
if (FractionalStepNumber == 1) //step 1
for (unsigned int i = 0; i < number_of_nodes; i++)
rResult[i] = GetGeometry()[i].GetDof(FRACT_VEL_X).EquationId();
else if (FractionalStepNumber == 2) //step 2
for (unsigned int i = 0; i < number_of_nodes; i++)
rResult[i] = GetGeometry()[i].GetDof(FRACT_VEL_Y).EquationId();
else if (FractionalStepNumber == 4) // pressure correction step
for (unsigned int i = 0; i < number_of_nodes; i++)
rResult[i] = GetGeometry()[i].GetDof(PRESSURE).EquationId();
}
//************************************************************************************
//************************************************************************************
void Fluid2DGLS::GetDofList(DofsVectorType& ElementalDofList, ProcessInfo& CurrentProcessInfo)
{
unsigned int number_of_nodes = GetGeometry().PointsNumber();
if (ElementalDofList.size() != number_of_nodes)
ElementalDofList.resize(number_of_nodes);
unsigned int FractionalStepNumber = CurrentProcessInfo[FRACTIONAL_STEP];
if (FractionalStepNumber == 1) //step 1
for (unsigned int i = 0; i < number_of_nodes; i++)
ElementalDofList[i] = GetGeometry()[i].pGetDof(FRACT_VEL_X);
else if (FractionalStepNumber == 2) //step 2
for (unsigned int i = 0; i < number_of_nodes; i++)
ElementalDofList[i] = GetGeometry()[i].pGetDof(FRACT_VEL_Y);
else if (FractionalStepNumber == 4) // pressure correction step
for (unsigned int i = 0; i < number_of_nodes; i++)
ElementalDofList[i] = GetGeometry()[i].pGetDof(PRESSURE);
}
//************************************************************************************
//************************************************************************************
double Fluid2DGLS::ComputeSmagorinskyViscosity(const boost::numeric::ublas::bounded_matrix<double, 3, 2 > & DN_DX,
const double& h,
const double& C,
const double nu
)
{
boost::numeric::ublas::bounded_matrix<double, 2, 2 > dv_dx = ZeroMatrix(2, 2);
// Compute Symmetric Grad(u). Note that only the lower half of the matrix is filled
for (unsigned int k = 0; k < 3; ++k)
{
const array_1d< double, 3 > & rNodeVel = this->GetGeometry()[k].FastGetSolutionStepValue(FRACT_VEL);
for (unsigned int i = 0; i < 2; ++i)
{
for (unsigned int j = 0; j < i; ++j) // Off-diagonal
dv_dx(i, j) += 0.5 * (DN_DX(k, j) * rNodeVel[i] + DN_DX(k, i) * rNodeVel[j]);
dv_dx(i, i) += DN_DX(k, i) * rNodeVel[i]; // Diagonal
}
}
// Norm[ Grad(u) ]
double NormS(0.0);
for (unsigned int i = 0; i < 2; ++i)
{
for (unsigned int j = 0; j < i; ++j)
NormS += 2.0 * dv_dx(i, j) * dv_dx(i, j); // Using symmetry, lower half terms of the matrix are added twice
NormS += dv_dx(i, i) * dv_dx(i, i); // Diagonal terms
}
NormS = sqrt(NormS);
// Total Viscosity
return 2.0 * C * C * h * h * NormS;
}
//************************************************************************************
int Fluid2DGLS::Check(const ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
//check the area
//check if if is in the XY plane
//check that no variable has zero key
return 0;
KRATOS_CATCH("");
}
//#undef GRADPN_FORM
} // Namespace Kratos
| 41.689015 | 236 | 0.614326 | [
"geometry",
"vector"
] |
025c413aa909d3ce23767adbe4e4461cffc4041d | 9,733 | cpp | C++ | src/sfm_iterative_functionbased.cpp | cmgladding/aslam-project | 3132374756c0179e3f09031765af556b5b4ee6b9 | [
"MIT"
] | null | null | null | src/sfm_iterative_functionbased.cpp | cmgladding/aslam-project | 3132374756c0179e3f09031765af556b5b4ee6b9 | [
"MIT"
] | null | null | null | src/sfm_iterative_functionbased.cpp | cmgladding/aslam-project | 3132374756c0179e3f09031765af556b5b4ee6b9 | [
"MIT"
] | null | null | null | //http://creativecommons.org/licenses/by-sa/4.0/
//http://hackingonspace.blogspot.com/2015/09/using-openmvg-library.html
#include <iostream>
#include "openMVG/sfm/sfm.hpp"
#include "openMVG/image/image.hpp"
#include "openMVG/stl/split.hpp"
#include "openMVG/matching_image_collection/Matcher_Regions_AllInMemory.hpp"
#include "openMVG/matching_image_collection/GeometricFilter.hpp"
#include "openMVG/matching_image_collection/F_ACRobust.hpp"
#include "openMVG/sfm/sfm.hpp"
#include <ros/console.h>
#include <cstdlib>
#include "openMVG/system/timer.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <ros/ros.h>
//#include <image_transport/image_transport.h>
//#include <cv_bridge/cv_bridge.h>
//#include <sensor_msgs/image_encodings.h>
//#include <opencv2/highgui/highgui.hpp>
//#include <opencv2/imgproc/imgproc.hpp>
//#include <sstream>
using namespace openMVG;
using namespace std;
using namespace openMVG::sfm;
using namespace openMVG::features;
using namespace openMVG::image;
using namespace openMVG::cameras;
using namespace openMVG::matching_image_collection;
using namespace stlplus;
class ImageList {
public:
ImageList();
~ImageList();
void setDirectory(const char* nm);
int countFiles();
void loadAllImages();
void loadImage(std::string s);
void generateFeatures();
void computeMatches();
void sequentialReconstruct();
private:
string _directory;
string _matches_full;
string _matches_filtered;
vector<string> _fnames;
SfM_Data _sfm_data;
unique_ptr<Regions> _regionsType;
};
ImageList::ImageList() {
}
ImageList::~ImageList() {
}
ImageList iml; //create GLOBAL imagelist structure to store data
void ImageList::setDirectory(const char* nm) {
vector<string> file_list;
_directory = nm;
_sfm_data.s_root_path = nm;
file_list = stlplus::folder_files(_directory);
sort(file_list.begin(), file_list.end());
for (vector<string>::const_iterator it = file_list.begin(); it != file_list.end(); it++) {
string which = *it;
string imnm = stlplus::create_filespec(_directory, which);
_fnames.push_back(imnm);
}
_matches_full = stlplus::create_filespec(_directory, "matches.putative.txt");
_matches_filtered = stlplus::create_filespec(_directory, "matches.f.txt");
}
int ImageList::countFiles() {
return _fnames.size();
}
void ImageList::loadAllImages() {
for ( vector<string>::const_iterator iter_image = _fnames.begin(); iter_image != _fnames.end(); iter_image++ ) {
string which = *iter_image;
loadImage(which);
}
return;
}
void ImageList::loadImage(string which) {
double width, height, image_focal;
double focal, ppx, ppy;
Views& views = _sfm_data.views;
Intrinsics& intrinsics = _sfm_data.intrinsics;
shared_ptr<IntrinsicBase> intrinsic (NULL);
if (GetFormat(which.c_str()) == openMVG::image::Unknown){
//ROS_ERROR("Format unknown");
return;
}
//Known values for multisim_sl from DRCsim .ini files
focal = 476.7030836014194; //focal length in pixels
width = 800.0; //sensor width in pixels
height = 800.0; //sensor height in pixels
ppx = width / 2.0; //image center point
ppy = height / 2.0; //image center point
printf("Image %s: %f x %f, Focal Length (pixels) %f\n", which.c_str(), width, height, focal);
View v(which, views.size(), views.size(), views.size(), width, height);
intrinsic = make_shared<Pinhole_Intrinsic_Radial_K3> (width, height, focal,
ppx, ppy, 0.0, 0.0, 0.0);
intrinsics[v.id_intrinsic] = intrinsic;
views[v.id_view] = std::make_shared<openMVG::sfm::View>(v);
}
void ImageList::generateFeatures(void) {
AKAZEParams params(AKAZEConfig(), AKAZE_MSURF);
unique_ptr<AKAZE_Image_describer> image_describer(new AKAZE_Image_describer(params, true));
image_describer->Allocate(_regionsType);
image_describer->Set_configuration_preset(NORMAL_PRESET);
for(Views::const_iterator iterViews = _sfm_data.views.begin(); iterViews != _sfm_data.views.end(); ++iterViews) {
const View * view = iterViews->second.get();
const string sFeat = stlplus::create_filespec(_directory, stlplus::basename_part(view->s_Img_path), "feat");
const string sDesc = stlplus::create_filespec(_directory, stlplus::basename_part(view->s_Img_path), "desc");
if (!stlplus::file_exists(sFeat)) {
Image<unsigned char> imageGray;
printf("Creating %s\n", sFeat.c_str());
ReadImage(view->s_Img_path.c_str(), &imageGray);
unique_ptr<Regions> regions;
image_describer->Describe(imageGray, regions);
image_describer->Save(regions.get(), sFeat, sDesc);
}
else {
printf("Using existing features from %s\n", sFeat.c_str());
}
}
}
void ImageList::computeMatches() {
float fDistRatio = 0.6f; // 0.6f dflt // Higher is stricter
openMVG::matching::PairWiseMatches map_PutativesMatches;
vector<string> vec_fileNames;
vector<pair<size_t, size_t> > vec_imagesSize;
for (Views::const_iterator iter = _sfm_data.GetViews().begin(); iter != _sfm_data.GetViews().end(); ++iter) {
const View * v = iter->second.get();
vec_fileNames.push_back(stlplus::create_filespec(_sfm_data.s_root_path, v->s_Img_path));
vec_imagesSize.push_back(make_pair( v->ui_width, v->ui_height) );
}
unique_ptr<Matcher_Regions_AllInMemory> collectionMatcher;
collectionMatcher.reset(new Matcher_Regions_AllInMemory(fDistRatio, openMVG::ANN_L2));
openMVG::Pair_Set pairs;
shared_ptr<Regions_Provider> regions_provider = make_shared<Regions_Provider>(); //added
if (!regions_provider->load(_sfm_data, _directory, _regionsType)){ //added
ROS_ERROR("Regions provider load failed");
return;
}
//no longer checking if data loads
pairs = openMVG::exhaustivePairs(_sfm_data.GetViews().size());
collectionMatcher->Match(_sfm_data,regions_provider, pairs, map_PutativesMatches); //revised
ofstream file_full(_matches_full); //changed file object name to avoid conflict
if (file_full.is_open()){
PairedIndMatchToStream(map_PutativesMatches, file_full);
}
file_full.close();
shared_ptr<Features_Provider> feats_provider = make_shared<Features_Provider>();
if (!feats_provider->load(_sfm_data, _directory, _regionsType)){
ROS_ERROR("Features provider load failed");
return;
}
openMVG::PairWiseMatches map_GeometricMatches;
std::unique_ptr<ImageCollectionGeometricFilter> filter_ptr(new ImageCollectionGeometricFilter(&_sfm_data, regions_provider));
const double maxResidualError = 1.0; // dflt 1.0; // Lower is stricter
filter_ptr->Robust_model_estimation(GeometricFilter_FMatrix_AC(maxResidualError), map_PutativesMatches); //added
map_GeometricMatches = filter_ptr->Get_geometric_matches(); //added
ofstream file_filtered(_matches_filtered); //changed file object name to avoid conflict
if (file_filtered.is_open()){
PairedIndMatchToStream(map_GeometricMatches, file_filtered);
}
file_filtered.close();
}
void ImageList::sequentialReconstruct() {
string output_directory = "/home/colin/catkin_ws/src/aslam_project/SfM_PointCloudData";
string sfm_data = stlplus::create_filespec(output_directory, "sfm_data", ".json");
string cloud_data = stlplus::create_filespec(output_directory, "cloud_and_poses", ".ply");
string report_name = stlplus::create_filespec(output_directory, "Reconstruction_Report", ".html");
if (!stlplus::folder_exists(output_directory))
stlplus::folder_create(output_directory);
SequentialSfMReconstructionEngine sfmEngine(_sfm_data, output_directory, report_name);
shared_ptr<Features_Provider> feats_provider = std::make_shared<Features_Provider>();
shared_ptr<Matches_Provider> matches_provider = std::make_shared<Matches_Provider>();
feats_provider->load(_sfm_data, _directory, _regionsType);
matches_provider->load(_sfm_data, _matches_filtered);
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
openMVG::Pair initialPairIndex;
Views::const_iterator it;
it = _sfm_data.GetViews().begin();
const View *v1 = it->second.get();
it++;
const View *v2 = it->second.get();
initialPairIndex.first = v1->id_view;
initialPairIndex.second = v2->id_view;
sfmEngine.setInitialPair(initialPairIndex);
sfmEngine.Set_bFixedIntrinsics(false);
sfmEngine.SetUnknownCameraType(EINTRINSIC(PINHOLE_CAMERA_RADIAL3));
sfmEngine.Process();
Save(sfmEngine.Get_SfM_Data(), sfm_data, ESfM_Data(openMVG::sfm::ALL));
Save(sfmEngine.Get_SfM_Data(), cloud_data, ESfM_Data(openMVG::sfm::ALL));
}
int LoadImageListing(string imagedir) {
iml->setDirectory(imagedir);
if (iml->countFiles() > 0) {
iml->loadAllImages();
}
return 0;
}
void sfmCB(const sensor_msgs::ImageConstPtr& msg)
{
//Add thread protection here?
string filepath;
filepath = "/home/colin/Documents/FilteredPhotoDump/"; //directory to check for images
//check if this should be in the initial pair - if so, set initialPairString
LoadImageListing(filepath);
/*move these functions into callback
setDirectory
loadAllImages
iml.generateFeatures();
iml.computeMatches();
iml.sequentialReconstruct();
*/
//End thread protection here?
}
int main(int argc, char* argv[])
{
//ImageList iml; //imagelist moved to global scope so callbacks can access member methods
/*move these functions into callback
LoadImageListing(&iml, argv[1]);
iml.generateFeatures();
iml.computeMatches();
iml.sequentialReconstruct();
*/
ros::init(argc, argv, "sfm_iterative");
ros::NodeHandle n;
ros::Subscriber sfm_sub = n.subscribe("/multisense_sl/left/image_raw", 1000, sfmCB);
ros::spin();
}
| 31.600649 | 125 | 0.737902 | [
"object",
"vector"
] |
025fc3c814eb054958db35c3779f14ca16210a60 | 489 | cpp | C++ | coding/bubble_sortWithVec/bubble_sortWithVec.cpp | manharjotkaur/ese2025-1 | 81c9a606d6ce1b067dfab4da910dbdfdb8de1572 | [
"MIT"
] | null | null | null | coding/bubble_sortWithVec/bubble_sortWithVec.cpp | manharjotkaur/ese2025-1 | 81c9a606d6ce1b067dfab4da910dbdfdb8de1572 | [
"MIT"
] | null | null | null | coding/bubble_sortWithVec/bubble_sortWithVec.cpp | manharjotkaur/ese2025-1 | 81c9a606d6ce1b067dfab4da910dbdfdb8de1572 | [
"MIT"
] | 2 | 2019-07-29T03:33:21.000Z | 2019-10-26T03:42:26.000Z | * bubble_sortWithVec.cpp
*
* Created on: Jul. 16, 2019
* Author: jass
*/
#include<iostream>
#include<vector>
#include<iterator>
#include<string>
#include<algorithm>
using namespace std;
vector<int>::iterator iter;
void print(vector<int> my_vec)
{
cout<<"The vector is = ";
for(iter=my_vec.begin();iter != my_vec.end();iter++)
{
cout<<" "<<*iter;
}
}
int main()
{
vector<int> my_vec ={1,3,5,2,6,8,9};
sort (my_vec.begin(),my_vec.end());
print(my_vec);
return 0;
}
| 12.868421 | 53 | 0.638037 | [
"vector"
] |
02615d55a6071d84f878c0eb1c5939f2ea0a8bf9 | 15,797 | cpp | C++ | test/test_class.cpp | YarikTH/v8pp | d62a0d581fd4ab05beb8a675216a12c72a5077c8 | [
"BSL-1.0"
] | null | null | null | test/test_class.cpp | YarikTH/v8pp | d62a0d581fd4ab05beb8a675216a12c72a5077c8 | [
"BSL-1.0"
] | null | null | null | test/test_class.cpp | YarikTH/v8pp | d62a0d581fd4ab05beb8a675216a12c72a5077c8 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2013-2016 Pavel Medvedev. All rights reserved.
//
// This file is part of v8pp (https://github.com/pmed/v8pp) project.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "v8pp/class.hpp"
#include "v8pp/json.hpp"
#include "v8pp/module.hpp"
#include "v8pp/object.hpp"
#include "v8pp/property.hpp"
#include "test.hpp"
#include <type_traits>
struct Xbase
{
int var = 1;
int get() const { return var; }
void set(int v) { var = v; }
int prop() const { return var; }
void prop(int v) { var = v; }
int fun1(int x) { return var + x; }
float fun2(float x) const { return var + x; }
std::string fun3(std::string const& x) volatile
{
return x + std::to_string(var);
}
std::vector<std::string> fun4(std::vector<std::string> x) const volatile
{
x.push_back(std::to_string(var));
return x;
}
static int static_fun(int x) { return x; }
v8::Local<v8::Value> to_json(v8::Isolate* isolate, v8::Local<v8::Value> key) const
{
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::Object> result = v8::Object::New(isolate);
v8pp::set_const(isolate, result, "key", key);
v8pp::set_const(isolate, result, "var", var);
return scope.Escape(result);
}
};
struct X : Xbase
{
};
template<typename Traits, typename X_ptr = typename v8pp::class_<X, Traits>::object_pointer_type>
static X_ptr create_X(v8::FunctionCallbackInfo<v8::Value> const& args)
{
X_ptr x(new X);
switch (args.Length())
{
case 1:
x->var = v8pp::from_v8<int>(args.GetIsolate(), args[0]);
break;
case 2:
throw std::runtime_error("C++ exception");
case 3:
v8pp::throw_ex(args.GetIsolate(), "JS exception");
}
return x;
}
struct Y : X
{
static int instance_count;
explicit Y(int x) { var = x; ++instance_count; }
~Y() { --instance_count; }
int useX(X& x) { return var + x.var; }
template<typename Traits, typename X_ptr = typename v8pp::class_<X, Traits>::object_pointer_type>
int useX_ptr(X_ptr x) { return var + x->var; }
};
int Y::instance_count = 0;
struct Z {};
namespace v8pp {
template<>
struct factory<Y, v8pp::raw_ptr_traits>
{
static Y* create(v8::Isolate*, int x) { return new Y(x); }
static void destroy(v8::Isolate*, Y* object) { delete object; }
};
template<>
struct factory<Y, v8pp::shared_ptr_traits>
{
static std::shared_ptr<Y> create(v8::Isolate*, int x)
{
return std::make_shared<Y>(x);
}
static void destroy(v8::Isolate*, std::shared_ptr<Y> const&) {}
};
} // v8pp
template<typename Traits>
static int extern_fun(v8::FunctionCallbackInfo<v8::Value> const& args)
{
int x = args[0]->Int32Value(args.GetIsolate()->GetCurrentContext()).FromJust();
auto self = v8pp::class_<X, Traits>::unwrap_object(args.GetIsolate(), args.This());
if (self) x += self->var;
return x;
}
template<typename Traits>
void test_class_()
{
Y::instance_count = 0;
v8pp::context context;
v8::Isolate* isolate = context.isolate();
v8::HandleScope scope(isolate);
using x_prop_get = int (X::*)() const;
using x_prop_set = void (X::*)(int);
int extra_ctor_context = 1;
auto const X_ctor = [extra_ctor_context](v8::FunctionCallbackInfo<v8::Value> const& args)
{
(void)extra_ctor_context;
return create_X<Traits>(args);
};
Z extra_dtor_context;
auto const X_dtor = [extra_dtor_context](v8::Isolate*, typename Traits::template object_pointer_type<X> const& obj)
{
(void)extra_dtor_context;
Traits::destroy(obj);
};
v8pp::class_<X, Traits> X_class(isolate, X_dtor);
X_class
.ctor(&create_X<Traits>)
.template ctor<v8::FunctionCallbackInfo<v8::Value> const&>(X_ctor)
.set_const("konst", 99)
.set("var", &X::var)
.set("rprop", v8pp::property(&X::get))
.set("wprop", v8pp::property(&X::get, &X::set))
.set("wprop2", v8pp::property(
static_cast<x_prop_get>(&X::prop),
static_cast<x_prop_set>(&X::prop)))
.set("fun1", &X::fun1)
.set("fun2", &X::fun2)
.set("fun3", &X::fun3)
.set("fun4", &X::fun4)
.set("static_fun", &X::static_fun)
.set("static_lambda", [](int x) { return x + 3; })
.set("extern_fun", extern_fun<Traits>)
.set("toJSON", &X::to_json)
.set_static("my_static_const_var", 42, true)
.set_static("my_static_var", 1)
;
static_assert(std::is_move_constructible<decltype(X_class)>::value, "");
static_assert(!std::is_move_assignable<decltype(X_class)>::value, "");
static_assert(!std::is_copy_assignable<decltype(X_class)>::value, "");
static_assert(!std::is_copy_constructible<decltype(X_class)>::value, "");
v8pp::class_<Y, Traits> Y_class(isolate);
Y_class
.template inherit<X>()
.template ctor<int>()
.set("useX", &Y::useX)
.set("useX_ptr", &Y::useX_ptr<Traits>)
;
auto Y_class_find = v8pp::class_<Y, Traits>::extend(isolate);
Y_class_find.set("toJSON", [](const v8::FunctionCallbackInfo<v8::Value>& args)
{
bool const with_functions = true;
args.GetReturnValue().Set(v8pp::json_object(args.GetIsolate(), args.This(), with_functions));
});
check_ex<std::runtime_error>("already wrapped class X", [isolate]()
{
v8pp::class_<X, Traits> X_class(isolate);
});
check_ex<std::runtime_error>("already inherited class X", [&Y_class]()
{
Y_class.template inherit<X>();
});
check_ex<std::runtime_error>("unwrapped class Z", [isolate]()
{
v8pp::class_<Z, Traits>::find_object(isolate, nullptr);
});
context
.set("X", X_class)
.set("Y", Y_class)
;
check_eq("C++ exception from X ctor",
run_script<std::string>(context, "ret = ''; try { new X(1, 2); } catch(err) { ret = err; } ret"),
"C++ exception");
check_eq("V8 exception from X ctor",
run_script<std::string>(context, "ret = ''; try { new X(1, 2, 3); } catch(err) { ret = err; } ret"),
"JS exception");
check_eq("X object", run_script<int>(context, "x = new X(); x.var += x.konst"), 100);
check_eq("X::rprop", run_script<int>(context, "x = new X(); x.rprop"), 1);
check_eq("X::wprop", run_script<int>(context, "x = new X(); ++x.wprop"), 2);
check_eq("X::wprop2", run_script<int>(context, "x = new X(); ++x.wprop2"), 2);
check_eq("X::fun1(1)", run_script<int>(context, "x = new X(); x.fun1(1)"), 2);
check_eq("X::fun2(2)", run_script<float>(context, "x = new X(); x.fun2(2)"), 3);
check_eq("X::fun3(str)", run_script<std::string>(context, "x = new X(); x.fun3('str')"), "str1");
check_eq("X::fun4([foo, bar])",
run_script<std::vector<std::string>>(context, "x = new X(); x.fun4(['foo', 'bar'])"),
std::vector<std::string>{ "foo", "bar", "1" });
check_eq("X::static_fun(1)", run_script<int>(context, "X.static_fun(1)"), 1);
check_eq("X::static_lambda(1)", run_script<int>(context, "X.static_lambda(1)"), 4);
check_eq("X::extern_fun(5)", run_script<int>(context, "x = new X(); x.extern_fun(5)"), 6);
check_eq("X::extern_fun(6)", run_script<int>(context, "X.extern_fun(6)"), 6);
check_eq("X::my_static_const_var", run_script<int>(context, "X.my_static_const_var"), 42);
check_eq("X::my_static_const_var after assign", run_script<int>(context, "X.my_static_const_var = 123; X.my_static_const_var"), 42);
check_eq("X::my_static_var", run_script<int>(context, "X.my_static_var"), 1);
check_eq("X::my_static_var after assign", run_script<int>(context, "X.my_static_var = 123; X.my_static_var"), 123);
check_ex<std::runtime_error>("call method with invalid instance", [&context]()
{
run_script<int>(context, "x = new X(); f = x.fun1; f(1)");
});
check_eq("JSON.stringify(X)",
run_script<std::string>(context, "JSON.stringify({'obj': new X(10), 'arr': [new X(11), new X(12)] })"),
R"({"obj":{"key":"obj","var":10},"arr":[{"key":"0","var":11},{"key":"1","var":12}]})"
);
check_eq("JSON.stringify(Y)",
run_script<std::string>(context, "JSON.stringify({'obj': new Y(10), 'arr': [new Y(11), new Y(12)] })"),
R"({"obj":{"useX":"function useX() { [native code] }","useX_ptr":"function useX_ptr() { [native code] }","toJSON":"function toJSON() { [native code] }","wprop2":10,"wprop":10,"rprop":10,"var":10,"konst":99,"fun1":"function fun1() { [native code] }","fun2":"function fun2() { [native code] }","fun3":"function fun3() { [native code] }","fun4":"function fun4() { [native code] }","static_fun":"function static_fun() { [native code] }","static_lambda":"function static_lambda() { [native code] }","extern_fun":"function extern_fun() { [native code] }"},"arr":[{"useX":"function useX() { [native code] }","useX_ptr":"function useX_ptr() { [native code] }","toJSON":"function toJSON() { [native code] }","wprop2":11,"wprop":11,"rprop":11,"var":11,"konst":99,"fun1":"function fun1() { [native code] }","fun2":"function fun2() { [native code] }","fun3":"function fun3() { [native code] }","fun4":"function fun4() { [native code] }","static_fun":"function static_fun() { [native code] }","static_lambda":"function static_lambda() { [native code] }","extern_fun":"function extern_fun() { [native code] }"},{"useX":"function useX() { [native code] }","useX_ptr":"function useX_ptr() { [native code] }","toJSON":"function toJSON() { [native code] }","wprop2":12,"wprop":12,"rprop":12,"var":12,"konst":99,"fun1":"function fun1() { [native code] }","fun2":"function fun2() { [native code] }","fun3":"function fun3() { [native code] }","fun4":"function fun4() { [native code] }","static_fun":"function static_fun() { [native code] }","static_lambda":"function static_lambda() { [native code] }","extern_fun":"function extern_fun() { [native code] }"}]})"
);
check_eq("Y object", run_script<int>(context, "y = new Y(-100); y.konst + y.var"), -1);
auto y1 = v8pp::factory<Y, Traits>::create(isolate, -1);
v8::Local<v8::Object> y1_obj =
v8pp::class_<Y, Traits>::reference_external(context.isolate(), y1);
check("y1", v8pp::from_v8<decltype(y1)>(isolate, y1_obj) == y1);
check("y1_obj", v8pp::to_v8(isolate, y1) == y1_obj);
auto y2 = v8pp::factory<Y, Traits>::create(isolate, -2);
v8::Local<v8::Object> y2_obj =
v8pp::class_<Y, Traits>::import_external(context.isolate(), y2);
check("y2", v8pp::from_v8<decltype(y2)>(isolate, y2_obj) == y2);
check("y2_obj", v8pp::to_v8(isolate, y2) == y2_obj);
v8::Local<v8::Object> y3_obj =
v8pp::class_<Y, Traits>::create_object(context.isolate(), -3);
auto y3 = v8pp::class_<Y, Traits>::unwrap_object(isolate, y3_obj);
check("y3", v8pp::from_v8<decltype(y3)>(isolate, y3_obj) == y3);
check("y3_obj", v8pp::to_v8(isolate, y3) == y3_obj);
check_eq("y3.var", y3->var, -3);
run_script<int>(context, "x = new X; for (i = 0; i < 10; ++i) { y = new Y(i); y.useX(x); y.useX_ptr(x); }");
check_eq("Y count", Y::instance_count, 13 + 4); // 13 + y + y1 + y2 + y3
run_script<int>(context, "y = null; 0");
v8pp::class_<Y, Traits>::unreference_external(isolate, y1);
check("unref y1", !v8pp::from_v8<decltype(y1)>(isolate, y1_obj));
check("unref y1_obj", v8pp::to_v8(isolate, y1).IsEmpty());
y1_obj.Clear();
check_ex<std::runtime_error>("y1 unreferenced", [isolate, &y1]()
{
v8pp::to_v8(isolate, y1);
});
v8pp::class_<Y, Traits>::destroy_object(isolate, y2);
check("unref y2", !v8pp::from_v8<decltype(y2)>(isolate, y2_obj));
check("unref y2_obj", v8pp::to_v8(isolate, y2).IsEmpty());
y2_obj.Clear();
v8pp::class_<Y, Traits>::destroy_object(isolate, y3);
check("unref y3", !v8pp::from_v8<decltype(y3)>(isolate, y3_obj));
check("unref y3_obj", v8pp::to_v8(isolate, y3).IsEmpty());
y3_obj.Clear();
std::string const v8_flags = "--expose_gc";
v8::V8::SetFlagsFromString(v8_flags.data(), (int)v8_flags.length());
context.isolate()->RequestGarbageCollectionForTesting(
v8::Isolate::GarbageCollectionType::kFullGarbageCollection);
bool const use_shared_ptr = std::is_same<Traits, v8pp::shared_ptr_traits>::value;
check_eq("Y count after GC", Y::instance_count,
1 + 2 * use_shared_ptr); // y1 + (y2 + y3 when use_shared_ptr)
y1_obj = v8pp::class_<Y, Traits>::reference_external(context.isolate(), y1);
check_eq("Y count before class_<Y>::destroy", Y::instance_count,
1 + 2 * use_shared_ptr); // y1 + (y2 + y3 when use_shared_ptr)
v8pp::class_<Y, Traits>::destroy(isolate);
check_eq("Y count after class_<Y>::destroy", Y::instance_count,
1 + 2 * use_shared_ptr); // y1 + (y2 + y3 when use_shared_ptr)
}
template<typename Traits>
void test_multiple_inheritance()
{
struct A
{
int x;
A() : x(1) {}
int f() { return x; }
void set_f(int v) { x = v; }
int z() const { return x; }
};
struct B
{
int x;
B() : x(2) {}
int g() { return x; }
void set_g(int v) { x = v; }
int z() const { return x; }
};
struct C : A, B
{
int x;
C() : x(3) {}
int h() { return x; }
void set_h(int v) { x = v; }
int z() const { return x; }
};
v8pp::context context;
v8::Isolate* isolate = context.isolate();
v8::HandleScope scope(isolate);
v8pp::class_<B, Traits> B_class(isolate);
B_class
.set("xB", &B::x)
.set("zB", &B::z)
.set("g", &B::g);
v8pp::class_<C, Traits> C_class(isolate);
C_class
.template inherit<B>()
.template ctor<>()
.set("xA", &A::x)
.set("xC", &C::x)
.set("zA", &A::z)
.set("zC", &C::z)
.set("f", &A::f)
.set("h", &C::h)
.set("rF", v8pp::property(&C::f))
.set("rG", v8pp::property(&C::g))
.set("rH", v8pp::property(&C::h))
.set("F", v8pp::property(&C::f, &C::set_f))
.set("G", v8pp::property(&C::g, &C::set_g))
.set("H", v8pp::property(&C::h, &C::set_h))
;
context.set("C", C_class);
check_eq("get attributes", run_script<int>(context, "c = new C(); c.xA + c.xB + c.xC"), 1 + 2 + 3);
check_eq("set attributes", run_script<int>(context,
"c = new C(); c.xA = 10; c.xB = 20; c.xC = 30; c.xA + c.xB + c.xC"), 10 + 20 + 30);
check_eq("functions", run_script<int>(context, "c = new C(); c.f() + c.g() + c.h()"), 1 + 2 + 3);
check_eq("z functions", run_script<int>(context, "c = new C(); c.zA() + c.zB() + c.zC()"), 1 + 2 + 3);
check_eq("rproperties", run_script<int>(context,
"c = new C(); c.rF + c.rG + c.rH"), 1 + 2 + 3);
check_eq("rwproperties", run_script<int>(context,
"c = new C(); c.F = 100; c.G = 200; c.H = 300; c.F + c.G + c.H"), 100 + 200 + 300);
}
template<typename Traits>
void test_const_instance_in_module()
{
struct X
{
int f(int x) { return x; }
static typename Traits::template object_pointer_type<X> xconst()
{
static auto const xconst_ = v8pp::factory<X, Traits>::create(v8::Isolate::GetCurrent());
return xconst_;
}
};
v8pp::context context;
v8::Isolate* isolate = context.isolate();
v8::HandleScope scope(isolate);
v8pp::class_<X, Traits> X_class(isolate);
X_class.set("f", &X::f);
v8pp::module api(isolate);
api.set("X", X_class);
api.set("xconst", v8pp::property(X::xconst));
X_class.reference_external(isolate, X::xconst());
context.set("api", api);
check_eq("xconst.f()", run_script<int>(context, "api.xconst.f(1)"), 1);
}
template<typename Traits>
void test_auto_wrap_objects()
{
struct X
{
int x;
explicit X(int x) : x(x) {}
int get_x() const { return x; }
};
v8pp::context context;
v8::Isolate* isolate = context.isolate();
v8::HandleScope scope(isolate);
v8pp::class_<X, Traits> X_class(isolate);
X_class
.template ctor<int>()
.auto_wrap_objects(true)
.set("x", v8pp::property(&X::get_x));
auto f0 = [](int x) { return X(x); };
auto f = v8pp::wrap_function<decltype(f0), Traits>(isolate, "f", std::move(f0));
context.set("X", X_class);
context.set("f", f);
check_eq("return X object", run_script<int>(context, "obj = f(123); obj.x"), 123);
}
void test_class()
{
test_class_<v8pp::raw_ptr_traits>();
test_class_<v8pp::shared_ptr_traits>();
test_multiple_inheritance<v8pp::raw_ptr_traits>();
test_multiple_inheritance<v8pp::shared_ptr_traits>();
test_const_instance_in_module<v8pp::raw_ptr_traits>();
test_const_instance_in_module<v8pp::shared_ptr_traits>();
test_auto_wrap_objects<v8pp::raw_ptr_traits>();
test_auto_wrap_objects<v8pp::shared_ptr_traits>();
}
| 34.192641 | 1,642 | 0.649047 | [
"object",
"vector"
] |
02623bd6957c76a634ee0fae559f3fe87cd7ce2d | 1,056 | cpp | C++ | Engine/src/Engine/Renderer/Renderer.cpp | PalliativeX/GameEngine | 704cf5f3ebc81fdf5e3e514908c3ac47305ccd33 | [
"Apache-2.0"
] | null | null | null | Engine/src/Engine/Renderer/Renderer.cpp | PalliativeX/GameEngine | 704cf5f3ebc81fdf5e3e514908c3ac47305ccd33 | [
"Apache-2.0"
] | null | null | null | Engine/src/Engine/Renderer/Renderer.cpp | PalliativeX/GameEngine | 704cf5f3ebc81fdf5e3e514908c3ac47305ccd33 | [
"Apache-2.0"
] | null | null | null | #include "enginepch.h"
#include "Engine/Renderer/Renderer.h"
#include "Platform/OpenGL/OpenGLShader.h"
#include "Renderer2D.h"
namespace Engine
{
Renderer::SceneData* Renderer::sceneData = new Renderer::SceneData;
void Renderer::init()
{
ENGINE_PROFILE_FUNCTION();
RenderCommand::init();
Renderer2D::init();
}
void Renderer::onWindowResize(uint32_t width, uint32_t height)
{
RenderCommand::setViewport(0, 0, width, height);
}
void Renderer::beginScene(OrthographicCamera& camera)
{
sceneData->viewProjectionMatrix = camera.getViewProjectionMatrix();
}
void Renderer::endScene()
{
}
void Renderer::submit(const std::shared_ptr<Shader>& shader, const std::shared_ptr<VertexArray>& vertexArray, const glm::mat4 transform)
{
shader->bind();
std::dynamic_pointer_cast<OpenGLShader>(shader)->uploadUniformMat4("viewProjection", sceneData->viewProjectionMatrix);
std::dynamic_pointer_cast<OpenGLShader>(shader)->uploadUniformMat4("model", transform);
vertexArray->bind();
RenderCommand::drawIndexed(vertexArray);
}
} | 24 | 137 | 0.751894 | [
"model",
"transform"
] |
0263d634edb65ead2f3d64b868a6b5794027a919 | 6,881 | cpp | C++ | zebROS_ws/src/frc_state_controllers/src/button_box_state_controller.cpp | FRC900/2020Offseason | 36ccd74667d379b07d9b7a1e937307c6d8119229 | [
"BSD-3-Clause"
] | 2 | 2021-09-23T22:34:11.000Z | 2022-01-13T00:20:12.000Z | zebROS_ws/src/frc_state_controllers/src/button_box_state_controller.cpp | FRC900/2020Offseason | 36ccd74667d379b07d9b7a1e937307c6d8119229 | [
"BSD-3-Clause"
] | 19 | 2021-03-20T01:10:04.000Z | 2022-01-17T22:51:05.000Z | zebROS_ws/src/frc_state_controllers/src/button_box_state_controller.cpp | FRC900/2020Offseason | 36ccd74667d379b07d9b7a1e937307c6d8119229 | [
"BSD-3-Clause"
] | null | null | null | #include "frc_state_controllers/button_box_state_controller.h"
namespace button_box_state_controller
{
bool ButtonBoxStateController::init(hardware_interface::JoystickStateInterface *hw,
ros::NodeHandle &root_nh,
ros::NodeHandle &controller_nh)
{
ROS_INFO_STREAM_NAMED("button_box_state_controller", "init is running");
std::string name;
if (!controller_nh.getParam("name", name))
{
ROS_ERROR("Could not read button box name parameter in ButtonBox State Controller");
return false;
}
std::vector<std::string> button_box_names = hw->getNames();
const auto it = std::find(button_box_names.begin(), button_box_names.end(), name);
if (it == button_box_names.cend())
{
ROS_ERROR_STREAM("Could not find requested name " << name << " in button box interface list");
return false;
}
button_box_state_ = hw->getHandle(*it);
const auto id = button_box_state_->getId();
std::stringstream pub_name;
// TODO : maybe use pub_names instead, or joy id unconditionally?
pub_name << "js" << id;
realtime_pub_.reset(new realtime_tools::RealtimePublisher<frc_msgs::ButtonBoxState>(root_nh, pub_name.str(), 1));
if (!controller_nh.getParam("publish_rate", publish_rate_))
ROS_WARN_STREAM("Could not read publish_rate in ButtonBox state controller, using default " << publish_rate_);
return true;
}
void ButtonBoxStateController::starting(const ros::Time &time)
{
last_publish_time_ = time;
}
void ButtonBoxStateController::update(const ros::Time &time, const ros::Duration & )
{
if ((publish_rate_ > 0.0) && (last_publish_time_ + ros::Duration(1.0 / publish_rate_) < time))
{
if (realtime_pub_->trylock())
{
last_publish_time_ = last_publish_time_ + ros::Duration(1.0 / publish_rate_);
const auto &bbs = button_box_state_;
auto &m = realtime_pub_->msg_;
m.header.stamp = time;
m.lockingSwitchButton = bbs->getButton(1);
m.topRedButton = bbs->getButton(2);
m.leftRedButton = bbs->getButton(3);
m.rightRedButton = bbs->getButton(4);
m.leftSwitchUpButton = bbs->getButton(5);
m.leftSwitchDownButton = bbs->getButton(6);
m.rightSwitchUpButton = bbs->getButton(7);
m.rightSwitchDownButton = bbs->getButton(8);
m.leftBlueButton = bbs->getButton(9);
m.rightBlueButton = bbs->getButton(10);
m.yellowButton = bbs->getButton(11);
m.leftGreenButton = bbs->getButton(12);
m.rightGreenButton = bbs->getButton(13);
m.topGreenButton = bbs->getButton(14);
m.bottomGreenButton = bbs->getButton(15);
m.bottomSwitchUpButton = bbs->getButton(16);
m.bottomSwitchDownButton = bbs->getButton(17);
// Creating press booleans by comparing the last publish to the current one
m.lockingSwitchPress = !prev_button_box_msg_.lockingSwitchButton && m.lockingSwitchButton;
m.topRedPress = !prev_button_box_msg_.topRedButton && m.topRedButton;
m.leftRedPress = !prev_button_box_msg_.leftRedButton && m.leftRedButton;
m.rightRedPress = !prev_button_box_msg_.rightRedButton && m.rightRedButton;
m.leftSwitchUpPress = !prev_button_box_msg_.leftSwitchUpButton && m.leftSwitchUpButton;
m.leftSwitchDownPress = !prev_button_box_msg_.leftSwitchDownButton && m.leftSwitchDownButton;
m.rightSwitchUpPress = !prev_button_box_msg_.rightSwitchUpButton && m.rightSwitchUpButton;
m.rightSwitchDownPress = !prev_button_box_msg_.rightSwitchDownButton && m.rightSwitchDownButton;
m.leftBluePress = !prev_button_box_msg_.leftBlueButton && m.leftBlueButton;
m.rightBluePress = !prev_button_box_msg_.rightBlueButton && m.rightBlueButton;
m.yellowPress = !prev_button_box_msg_.yellowButton && m.yellowButton;
m.leftGreenPress = !prev_button_box_msg_.leftGreenButton && m.leftGreenButton;
m.rightGreenPress = !prev_button_box_msg_.rightGreenButton && m.rightGreenButton;
m.topGreenPress = !prev_button_box_msg_.topGreenButton && m.topGreenButton;
m.bottomGreenPress = !prev_button_box_msg_.bottomGreenButton && m.bottomGreenButton;
m.bottomSwitchUpPress = !prev_button_box_msg_.bottomSwitchUpButton && m.bottomSwitchUpButton;
m.bottomSwitchDownPress = !prev_button_box_msg_.bottomSwitchDownButton && m.bottomSwitchDownButton;
// Creating release booleans by comparing the last publish to the current one
m.lockingSwitchRelease = prev_button_box_msg_.lockingSwitchButton && !m.lockingSwitchButton;
m.topRedRelease = prev_button_box_msg_.topRedButton && !m.topRedButton;
m.leftRedRelease = prev_button_box_msg_.leftRedButton && !m.leftRedButton;
m.rightRedRelease = prev_button_box_msg_.rightRedButton && !m.rightRedButton;
m.leftSwitchUpRelease = prev_button_box_msg_.leftSwitchUpButton && !m.leftSwitchUpButton;
m.leftSwitchDownRelease = prev_button_box_msg_.leftSwitchDownButton && !m.leftSwitchDownButton;
m.rightSwitchUpRelease = prev_button_box_msg_.rightSwitchUpButton && !m.rightSwitchUpButton;
m.rightSwitchDownRelease = prev_button_box_msg_.rightSwitchDownButton && !m.rightSwitchDownButton;
m.leftBlueRelease = prev_button_box_msg_.leftBlueButton && !m.leftBlueButton;
m.rightBlueRelease = prev_button_box_msg_.rightBlueButton && !m.rightBlueButton;
m.yellowRelease = prev_button_box_msg_.yellowButton && !m.yellowButton;
m.leftGreenRelease = prev_button_box_msg_.leftGreenButton && !m.leftGreenButton;
m.rightGreenRelease = prev_button_box_msg_.rightGreenButton && !m.rightGreenButton;
m.topGreenRelease = prev_button_box_msg_.topGreenButton && !m.topGreenButton;
m.bottomGreenRelease = prev_button_box_msg_.bottomGreenButton && !m.bottomGreenButton;
m.bottomSwitchUpRelease = prev_button_box_msg_.bottomSwitchUpButton && !m.bottomSwitchUpButton;
m.bottomSwitchDownRelease = prev_button_box_msg_.bottomSwitchDownButton && !m.bottomSwitchDownButton;
realtime_pub_->unlockAndPublish();
prev_button_box_msg_ = m;
}
}
}
void ButtonBoxStateController::stopping(const ros::Time & )
{}
} // namespace
PLUGINLIB_EXPORT_CLASS(button_box_state_controller::ButtonBoxStateController, controller_interface::ControllerBase)
| 55.491935 | 119 | 0.675919 | [
"vector"
] |
02691e1c41b0e12d3f9d9871bb51c8a6d5a0f009 | 20,524 | hxx | C++ | src/CXX/libnn/topo/nn.hxx | vencik/libnn | 2385acc2e2601552627785cfd0fe8e09ae73fea2 | [
"BSD-3-Clause"
] | null | null | null | src/CXX/libnn/topo/nn.hxx | vencik/libnn | 2385acc2e2601552627785cfd0fe8e09ae73fea2 | [
"BSD-3-Clause"
] | null | null | null | src/CXX/libnn/topo/nn.hxx | vencik/libnn | 2385acc2e2601552627785cfd0fe8e09ae73fea2 | [
"BSD-3-Clause"
] | null | null | null | #ifndef libnn__topo__nn_hxx
#define libnn__topo__nn_hxx
/**
* Neural network topology
*
* \date 2015/09/04
* \author Vaclav Krpec <vencik@razdva.cz>
*
*
* LEGAL NOTICE
*
* Copyright (c) 2015, Vaclav Krpec
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "libnn/misc/fixable.hxx"
#include <list>
#include <vector>
#include <memory>
#include <algorithm>
#include <stdexcept>
namespace libnn {
namespace topo {
/**
* \brief Neural network
*
* \tparam Base_t Base numeric type
* \tparam Act_fn Activation function
*/
template <typename Base_t, class Act_fn>
class nn {
public:
/**
* \brief Neuron
*
* Neural cell model.
*/
class neuron {
public:
/** Neuron type */
enum type_t {
INNER = 0, /**< Inner neuron */
INPUT, /**< Input layer neuron */
OUTPUT, /**< Output layer neuron */
}; // end of enum type_t
/**
* \brief Dendrite
*
* Neuron's input connection (aka synapsis) to another neuron.
*/
struct dendrite {
Base_t weight; /**< Weight */
neuron & source; /**< Source neuron */
/**
* \brief Constructor (default weight)
*
* \param src Input neuron
*/
dendrite(neuron & src): source(src) {}
/**
* \brief Constructor
*
* \param src Input neuron
* \param w Weight of the synapse
*/
dendrite(neuron & src, const Base_t & w):
weight(w),
source(src)
{}
}; // end of struct dendrite
typedef std::list<dendrite> dendrites_t; /**< List of dendrites */
private:
size_t m_index; /**< Index */
type_t m_type; /**< Neuron type */
Act_fn m_act_fn; /**< Activation function */
dendrites_t m_dendrites; /**< Dendrites */
/** Index setter */
size_t index(size_t new_index) {
return m_index = new_index;
}
/** Type setter */
type_t type(type_t new_type) {
return m_type = new_type;
}
/**
* \brief Add another dendrite
*
* Note that the function DOES NOT CHECK for prior existence
* of other dendrites to the neuron.
*
* \param n Source neuron
* \param w Synapsis weight
*
* \return New dendrite
*/
dendrite & add_dendrite(neuron & n, Base_t w = Base_t()) {
m_dendrites.emplace_back(n, w);
return m_dendrites.back();
}
/**
* \brief Remove dendrite
*
* \param d_iter Dendrite iterator
*
* \return Iterator to next dendrite (or end iterator)
*/
typename dendrites_t::iterator
remove_dendrite(typename dendrites_t::iterator d_iter) {
return m_dendrites.erase(d_iter);
}
/**
* \brief Get dendrite iterator
*
* \param n Source neuron
*
* \return Dendrite to \c n or \c m_dendrites.end() if it doesn't exist
*/
typename dendrites_t::iterator get_dendrite_iter(const neuron & n) {
auto d_iter = m_dendrites.begin();
while (d_iter != m_dendrites.end() && &(d_iter->source) != &n)
++d_iter;
return d_iter;
}
public:
/**
* \brief Constructor
*
* \tparam Args Types of activation functor constructor arguments
* \param index Neuron index
* \param type Neuron type
* \param args Activation functor constructor arguments
*/
template <typename... Args>
neuron(size_t index,
type_t type = INNER,
Args... args)
:
m_index(index),
m_type(type),
m_act_fn(args...)
{}
/** Index getter */
size_t index() const { return m_index; }
/** Type getter */
type_t type() const { return m_type; }
/** Activation functor getter (const) */
const Act_fn & act_fn() const { return m_act_fn; }
/** Activation functor getter */
Act_fn & act_fn() { return m_act_fn; }
/** Activation function evalueation */
Base_t act_fn(const Base_t & arg) const { return m_act_fn(arg); }
/** Dendrite count getter */
size_t dendrite_cnt() const { return m_dendrites.size(); }
/**
* \brief Get dendrite (i.e. synapsis to another neuron)
*
* \param n Source neuron
*
* \return Dendrite to \c n or \c NULL if it doesn't exist
*/
dendrite * get_dendrite(const neuron & n) {
auto d_iter = get_dendrite_iter(n);
return m_dendrites.end() == d_iter ? NULL : &*d_iter;
}
/**
* \brief Set dendrite (i.e. synapsis to another neuron)
*
* If no such dendrite already exists, it is added.
*
* \param n Source neuron
* \param w Synapsis weight
*
* \return Dendrite to \c n
*/
dendrite & set_dendrite(neuron & n, Base_t w = Base_t()) {
auto d_iter = get_dendrite_iter(n);
if (m_dendrites.end() == d_iter) return add_dendrite(n, w);
d_iter->weight = w;
return *d_iter;
}
/**
* \brief Unset dendrite (i.e. remove synapsis to another neuron)
*
* If such a synapsis exists, it is removed.
*
* \param n Source neuron
*/
void unset_dendrite(const neuron & n) {
auto d_iter = get_dendrite_iter(n);
if (m_dendrites.end() == d_iter) return;
remove_dendrite(d_iter);
}
/**
* \brief Minimise dendrite count
*
* The function removes all synapses that are equal to 0.
* Note that the equality is checked by the \n == operator
* of \c Base_t type; it is actually possible that the weight
* is not strictly 0, but just very close to it.
*/
void minimise_dendrites() {
Base_t w = 0;
auto d_iter = m_dendrites.begin();
while (d_iter != m_dendrites.end()) {
if (d_iter->weight == 0) {
w += d_iter->weight;
d_iter = remove_dendrite(d_iter);
}
else
++d_iter;
}
}
/**
* \brief Iterate over dendrits (const)
*
* \tparam Fn Injection type
* \param fn Injection
*/
template <class Fn>
void for_each_dendrite(Fn fn) const {
std::for_each(m_dendrites.begin(), m_dendrites.end(),
[fn](const dendrite & dend) {
fn(dend);
});
}
/**
* \brief Iterate over dendrits
*
* \tparam Fn Injection type
* \param fn Injection
*/
template <class Fn>
void for_each_dendrite(Fn fn) {
std::for_each(m_dendrites.begin(), m_dendrites.end(),
[fn](dendrite & dend) {
fn(dend);
});
}
}; // end of class neuron
private:
typedef std::unique_ptr<neuron> neuron_ptr; /**< Neuron pointer */
typedef std::vector<neuron_ptr> neurons_t; /**< Neurons list */
typedef std::list<size_t> indices_t; /**< Indices list */
size_t m_size; /**< Number of neurons */
neurons_t m_neurons; /**< Neurons */
indices_t m_inputs; /**< Input layer */
indices_t m_outputs; /**< Output layer */
/**
* \brief Iterate over valid neuron pointers
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_neuron_ptr(Fn fn) {
std::for_each(m_neurons.begin(), m_neurons.end(),
[fn](neuron_ptr & n_ptr) {
if (n_ptr) fn(n_ptr);
});
}
/**
* \brief Iterate over valid neuron pointers (const)
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_neuron_ptr(Fn fn) const {
std::for_each(m_neurons.begin(), m_neurons.end(),
[fn](const neuron_ptr & n_ptr) {
if (n_ptr) fn(n_ptr);
});
}
/**
* \brief Resolve I/O layer
*
* The function return I/O layer definition for I/O neuron type,
* or \c NULL if the type is different.
*
* \param type Neuron type
*
* \return I/O layer definition pointer or \c NULL if N/A
*/
indices_t * io_resolve(typename neuron::type_t type) {
switch (type) {
case neuron::INNER: break;
case neuron::INPUT: return &m_inputs;
case neuron::OUTPUT: return &m_outputs;
}
return NULL;
}
/**
* \brief Add I/O layer neuron entry
*
* If the \c n neuron belongs to input or output layer of the network,
* the function adds its index to according layer definition.
*
* \param n Neuron
*/
void io_add(const neuron & n) {
auto layer = io_resolve(n.type());
if (NULL != layer) layer->push_back(n.index());
}
/**
* \brief Remove I/O layer neuron entry
*
* If the \c n neuron belongs to input or output layer of the network,
* the function removes its index from according layer definition.
*
* \param n Neuron
*/
void io_remove(const neuron & n) {
auto layer = io_resolve(n.type());
if (NULL != layer) layer->remove(n.index());
}
/**
* \brief Remove all synapses to a neuron
*
* \param n Neuron
*/
void synapses_remove(const neuron & n) {
for_each_neuron([&n](neuron & n_other) {
n_other.unset_dendrite(n);
});
}
public:
/**
* \brief Constructor (empty network)
*/
nn() {}
/**
* \brief Network size (i.e. number of neurons) getter
*/
size_t size() const { return m_size; }
/**
* \brief Neuron slot count (should you want to create an indexed vector)
*/
size_t slot_cnt() const { return m_neurons.size(); }
/**
* \brief Input dimension (i.e. number of input layer neurons) getter
*/
size_t input_size() const { return m_inputs.size(); }
/**
* \brief Output dimension (i.e. number of output layer neurons) getter
*/
size_t output_size() const { return m_outputs.size(); }
/** Clear network */
void clear() {
m_inputs.clear();
m_outputs.clear();
m_neurons.clear();
m_size = 0;
}
/**
* \brief Iterate over neurons
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_neuron(Fn fn) {
for_each_neuron_ptr([fn](neuron_ptr & n_ptr) {
fn(*n_ptr);
});
}
/**
* \brief Iterate over neurons of const model
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_neuron(Fn fn) const {
for_each_neuron_ptr([fn](const neuron_ptr & n_ptr) {
fn(*n_ptr);
});
}
/**
* \brief Iterate over input layer neurons
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_input(Fn fn) {
std::for_each(m_inputs.begin(), m_inputs.end(),
[this, fn](size_t index) {
fn(*m_neurons[index]);
});
}
/**
* \brief Iterate over input layer neurons of const model
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_input(Fn fn) const {
std::for_each(m_inputs.begin(), m_inputs.end(),
[this, fn](size_t index) {
fn(*m_neurons[index]);
});
}
/**
* \brief Iterate over output layer neurons
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_output(Fn fn) {
std::for_each(m_outputs.begin(), m_outputs.end(),
[this, fn](size_t index) {
fn(*m_neurons[index]);
});
}
/**
* \brief Iterate over output layer neurons of const model
*
* \tparam Fn Action type
* \param fn Action
*/
template <class Fn>
void for_each_output(Fn fn) const {
std::for_each(m_outputs.begin(), m_outputs.end(),
[this, fn](size_t index) {
fn(*m_neurons[index]);
});
}
/**
* \brief Get neuron by index
*
* The function provides neuron by ts index (in O(1) time).
* If no such neuron exists, an exception is thrown.
*
* \param index Neuron index
*
* \return Neuron
*/
neuron & get_neuron(size_t index) {
neuron * n;
if (!(index < m_neurons.size()) || NULL == (n = m_neurons[index].get()))
throw std::range_error(
"libnn::nn::get_neuron: invalid index");
return *n;
}
/**
* \brief Get neuron by index (const)
*
* The function provides neuron by ts index (in O(1) time).
* If no such neuron exists, an exception is thrown.
*
* \param index Neuron index
*
* \return Neuron
*/
const neuron & get_neuron(size_t index) const {
neuron * n;
if (!(index < m_neurons.size()) || NULL == (n = m_neurons[index].get()))
throw std::range_error(
"libnn::nn::get_neuron: invalid index");
return *n;
}
/**
* \brief Add neuron
*
* Note that this invalidates any existing indexation-based objects
* created for the former state of the object.
*
* \tparam Args Types of activation functor constructor arguments
* \param type Neuron type
* \param args Activation functor constructor arguments
*
* \return Added neuron
*/
template <typename... Args>
neuron & add_neuron(
typename neuron::type_t type = neuron::INNER,
Args... args)
{
size_t index = m_neurons.size();
auto n = new neuron(index, type, args...);
m_neurons.emplace_back(n);
++m_size;
io_add(*n); // add I/O layer entry
return *n;
}
/**
* \brief Remove neuron
*
* Note that this technically doesn't invalidates any existing
* indexation-based objects, as long as you only access existing
* neurons' indices.
*
* \param n Neuron to remove
*/
void remove_neuron(neuron & n) {
io_remove(n); // remove I/O layer entry
synapses_remove(n); // remove all synapses to the neuron
// Destroy the neuron
m_neurons[n.index()].reset();
--m_size;
}
/**
* \brief Set neuron
*
* Sets neuron with \c index.
* Note that this invalidates any existing indexation-based objects
* created for the former state of the object.
*
* \tparam Args Types of activation functor constructor arguments
* \param index Neuron index
* \param type Neuron type
* \param args Activation functor constructor arguments
*
* \return Set neuron
*/
template <typename... Args>
neuron & set_neuron(
size_t index,
typename neuron::type_t type = neuron::INNER,
Args... args)
{
while (!(index < m_neurons.size()))
m_neurons.emplace_back();
if (NULL != m_neurons[index]) {
const auto & n = *m_neurons[index];
io_remove(n); // remove I/O layer entry
synapses_remove(n); // remove all synapses to the neuron
}
else
++m_size; // only increment if neuron isn't replaced
auto n = new neuron(index, type, args...);
m_neurons[index].reset(n);
io_add(*n); // add I/O layer entry
return *n;
}
/**
* \brief Reindex network
*
* Reassigns neurons indices so that there are no gaps.
* Note that this invalidates any existing indexation-based objects!
*/
void reindex() {
neurons_t neurons;
neurons.reserve(m_size);
// Clear I/O layer definitions
m_inputs.clear();
m_outputs.clear();
for_each_neuron_ptr([&neurons](neuron_ptr & n_ptr) {
size_t index = neurons.size();
n_ptr->index(index);
neurons.push_back(n_ptr);
io_add(*n_ptr); // resolve I/O layer
});
m_neurons.swap(neurons);
}
/**
* \brief Prune network
*
* The function removes useless dendrites (i.e. dendrites with 0 weight)
* from network's neurons.
* \see neuron::minimise_dendrites.
* This should be generally harmless, since such synapses don't affect
* the activation function value.
*/
void prune() {
for_each_neuron([](neuron & n) {
n.minimise_dendrites;
});
}
/**
* \brief Minimise network
*
* First, the function prunes the network (see \ref prune).
* Then it removes all inner neurons with no synapses.
* Note that this step MAY in fact alter the network functionality
* in case the activation function is non-zero for 0 argument.
* In such case, you probably don't want to do this.
* Input and output neurons are kept in any case to keep the network
* interface intact.
* If any neuron was removed, the above step is repeated (since
* by removal of a neuron, more of them might have lost all synapses).
* Finally, it reindexes the network (see \ref reindex).
*/
void minimise() {
prune();
size_t rm_cnt;
do {
rm_cnt = 0;
for_each_neuron([this, &rm_cnt](neuron & n) {
if (n.type() == neuron::INNER &&
0 == n.dendrite_cnt())
{
remove_neuron(n);
++rm_cnt;
}
});
} while (rm_cnt);
reindex();
}
}; // end of template class nn
}} // end of namespace libnn::topo
#endif // end of #ifndef libnn__topo__nn_hxx
| 28.348066 | 80 | 0.538345 | [
"object",
"vector",
"model"
] |
02714f9abe0ee018edcd6735ba3f4875f91a512e | 6,071 | cpp | C++ | src/geode/inspector/criterion/private/colocation_impl.cpp | Geode-solutions/OpenGeode-Inspector | 837ab6bf0742195daf0ecadd230e660f9426bd81 | [
"MIT"
] | 6 | 2022-03-23T03:14:33.000Z | 2022-03-30T07:44:24.000Z | src/geode/inspector/criterion/private/colocation_impl.cpp | Geode-solutions/OpenGeode-Inspector | 837ab6bf0742195daf0ecadd230e660f9426bd81 | [
"MIT"
] | 1 | 2022-03-31T13:03:28.000Z | 2022-03-31T13:03:28.000Z | src/geode/inspector/criterion/private/colocation_impl.cpp | Geode-solutions/OpenGeode-Inspector | 837ab6bf0742195daf0ecadd230e660f9426bd81 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2019 - 2022 Geode-solutions
*
* 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 <geode/inspector/criterion/private/colocation_impl.h>
#include <geode/basic/logger.h>
#include <geode/mesh/core/edged_curve.h>
#include <geode/mesh/core/point_set.h>
#include <geode/mesh/core/solid_mesh.h>
#include <geode/mesh/core/surface_mesh.h>
#include <geode/geometry/point.h>
namespace
{
template < geode::index_t dimension, typename Mesh >
typename geode::NNSearch< dimension >::ColocatedInfo
mesh_points_colocated_info(
const Mesh& mesh, double colocation_distance )
{
std::vector< geode::Point< dimension > > mesh_points(
mesh.nb_vertices() );
for( const auto point_index : geode::Range{ mesh.nb_vertices() } )
{
mesh_points[point_index] = mesh.point( point_index );
}
const geode::NNSearch< dimension > nnsearch{ mesh_points };
return nnsearch.colocated_index_mapping( colocation_distance );
}
} // namespace
namespace geode
{
namespace detail
{
template < index_t dimension, typename Mesh >
ColocationImpl< dimension, Mesh >::ColocationImpl(
const Mesh& mesh, bool verbose )
: mesh_( mesh ), verbose_( verbose )
{
}
template < index_t dimension, typename Mesh >
bool
ColocationImpl< dimension, Mesh >::mesh_has_colocated_points() const
{
return mesh_points_colocated_info< dimension, Mesh >(
mesh_, global_epsilon )
.nb_colocated_points()
> 0;
}
template < index_t dimension, typename Mesh >
index_t ColocationImpl< dimension, Mesh >::nb_colocated_points() const
{
return mesh_points_colocated_info< dimension, Mesh >(
mesh_, global_epsilon )
.nb_colocated_points();
}
template < index_t dimension, typename Mesh >
std::vector< std::vector< index_t > >
ColocationImpl< dimension, Mesh >::colocated_points_groups() const
{
const auto mesh_colocation_info =
mesh_points_colocated_info< dimension, Mesh >(
mesh_, global_epsilon );
std::vector< std::vector< index_t > > colocated_points_indices(
mesh_colocation_info.nb_unique_points() );
for( const auto point_index :
Indices{ mesh_colocation_info.colocated_mapping } )
{
colocated_points_indices[mesh_colocation_info
.colocated_mapping[point_index]]
.push_back( point_index );
}
const auto colocated_points_groups_end =
std::remove_if( colocated_points_indices.begin(),
colocated_points_indices.end(),
[]( const std::vector< index_t >& colocated_points_group ) {
return colocated_points_group.size() < 2;
} );
colocated_points_indices.erase(
colocated_points_groups_end, colocated_points_indices.end() );
if( verbose_ )
{
for( const auto colocated_points_group :
colocated_points_indices )
{
for( const auto point_index :
Range{ 1, colocated_points_group.size() } )
{
Logger::info( "Vertex with index ",
colocated_points_group[0],
" is colocated with vertex with index ",
colocated_points_group[point_index],
", at position [",
mesh_colocation_info
.unique_points
[mesh_colocation_info.colocated_mapping
[colocated_points_group[0]]]
.string(),
"]." );
}
}
}
return colocated_points_indices;
}
template class opengeode_inspector_inspector_api
ColocationImpl< 2, PointSet2D >;
template class opengeode_inspector_inspector_api
ColocationImpl< 3, PointSet3D >;
template class opengeode_inspector_inspector_api
ColocationImpl< 2, EdgedCurve2D >;
template class opengeode_inspector_inspector_api
ColocationImpl< 3, EdgedCurve3D >;
template class opengeode_inspector_inspector_api
ColocationImpl< 2, SurfaceMesh2D >;
template class opengeode_inspector_inspector_api
ColocationImpl< 3, SurfaceMesh3D >;
template class opengeode_inspector_inspector_api
ColocationImpl< 3, SolidMesh3D >;
} // namespace detail
} // namespace geode
| 41.29932 | 80 | 0.598089 | [
"mesh",
"geometry",
"vector"
] |
0272cb3bdc10a664559e608dc81a009ecdc313c3 | 4,876 | cpp | C++ | Project1P1.cpp | anikethsukhtankar/Hash-Tables | 0dbb6abc5a98710d95cf64f2a420954f2934500f | [
"MIT"
] | null | null | null | Project1P1.cpp | anikethsukhtankar/Hash-Tables | 0dbb6abc5a98710d95cf64f2a420954f2934500f | [
"MIT"
] | null | null | null | Project1P1.cpp | anikethsukhtankar/Hash-Tables | 0dbb6abc5a98710d95cf64f2a420954f2934500f | [
"MIT"
] | null | null | null | //**************************************************************
// main.cpp
// HashTable
//
// Created by Aniketh Sukhtankar on October 11, 2016.
// Demonstrate a simple Hash Table in C++.
// Implements a Linked List class.
//**************************************************************
#include "HashTable.h"
#include "HashTable.cpp"
#include "LinkedList.h"
#include "LinkedList.cpp"
#include <iostream> //to use cout
#include <iomanip> //to format output
#include <sstream>
#include <string>
#include <deque>
#include <vector>
#include <stdlib.h>
using namespace std;
void printMenu();
int main()
{
// local variables, can be accessed anywhere from the main method
string inputInfo;
string discipline, gender, isTeam, event, venue, medal, athlete, country, itemKey;
Item * found;
int tablesize,count=0,numofcommands;
string line="";
bool success = false;
cout << "Please Enter The Table Size:\n";
cin >> tablesize;
// Create a Hash Table of 13 Linked List elements.
HashTable table(tablesize);
cout << "Please Enter Athlete Data:\n";
while(line!="InsertionEnd"){
getline(cin, line);
istringstream ss(line);
string token;
string athleteData[8];
int i =0;
if(line!="InsertionEnd" && line!=""){
while(std::getline(ss, token, ',')) {
//std::cout << token << '\n'; Debug
athleteData[i] = token;
//std::cout << athleteData[i] << '\n'; Debug
i=i+1;
}
//struct Item* A = (struct Item*) malloc(sizeof(struct Item));
Item*A=new Item();
A->key = athleteData[0]+athleteData[1]+athleteData[3]+athleteData[6];
A->discipline = athleteData[0];
A->gender = athleteData[1];
A->isTeam = athleteData[2];
A->event = athleteData[3];
A->venue = athleteData[4];
A->medal = athleteData[5];
A->athlete = athleteData[6];
A->country = athleteData[7];
A->next = NULL;
//Item * A = new Item{athleteData[0]+athleteData[1]+athleteData[3]+athleteData[6],athleteData[0],athleteData[1],athleteData[2],athleteData[3],athleteData[4],athleteData[5],athleteData[6],athleteData[7], NULL};
table.insertItem(A);
}
};
cout << "Please Enter The Number Of Commands To Follow:\n";
cin >> numofcommands;
cin.ignore();
while(line!="quit"){
printMenu();
cout << "Please Enter A Command:\n";
getline(cin, line);
istringstream ss(line);
string token;
string commandLine[5];
int i =0;
while(std::getline(ss, token, ',')) {
//std::cout << token << '\n'; Debug
commandLine[i] = token;
//std::cout << athleteData[i] << '\n'; Debug
i=i+1;
}
itemKey = commandLine[1]+commandLine[2]+commandLine[3]+commandLine[4];
if(commandLine[0]=="hash_display"){
table.printTable();
}
if(commandLine[0]=="hash_search"){
//cout << itemKey; Debug
found = table.getItemByKey( itemKey );
if (found != NULL )
cout << "The medal recipient "<< commandLine[4] << " has the medal of "<< found -> medal <<"\n";
else
cout << commandLine[4] <<" for "<< commandLine[1] <<" with event "<<commandLine[3]<<" not found\n";
}
if(commandLine[0]=="hash_delete"){
//cout << itemKey; Debug
success = table.removeItem( itemKey );
if (success == true)
cout << "The medal recipient "<< commandLine[4] <<" for " << commandLine[1] <<" with event "<<commandLine[3] <<" deleted\n";
else
cout << commandLine[4] <<" for "<<commandLine[1]<<" with event "<<commandLine[3]<<" not found\n";
}
if(count >= numofcommands){
break;
}
count=count+1;
}
return 0;
}
/** The method printMenu displays the menu to a user**/
void printMenu()
{
cout << "\n\nCommand\n";
cout << "------\t\t------\n";
//cout << "A\t\tAdd Athlete Data\n";
cout << "hash_display\n";
cout << "hash_search\n";
cout << "hash_delete\n";
cout << "quit\n\n";
//cout << "?\t\tDisplay Help\n\n";
}
| 34.097902 | 226 | 0.474979 | [
"vector"
] |
02735c5c7e3bad5504e27e1b0b6574622215b6ca | 1,714 | cc | C++ | src/memory-bus.cc | dualslash/risc-v-emulator | 54638866e35d65472e5f3465fc0ed35ce0f52534 | [
"MIT"
] | null | null | null | src/memory-bus.cc | dualslash/risc-v-emulator | 54638866e35d65472e5f3465fc0ed35ce0f52534 | [
"MIT"
] | null | null | null | src/memory-bus.cc | dualslash/risc-v-emulator | 54638866e35d65472e5f3465fc0ed35ce0f52534 | [
"MIT"
] | null | null | null | /*
* rv64-emu -- Simple 64-bit RISC-V simulator
* memory-bus.h - "Interconnect" for different memory bus clients.
*/
#include "memory-bus.h"
MemoryBus::MemoryBus(std::vector<std::shared_ptr<MemoryInterface> > &&clients)
: clients(std::move(clients))
{
}
MemoryBus::~MemoryBus()
{
}
void
MemoryBus::addClient(std::shared_ptr<MemoryInterface> client)
{
clients.push_back(client);
}
uint8_t
MemoryBus::readByte(MemAddress addr)
{
return getClient(addr)->readByte(addr);
}
uint16_t
MemoryBus::readHalfWord(MemAddress addr)
{
return getClient(addr)->readHalfWord(addr);
}
uint32_t
MemoryBus::readWord(MemAddress addr)
{
return getClient(addr)->readWord(addr);
}
uint64_t
MemoryBus::readDoubleWord(MemAddress addr)
{
return getClient(addr)->readDoubleWord(addr);
}
void
MemoryBus::writeByte(MemAddress addr, uint8_t value)
{
return getClient(addr)->writeByte(addr, value);
}
void
MemoryBus::writeHalfWord(MemAddress addr, uint16_t value)
{
return getClient(addr)->writeHalfWord(addr, value);
}
void
MemoryBus::writeWord(MemAddress addr, uint32_t value)
{
return getClient(addr)->writeWord(addr, value);
}
void
MemoryBus::writeDoubleWord(MemAddress addr, uint64_t value)
{
return getClient(addr)->writeDoubleWord(addr, value);
}
bool
MemoryBus::contains(MemAddress addr) const
{
return true;
}
/*
* Private methods
*/
std::shared_ptr<MemoryInterface>
MemoryBus::findClient(MemAddress addr) noexcept
{
for (auto &client : clients)
if (client->contains(addr))
return client;
return nullptr;
}
std::shared_ptr<MemoryInterface>
MemoryBus::getClient(MemAddress addr)
{
auto client = findClient(addr);
if (!client)
throw IllegalAccess(addr);
return client;
}
| 17.313131 | 78 | 0.737456 | [
"vector"
] |
0277471f403fc93e6ddd490b2b72ace4904abd22 | 8,678 | hpp | C++ | myparser_rule.hpp | hczhcz/myparser | deb708c73e6b5a497573b4d3ac4122ee559651a3 | [
"MIT"
] | 7 | 2015-01-17T16:36:51.000Z | 2020-03-02T17:56:03.000Z | myparser_rule.hpp | hczhcz/myparser | deb708c73e6b5a497573b4d3ac4122ee559651a3 | [
"MIT"
] | null | null | null | myparser_rule.hpp | hczhcz/myparser | deb708c73e6b5a497573b4d3ac4122ee559651a3 | [
"MIT"
] | 2 | 2016-09-27T09:51:12.000Z | 2021-01-19T11:11:53.000Z | #pragma once
#include "myparser_ast_spec.hpp"
namespace myparser {
// builtin names -> myparser_ast.hpp
using ErrorList = MP_STR("Nothing matched");
using ErrorRegex = MP_STR("Regex not matched");
using ErrorChecking = MP_STR("Match not accepted");
using ErrorKeyword = MP_STR("Bad keyword");
template <size_t L, size_t M>
class Tag {
public:
static const size_t least = L;
static const size_t most = M;
};
using TagNormal = Tag<1, 1>;
using TagMaybe = Tag<0, 1>;
using TagAny0 = Tag<0, std::numeric_limits<size_t>::max()>;
using TagAny1 = Tag<1, std::numeric_limits<size_t>::max()>;
template <class N>
class Rule {
private:
inline Rule() = delete; // force static
// virtual ~Rule() = delete;
};
// need specialize
template <class N>
class RuleDef;
template <>
class RuleDef<BuiltinError>: public Rule<BuiltinError> {};
//////// Named ////////
template <class N, class... RL>
class RuleList: public Rule<N> {
private:
template <size_t I, class R, class... Rx>
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> runRule(
Input &input, const Input &end
) {
using Line = typename R::template Helper<N, I>;
Input input_rev = input;
auto current = Line::parse(input, end);
if (current.first) {
return current;
} else {
input = input_rev;
auto next = runRule<I + 1, Rx...>(input, end);
if (!next.second) {
return {next.first, current.second};
} else {
return {
next.first,
next.second->challengeLonger(current.second)
};
}
}
}
template <size_t I> // iteration finished
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> runRule(
Input &input, const Input &
) {
return {
nullptr,
new NodeTypedError<N, ErrorList>(input)
};
}
public:
static std::pair<Node<> *, Node<> *> parse(
Input &input, const Input &end
) {
return runRule<0, RL...>(input, end);
}
};
template <class N, class RX>
class RuleRegex: public Rule<N> {
public:
using Result = NodeTypedText<N>;
private:
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> runRegex(
Input &input, const Input &end
) {
#if defined(MYPARSER_BOOST_XPRESSIVE)
static const regex_lib::basic_regex<Input> re =
regex_lib::basic_regex<Input>::compile<Input>(
RX::getStr().cbegin(),
RX::getStr().cend()
);
#else
static const regex_lib::regex re(
RX::getStr()
);
#endif
regex_lib::match_results<Input> mdata;
if (
regex_lib::regex_search(
input, end, mdata, re,
regex_lib::regex_constants::match_continuous
)
) {
Result *result =
new Result(input, input + mdata.length());
if (result->accepted()) {
input += mdata.length();
return {result, nullptr};
} else {
return {nullptr, result};
}
} else {
return {
nullptr,
new NodeTypedError<N, ErrorRegex>(input)
};
}
}
public:
static std::pair<Node<> *, Node<> *> parse(
Input &input, const Input &end
) {
return runRegex(input, end);
}
};
//////// Cell ////////
template <class N = BuiltinSpace, class TAG = TagNormal>
class RuleItemSpace: public TAG {
public:
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> parse(
Input &input, const Input &end
) {
return RuleDef<N>::parse(input, end);
}
};
template <class KW, class N = BuiltinKeyword, class TAG = TagNormal>
class RuleItemKeyword: public TAG {
public:
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> parse(
Input &input, const Input &end
) {
auto current = RuleDef<N>::parse(input, end);
if (
current.first
&&
current.first->getFullText() == KW::getStr()
) {
return current;
} else {
if (current.first) {
current.first->free();
}
if (current.second) {
current.second->free();
}
return {
nullptr,
new NodeTypedError<N, ErrorKeyword>(input)
};
}
}
};
template <class N, class TAG = TagNormal>
class RuleItemRef: public TAG {
public:
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> parse(
Input &input, const Input &end
) {
return RuleDef<N>::parse(input, end);
}
};
template <class E, class TAG = TagNormal>
class RuleItemError: public TAG {
public:
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> parse(
Input &input, const Input &
) {
return {
nullptr,
new NodeTypedError<BuiltinError, E>(input)
};
}
};
//////// Misc ////////
template <class... RL>
class RuleLine {
public:
template <class N, size_t I>
class Helper {
public:
using Result = NodeTypedList<N, I>;
private:
template <class R, class... Rx>
static MYPARSER_INLINE bool runRule(
Result *&result, Node<> *&err, size_t &errpos,
Input &input, const Input &end
) {
for (size_t i = 0; i < R::most; ++i) {
auto current = R::parse(input, end);
if (current.second) {
err = current.second->challengeLonger(err);
// if err updated
if (err == current.second) {
errpos = result->getChildren().size();
}
}
if (!current.first) {
if (i < R::least) {
return false;
} else {
break;
}
} else {
result->putChild(current.first);
}
}
return runRule<Rx...>(result, err, errpos, input, end);
}
template <std::nullptr_t P = nullptr> // iteration finished
static MYPARSER_INLINE bool runRule(
Result *&, Node<> *&, size_t &,
Input &, const Input &
) {
return true;
}
public:
static MYPARSER_INLINE std::pair<Node<> *, Node<> *> parse(
Input &input, const Input &end
) {
Result *result = new Result(input);
Result *result_err = new Result(input);
Node<> *err = nullptr;
size_t errpos = 0;
bool succeed = runRule<RL...>(result, err, errpos, input, end);
result->bind(result_err, errpos);
result_err->bind(result, errpos);
if (err) {
for (size_t i = 0; i < errpos; ++i) {
result_err->putChild(result->getChildren()[i]);
}
result_err->putChild(err);
} else {
result_err->free();
result_err = nullptr;
}
if (!succeed) {
result->free();
result = nullptr;
}
return {result, result_err};
}
};
};
template <class N = BuiltinRoot>
class Parser {
public:
static inline Node<> *parse(
Input &input, const Input &end, const bool dothrow = false
) {
auto current = RuleDef<N>::parse(input, end);
if (current.first) {
if (current.second) {
current.second->free();
}
return current.first;
} else {
if (dothrow) {
throw current.second;
} else {
return current.second;
}
}
}
static inline Node<> *parse(
const std::string &text, const bool dothrow = false
) {
Input input = text.cbegin();
return parse(input, text.cend(), dothrow);
}
static inline Node<> *parseFile(
const std::string &filename, const bool dothrow = false
) {
static std::vector<std::string> storage;
std::ifstream fs(filename);
std::istreambuf_iterator<char> input(fs);
std::istreambuf_iterator<char> end;
storage.push_back(std::string(input, end));
return parse(storage.back(), dothrow);
}
};
}
| 25.374269 | 75 | 0.503803 | [
"vector"
] |
0277d793ed8906353daeee2797803232963eb34c | 3,735 | cpp | C++ | libraries/CtrlLoop.cpp | Tfmenard/3d_scanner_pg_embedded | 52cb5a57d2a24a51f9ea7bd3f40aab90dcda38bb | [
"MIT"
] | null | null | null | libraries/CtrlLoop.cpp | Tfmenard/3d_scanner_pg_embedded | 52cb5a57d2a24a51f9ea7bd3f40aab90dcda38bb | [
"MIT"
] | null | null | null | libraries/CtrlLoop.cpp | Tfmenard/3d_scanner_pg_embedded | 52cb5a57d2a24a51f9ea7bd3f40aab90dcda38bb | [
"MIT"
] | null | null | null | #include "CtrlLoop.h"
#include "Arduino.h"
CtrlLoop::CtrlLoop(char _id, Encoder *mEncoder, Motor *_motor, PID *_pid, double &_Setpoint, double &_Input, double &_Output)
: id(_id), encoder(mEncoder), motor(_motor), pid(_pid), Setpoint(_Setpoint), Input(_Input), Output(_Output)
{
pid->SetMode(AUTOMATIC);
this->Setpoint = 0;
}
CtrlLoop::CtrlLoop(char id, Encoder *mEncoder, Motor *_motor, double K_p, double K_i, double K_d)
: id(id), encoder(mEncoder), motor(_motor)
{
//TODO: Fix this section to initialize member object pid
pid = new PID (&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
//_pid.SetMode(AUTOMATIC);
//pid = &_pid;
pid->SetMode(AUTOMATIC);
//motor = _motor;
//TODO: Fix this by initializing Setpoint first
this->Setpoint = 0;
}
void CtrlLoop::updatePosition()
{
newPosition = encoder->read();
if (newPosition != oldPosition) {
oldPosition = newPosition;
Input = newPosition;
}
}
bool CtrlLoop::updatePID()
{
this->pid->Compute();
}
void CtrlLoop::findMotorDirection()
{
if (Setpoint < Input)
{
pid->SetControllerDirection(REVERSE);
// Serial.print("Reverse controller mode");
//TODO: replace with goBackward function
motor->goBackward();
//xMotor.goForward();
// Serial.print("Go backward");
}
else
{
pid->SetControllerDirection(DIRECT);
// Serial.print("DIRECT Controller Mode");
//TODO: replace with goBackward function
motor->goForward();
// Serial.print("Go forward");
}
}
void CtrlLoop::homing()
{
isHoming = true;
homingTerminated = false;
motor->isMoving = true;
if (id == 'Y')
{
Setpoint = (999999);//to ensure that Y motor rotates in the right direction
}
else
{
Setpoint = (-999999);//arbitrary long distance
if (id == 'B')
{
encoder->write(0);
Setpoint = 0;
isHoming = false;
motor->isMoving = false;
homingTerminated = false;
}
}
}
void CtrlLoop::checkIfHomingDone(int switchPin)
{
if (digitalRead(switchPin) != 0 && (isHoming) )
{
encoder->write(0);
Setpoint = 0;
isHoming = false;
homingTerminated = true;
//Serial.print("switch activated homing");
//Serial.print('\n');
}
}
void CtrlLoop::sendFBackStreamIfMoving()//Streams encoder position only when the motor is moving
{
bool close_enough = (Input > (Setpoint - posThreshold)) && (Input < (Setpoint + posThreshold));
if(homingTerminated && motor->isMoving)
{
//Send current position status
sendFeedBackStatus("HCD,");
}
else if(motor->isMoving)
{
//Send current position status
sendFeedBackStatus("ECD,");
}
}
void CtrlLoop::sendFBackStreamHoming()//Streams encoder position only when the motor is moving
{
if(motor->isMoving && isHoming)
{
//Send current position status
sendFeedBackStatus("ECD,");
}
else if(homingTerminated && motor->isMoving)
{
//Send current position status
sendFeedBackStatus("HCD,");
}
}
void CtrlLoop::sendFeedBackStatus(String cmd_id)
{
//Print current position status
String cmdStringHead = cmd_id;
cmdStringHead += motor->motorID;
cmdStringHead += ',';
double posAsDouble = abs(Input/motor->gear_ratio);
uint16_t posAsUint16 = static_cast<uint16_t>(posAsDouble + 0.5);
String cmdStringTail = ",";
char startMsgChar = '{';
char endMsgChar = '}';
double dividerAsDouble = posAsDouble/120.0;
uint8_t dividerAsInt = (uint8_t)dividerAsDouble;
int posAsInt = (int)posAsDouble;
int remainderAsInt = posAsInt%120;
uint8_t remainder = (uint8_t)remainderAsInt;
uint8_t posHead = dividerAsInt;
uint8_t posTail = remainder;
Serial.write(startMsgChar);
Serial.print(cmdStringHead);
Serial.write(posHead);
Serial.write(posTail);
Serial.print(cmdStringTail);
Serial.write(endMsgChar);
} | 22.232143 | 125 | 0.685408 | [
"object"
] |
027ac67585c213ff9c4a4b6729016b43909dad08 | 1,309 | cpp | C++ | dynamic_programing/4_keys_keyboard.cpp | zm66260/Data_Structure_and_Algorithms | f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e | [
"MIT"
] | null | null | null | dynamic_programing/4_keys_keyboard.cpp | zm66260/Data_Structure_and_Algorithms | f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e | [
"MIT"
] | null | null | null | dynamic_programing/4_keys_keyboard.cpp | zm66260/Data_Structure_and_Algorithms | f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e | [
"MIT"
] | null | null | null | // 4 keys keyboard
// Imagine you have a special keyboard with the following keys:
// Key 1: (A): Print one 'A' on screen.
// Key 2: (Ctrl-A): Select the whole screen.
// Key 3: (Ctrl-C): Copy selection to buffer.
// Key 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed.
// Now, you can only press the keyboard for N times (with the above four keys), find out the maximum numbers of 'A' you can print on screen.
// Example 1:
// Input: N = 3
// Output: 3
// Explanation:
// We can at most get 3 A's on screen by pressing following key sequence:
// A, A, A
// Example 2:
// Input: N = 7
// Output: 9
// Explanation:
// We can at most get 9 A's on screen by pressing following key sequence:
// A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
// Note:
// 1 <= N <= 50
// Answers will be in the range of 32-bit signed integer.
#include<vector>
using namespace std;
class Solution {
public:
int maxA(int N){
vector<int> dp(N+1, 0);
for(int i = 1; i <= N; i++){
dp[i] = dp[i-1] + 1;
for(int j = 2; j < i; j++){
// i-j是ctr+v的个数,1是指原本已经存在的A
dp[i] = max(dp[i], dp[j-2]*(i - j + 1));
}
}
return dp[N];
}
};
| 23.375 | 141 | 0.550038 | [
"vector"
] |
028ed80761a5414beb36054c2b3f96845b5f3df8 | 2,505 | cpp | C++ | code/dunglish.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/dunglish.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/dunglish.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #define _USE_MATH_DEFINES
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <stack>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int main()
{
ll i, j, k;
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
ll numWords;
cin >> numWords;
ll numTranslations;
vector<string> words(numWords);
map<string, vector<string>> correct;
map<string, vector<string>> incorrect;
for(int i = 0; i < numWords; i++)
{
cin >> words[i];
}
cin >> numTranslations;
string dutch, english, correctness;
for(int i = 0; i < numTranslations; i++)
{
cin >> dutch >> english >> correctness;
if(correctness == "correct")
{
correct[dutch].push_back(english);
}
else
{
incorrect[dutch].push_back(english);
}
}
ll totalCorrect = correct[words[0]].size();
ll totalIncorrect = incorrect[words[0]].size();
for(int i = 1; i < numWords; i++)
{
ll newCorrect = 0;
ll newIncorrect = 0;
auto elem = correct.find(words[i]);
if(elem != correct.end())
{
newCorrect = elem->second.size();
}
elem = incorrect.find(words[i]);
if(elem != incorrect.end())
{
newIncorrect = elem->second.size();
}
ll oldIncorrect = totalIncorrect;
totalIncorrect = (totalCorrect + totalIncorrect) * newIncorrect;
totalIncorrect += oldIncorrect * newCorrect;
totalCorrect *= newCorrect;
}
if(totalCorrect + totalIncorrect == 1)
{
for(int i = 0; i < numWords; i++)
{
auto found = incorrect.find(words[i]);
if(found != incorrect.end())
{
for(auto elem : incorrect[words[i]])
{
cout << elem << " ";
}
}
found = correct.find(words[i]);
if(found != correct.end())
{
for(auto elem : correct[words[i]])
{
cout << elem << " ";
}
}
//else
//{
// cout << correct[words[i]][0] << " ";
//}
}
if(totalCorrect == 1)
{
cout << "\ncorrect\n";
}
else
{
cout << "\nincorrect\n";
}
}
else
{
cout << totalCorrect << " correct\n";
cout << totalIncorrect << " incorrect\n";
}
return 0;
}
| 20.532787 | 69 | 0.545709 | [
"vector"
] |
0297328991093abcc2371e559c582f9d007ac517 | 15,609 | cpp | C++ | reluplex/Reluplex2py.cpp | rnbguy/python-reluplex | 42c23b010dbc28f1d0cb8faa9fbe635686adf264 | [
"MIT"
] | 2 | 2019-07-02T07:51:34.000Z | 2021-04-23T13:51:53.000Z | reluplex/Reluplex2py.cpp | rnbguy/python-reluplex | 42c23b010dbc28f1d0cb8faa9fbe635686adf264 | [
"MIT"
] | null | null | null | reluplex/Reluplex2py.cpp | rnbguy/python-reluplex | 42c23b010dbc28f1d0cb8faa9fbe635686adf264 | [
"MIT"
] | 1 | 2021-09-02T11:32:29.000Z | 2021-09-02T11:32:29.000Z | #include <Python.h>
#include <vector>
#include <NeuralReluplex.h>
#include <Reluplex.h>
#include <numpy/ndarraytypes.h>
#include <numpy/ufuncobject.h>
#include <numpy/npy_3kcompat.h>
PyObject* construct(PyObject* self, PyObject* args) {
NeuralReluplex* neuralReluplex = new NeuralReluplex();
PyObject* neuralReluplexCapsule = PyCapsule_New((void *)neuralReluplex, "NeuralReluplexPtr", NULL);
PyCapsule_SetPointer(neuralReluplexCapsule, (void *)neuralReluplex);
return Py_BuildValue("O", neuralReluplexCapsule);
}
//
// PyObject* initializeCell(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// unsigned int row_;
// unsigned int column_;
// double value_;
//
// PyArg_ParseTuple(args, "OIId",
// &neuralReluplexCapsule_,
// &row_,
// &column_,
// &value_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->initializeCell(row_, column_, value_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* markBasic(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// unsigned int variable_;
//
// PyArg_ParseTuple(args, "OI",
// &neuralReluplexCapsule_,
// &variable_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->markBasic(variable_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* setLowerBound(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// unsigned int variable_;
// double bound_;
//
// PyArg_ParseTuple(args, "OId",
// &neuralReluplexCapsule_,
// &variable_,
// &bound_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->setLowerBound(variable_, bound_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* setUpperBound(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// unsigned int variable_;
// double bound_;
//
// PyArg_ParseTuple(args, "OId",
// &neuralReluplexCapsule_,
// &variable_,
// &bound_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->setUpperBound(variable_, bound_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* setReluPair(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// unsigned int backward_;
// unsigned int forward_;
//
// PyArg_ParseTuple(args, "OII",
// &neuralReluplexCapsule_,
// &backward_,
// &forward_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->setReluPair(backward_, forward_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* setName(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// unsigned int variable_;
// const char* name_;
//
// PyArg_ParseTuple(args, "OIs",
// &neuralReluplexCapsule_,
// &variable_,
// &name_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->setName(variable_, name_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* setLogging(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// int flag_;
//
// PyArg_ParseTuple(args, "Op",
// &neuralReluplexCapsule_,
// &flag_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->reluplex->setLogging(flag_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* setDumpStates(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// int flag_;
//
// PyArg_ParseTuple(args, "Op",
// &neuralReluplexCapsule_,
// &flag_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->reluplex->setDumpStates(flag_);
//
// Py_RETURN_NONE;
// }
//
// PyObject* toggleAlmostBrokenReluEliminiation(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// int flag_;
//
// PyArg_ParseTuple(args, "Op",
// &neuralReluplexCapsule_,
// &flag_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// neuralReluplex->reluplex->toggleAlmostBrokenReluEliminiation(flag_);
//
// Py_RETURN_NONE;
// }
// PyObject* getAssignment(PyObject* self, PyObject* args) {
// PyObject* neuralReluplexCapsule_;
// unsigned int variable_;
//
// PyArg_ParseTuple(args, "OI",
// &neuralReluplexCapsule_,
// &variable_);
//
// NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
//
// double assignment = neuralReluplex->reluplex->getAssignment(variable_);
//
// return Py_BuildValue("d", assignment);
// }
PyObject* getInputAssignment(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
PyArg_ParseTuple(args, "O",
&neuralReluplexCapsule_);
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
std::vector<double> assignment = neuralReluplex->getInputAssignment();
int nd = 1;
npy_intp dims[] = {(long)assignment.size()};
PyObject* np_assignment = PyArray_SimpleNew(nd, dims, NPY_DOUBLE);
for(auto i = 0ul; i < assignment.size(); ++i) {
auto ptr = (npy_double*)PyArray_GETPTR1(np_assignment,i);
*ptr = assignment[i];
}
return np_assignment;
}
PyObject* inputFromIntervalBox(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
PyObject *arg_=NULL;
PyArrayObject *arr_=NULL;
PyArg_ParseTuple(args, "OO", &neuralReluplexCapsule_, &arg_);
// // arr_ = PyArray_FROM_OTF(arg_, NPY_DOUBLE, NPY_IN_ARRAY);
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
arr_ = (PyArrayObject*) arg_;
npy_intp *sp=PyArray_SHAPE(arr_);
std::vector<double> l_bound;
std::vector<double> u_bound;
for (int i=0; i<*sp; i++) {
l_bound.push_back(*((npy_double*)PyArray_GETPTR2(arr_,i, 0)));
u_bound.push_back(*((npy_double*)PyArray_GETPTR2(arr_,i, 1)));
}
neuralReluplex->input_interval_box(l_bound, u_bound);
Py_RETURN_NONE;
}
PyObject* inputNotFromIntervalBox(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
PyObject *arg_=NULL;
PyArrayObject *arr_=NULL;
PyArg_ParseTuple(args, "OO", &neuralReluplexCapsule_, &arg_);
// // arr_ = PyArray_FROM_OTF(arg_, NPY_DOUBLE, NPY_IN_ARRAY);
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
arr_ = (PyArrayObject*) arg_;
npy_intp *sp=PyArray_SHAPE(arr_);
std::vector<double> l_bound;
std::vector<double> u_bound;
for (int i=0; i<*sp; i++) {
l_bound.push_back(*((npy_double*)PyArray_GETPTR2(arr_,i, 0)));
u_bound.push_back(*((npy_double*)PyArray_GETPTR2(arr_,i, 1)));
}
neuralReluplex->input_neg_interval_box(l_bound, u_bound);
Py_RETURN_NONE;
}
PyObject* i_does_not_win(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
unsigned i;
PyArg_ParseTuple(args, "OI", &neuralReluplexCapsule_, &i);
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
neuralReluplex->i_output_does_not_win(i);
Py_RETURN_NONE;
}
PyObject* getOutputAssignment(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
PyArg_ParseTuple(args, "O",
&neuralReluplexCapsule_);
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
std::vector<double> assignment = neuralReluplex->getOutputAssignment();
int nd = 1;
npy_intp dims[] = {(long)assignment.size()};
PyObject* np_assignment = PyArray_SimpleNew(nd, dims, NPY_DOUBLE);
for(auto i = 0ul; i < assignment.size(); ++i) {
auto ptr = (npy_double*)PyArray_GETPTR1(np_assignment,i);
*ptr = assignment[i];
}
return np_assignment;
}
PyObject* solve(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
PyArg_ParseTuple(args, "O",
&neuralReluplexCapsule_);
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
neuralReluplex->build_reluplex();
Reluplex::FinalStatus result = neuralReluplex->solve();
if ( result == Reluplex::SAT )
return Py_BuildValue("I", 0);
else if ( result == Reluplex::UNSAT )
return Py_BuildValue("I", 1);
else if ( result == Reluplex::ERROR )
return Py_BuildValue("I", 2);
else
return Py_BuildValue("I", 3);
}
PyObject* delete_object(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
PyArg_ParseTuple(args, "O",
&neuralReluplexCapsule_);
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
delete neuralReluplex;
Py_RETURN_NONE;
}
PyObject* build_network(PyObject* self, PyObject* args) {
PyObject* neuralReluplexCapsule_;
PyObject* list_;
PyArrayObject* arr;
PyArg_ParseTuple(args, "OO", &neuralReluplexCapsule_, &list_);
std::vector<std::vector<std::vector<double> > > weights;
Py_ssize_t size = PyList_GET_SIZE(list_);
for(Py_ssize_t i = 0; i < size; ++i) {
std::vector<std::vector<double> > layer_weight;
arr = (PyArrayObject*)PySequence_GetItem(list_, i);
int nd=PyArray_NDIM(arr);
if (nd == 1) {
npy_intp *sp=PyArray_SHAPE(arr);
std::vector<double> layer_weight_i;
for (int i = 0; i < *sp; i++) {
layer_weight_i.push_back(*((npy_double*)PyArray_GETPTR1(arr,i)));
}
layer_weight.push_back(layer_weight_i);
} else if (nd == 2) {
npy_intp *sp=PyArray_SHAPE(arr);
for (int i=0; i<*sp; i++) {
std::vector<double> layer_weight_i;
for (int j=0; j<*(sp+1); j++) {
layer_weight_i.push_back(*((npy_double*)PyArray_GETPTR2(arr,i, j)));
}
layer_weight.push_back(layer_weight_i);
}
} else {
// should not reach
}
weights.push_back(layer_weight);
Py_CLEAR(arr);
}
NeuralReluplex* neuralReluplex = (NeuralReluplex*)PyCapsule_GetPointer(neuralReluplexCapsule_, "NeuralReluplexPtr");
neuralReluplex->load_weights(weights);
Py_RETURN_NONE;
}
PyMethodDef cNeuralReluplexFunctions[] = {
{"construct",
construct, METH_VARARGS,
"Create `NeuralReluplex` object"},
// {"initializeCell",
// initializeCell, METH_VARARGS,
// "Initialize cells in NeuralReluplex"},
//
// {"markBasic",
// markBasic, METH_VARARGS,
// "Mark Basic variables in NeuralReluplex"},
//
// {"setLowerBound",
// setLowerBound, METH_VARARGS,
// "Set lower bound of a variable in NeuralReluplex"},
//
// {"setUpperBound",
// setUpperBound, METH_VARARGS,
// "Set upper bound of a variable in NeuralReluplex"},
//
// {"setReluPair",
// setReluPair, METH_VARARGS,
// "Set ReluPair of two forward and backward variables in NeuralReluplex"},
//
// {"setName",
// setName, METH_VARARGS,
// "Set name of a variable in NeuralReluplex"},
//
// {"getAssignment",
// getAssignment, METH_VARARGS,
// "Get assignment of a variable in NeuralReluplex"},
//
// {"setLogging",
// setLogging, METH_VARARGS,
// "Set logging flag in NeuralReluplex"},
//
// {"setDumpStates",
// setDumpStates, METH_VARARGS,
// "Set DumpStates flag in NeuralReluplex"},
//
// {"toggleAlmostBrokenReluEliminiation",
// toggleAlmostBrokenReluEliminiation, METH_VARARGS,
// "toggle AlmostBrokenReluEliminiation flag in NeuralReluplex"},
{"solve",
solve, METH_VARARGS,
"Solve NeuralReluplex"},
{"getInputAssignment",
getInputAssignment, METH_VARARGS,
"Get assignment of input layer in NeuralReluplex"},
{"getOutputAssignment",
getOutputAssignment, METH_VARARGS,
"Get assignment of output layer in NeuralReluplex"},
{"delete_object",
delete_object, METH_VARARGS,
"Delete `NeuralReluplex` object"},
{"build_network",
build_network, METH_VARARGS,
"Build neural network from weights in `NeuralReluplex` object"},
{"inputFromIntervalBox",
inputFromIntervalBox, METH_VARARGS,
"Input are from this interval box"},
{"inputNotFromIntervalBox",
inputNotFromIntervalBox, METH_VARARGS,
"Input are not from this interval box"},
{"i_does_not_win",
i_does_not_win, METH_VARARGS,
"i-th output does not win"},
{NULL, NULL, 0, NULL}
};
struct PyModuleDef cNeuralReluplexModule = {
PyModuleDef_HEAD_INIT,
"cReluplex",
NULL,
-1,
cNeuralReluplexFunctions
};
PyMODINIT_FUNC PyInit_cNeuralReluplex(void) {
import_array();
return PyModule_Create(&cNeuralReluplexModule);
}
| 33.567742 | 127 | 0.590621 | [
"object",
"vector"
] |
029a73ac3b9149894bcc62e23e77fb5c895a4238 | 200 | cpp | C++ | MIDIAvoided/Button/LambdaButton.cpp | hyoiutu/AVOMID | c9f904f4d1f96feb9ed4e2b5c8b16989039752be | [
"MIT"
] | 2 | 2016-12-09T02:21:23.000Z | 2017-08-31T13:49:13.000Z | Game/Button/LambdaButton.cpp | IndistinQuest/Game | 3c8363026388a452a1e1b5a46ff34bb8fa8baff4 | [
"MIT"
] | null | null | null | Game/Button/LambdaButton.cpp | IndistinQuest/Game | 3c8363026388a452a1e1b5a46ff34bb8fa8baff4 | [
"MIT"
] | null | null | null | #include "LambdaButton.h"
LambdaButton::LambdaButton(Shape shape, std::function<void(void)> handler)
:BasicButton(shape), handler_m(handler){}
void LambdaButton::onClicked()
{
handler_m();
} | 22.222222 | 74 | 0.73 | [
"shape"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.