hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed391cd4cb8dd757beeb5e4978a567be37229eb8 | 5,489 | cc | C++ | daemon/protocol/mcbp/get_context.cc | cgvarela/memcached | 493a2ed939e87d18eb368f17bec5b948701e9d2d | [
"BSD-3-Clause"
] | null | null | null | daemon/protocol/mcbp/get_context.cc | cgvarela/memcached | 493a2ed939e87d18eb368f17bec5b948701e9d2d | [
"BSD-3-Clause"
] | null | null | null | daemon/protocol/mcbp/get_context.cc | cgvarela/memcached | 493a2ed939e87d18eb368f17bec5b948701e9d2d | [
"BSD-3-Clause"
] | null | null | null | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "engine_wrapper.h"
#include "get_context.h"
#include <daemon/debug_helpers.h>
#include <daemon/mcbp.h>
#include <xattr/utils.h>
#include <daemon/mcaudit.h>
GetCommandContext::~GetCommandContext() {
if (it != nullptr) {
bucket_release_item(&connection, it);
}
}
ENGINE_ERROR_CODE GetCommandContext::getItem() {
auto ret = bucket_get(&connection, &it, key, vbucket);
if (ret == ENGINE_SUCCESS) {
if (!bucket_get_item_info(&connection, it, &info)) {
LOG_WARNING(&connection, "%u: Failed to get item info",
connection.getId());
return ENGINE_FAILED;
}
payload.buf = static_cast<const char*>(info.value[0].iov_base);
payload.len = info.value[0].iov_len;
bool need_inflate = false;
if (mcbp::datatype::is_snappy(info.datatype)) {
need_inflate = mcbp::datatype::is_xattr(info.datatype) ||
!connection.isSnappyEnabled();
}
if (need_inflate) {
state = State::InflateItem;
} else {
state = State::SendResponse;
}
} else if (ret == ENGINE_KEY_ENOENT) {
state = State::NoSuchItem;
ret = ENGINE_SUCCESS;
}
return ret;
}
ENGINE_ERROR_CODE GetCommandContext::inflateItem() {
try {
if (!cb::compression::inflate(cb::compression::Algorithm::Snappy,
payload.buf, payload.len, buffer)) {
LOG_WARNING(&connection, "%u: Failed to inflate item",
connection.getId());
return ENGINE_FAILED;
}
payload.buf = buffer.data.get();
payload.len = buffer.len;
} catch (const std::bad_alloc&) {
return ENGINE_ENOMEM;
}
state = State::SendResponse;
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE GetCommandContext::sendResponse() {
protocol_binary_datatype_t datatype = info.datatype;
if (mcbp::datatype::is_xattr(datatype)) {
payload = cb::xattr::get_body(payload);
datatype &= ~PROTOCOL_BINARY_DATATYPE_XATTR;
}
datatype = connection.getEnabledDatatypes(datatype);
auto* rsp = reinterpret_cast<protocol_binary_response_get*>(connection.write.buf);
uint16_t keylen = 0;
uint32_t bodylen = sizeof(rsp->message.body) + payload.len;
if (shouldSendKey()) {
keylen = uint16_t(key.size());
bodylen += keylen;
}
mcbp_add_header(&connection,
PROTOCOL_BINARY_RESPONSE_SUCCESS,
sizeof(rsp->message.body),
keylen, bodylen, datatype);
rsp->message.header.response.cas = htonll(info.cas);
/* add the flags */
rsp->message.body.flags = info.flags;
connection.addIov(&rsp->message.body, sizeof(rsp->message.body));
if (shouldSendKey()) {
connection.addIov(info.key, info.nkey);
}
connection.addIov(payload.buf, payload.len);
connection.setState(conn_mwrite);
cb::audit::document::add(connection, cb::audit::document::Operation::Read);
STATS_HIT(&connection, get);
update_topkeys(key, &connection);
state = State::Done;
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE GetCommandContext::noSuchItem() {
STATS_MISS(&connection, get);
MEMCACHED_COMMAND_GET(connection.getId(),
reinterpret_cast<const char*>(key.data()),
int(key.size()), -1, 0);
if (connection.isNoReply()) {
++connection.getBucket()
.responseCounters[PROTOCOL_BINARY_RESPONSE_KEY_ENOENT];
connection.setState(conn_new_cmd);
} else {
if (shouldSendKey()) {
mcbp_add_header(&connection,
PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
0, uint16_t(key.size()),
uint32_t(key.size()),
PROTOCOL_BINARY_RAW_BYTES);
connection.addIov(key.data(), key.size());
connection.setState(conn_mwrite);
} else {
mcbp_write_packet(&connection, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT);
}
}
state = State::Done;
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE GetCommandContext::step() {
ENGINE_ERROR_CODE ret;
do {
switch (state) {
case State::GetItem:
ret = getItem();
break;
case State::NoSuchItem:
ret = noSuchItem();
break;
case State::InflateItem:
ret = inflateItem();
break;
case State::SendResponse:
ret = sendResponse();
break;
case State::Done:
return ENGINE_SUCCESS;
}
} while (ret == ENGINE_SUCCESS);
return ret;
}
| 31.011299 | 86 | 0.599198 | cgvarela |
ed3d9f0b86d763cd5ba8c5ac2cab8633a9cf7b04 | 312 | cpp | C++ | uppdev/RMutex/RMutex.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppdev/RMutex/RMutex.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppdev/RMutex/RMutex.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include <Core/Core.h>
class Mutex {
int count;
void *threadid;
void Enter() {
if(self_thread == threadid) {
count++;
return;
}
Enter...
threadid = self_thread
count = 1;
}
void Leave() {
if(--count != 0) return;
Leave...
}
};
CONSOLE_APP_MAIN
{
}
| 11.555556 | 32 | 0.516026 | dreamsxin |
ed3dd0c8fa7bd7278b15a67812dfd032af549b22 | 3,521 | cpp | C++ | DataStructures/GraphMain.cpp | SimpleTechTalks/SimpleTechTalks | eefdb4cffc955f43535f4054d1558978ae0088e1 | [
"MIT"
] | null | null | null | DataStructures/GraphMain.cpp | SimpleTechTalks/SimpleTechTalks | eefdb4cffc955f43535f4054d1558978ae0088e1 | [
"MIT"
] | null | null | null | DataStructures/GraphMain.cpp | SimpleTechTalks/SimpleTechTalks | eefdb4cffc955f43535f4054d1558978ae0088e1 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
#include "GraphDefine.h"
void add_header (const char *line)
{
cout << "========================================================================" << endl;
cout << line << endl;
cout << "========================================================================" << endl;
}
void weightedGraphFunctionality ()
{
Graph g(7, false);
g.addEdgeWithWeight (0, 1, 3);
g.addEdgeWithWeight (0, 2, 2);
g.addEdgeWithWeight (0, 3, 6);
g.addEdgeWithWeight (2, 1, 2);
g.addEdgeWithWeight (1, 4, 6);
g.addEdgeWithWeight (1, 5, 1);
g.addEdgeWithWeight (4, 6, 1);
g.addEdgeWithWeight (5, 6, 5);
g.addEdgeWithWeight (3, 6, 2);
g.addEdgeWithWeight (5, 3, 1);
g.addEdgeWithWeight (1, 0, -5);
g.getEdgesIn2DFormat ();
add_header ("Finding shortest path in weighted graph from Node 0 using Bellman's Ford algo");
g.shortestPathInWeightedGraph (0);
add_header ("Finding shortest path in weighted graph from Node 0 using Dijkstra algo");
g.shortestPathInWeightedGraph_dijkstra (0);
}
int main ()
{
Graph g(5, true);
g.addEdge (1,2);
g.addEdge (0,2);
g.addEdge (3,2);
g.addEdge (4,2);
g.addEdge (1,3);
g.addEdge (1,4);
g.addEdge (1,5);
g.addEdge (1,7);
g.addEdge (1,0);
g.addEdge (2,2);
g.addEdge (3,2);
g.addEdge (4,2);
g.addEdge (5,2);
cout << "Graph has nodes: " << g.getNumberOfNodes () << endl;
cout << "Graph has edges: " << g.getNumberOfEdges () << endl;
add_header ("Printing Edges information in Adjecency Matrix Format.");
g.getEdgesIn2DFormat ();
add_header ("Printing BFS traversal of Graph");
g.BFS (4);
add_header ("Printing DFS traversal of Graph");
g.DFS (0);
add_header ("Checking Graph Connected Status");
cout << "Graph connected status: " << g.isConnectedGraph () << endl;
add_header ("Checking Graph Mother Vertex Information");
g.printMotherVertex ();
Graph g1(5, false);
g1.addEdge (1,2);
g1.addEdge (0,2);
g1.addEdge (3,2);
g1.addEdge (4,2);
g1.addEdge (1,3);
g1.addEdge (1,4);
g1.addEdge (1,5);
g1.addEdge (1,7);
g1.addEdge (1,0);
g1.addEdge (2,2);
g1.addEdge (3,2);
g1.addEdge (4,1);
g1.addEdge (5,2);
cout << "Graph has nodes: " << g1.getNumberOfNodes () << endl;
cout << "Graph has edges: " << g1.getNumberOfEdges () << endl;
add_header ("Printing Edges information in Adjecency Matrix Format.");
g1.getEdges ();
add_header ("Printing BFS traversal of Graph");
g1.BFS (0);
add_header ("Printing DFS traversal of Graph");
g1.DFS (0);
add_header ("Checking Graph Connected Status");
cout << "Graph connected status: " << g1.isConnectedGraph () << endl;
add_header ("Checking Graph Mother Vertex Information");
g1.printMotherVertex ();
add_header ("Sorting Graph Using Topological Sort");
Graph g2(11, false);
g2.addEdge (0,4);
g2.addEdge (1,0);
g2.addEdge (6,1);
g2.addEdge (1,2);
g2.addEdge (1,5);
g2.addEdge (2,3);
g2.addEdge (6,3);
g2.addEdge (3,7);
g2.addEdge (4,8);
g2.addEdge (5,8);
g2.addEdge (9,7);
g2.addEdge (8,9);
g2.addEdge (9,10);
g2.getEdgesIn2DFormat ();
g2.topologicalSort ();
add_header ("Finding shortest path from Node 6");
g2.shortestPathInUnweightedGraph (6);
add_header ("Finding shortest path from Node 0");
g2.shortestPathInUnweightedGraph (0);
weightedGraphFunctionality ();
}
| 31.4375 | 97 | 0.590457 | SimpleTechTalks |
ed3e3e3d927bc9cc698220827b30d7426542c5e4 | 510 | cpp | C++ | test/HttpClientTest.cpp | taozhijiang/roo | bea672b9274f91f4002a9742e096152b0d62f122 | [
"BSD-3-Clause"
] | null | null | null | test/HttpClientTest.cpp | taozhijiang/roo | bea672b9274f91f4002a9742e096152b0d62f122 | [
"BSD-3-Clause"
] | null | null | null | test/HttpClientTest.cpp | taozhijiang/roo | bea672b9274f91f4002a9742e096152b0d62f122 | [
"BSD-3-Clause"
] | 2 | 2019-08-23T02:31:42.000Z | 2020-05-02T00:12:36.000Z | #include <gmock/gmock.h>
#include <string>
#include <iostream>
#include <other/HttpClient.h>
using namespace ::testing;
using namespace roo;
TEST(HttpClientTest, HttpClientSmokeTest) {
const char* url_404 = "http://www.example.com/bb";
const char* url_200 = "http://www.example.com/index.html";
auto client = std::make_shared<HttpClient>();
int code = client->GetByHttp(url_404);
ASSERT_THAT(code, Ne(0));
code = client->GetByHttp(url_200);
ASSERT_THAT(code, Eq(0));
}
| 20.4 | 62 | 0.678431 | taozhijiang |
ed43fc400c22daaa49802b65ad3d11383d2432ff | 6,037 | cpp | C++ | constraintsolver/src/CGSolver.cpp | rapyuta-robotics/alica-supplementary-1 | 6ffd66d0a479d6a77c0caf1e6a41db75f2a95b9c | [
"MIT"
] | 1 | 2018-12-28T12:06:45.000Z | 2018-12-28T12:06:45.000Z | constraintsolver/src/CGSolver.cpp | rapyuta-robotics/alica-supplementary-1 | 6ffd66d0a479d6a77c0caf1e6a41db75f2a95b9c | [
"MIT"
] | 12 | 2018-05-28T05:27:04.000Z | 2021-11-23T07:52:35.000Z | constraintsolver/src/CGSolver.cpp | rapyuta-robotics/alica-supplementary-1 | 6ffd66d0a479d6a77c0caf1e6a41db75f2a95b9c | [
"MIT"
] | 3 | 2019-03-27T01:05:10.000Z | 2020-07-23T19:11:09.000Z | #include "constraintsolver/CGSolver.h"
#include "constraintsolver/GSolver.h"
#include <engine/AlicaEngine.h>
#include <engine/constraintmodul/ProblemDescriptor.h>
#include <engine/constraintmodul/VariableSyncModule.h>
#include <engine/model/Variable.h>
#include <autodiff/Term.h>
#include <autodiff/TermHolder.h>
#include <autodiff/Variable.h>
#include <limits>
#include <iostream>
namespace alica
{
namespace reasoner
{
using alica::VariableGrp;
using autodiff::TermHolder;
using autodiff::TermPtr;
CGSolver::CGSolver(AlicaEngine* ae)
: ISolver(ae)
, _lastUtil(0.0)
, _lastFEvals(0.0)
, _lastRuns(0.0)
, _gs(ae->getConfig())
, _sgs(ae->getConfig())
{
autodiff::Term::setAnd(autodiff::AndType::AND);
autodiff::Term::setOr(autodiff::OrType::MAX);
}
CGSolver::~CGSolver() {}
bool CGSolver::existsSolutionImpl(SolverContext* ctx, const std::vector<std::shared_ptr<ProblemDescriptor>>& calls)
{
TermHolder* holder = static_cast<TermHolder*>(ctx);
TermPtr constraint = holder->trueConstant();
const int dim = holder->getDim();
std::vector<Interval<double>> ranges(dim, Interval<double>(std::numeric_limits<double>::lowest() / 2, std::numeric_limits<double>::max() / 2));
int i = 0;
for (const autodiff::Variable* v : holder->getVariables()) {
if (!v->getRange().isValid()) {
return false;
}
ranges[i] = v->getRange();
++i;
}
for (const std::shared_ptr<ProblemDescriptor>& c : calls) {
if (dynamic_cast<autodiff::Term*>(c->getConstraint()) == nullptr) {
std::cerr << "CGSolver: Constraint type not compatible with selected solver" << std::endl;
return false;
}
constraint = constraint & TermPtr(static_cast<autodiff::Term*>(c->getConstraint()));
}
std::vector<Variant> serial_seeds;
int seed_num = getAlicaEngine()->getResultStore().getSeeds(holder->getVariables(), ranges, serial_seeds);
std::vector<double> seeds;
seeds.reserve(seed_num * dim);
std::transform(serial_seeds.begin(), serial_seeds.end(), std::back_inserter(seeds),
[](Variant v) -> double { return v.isDouble() ? v.getDouble() : std::numeric_limits<double>::quiet_NaN(); });
return _sgs.solveSimple(constraint, *holder, ranges, seeds);
}
bool CGSolver::getSolutionImpl(SolverContext* ctx, const std::vector<std::shared_ptr<ProblemDescriptor>>& calls, std::vector<double>& results)
{
TermHolder* holder = static_cast<TermHolder*>(ctx);
TermPtr constraint = holder->trueConstant();
TermPtr utility = holder->constant(1);
const int dim = holder->getDim();
// create lists of constraint variables and corresponding ranges
std::vector<Interval<double>> ranges(dim, Interval<double>(std::numeric_limits<double>::lowest() / 2, std::numeric_limits<double>::max() / 2));
int i = 0;
for (const autodiff::Variable* v : holder->getVariables()) {
if (!v->getRange().isValid()) {
std::cerr << "CGSolver: Ranges do not allow a solution!" << std::endl;
return false;
}
ranges[i] = v->getRange();
++i;
}
// get some utility significance threshold value if one exists
double usigVal = calls[0]->getUtilitySignificanceThreshold();
for (int i = 1; i < static_cast<int>(calls.size()); ++i) {
// TODO: fixed Values
if (calls.at(i)->isSettingUtilitySignificanceThreshold()) {
usigVal = calls[i]->getUtilitySignificanceThreshold();
}
}
double sufficientUtility = 0.0;
for (const std::shared_ptr<ProblemDescriptor>& c : calls) {
TermPtr constraintTerm = dynamic_cast<autodiff::Term*>(c->getConstraint());
if (constraintTerm.get() == nullptr) {
std::cerr << "CGSolver: Constraint type not compatible with selected solver or constraint does not exist." << std::endl;
return false;
}
constraint = constraint & constraintTerm;
TermPtr utilityTerm = dynamic_cast<autodiff::Term*>(c->getUtility());
if (utilityTerm.get() == nullptr) {
std::cerr << "CGSolver: Utility type not compatible with selected solver or utility does not exist." << std::endl;
return false;
}
utility = utility + utilityTerm;
sufficientUtility += c->getUtilitySufficiencyThreshold();
}
TermPtr all = holder->constraintUtility(constraint, utility);
std::vector<Variant> serial_seeds;
int seed_num = getAlicaEngine()->getResultStore().getSeeds(holder->getVariables(), ranges, serial_seeds);
std::vector<double> seeds;
seeds.reserve(seed_num * dim);
std::transform(serial_seeds.begin(), serial_seeds.end(), std::back_inserter(seeds),
[](Variant v) -> double { return v.isDouble() ? v.getDouble() : std::numeric_limits<double>::quiet_NaN(); });
#ifdef CGSolver_DEBUG
for (int i = 0; i < seeds.size(); i += dim) {
std::cout << "----CGS: seed " << (i / dim) << " ";
for (int j = 0; j < dim; ++j) {
std::cout << seeds[i + j] << " ";
}
std::cout << endl;
}
#endif
double util = 0;
bool solved;
{ // for lock_guard
std::lock_guard<std::mutex> lock(_mtx);
_gs.setUtilitySignificanceThreshold(usigVal);
solved = _gs.solve(all, *holder, ranges, seeds, sufficientUtility, util, results);
}
_lastUtil = util;
_lastFEvals = _gs.getFEvals();
_lastRuns = _gs.getRuns();
#ifdef CGSolver_DEBUG
std::cout << "CGS: result ";
for (int i = 0; i < results.size(); ++i) {
std::cout << results[i] << " ";
}
std::cout << std::endl;
#endif
return solved;
}
SolverVariable* CGSolver::createVariable(int64_t id, SolverContext* ctx)
{
return static_cast<TermHolder*>(ctx)->createVariable(id);
}
std::unique_ptr<SolverContext> CGSolver::createSolverContext()
{
return std::unique_ptr<SolverContext>(new TermHolder());
}
} // namespace reasoner
} // namespace alica
| 34.497143 | 147 | 0.640219 | rapyuta-robotics |
ed47362f62e368f1af948cc9403e4f0db1e602da | 806 | hpp | C++ | include/yaul/tml/numeric_cast_fwd.hpp | ptomulik/yaul-tml | 2b8bf3f88742996bd8199375678cdebd6e3206d9 | [
"BSL-1.0"
] | null | null | null | include/yaul/tml/numeric_cast_fwd.hpp | ptomulik/yaul-tml | 2b8bf3f88742996bd8199375678cdebd6e3206d9 | [
"BSL-1.0"
] | 2 | 2015-03-07T13:52:46.000Z | 2015-03-07T13:53:14.000Z | include/yaul/tml/numeric_cast_fwd.hpp | ptomulik/yaul-tml | 2b8bf3f88742996bd8199375678cdebd6e3206d9 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2014, Pawel Tomulik <ptomulik@meil.pw.edu.pl>
//
// 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)
// yaul/tml/numeric_cast_fwd.hpp
/** // doc: yaul/tml/numeric_cast_fwd.hpp {{{
* \file yaul/tml/numeric_cast_fwd.hpp
* \brief Forward declarations for \ref yaul/tml/numeric_cast.hpp
*/ // }}}
#ifndef YAUL_TML_NUMERIC_CAST_FWD_HPP
#define YAUL_TML_NUMERIC_CAST_FWD_HPP
namespace yaul { namespace tml {
template <class FromTag, class ToTag>
struct numeric_cast
{
template<class N>
struct apply;
};
} } // end namespace yaul::tml
#endif /* YAUL_TML_NUMERIC_CAST_FWD_HPP */
// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:
| 28.785714 | 65 | 0.729529 | ptomulik |
ed4b7d4ef2ca4aff73d6d0a5e7254fd29d210efa | 50,241 | cpp | C++ | control/mpc_follower/src/mpc_follower_core.cpp | loop-perception/AutowareArchitectureProposal.iv | 5d8dff0db51634f0c42d2a3e87ca423fbee84348 | [
"Apache-2.0"
] | 1 | 2022-03-09T05:53:04.000Z | 2022-03-09T05:53:04.000Z | control/mpc_follower/src/mpc_follower_core.cpp | loop-perception/AutowareArchitectureProposal.iv | 5d8dff0db51634f0c42d2a3e87ca423fbee84348 | [
"Apache-2.0"
] | 4 | 2022-01-07T21:21:04.000Z | 2022-03-14T21:25:37.000Z | control/mpc_follower/src/mpc_follower_core.cpp | loop-perception/AutowareArchitectureProposal.iv | 5d8dff0db51634f0c42d2a3e87ca423fbee84348 | [
"Apache-2.0"
] | 2 | 2021-03-09T00:20:39.000Z | 2021-04-16T10:23:36.000Z | // Copyright 2018-2019 Autoware Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mpc_follower/mpc_follower_core.hpp"
#include <tf2_ros/create_timer_ros.h>
#include <algorithm>
#include <deque>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#define DEG2RAD 3.1415926535 / 180.0
#define RAD2DEG 180.0 / 3.1415926535
using namespace std::literals::chrono_literals;
namespace
{
template <typename T>
void update_param(
const std::vector<rclcpp::Parameter> & parameters, const std::string & name, T & value)
{
auto it = std::find_if(
parameters.cbegin(), parameters.cend(),
[&name](const rclcpp::Parameter & parameter) { return parameter.get_name() == name; });
if (it != parameters.cend()) {
value = it->template get_value<T>();
}
}
} // namespace
MPCFollower::MPCFollower(const rclcpp::NodeOptions & node_options)
: Node("mpc_follower", node_options), tf_buffer_(this->get_clock()), tf_listener_(tf_buffer_)
{
using std::placeholders::_1;
ctrl_period_ = declare_parameter("ctrl_period", 0.03);
enable_path_smoothing_ = declare_parameter("enable_path_smoothing", true);
path_filter_moving_ave_num_ = declare_parameter("path_filter_moving_ave_num", 35);
curvature_smoothing_num_traj_ = declare_parameter("curvature_smoothing_num_traj", 1);
curvature_smoothing_num_ref_steer_ = declare_parameter("curvature_smoothing_num_ref_steer", 35);
traj_resample_dist_ = declare_parameter("traj_resample_dist", 0.1); // [m]
admissible_position_error_ = declare_parameter("admissible_position_error", 5.0);
admissible_yaw_error_rad_ = declare_parameter("admissible_yaw_error_rad", M_PI_2);
use_steer_prediction_ = declare_parameter("use_steer_prediction", false);
mpc_param_.steer_tau = declare_parameter("vehicle_model_steer_tau", 0.1);
/* stop state parameters */
stop_state_entry_ego_speed_ = declare_parameter("stop_state_entry_ego_speed", 0.2); // [m]
stop_state_entry_target_speed_ = declare_parameter("stop_state_entry_target_speed", 0.1); // [m]
/* mpc parameters */
double steer_lim_deg, steer_rate_lim_dps;
steer_lim_deg = declare_parameter("steer_lim_deg", 35.0);
steer_rate_lim_dps = declare_parameter("steer_rate_lim_dps", 150.0);
steer_lim_ = steer_lim_deg * DEG2RAD;
steer_rate_lim_ = steer_rate_lim_dps * DEG2RAD;
const auto vehicle_info = vehicle_info_util::VehicleInfoUtil(*this).getVehicleInfo();
wheelbase_ = vehicle_info.wheel_base_m;
/* vehicle model setup */
vehicle_model_type_ = declare_parameter("vehicle_model_type", "kinematics");
if (vehicle_model_type_ == "kinematics") {
vehicle_model_ptr_ =
std::make_shared<KinematicsBicycleModel>(wheelbase_, steer_lim_, mpc_param_.steer_tau);
} else if (vehicle_model_type_ == "kinematics_no_delay") {
vehicle_model_ptr_ = std::make_shared<KinematicsBicycleModelNoDelay>(wheelbase_, steer_lim_);
} else if (vehicle_model_type_ == "dynamics") {
double mass_fl = declare_parameter("mass_fl", 600);
double mass_fr = declare_parameter("mass_fr", 600);
double mass_rl = declare_parameter("mass_rl", 600);
double mass_rr = declare_parameter("mass_rr", 600);
double cf = declare_parameter("cf", 155494.663);
double cr = declare_parameter("cr", 155494.663);
// vehicle_model_ptr_ is only assigned in ctor, so parameter value have to be passed at init
// time // NOLINT
vehicle_model_ptr_ = std::make_shared<DynamicsBicycleModel>(
wheelbase_, mass_fl, mass_fr, mass_rl, mass_rr, cf, cr);
} else {
RCLCPP_ERROR(get_logger(), "vehicle_model_type is undefined");
}
/* QP solver setup */
const std::string qp_solver_type = declare_parameter("qp_solver_type", "unconstraint_fast");
if (qp_solver_type == "unconstraint_fast") {
qpsolver_ptr_ = std::make_shared<QPSolverEigenLeastSquareLLT>();
} else if (qp_solver_type == "osqp") {
qpsolver_ptr_ = std::make_shared<QPSolverOSQP>(get_logger());
} else {
RCLCPP_ERROR(get_logger(), "qp_solver_type is undefined");
}
/* delay compensation */
{
const double delay_tmp = declare_parameter("input_delay", 0.0);
const int delay_step = std::round(delay_tmp / ctrl_period_);
mpc_param_.input_delay = delay_step * ctrl_period_;
input_buffer_ = std::deque<double>(delay_step, 0.0);
}
/* initialize lowpass filter */
{
const double steering_lpf_cutoff_hz = declare_parameter("steering_lpf_cutoff_hz", 3.0);
const double error_deriv_lpf_cutoff_hz = declare_parameter("error_deriv_lpf_cutoff_hz", 5.0);
lpf_steering_cmd_.initialize(ctrl_period_, steering_lpf_cutoff_hz);
lpf_lateral_error_.initialize(ctrl_period_, error_deriv_lpf_cutoff_hz);
lpf_yaw_error_.initialize(ctrl_period_, error_deriv_lpf_cutoff_hz);
}
/* set up ros system */
initTimer(ctrl_period_);
pub_ctrl_cmd_ =
create_publisher<autoware_control_msgs::msg::ControlCommandStamped>("~/output/control_raw", 1);
pub_predicted_traj_ =
create_publisher<autoware_planning_msgs::msg::Trajectory>("~/output/predicted_trajectory", 1);
sub_ref_path_ = create_subscription<autoware_planning_msgs::msg::Trajectory>(
"~/input/reference_trajectory", rclcpp::QoS{1},
std::bind(&MPCFollower::onTrajectory, this, _1));
sub_current_vel_ = create_subscription<geometry_msgs::msg::TwistStamped>(
"~/input/current_velocity", rclcpp::QoS{1}, std::bind(&MPCFollower::onVelocity, this, _1));
sub_steering_ = create_subscription<autoware_vehicle_msgs::msg::Steering>(
"~/input/current_steering", rclcpp::QoS{1}, std::bind(&MPCFollower::onSteering, this, _1));
/* for debug */
pub_debug_marker_ = create_publisher<visualization_msgs::msg::MarkerArray>("~/debug/markers", 10);
pub_debug_mpc_calc_time_ =
create_publisher<autoware_debug_msgs::msg::Float32Stamped>("~/debug/mpc_calc_time", 1);
pub_debug_values_ =
create_publisher<autoware_debug_msgs::msg::Float32MultiArrayStamped>("~/debug/debug_values", 1);
pub_debug_steer_cmd_ =
create_publisher<autoware_vehicle_msgs::msg::Steering>("~/debug/steering_cmd", 1);
// TODO(Frederik.Beaujean) ctor is too long, should factor out parameter declarations
declareMPCparameters();
/* get parameter updates */
set_param_res_ =
this->add_on_set_parameters_callback(std::bind(&MPCFollower::paramCallback, this, _1));
}
MPCFollower::~MPCFollower()
{
autoware_control_msgs::msg::ControlCommand stop_cmd = getStopControlCommand();
publishCtrlCmd(stop_cmd);
}
void MPCFollower::onTimer()
{
updateCurrentPose();
if (!checkData()) {
publishCtrlCmd(getStopControlCommand());
return;
}
autoware_control_msgs::msg::ControlCommand ctrl_cmd;
if (!is_ctrl_cmd_prev_initialized_) {
ctrl_cmd_prev_ = getInitialControlCommand();
is_ctrl_cmd_prev_initialized_ = true;
}
const bool is_mpc_solved = calculateMPC(&ctrl_cmd);
if (isStoppedState()) {
// Reset input buffer
for (auto & value : input_buffer_) {
value = ctrl_cmd_prev_.steering_angle;
}
// Use previous command value as previous raw steer command
raw_steer_cmd_prev_ = ctrl_cmd_prev_.steering_angle;
publishCtrlCmd(ctrl_cmd_prev_);
return;
}
if (!is_mpc_solved) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (5000ms).count(), "MPC is not solved. publish 0 velocity.");
ctrl_cmd = getStopControlCommand();
}
ctrl_cmd_prev_ = ctrl_cmd;
publishCtrlCmd(ctrl_cmd);
}
bool MPCFollower::checkData()
{
if (!vehicle_model_ptr_ || !qpsolver_ptr_) {
RCLCPP_DEBUG(
get_logger(), "vehicle_model = %d, qp_solver = %d", vehicle_model_ptr_ != nullptr,
qpsolver_ptr_ != nullptr);
return false;
}
if (!current_pose_ptr_ || !current_velocity_ptr_ || !current_steer_ptr_) {
RCLCPP_DEBUG(
get_logger(), "waiting data. pose = %d, velocity = %d, steer = %d",
current_pose_ptr_ != nullptr, current_velocity_ptr_ != nullptr,
current_steer_ptr_ != nullptr);
return false;
}
if (ref_traj_.size() == 0) {
RCLCPP_DEBUG(get_logger(), "trajectory size is zero.");
return false;
}
return true;
}
// TODO(Frederik.Beaujean) This method is too long, could be refactored into many smaller units
bool MPCFollower::calculateMPC(autoware_control_msgs::msg::ControlCommand * ctrl_cmd)
{
auto start = std::chrono::system_clock::now();
if (!ctrl_cmd) {
return false;
}
/* recalculate velocity from ego-velocity with dynamics */
MPCTrajectory reference_trajectory =
applyVelocityDynamicsFilter(ref_traj_, current_velocity_ptr_->twist.linear.x);
MPCData mpc_data;
if (!getData(reference_trajectory, &mpc_data)) {
RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), (1000ms).count(), "fail to get Data.");
return false;
}
/* define initial state for error dynamics */
Eigen::VectorXd x0 = getInitialState(mpc_data);
/* delay compensation */
if (!updateStateForDelayCompensation(reference_trajectory, mpc_data.nearest_time, &x0)) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(),
"updateStateForDelayCompensation failed. stop computation.");
return false;
}
/* resample ref_traj with mpc sampling time */
MPCTrajectory mpc_resampled_ref_traj;
const double mpc_start_time = mpc_data.nearest_time + mpc_param_.input_delay;
if (!resampleMPCTrajectoryByTime(mpc_start_time, reference_trajectory, &mpc_resampled_ref_traj)) {
RCLCPP_WARN_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "trajectory resampling failed.");
return false;
}
/* generate mpc matrix : predict equation Xec = Aex * x0 + Bex * Uex + Wex */
MPCMatrix mpc_matrix = generateMPCMatrix(mpc_resampled_ref_traj);
/* solve quadratic optimization */
Eigen::VectorXd Uex;
if (!executeOptimization(mpc_matrix, x0, &Uex)) {
RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), (1000ms).count(), "optimization failed.");
return false;
}
/* apply saturation and filter */
const double u_saturated = std::max(std::min(Uex(0), steer_lim_), -steer_lim_);
const double u_filtered = lpf_steering_cmd_.filter(u_saturated);
/* set control command */
{
const auto & dt = mpc_param_.prediction_dt;
const int prev_idx = std::max(0, static_cast<int>(mpc_data.nearest_idx) - 1);
ctrl_cmd->steering_angle = u_filtered;
ctrl_cmd->steering_angle_velocity = (Uex(1) - Uex(0)) / dt;
ctrl_cmd->velocity = ref_traj_.vx[mpc_data.nearest_idx];
ctrl_cmd->acceleration = (ref_traj_.vx[mpc_data.nearest_idx] - ref_traj_.vx[prev_idx]) / dt;
}
storeSteerCmd(u_filtered);
/* save input to buffer for delay compensation*/
input_buffer_.push_back(ctrl_cmd->steering_angle);
input_buffer_.pop_front();
raw_steer_cmd_pprev_ = raw_steer_cmd_prev_;
raw_steer_cmd_prev_ = Uex(0);
/* ---------- DEBUG ---------- */
const builtin_interfaces::msg::Time & stamp = current_trajectory_ptr_->header.stamp;
/* publish predicted trajectory */
{
Eigen::VectorXd Xex = mpc_matrix.Aex * x0 + mpc_matrix.Bex * Uex + mpc_matrix.Wex;
MPCTrajectory mpc_predicted_traj;
const auto & traj = mpc_resampled_ref_traj;
for (int i = 0; i < mpc_param_.prediction_horizon; ++i) {
const int DIM_X = vehicle_model_ptr_->getDimX();
const double lat_error = Xex(i * DIM_X);
const double yaw_error = Xex(i * DIM_X + 1);
const double x = traj.x[i] - std::sin(traj.yaw[i]) * lat_error;
const double y = traj.y[i] + std::cos(traj.yaw[i]) * lat_error;
const double z = traj.z[i];
const double yaw = traj.yaw[i] + yaw_error;
const double vx = traj.vx[i];
const double k = traj.k[i];
const double smooth_k = traj.smooth_k[i];
const double relative_time = traj.relative_time[i];
mpc_predicted_traj.push_back(x, y, z, yaw, vx, k, smooth_k, relative_time);
}
autoware_planning_msgs::msg::Trajectory predicted_traj;
predicted_traj.header.stamp = current_trajectory_ptr_->header.stamp;
predicted_traj.header.frame_id = current_trajectory_ptr_->header.frame_id;
MPCUtils::convertToAutowareTrajectory(mpc_predicted_traj, &predicted_traj);
pub_predicted_traj_->publish(predicted_traj);
auto markers = MPCUtils::convertTrajToMarker(
mpc_predicted_traj, "predicted_trajectory", 0.99, 0.99, 0.99, 0.2,
current_trajectory_ptr_->header.frame_id, stamp);
pub_debug_marker_->publish(markers);
}
/* publish debug values */
{
double curr_v = current_velocity_ptr_->twist.linear.x;
double nearest_k = reference_trajectory.k[mpc_data.nearest_idx];
double nearest_smooth_k = reference_trajectory.smooth_k[mpc_data.nearest_idx];
double steer_cmd = ctrl_cmd->steering_angle;
autoware_debug_msgs::msg::Float32MultiArrayStamped d;
d.stamp = stamp;
const auto & ps = mpc_data.predicted_steer;
const auto & W = wheelbase_;
d.data.push_back(steer_cmd); // [0] final steering command (MPC + LPF)
d.data.push_back(Uex(0)); // [1] mpc calculation result
d.data.push_back(mpc_matrix.Uref_ex(0)); // [2] feedforward steering value
d.data.push_back(std::atan(nearest_smooth_k * W)); // [3] feedforward steering value raw
d.data.push_back(mpc_data.steer); // [4] current steering angle
d.data.push_back(mpc_data.lateral_err); // [5] lateral error
d.data.push_back(tf2::getYaw(current_pose_ptr_->pose.orientation)); // [6] current_pose yaw
d.data.push_back(tf2::getYaw(mpc_data.nearest_pose.orientation)); // [7] nearest_pose yaw
d.data.push_back(mpc_data.yaw_err); // [8] yaw error
d.data.push_back(ctrl_cmd->velocity); // [9] command velocities
d.data.push_back(current_velocity_ptr_->twist.linear.x); // [10] measured velocity
d.data.push_back(curr_v * tan(steer_cmd) / W); // [11] angvel from steer command
d.data.push_back(curr_v * tan(mpc_data.steer) / W); // [12] angvel from measured steer
d.data.push_back(curr_v * nearest_smooth_k); // [13] angvel from path curvature
d.data.push_back(nearest_smooth_k); // [14] nearest path curvature (used for feedforward)
d.data.push_back(nearest_k); // [15] nearest path curvature (not smoothed)
d.data.push_back(ps); // [16] predicted steer
d.data.push_back(curr_v * tan(ps) / W); // [17] angvel from predicted steer
pub_debug_values_->publish(d);
}
/* publish computing time */
{
auto end = std::chrono::system_clock::now();
auto t = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() * 1.0e-6;
autoware_debug_msgs::msg::Float32Stamped calc_time;
calc_time.stamp = stamp;
calc_time.data = t; // [ms]
pub_debug_mpc_calc_time_->publish(calc_time);
}
return true;
}
void MPCFollower::resetPrevResult()
{
raw_steer_cmd_prev_ = current_steer_ptr_->data;
raw_steer_cmd_pprev_ = current_steer_ptr_->data;
}
bool MPCFollower::getData(const MPCTrajectory & traj, MPCData * data)
{
static constexpr auto duration = (5000ms).count();
if (!MPCUtils::calcNearestPoseInterp(
traj, current_pose_ptr_->pose, &(data->nearest_pose), &(data->nearest_idx),
&(data->nearest_time), get_logger(), *get_clock())) {
// reset previous MPC result
// Note: When a large deviation from the trajectory occurs, the optimization stops and
// the vehicle will return to the path by re-planning the trajectory or external operation.
// After the recovery, the previous value of the optimization may deviate greatly from
// the actual steer angle, and it may make the optimization result unstable.
resetPrevResult();
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), duration,
"calculateMPC: error in calculating nearest pose. stop mpc.");
return false;
}
/* get data */
data->steer = current_steer_ptr_->data;
data->lateral_err = MPCUtils::calcLateralError(current_pose_ptr_->pose, data->nearest_pose);
data->yaw_err = MPCUtils::normalizeRadian(
tf2::getYaw(current_pose_ptr_->pose.orientation) - tf2::getYaw(data->nearest_pose.orientation));
/* get predicted steer */
if (!steer_prediction_prev_) {
steer_prediction_prev_ = std::make_shared<double>(current_steer_ptr_->data);
}
data->predicted_steer = calcSteerPrediction();
*steer_prediction_prev_ = data->predicted_steer;
/* check error limit */
const double dist_err = MPCUtils::calcDist2d(current_pose_ptr_->pose, data->nearest_pose);
if (dist_err > admissible_position_error_) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), duration, "position error is over limit. error = %fm, limit: %fm",
dist_err, admissible_position_error_);
return false;
}
/* check yaw error limit */
if (std::fabs(data->yaw_err) > admissible_yaw_error_rad_) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), duration, "yaw error is over limit. error = %f deg, limit %f deg",
RAD2DEG * data->yaw_err, RAD2DEG * admissible_yaw_error_rad_);
return false;
}
/* check trajectory time length */
auto end_time = data->nearest_time + mpc_param_.input_delay + getPredictionTime();
if (end_time > traj.relative_time.back()) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "path is too short for prediction.");
return false;
}
return true;
}
double MPCFollower::calcSteerPrediction()
{
auto t_start = time_prev_;
auto t_end = this->now();
time_prev_ = t_end;
const double duration = (t_end - t_start).seconds();
const double time_constant = mpc_param_.steer_tau;
const double initial_response = std::exp(-duration / time_constant) * (*steer_prediction_prev_);
if (ctrl_cmd_vec_.size() <= 2) {
return initial_response;
}
return initial_response + getSteerCmdSum(t_start, t_end, time_constant);
}
double MPCFollower::getSteerCmdSum(
const rclcpp::Time & t_start, const rclcpp::Time & t_end, const double time_constant)
{
if (ctrl_cmd_vec_.size() <= 2) {
return 0.0;
}
// Find first index of control command container
size_t idx = 1;
while (t_start > rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp)) {
if ((idx + 1) >= ctrl_cmd_vec_.size()) {
return 0.0;
}
++idx;
}
// Compute steer command input response
double steer_sum = 0.0;
auto t = t_start;
while (t_end > rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp)) {
const double duration = (rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp) - t).seconds();
t = rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp);
steer_sum +=
(1 - std::exp(-duration / time_constant)) * ctrl_cmd_vec_.at(idx - 1).control.steering_angle;
++idx;
if (idx >= ctrl_cmd_vec_.size()) {
break;
}
}
const double duration = (t_end - t).seconds();
steer_sum +=
(1 - std::exp(-duration / time_constant)) * ctrl_cmd_vec_.at(idx - 1).control.steering_angle;
return steer_sum;
}
void MPCFollower::storeSteerCmd(const double steer)
{
const auto time_delayed = this->now() + rclcpp::Duration::from_seconds(mpc_param_.input_delay);
autoware_control_msgs::msg::ControlCommandStamped cmd;
cmd.header.stamp = time_delayed;
cmd.control.steering_angle = steer;
// store published ctrl cmd
ctrl_cmd_vec_.emplace_back(cmd);
if (ctrl_cmd_vec_.size() <= 2) {
return;
}
// remove unused ctrl cmd
constexpr double store_time = 0.3;
if (
(time_delayed - ctrl_cmd_vec_.at(1).header.stamp).seconds() >
mpc_param_.input_delay + store_time) {
ctrl_cmd_vec_.erase(ctrl_cmd_vec_.begin());
}
}
bool MPCFollower::resampleMPCTrajectoryByTime(
double ts, const MPCTrajectory & input, MPCTrajectory * output) const
{
std::vector<double> mpc_time_v;
for (int i = 0; i < mpc_param_.prediction_horizon; ++i) {
mpc_time_v.push_back(ts + i * mpc_param_.prediction_dt);
}
if (!MPCUtils::linearInterpMPCTrajectory(input.relative_time, input, mpc_time_v, output)) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), const_cast<rclcpp::Clock &>(*get_clock()), (1000ms).count(),
"calculateMPC: mpc resample error. stop mpc calculation. check code!");
return false;
}
return true;
}
Eigen::VectorXd MPCFollower::getInitialState(const MPCData & data)
{
const int DIM_X = vehicle_model_ptr_->getDimX();
Eigen::VectorXd x0 = Eigen::VectorXd::Zero(DIM_X);
const auto & lat_err = data.lateral_err;
const auto & steer = use_steer_prediction_ ? data.predicted_steer : data.steer;
const auto & yaw_err = data.yaw_err;
if (vehicle_model_type_ == "kinematics") {
x0 << lat_err, yaw_err, steer;
} else if (vehicle_model_type_ == "kinematics_no_delay") {
x0 << lat_err, yaw_err;
} else if (vehicle_model_type_ == "dynamics") {
double dlat = (lat_err - lateral_error_prev_) / ctrl_period_;
double dyaw = (yaw_err - yaw_error_prev_) / ctrl_period_;
lateral_error_prev_ = lat_err;
yaw_error_prev_ = yaw_err;
dlat = lpf_lateral_error_.filter(dlat);
dyaw = lpf_yaw_error_.filter(dyaw);
x0 << lat_err, dlat, yaw_err, dyaw;
RCLCPP_DEBUG(get_logger(), "(before lpf) dot_lat_err = %f, dot_yaw_err = %f", dlat, dyaw);
RCLCPP_DEBUG(get_logger(), "(after lpf) dot_lat_err = %f, dot_yaw_err = %f", dlat, dyaw);
} else {
RCLCPP_ERROR(get_logger(), "vehicle_model_type is undefined");
}
return x0;
}
bool MPCFollower::updateStateForDelayCompensation(
const MPCTrajectory & traj, const double & start_time, Eigen::VectorXd * x)
{
const int DIM_X = vehicle_model_ptr_->getDimX();
const int DIM_U = vehicle_model_ptr_->getDimU();
const int DIM_Y = vehicle_model_ptr_->getDimY();
Eigen::MatrixXd Ad(DIM_X, DIM_X);
Eigen::MatrixXd Bd(DIM_X, DIM_U);
Eigen::MatrixXd Wd(DIM_X, 1);
Eigen::MatrixXd Cd(DIM_Y, DIM_X);
Eigen::MatrixXd x_curr = *x;
double mpc_curr_time = start_time;
for (unsigned int i = 0; i < input_buffer_.size(); ++i) {
double k = 0.0;
double v = 0.0;
if (
!LinearInterpolate::interpolate(traj.relative_time, traj.k, mpc_curr_time, k) ||
!LinearInterpolate::interpolate(traj.relative_time, traj.vx, mpc_curr_time, v)) {
RCLCPP_ERROR(
get_logger(),
"mpc resample error at delay compensation, stop mpc calculation. check code!");
return false;
}
/* get discrete state matrix A, B, C, W */
vehicle_model_ptr_->setVelocity(v);
vehicle_model_ptr_->setCurvature(k);
vehicle_model_ptr_->calculateDiscreteMatrix(Ad, Bd, Cd, Wd, ctrl_period_);
Eigen::MatrixXd ud = Eigen::MatrixXd::Zero(DIM_U, 1);
ud(0, 0) = input_buffer_.at(i); // for steering input delay
x_curr = Ad * x_curr + Bd * ud + Wd;
mpc_curr_time += ctrl_period_;
}
*x = x_curr;
return true;
}
MPCTrajectory MPCFollower::applyVelocityDynamicsFilter(const MPCTrajectory & input, const double v0)
{
int nearest_idx = MPCUtils::calcNearestIndex(input, current_pose_ptr_->pose);
if (nearest_idx < 0) {
return input;
}
const double acc_lim = mpc_param_.acceleration_limit;
const double tau = mpc_param_.velocity_time_constant;
MPCTrajectory output = input;
MPCUtils::dynamicSmoothingVelocity(nearest_idx, v0, acc_lim, tau, &output);
const double t_ext = 100.0; // extra time to prevent mpc calculation failure due to short time
const double t_end = output.relative_time.back() + getPredictionTime() + t_ext;
const double v_end = 0.0;
output.vx.back() = v_end; // set for end point
output.push_back(
output.x.back(), output.y.back(), output.z.back(), output.yaw.back(), v_end, output.k.back(),
output.smooth_k.back(), t_end);
return output;
}
/*
* predict equation: Xec = Aex * x0 + Bex * Uex + Wex
* cost function: J = Xex' * Qex * Xex + (Uex - Uref)' * R1ex * (Uex - Uref_ex) + Uex' * R2ex * Uex
* Qex = diag([Q,Q,...]), R1ex = diag([R,R,...])
*/
MPCFollower::MPCMatrix MPCFollower::generateMPCMatrix(const MPCTrajectory & reference_trajectory)
{
using Eigen::MatrixXd;
const int N = mpc_param_.prediction_horizon;
const double DT = mpc_param_.prediction_dt;
const int DIM_X = vehicle_model_ptr_->getDimX();
const int DIM_U = vehicle_model_ptr_->getDimU();
const int DIM_Y = vehicle_model_ptr_->getDimY();
MPCMatrix m;
m.Aex = MatrixXd::Zero(DIM_X * N, DIM_X);
m.Bex = MatrixXd::Zero(DIM_X * N, DIM_U * N);
m.Wex = MatrixXd::Zero(DIM_X * N, 1);
m.Cex = MatrixXd::Zero(DIM_Y * N, DIM_X * N);
m.Qex = MatrixXd::Zero(DIM_Y * N, DIM_Y * N);
m.R1ex = MatrixXd::Zero(DIM_U * N, DIM_U * N);
m.R2ex = MatrixXd::Zero(DIM_U * N, DIM_U * N);
m.Uref_ex = MatrixXd::Zero(DIM_U * N, 1);
/* weight matrix depends on the vehicle model */
MatrixXd Q = MatrixXd::Zero(DIM_Y, DIM_Y);
MatrixXd R = MatrixXd::Zero(DIM_U, DIM_U);
MatrixXd Q_adaptive = MatrixXd::Zero(DIM_Y, DIM_Y);
MatrixXd R_adaptive = MatrixXd::Zero(DIM_U, DIM_U);
MatrixXd Ad(DIM_X, DIM_X);
MatrixXd Bd(DIM_X, DIM_U);
MatrixXd Wd(DIM_X, 1);
MatrixXd Cd(DIM_Y, DIM_X);
MatrixXd Uref(DIM_U, 1);
constexpr double ep = 1.0e-3; // large enough to ignore velocity noise
/* predict dynamics for N times */
for (int i = 0; i < N; ++i) {
const double ref_vx = reference_trajectory.vx[i];
const double ref_vx_squared = ref_vx * ref_vx;
// curvature will be 0 when vehicle stops
const double ref_k = reference_trajectory.k[i] * sign_vx_;
const double ref_smooth_k = reference_trajectory.smooth_k[i] * sign_vx_;
/* get discrete state matrix A, B, C, W */
vehicle_model_ptr_->setVelocity(ref_vx);
vehicle_model_ptr_->setCurvature(ref_k);
vehicle_model_ptr_->calculateDiscreteMatrix(Ad, Bd, Cd, Wd, DT);
Q = Eigen::MatrixXd::Zero(DIM_Y, DIM_Y);
R = Eigen::MatrixXd::Zero(DIM_U, DIM_U);
Q(0, 0) = getWeightLatError(ref_k);
Q(1, 1) = getWeightHeadingError(ref_k);
R(0, 0) = getWeightSteerInput(ref_k);
Q_adaptive = Q;
R_adaptive = R;
if (i == N - 1) {
Q_adaptive(0, 0) = mpc_param_.weight_terminal_lat_error;
Q_adaptive(1, 1) = mpc_param_.weight_terminal_heading_error;
}
Q_adaptive(1, 1) += ref_vx_squared * getWeightHeadingErrorSqVel(ref_k);
R_adaptive(0, 0) += ref_vx_squared * getWeightSteerInputSqVel(ref_k);
/* update mpc matrix */
int idx_x_i = i * DIM_X;
int idx_x_i_prev = (i - 1) * DIM_X;
int idx_u_i = i * DIM_U;
int idx_y_i = i * DIM_Y;
if (i == 0) {
m.Aex.block(0, 0, DIM_X, DIM_X) = Ad;
m.Bex.block(0, 0, DIM_X, DIM_U) = Bd;
m.Wex.block(0, 0, DIM_X, 1) = Wd;
} else {
m.Aex.block(idx_x_i, 0, DIM_X, DIM_X) = Ad * m.Aex.block(idx_x_i_prev, 0, DIM_X, DIM_X);
for (int j = 0; j < i; ++j) {
int idx_u_j = j * DIM_U;
m.Bex.block(idx_x_i, idx_u_j, DIM_X, DIM_U) =
Ad * m.Bex.block(idx_x_i_prev, idx_u_j, DIM_X, DIM_U);
}
m.Wex.block(idx_x_i, 0, DIM_X, 1) = Ad * m.Wex.block(idx_x_i_prev, 0, DIM_X, 1) + Wd;
}
m.Bex.block(idx_x_i, idx_u_i, DIM_X, DIM_U) = Bd;
m.Cex.block(idx_y_i, idx_x_i, DIM_Y, DIM_X) = Cd;
m.Qex.block(idx_y_i, idx_y_i, DIM_Y, DIM_Y) = Q_adaptive;
m.R1ex.block(idx_u_i, idx_u_i, DIM_U, DIM_U) = R_adaptive;
/* get reference input (feed-forward) */
vehicle_model_ptr_->setCurvature(ref_smooth_k);
vehicle_model_ptr_->calculateReferenceInput(Uref);
if (std::fabs(Uref(0, 0)) < DEG2RAD * mpc_param_.zero_ff_steer_deg) {
Uref(0, 0) = 0.0; // ignore curvature noise
}
m.Uref_ex.block(i * DIM_U, 0, DIM_U, 1) = Uref;
}
/* add lateral jerk : weight for (v * {u(i) - u(i-1)} )^2 */
for (int i = 0; i < N - 1; ++i) {
const double ref_vx = reference_trajectory.vx[i];
sign_vx_ = ref_vx > ep ? 1 : (ref_vx < -ep ? -1 : sign_vx_);
const double ref_k = reference_trajectory.k[i] * sign_vx_;
const double j = ref_vx * ref_vx * getWeightLatJerk(ref_k) / (DT * DT); // lateral jerk weight
const Eigen::Matrix2d J = (Eigen::Matrix2d() << j, -j, -j, j).finished();
m.R2ex.block(i, i, 2, 2) += J;
}
addSteerWeightR(&m.R1ex);
return m;
}
/*
* solve quadratic optimization.
* cost function: J = Xex' * Qex * Xex + (Uex - Uref)' * R1ex * (Uex - Uref_ex) + Uex' * R2ex * Uex
* , Qex = diag([Q,Q,...]), R1ex = diag([R,R,...])
* constraint matrix : lb < U < ub, lbA < A*U < ubA
* current considered constraint
* - steering limit
* - steering rate limit
*
* (1)lb < u < ub && (2)lbA < Au < ubA --> (3)[lb, lbA] < [I, A]u < [ub, ubA]
* (1)lb < u < ub ...
* [-u_lim] < [ u0 ] < [u_lim]
* [-u_lim] < [ u1 ] < [u_lim]
* ~~~
* [-u_lim] < [ uN ] < [u_lim] (*N... DIM_U)
* (2)lbA < Au < ubA ...
* [prev_u0 - au_lim*ctp] < [ u0 ] < [prev_u0 + au_lim*ctp] (*ctp ... ctrl_period)
* [ -au_lim * dt ] < [u1 - u0] < [ au_lim * dt ]
* [ -au_lim * dt ] < [u2 - u1] < [ au_lim * dt ]
* ~~~
* [ -au_lim * dt ] < [uN-uN-1] < [ au_lim * dt ] (*N... DIM_U)
*/
bool MPCFollower::executeOptimization(
const MPCMatrix & m, const Eigen::VectorXd & x0, Eigen::VectorXd * Uex)
{
using Eigen::MatrixXd;
using Eigen::VectorXd;
if (!isValid(m)) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "model matrix is invalid. stop MPC.");
return false;
}
const int DIM_U_N = mpc_param_.prediction_horizon * vehicle_model_ptr_->getDimU();
// cost function: 1/2 * Uex' * H * Uex + f' * Uex, H = B' * C' * Q * C * B + R
const MatrixXd CB = m.Cex * m.Bex;
const MatrixXd QCB = m.Qex * CB;
// MatrixXd H = CB.transpose() * QCB + m.R1ex + m.R2ex; // This calculation is heavy. looking for
// a good way. //NOLINT
MatrixXd H = MatrixXd::Zero(DIM_U_N, DIM_U_N);
H.triangularView<Eigen::Upper>() = CB.transpose() * QCB;
H.triangularView<Eigen::Upper>() += m.R1ex + m.R2ex;
H.triangularView<Eigen::Lower>() = H.transpose();
MatrixXd f = (m.Cex * (m.Aex * x0 + m.Wex)).transpose() * QCB - m.Uref_ex.transpose() * m.R1ex;
addSteerWeightF(&f);
MatrixXd A = MatrixXd::Identity(DIM_U_N, DIM_U_N);
for (int i = 1; i < DIM_U_N; i++) {
A(i, i - 1) = -1.0;
}
VectorXd lb = VectorXd::Constant(DIM_U_N, -steer_lim_); // min steering angle
VectorXd ub = VectorXd::Constant(DIM_U_N, steer_lim_); // max steering angle
VectorXd lbA = VectorXd::Constant(DIM_U_N, -steer_rate_lim_ * mpc_param_.prediction_dt);
VectorXd ubA = VectorXd::Constant(DIM_U_N, steer_rate_lim_ * mpc_param_.prediction_dt);
lbA(0, 0) = raw_steer_cmd_prev_ - steer_rate_lim_ * ctrl_period_;
ubA(0, 0) = raw_steer_cmd_prev_ + steer_rate_lim_ * ctrl_period_;
auto t_start = std::chrono::system_clock::now();
bool solve_result = qpsolver_ptr_->solve(H, f.transpose(), A, lb, ub, lbA, ubA, *Uex);
auto t_end = std::chrono::system_clock::now();
if (!solve_result) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(get_logger(), *get_clock(), (1000ms).count(), "qp solver error");
return false;
}
{
auto t = std::chrono::duration_cast<std::chrono::nanoseconds>(t_end - t_start).count() * 1.0e-6;
RCLCPP_DEBUG(get_logger(), "qp solver calculation time = %f [ms]", t);
}
if (Uex->array().isNaN().any()) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "model Uex includes NaN, stop MPC.");
return false;
}
return true;
}
void MPCFollower::addSteerWeightR(Eigen::MatrixXd * R_ptr) const
{
const int N = mpc_param_.prediction_horizon;
const double DT = mpc_param_.prediction_dt;
auto & R = *R_ptr;
/* add steering rate : weight for (u(i) - u(i-1) / dt )^2 */
{
const double steer_rate_r = mpc_param_.weight_steer_rate / (DT * DT);
const Eigen::Matrix2d D = steer_rate_r * (Eigen::Matrix2d() << 1.0, -1.0, -1.0, 1.0).finished();
for (int i = 0; i < N - 1; ++i) {
R.block(i, i, 2, 2) += D;
}
if (N > 1) {
// steer rate i = 0
R(0, 0) += mpc_param_.weight_steer_rate / (ctrl_period_ * ctrl_period_);
}
}
/* add steering acceleration : weight for { (u(i+1) - 2*u(i) + u(i-1)) / dt^2 }^2 */
{
const double w = mpc_param_.weight_steer_acc;
const double steer_acc_r = w / std::pow(DT, 4);
const double steer_acc_r_cp1 = w / (std::pow(DT, 3) * ctrl_period_);
const double steer_acc_r_cp2 = w / (std::pow(DT, 2) * std::pow(ctrl_period_, 2));
const double steer_acc_r_cp4 = w / std::pow(ctrl_period_, 4);
const Eigen::Matrix3d D =
steer_acc_r *
(Eigen::Matrix3d() << 1.0, -2.0, 1.0, -2.0, 4.0, -2.0, 1.0, -2.0, 1.0).finished();
for (int i = 1; i < N - 1; ++i) {
R.block(i - 1, i - 1, 3, 3) += D;
}
if (N > 1) {
// steer acc i = 1
R(0, 0) += steer_acc_r * 1.0 + steer_acc_r_cp2 * 1.0 + steer_acc_r_cp1 * 2.0;
R(1, 0) += steer_acc_r * -1.0 + steer_acc_r_cp1 * -1.0;
R(0, 1) += steer_acc_r * -1.0 + steer_acc_r_cp1 * -1.0;
R(1, 1) += steer_acc_r * 1.0;
// steer acc i = 0
R(0, 0) += steer_acc_r_cp4 * 1.0;
}
}
}
void MPCFollower::addSteerWeightF(Eigen::MatrixXd * f_ptr) const
{
if (f_ptr->rows() < 2) {
return;
}
const double DT = mpc_param_.prediction_dt;
auto & f = *f_ptr;
// steer rate for i = 0
f(0, 0) += -2.0 * mpc_param_.weight_steer_rate / (std::pow(DT, 2)) * 0.5;
// const double steer_acc_r = mpc_param_.weight_steer_acc / std::pow(DT, 4);
const double steer_acc_r_cp1 = mpc_param_.weight_steer_acc / (std::pow(DT, 3) * ctrl_period_);
const double steer_acc_r_cp2 =
mpc_param_.weight_steer_acc / (std::pow(DT, 2) * std::pow(ctrl_period_, 2));
const double steer_acc_r_cp4 = mpc_param_.weight_steer_acc / std::pow(ctrl_period_, 4);
// steer acc i = 0
f(0, 0) += ((-2.0 * raw_steer_cmd_prev_ + raw_steer_cmd_pprev_) * steer_acc_r_cp4) * 0.5;
// steer acc for i = 1
f(0, 0) += (-2.0 * raw_steer_cmd_prev_ * (steer_acc_r_cp1 + steer_acc_r_cp2)) * 0.5;
f(0, 1) += (2.0 * raw_steer_cmd_prev_ * steer_acc_r_cp1) * 0.5;
}
double MPCFollower::getPredictionTime() const
{
return (mpc_param_.prediction_horizon - 1) * mpc_param_.prediction_dt + mpc_param_.input_delay +
ctrl_period_;
}
bool MPCFollower::isValid(const MPCMatrix & m) const
{
if (
m.Aex.array().isNaN().any() || m.Bex.array().isNaN().any() || m.Cex.array().isNaN().any() ||
m.Wex.array().isNaN().any() || m.Qex.array().isNaN().any() || m.R1ex.array().isNaN().any() ||
m.R2ex.array().isNaN().any() || m.Uref_ex.array().isNaN().any()) {
return false;
}
if (
m.Aex.array().isInf().any() || m.Bex.array().isInf().any() || m.Cex.array().isInf().any() ||
m.Wex.array().isInf().any() || m.Qex.array().isInf().any() || m.R1ex.array().isInf().any() ||
m.R2ex.array().isInf().any() || m.Uref_ex.array().isInf().any()) {
return false;
}
return true;
}
void MPCFollower::onTrajectory(const autoware_planning_msgs::msg::Trajectory::SharedPtr msg)
{
if (!current_pose_ptr_) {
return;
}
current_trajectory_ptr_ = msg;
if (msg->points.size() < 3) {
RCLCPP_DEBUG(get_logger(), "received path size is < 3, not enough.");
return;
}
if (!isValidTrajectory(*msg)) {
RCLCPP_ERROR(get_logger(), "Trajectory is invalid!! stop computing.");
return;
}
MPCTrajectory mpc_traj_raw; // received raw trajectory
MPCTrajectory mpc_traj_resampled; // resampled trajectory
MPCTrajectory mpc_traj_smoothed; // smooth filtered trajectory
/* resampling */
MPCUtils::convertToMPCTrajectory(*current_trajectory_ptr_, &mpc_traj_raw);
if (!MPCUtils::resampleMPCTrajectoryByDistance(
mpc_traj_raw, traj_resample_dist_, &mpc_traj_resampled)) {
RCLCPP_WARN(get_logger(), "spline error!!!!!!");
return;
}
/* path smoothing */
mpc_traj_smoothed = mpc_traj_resampled;
int mpc_traj_resampled_size = static_cast<int>(mpc_traj_resampled.size());
if (enable_path_smoothing_ && mpc_traj_resampled_size > 2 * path_filter_moving_ave_num_) {
if (
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.x) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.y) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.yaw) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.vx)) {
RCLCPP_DEBUG(get_logger(), "path callback: filtering error. stop filtering.");
mpc_traj_smoothed = mpc_traj_resampled;
}
}
/* calculate yaw angle */
const int nearest_idx = MPCUtils::calcNearestIndex(mpc_traj_smoothed, current_pose_ptr_->pose);
const double ego_yaw = tf2::getYaw(current_pose_ptr_->pose.orientation);
MPCUtils::calcTrajectoryYawFromXY(&mpc_traj_smoothed, nearest_idx, ego_yaw);
MPCUtils::convertEulerAngleToMonotonic(&mpc_traj_smoothed.yaw);
/* calculate curvature */
MPCUtils::calcTrajectoryCurvature(
curvature_smoothing_num_traj_, curvature_smoothing_num_ref_steer_, &mpc_traj_smoothed);
/* add end point with vel=0 on traj for mpc prediction */
{
auto & t = mpc_traj_smoothed;
const double t_ext = 100.0; // extra time to prevent mpc calculation failure due to short time
const double t_end = t.relative_time.back() + getPredictionTime() + t_ext;
const double v_end = 0.0;
t.vx.back() = v_end; // set for end point
t.push_back(
t.x.back(), t.y.back(), t.z.back(), t.yaw.back(), v_end, t.k.back(), t.smooth_k.back(),
t_end);
}
if (!mpc_traj_smoothed.size()) {
RCLCPP_DEBUG(get_logger(), "path callback: trajectory size is undesired.");
return;
}
ref_traj_ = mpc_traj_smoothed;
/* publish debug marker */
{
const auto & stamp = current_trajectory_ptr_->header.stamp;
using MPCUtils::convertTrajToMarker;
visualization_msgs::msg::MarkerArray m;
std::string frame = msg->header.frame_id;
m = convertTrajToMarker(mpc_traj_raw, "trajectory raw", 0.9, 0.5, 0.0, 0.05, frame, stamp);
pub_debug_marker_->publish(m);
m = convertTrajToMarker(
mpc_traj_resampled, "trajectory spline", 0.5, 0.1, 1.0, 0.05, frame, stamp);
pub_debug_marker_->publish(m);
m = convertTrajToMarker(
mpc_traj_smoothed, "trajectory smoothed", 0.0, 1.0, 0.0, 0.05, frame, stamp);
pub_debug_marker_->publish(m);
}
}
void MPCFollower::updateCurrentPose()
{
geometry_msgs::msg::TransformStamped transform;
try {
transform = tf_buffer_.lookupTransform("map", "base_link", tf2::TimePointZero);
} catch (tf2::TransformException & ex) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (5000ms).count(), "cannot get map to base_link transform. %s",
ex.what());
return;
}
geometry_msgs::msg::PoseStamped ps;
ps.header = transform.header;
ps.pose.position.x = transform.transform.translation.x;
ps.pose.position.y = transform.transform.translation.y;
ps.pose.position.z = transform.transform.translation.z;
ps.pose.orientation = transform.transform.rotation;
current_pose_ptr_ = std::make_shared<geometry_msgs::msg::PoseStamped>(ps);
}
void MPCFollower::onSteering(const autoware_vehicle_msgs::msg::Steering::SharedPtr msg)
{
current_steer_ptr_ = msg;
}
void MPCFollower::onVelocity(geometry_msgs::msg::TwistStamped::SharedPtr msg)
{
current_velocity_ptr_ = msg;
}
autoware_control_msgs::msg::ControlCommand MPCFollower::getStopControlCommand() const
{
autoware_control_msgs::msg::ControlCommand cmd;
cmd.steering_angle = steer_cmd_prev_;
cmd.steering_angle_velocity = 0.0;
cmd.velocity = 0.0;
cmd.acceleration = -1.5;
return cmd;
}
autoware_control_msgs::msg::ControlCommand MPCFollower::getInitialControlCommand() const
{
autoware_control_msgs::msg::ControlCommand cmd;
cmd.steering_angle = current_steer_ptr_->data;
cmd.steering_angle_velocity = 0.0;
cmd.velocity = 0.0;
cmd.acceleration = -1.5;
return cmd;
}
bool MPCFollower::isStoppedState() const
{
// Note: This function used to take into account the distance to the stop line
// for the stop state judgement. However, it has been removed since the steering
// control was turned off when approaching/exceeding the stop line on a curve or
// emergency stop situation and it caused large tracking error.
const int nearest = MPCUtils::calcNearestIndex(*current_trajectory_ptr_, current_pose_ptr_->pose);
// If the nearest index is not found, return false
if (nearest < 0) {
return false;
}
const double current_vel = current_velocity_ptr_->twist.linear.x;
const double target_vel = current_trajectory_ptr_->points.at(nearest).twist.linear.x;
if (
std::fabs(current_vel) < stop_state_entry_ego_speed_ &&
std::fabs(target_vel) < stop_state_entry_target_speed_) {
return true;
} else {
return false;
}
}
double MPCFollower::calcStopDistance(const int origin) const
{
constexpr double zero_velocity = std::numeric_limits<double>::epsilon();
const double origin_velocity = current_trajectory_ptr_->points.at(origin).twist.linear.x;
double stop_dist = 0.0;
// search forward
if (std::fabs(origin_velocity) > zero_velocity) {
for (int i = origin + 1; i < static_cast<int>(current_trajectory_ptr_->points.size()) - 1;
++i) {
const auto & p0 = current_trajectory_ptr_->points.at(i);
const auto & p1 = current_trajectory_ptr_->points.at(i - 1);
stop_dist += MPCUtils::calcDist2d(p0.pose, p1.pose);
if (std::fabs(p0.twist.linear.x) < zero_velocity) {
break;
}
}
return stop_dist;
}
// search backward
for (int i = origin - 1; 0 < i; --i) {
const auto & p0 = current_trajectory_ptr_->points.at(i);
const auto & p1 = current_trajectory_ptr_->points.at(i + 1);
if (std::fabs(p0.twist.linear.x) > zero_velocity) {
break;
}
stop_dist -= MPCUtils::calcDist2d(p0.pose, p1.pose);
}
return stop_dist;
}
void MPCFollower::publishCtrlCmd(const autoware_control_msgs::msg::ControlCommand & ctrl_cmd)
{
autoware_control_msgs::msg::ControlCommandStamped cmd;
cmd.header.frame_id = "base_link";
cmd.header.stamp = this->now();
cmd.control = ctrl_cmd;
pub_ctrl_cmd_->publish(cmd);
steer_cmd_prev_ = ctrl_cmd.steering_angle;
autoware_vehicle_msgs::msg::Steering s;
s.data = ctrl_cmd.steering_angle;
s.header = cmd.header;
pub_debug_steer_cmd_->publish(s);
}
void MPCFollower::initTimer(double period_s)
{
auto timer_callback = std::bind(&MPCFollower::onTimer, this);
const auto period_ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<double>(period_s));
timer_ = std::make_shared<rclcpp::GenericTimer<decltype(timer_callback)>>(
this->get_clock(), period_ns, std::move(timer_callback),
this->get_node_base_interface()->get_context());
this->get_node_timers_interface()->add_timer(timer_, nullptr);
}
void MPCFollower::declareMPCparameters()
{
// the type of the ROS parameter is defined by the type of the default value, so 50 is not
// equivalent to 50.0! //NOLINT
mpc_param_.prediction_horizon = declare_parameter("mpc_prediction_horizon", 50);
mpc_param_.prediction_dt = declare_parameter("mpc_prediction_dt", 0.1);
mpc_param_.weight_lat_error = declare_parameter("mpc_weight_lat_error", 0.1);
mpc_param_.weight_heading_error = declare_parameter("mpc_weight_heading_error", 0.0);
mpc_param_.weight_heading_error_squared_vel =
declare_parameter("mpc_weight_heading_error_squared_vel", 0.3);
mpc_param_.weight_steering_input = declare_parameter("mpc_weight_steering_input", 1.0);
mpc_param_.weight_steering_input_squared_vel =
declare_parameter("mpc_weight_steering_input_squared_vel", 0.25);
mpc_param_.weight_lat_jerk = declare_parameter("mpc_weight_lat_jerk", 0.0);
mpc_param_.weight_steer_rate = declare_parameter("mpc_weight_steer_rate", 0.0);
mpc_param_.weight_steer_acc = declare_parameter("mpc_weight_steer_acc", 0.000001);
mpc_param_.low_curvature_weight_lat_error =
declare_parameter("mpc_low_curvature_weight_lat_error", 0.1);
mpc_param_.low_curvature_weight_heading_error =
declare_parameter("mpc_low_curvature_weight_heading_error", 0.0);
mpc_param_.low_curvature_weight_heading_error_squared_vel =
declare_parameter("mpc_low_curvature_weight_heading_error_squared_vel", 0.3);
mpc_param_.low_curvature_weight_steering_input =
declare_parameter("mpc_low_curvature_weight_steering_input", 1.0);
mpc_param_.low_curvature_weight_steering_input_squared_vel =
declare_parameter("mpc_low_curvature_weight_steering_input_squared_vel", 0.25);
mpc_param_.low_curvature_weight_lat_jerk =
declare_parameter("mpc_low_curvature_weight_lat_jerk", 0.0);
mpc_param_.low_curvature_weight_steer_rate =
declare_parameter("mpc_low_curvature_weight_steer_rate", 0.0);
mpc_param_.low_curvature_weight_steer_acc =
declare_parameter("mpc_low_curvature_weight_steer_acc", 0.000001);
mpc_param_.low_curvature_thresh_curvature =
declare_parameter("mpc_low_curvature_thresh_curvature", 0.0);
mpc_param_.weight_terminal_lat_error = declare_parameter("mpc_weight_terminal_lat_error", 1.0);
mpc_param_.weight_terminal_heading_error =
declare_parameter("mpc_weight_terminal_heading_error", 0.1);
mpc_param_.zero_ff_steer_deg = declare_parameter("mpc_zero_ff_steer_deg", 0.5);
mpc_param_.acceleration_limit = declare_parameter("acceleration_limit", 2.0);
mpc_param_.velocity_time_constant = declare_parameter("velocity_time_constant", 0.3);
}
rcl_interfaces::msg::SetParametersResult MPCFollower::paramCallback(
const std::vector<rclcpp::Parameter> & parameters)
{
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
result.reason = "success";
// strong exception safety wrt MPCParam
MPCParam param = mpc_param_;
try {
update_param(parameters, "mpc_prediction_horizon", param.prediction_horizon);
update_param(parameters, "mpc_prediction_dt", param.prediction_dt);
update_param(parameters, "mpc_weight_lat_error", param.weight_lat_error);
update_param(parameters, "mpc_weight_heading_error", param.weight_heading_error);
update_param(
parameters, "mpc_weight_heading_error_squared_vel", param.weight_heading_error_squared_vel);
update_param(parameters, "mpc_weight_steering_input", param.weight_steering_input);
update_param(
parameters, "mpc_weight_steering_input_squared_vel", param.weight_steering_input_squared_vel);
update_param(parameters, "mpc_weight_lat_jerk", param.weight_lat_jerk);
update_param(parameters, "mpc_weight_steer_rate", param.weight_steer_rate);
update_param(parameters, "mpc_weight_steer_acc", param.weight_steer_acc);
update_param(
parameters, "mpc_low_curvature_weight_lat_error", param.low_curvature_weight_lat_error);
update_param(
parameters, "mpc_low_curvature_weight_heading_error",
param.low_curvature_weight_heading_error);
update_param(
parameters, "mpc_low_curvature_weight_heading_error_squared_vel",
param.low_curvature_weight_heading_error_squared_vel);
update_param(
parameters, "mpc_low_curvature_weight_steering_input",
param.low_curvature_weight_steering_input);
update_param(
parameters, "mpc_low_curvature_weight_steering_input_squared_vel",
param.low_curvature_weight_steering_input_squared_vel);
update_param(
parameters, "mpc_low_curvature_weight_lat_jerk", param.low_curvature_weight_lat_jerk);
update_param(
parameters, "mpc_low_curvature_weight_steer_rate", param.low_curvature_weight_steer_rate);
update_param(
parameters, "mpc_low_curvature_weight_steer_acc", param.low_curvature_weight_steer_acc);
update_param(
parameters, "mpc_low_curvature_thresh_curvature", param.low_curvature_thresh_curvature);
update_param(parameters, "mpc_weight_terminal_lat_error", param.weight_terminal_lat_error);
update_param(
parameters, "mpc_weight_terminal_heading_error", param.weight_terminal_heading_error);
update_param(parameters, "mpc_zero_ff_steer_deg", param.zero_ff_steer_deg);
update_param(parameters, "acceleration_limit", param.acceleration_limit);
update_param(parameters, "velocity_time_constant", param.velocity_time_constant);
// initialize input buffer
update_param(parameters, "input_delay", param.input_delay);
const int delay_step = std::round(param.input_delay / ctrl_period_);
const double delay = delay_step * ctrl_period_;
if (param.input_delay != delay) {
const int delay_step = std::round(param.input_delay / ctrl_period_);
param.input_delay = delay;
input_buffer_ = std::deque<double>(delay_step, 0.0);
}
// transaction succeeds, now assign values
mpc_param_ = param;
} catch (const rclcpp::exceptions::InvalidParameterTypeException & e) {
result.successful = false;
result.reason = e.what();
}
// TODO(Frederik.Beaujean) extend to other params declared in ctor
return result;
}
bool MPCFollower::isValidTrajectory(const autoware_planning_msgs::msg::Trajectory & traj) const
{
for (const auto & points : traj.points) {
const auto & p = points.pose.position;
const auto & o = points.pose.orientation;
const auto & t = points.twist.linear;
const auto & a = points.accel.linear;
if (
!isfinite(p.x) || !isfinite(p.y) || !isfinite(p.z) || !isfinite(o.x) || !isfinite(o.y) ||
!isfinite(o.z) || !isfinite(o.w) || !isfinite(t.x) || !isfinite(t.y) || !isfinite(t.z) ||
!isfinite(a.x) || !isfinite(a.y) || !isfinite(a.z)) {
return false;
}
}
return true;
}
#include <rclcpp_components/register_node_macro.hpp>
RCLCPP_COMPONENTS_REGISTER_NODE(MPCFollower)
| 39.220141 | 100 | 0.699409 | loop-perception |
ed4ba278c0457cd58551f29d9fbea4bce10a4d7f | 2,258 | cpp | C++ | pxr/base/lib/tf/wrapRefPtrTracker.cpp | marsupial/USD | 98d49911893d59be5a9904a29e15959affd530ec | [
"BSD-3-Clause"
] | 9 | 2021-03-31T21:23:48.000Z | 2022-03-05T09:29:27.000Z | pxr/base/lib/tf/wrapRefPtrTracker.cpp | marsupial/USD | 98d49911893d59be5a9904a29e15959affd530ec | [
"BSD-3-Clause"
] | null | null | null | pxr/base/lib/tf/wrapRefPtrTracker.cpp | marsupial/USD | 98d49911893d59be5a9904a29e15959affd530ec | [
"BSD-3-Clause"
] | 1 | 2021-04-15T16:18:55.000Z | 2021-04-15T16:18:55.000Z | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
/// \file wrapRefPtrTracker.cpp
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/refPtrTracker.h"
#include "pxr/base/tf/pySingleton.h"
#include <boost/python/class.hpp>
#include <sstream>
using namespace boost::python;
static
std::string
_ReportAllWatchedCounts(TfRefPtrTracker& tracker)
{
std::ostringstream s;
tracker.ReportAllWatchedCounts(s);
return s.str();
}
static
std::string
_ReportAllTraces(TfRefPtrTracker& tracker)
{
std::ostringstream s;
tracker.ReportAllTraces(s);
return s.str();
}
static
std::string
_ReportTracesForWatched(TfRefPtrTracker& tracker, uintptr_t ptr)
{
std::ostringstream s;
tracker.ReportTracesForWatched(s, (TfRefBase*)ptr);
return s.str();
}
void
wrapRefPtrTracker()
{
typedef TfRefPtrTracker This;
typedef TfWeakPtr<TfRefPtrTracker> ThisPtr;
class_<This, ThisPtr, boost::noncopyable>("RefPtrTracker", no_init)
.def(TfPySingleton())
.def("GetAllWatchedCountsReport", _ReportAllWatchedCounts)
.def("GetAllTracesReport", _ReportAllTraces)
.def("GetTracesReportForWatched", _ReportTracesForWatched)
;
}
| 29.324675 | 75 | 0.734278 | marsupial |
ed4d99bc1997078b804af517225dbf8733350659 | 2,035 | cpp | C++ | others/DDCC/D_ver2.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | others/DDCC/D_ver2.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | others/DDCC/D_ver2.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | //#include <cassert>
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <iomanip>
//#include <sstream>
//#include <vector>
//#include <set>
//#include <map>
//#include <queue>
//#include <numeric>
//#include <algorithm>
//
//using namespace std;
//using lint = long long;
//constexpr int MOD = 1000000007, INF = 1010101010;
//constexpr lint LINF = 1LL << 60;
//
//template <class T>
//ostream &operator<<(ostream &os, const vector<T> &vec) {
// for (const auto &e : vec) os << e << (&e == &vec.back() ? "\n" : " ");
// return os;
//}
//
//#ifdef _DEBUG
//template <class T>
//void dump(const char* str, T &&h) { cerr << str << " = " << h << "\n"; };
//template <class Head, class... Tail>
//void dump(const char* str, Head &&h, Tail &&... t) {
// while (*str != ',') cerr << *str++; cerr << " = " << h << "\n";
// dump(str + (*(str + 1) == ' ' ? 2 : 1), t...);
//}
//#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)
//#else
//#define DMP(...) ((void)0)
//#endif
//
//void halve(int d, lint c, lint &cnt, vector<int> &rem) {
//
// if (c == 1) {
// rem.emplace_back(d);
// return;
// }
//
// if (c & 1) rem.emplace_back(d);
//
// if (d <= 4) {
// d *= 2;
// cnt += c / 2;
// }
// else {
// d = 1 + 2 * d % 10;
// cnt += c - (c & 1);
// }
//
// halve(d, c / 2, cnt, rem);
//
//};
//
//void simulate(lint &cnt, vector<int> &vec) {
//
// if (vec.size() == 1) return;
//
// assert(vec.size() != 0);
//
// int back1 = vec.back();
// vec.pop_back();
// int back2 = vec.back();
//
// DMP(back1, back2);
//
// int sum = back1 + back2;
// if (sum <= 9) {
// cnt++;
// vec.back() = sum;
// }
// else {
// cnt += 2;
// vec.back() = 1 + sum % 10;
// }
//
// simulate(cnt, vec);
//
//}
//
//int main() {
//
// cin.tie(nullptr);
// ios::sync_with_stdio(false);
//
// int M;
// cin >> M;
// lint ans = 0;
// vector<int> rem;
// for (int i = 0; i < M; i++) {
//
// lint d, c;
// cin >> d >> c;
// halve(d, c, ans, rem);
//
// }
//
// DMP(ans, rem);
// simulate(ans, rem);
//
// cout << ans << "\n";
//
// return 0;
//} | 18.669725 | 75 | 0.490418 | rajyan |
ed4f2e9715b259a42ed9162674e0b7d7035b5a09 | 1,071 | cpp | C++ | TAP 2020.1/brincando-com-conjuntos_2222.cpp | lucianovianna/IP-2019-1 | 585ab983d87de1bda4cb000581ebbee10214651e | [
"Apache-2.0"
] | 1 | 2019-04-20T01:02:13.000Z | 2019-04-20T01:02:13.000Z | TAP 2020.1/brincando-com-conjuntos_2222.cpp | lucianovianna/study_C | 585ab983d87de1bda4cb000581ebbee10214651e | [
"Apache-2.0"
] | null | null | null | TAP 2020.1/brincando-com-conjuntos_2222.cpp | lucianovianna/study_C | 585ab983d87de1bda4cb000581ebbee10214651e | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// https://www.urionlinejudge.com.br/judge/pt/problems/view/2222
typedef unsigned long long int ull;
int main()
{
ios_base::sync_with_stdio( false );
cin.tie( NULL );
int T;
cin >> T;
vector< vector<ull> > cj;
while(T--)
{
int n;
cin >> n;
cj.resize(n+2);
for (int i = 1; i <= n; ++i)
{
int Mi;
cin >> Mi;
while(Mi--)
{
ull a;
cin >> a;
cj[i].push_back(a);
}
}
int Q;
cin >> Q;
while(Q--)
{
int op, ca, cb;
cin >> op >> ca >> cb;
ull a = 0 , b = 0, c = 0;
for (int i = 0; i < cj[ca].size(); ++i) {
a |= (1LL << cj[ca][i]);
}
for (int i = 0; i < cj[cb].size(); ++i) {
b |= (1LL << cj[cb][i]);
}
(op == 2) ? c = a | b : c = a & b;
cout << __builtin_popcountll(c) << endl;
}
// for (int i = 0; i <= n+1; ++i) cj[i].clear();
cj.clear();
}
return 0;
}
| 15.521739 | 64 | 0.394024 | lucianovianna |
ed5016f0f13c2dfa2f4f9358bf4c802c925dedc2 | 2,717 | cc | C++ | Memcached/MCBug5/memcached-127/libmemcached-0.49/tests/pool.cc | uditagarwal97/nekara-artifact | b210ccaf751aca6bae7189d4f4db537b6158c525 | [
"MIT"
] | 2 | 2021-07-15T15:58:18.000Z | 2021-07-16T14:37:26.000Z | Memcached/MCBug5/memcached-127/libmemcached-0.49/tests/pool.cc | uditagarwal97/nekara-artifact | b210ccaf751aca6bae7189d4f4db537b6158c525 | [
"MIT"
] | null | null | null | Memcached/MCBug5/memcached-127/libmemcached-0.49/tests/pool.cc | uditagarwal97/nekara-artifact | b210ccaf751aca6bae7189d4f4db537b6158c525 | [
"MIT"
] | 2 | 2021-07-15T12:19:06.000Z | 2021-09-06T04:28:19.000Z | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Libmemcached Client and Server
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* 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.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <config.h>
#include <vector>
#include <iostream>
#include <string>
#include <errno.h>
#include <libmemcached/memcached.h>
#include <libmemcached/util.h>
#include <tests/pool.h>
test_return_t memcached_pool_test(memcached_st *)
{
memcached_return_t rc;
const char *config_string= "--SERVER=host10.example.com --SERVER=host11.example.com --SERVER=host10.example.com --POOL-MIN=10 --POOL-MAX=32";
char buffer[2048];
rc= libmemcached_check_configuration(config_string, sizeof(config_string) -1, buffer, sizeof(buffer));
test_true_got(rc != MEMCACHED_SUCCESS, buffer);
memcached_pool_st* pool= memcached_pool(config_string, strlen(config_string));
test_true_got(pool, strerror(errno));
memcached_st *memc= memcached_pool_pop(pool, false, &rc);
test_true(rc == MEMCACHED_SUCCESS);
test_true(memc);
/*
Release the memc_ptr that was pulled from the pool
*/
memcached_pool_push(pool, memc);
/*
Destroy the pool.
*/
memcached_pool_destroy(pool);
return TEST_SUCCESS;
}
| 34.392405 | 143 | 0.744571 | uditagarwal97 |
ed567ad96a62ddff18cf733b12d5787962da1e6a | 804 | cpp | C++ | 290-word-pattern/290-word-pattern.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | 2 | 2022-01-02T19:15:00.000Z | 2022-01-05T21:12:24.000Z | 290-word-pattern/290-word-pattern.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | null | null | null | 290-word-pattern/290-word-pattern.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | 1 | 2022-03-11T17:11:07.000Z | 2022-03-11T17:11:07.000Z | class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string>v(pattern.length()+1);
int j=0;
for(int i=0;i<s.length();i++){
if(s[i]!=' ')
{
v[j]+=s[i];
}
else
j++;
}
map<string,char>ms;
map<char,bool>visited;
for(int i=0;i<v.size();i++){
cout<<v[i]<<endl;
}
for(int i=0;i<v.size();i++){
if(ms.find(v[i])==ms.end() && visited[pattern[i]]==false){
visited[pattern[i]]=true;
ms[v[i]]=pattern[i];
}
else
if(ms[v[i]]!=pattern[i])
return false;
}
return true;
}
}; | 24.363636 | 70 | 0.365672 | Ananyaas |
ed5b37cde35b82cfdc3bd8ff014da35df126ed5d | 2,418 | cpp | C++ | UVA/NetworkConnections.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | 1 | 2019-09-29T03:58:35.000Z | 2019-09-29T03:58:35.000Z | UVA/NetworkConnections.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | null | null | null | UVA/NetworkConnections.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | null | null | null | #include <cctype>
#include <set>
#include <queue>
#include <map>
#include <stack>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <sstream>
#include <cstdlib>
#include <locale>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstring>
#define scd(x) scanf("%d", &x)
#define scc(x) scanf("%c", &x)
#define scd2(x,y) scanf("%d %d", &x, &y)
#define prd(x) printf("%d\n", x)
#define dprd(x) printf("|| %d\n", x)
#define dprd2(x, y) printf("|| %d | %d\n", x, y)
#define prd2(x,y) printf("%d %d\n", x,y)
#define prnl() printf("\n")
#define prc(c) printf("%c\n", c)
#define fora(i,a,n) for(i = a; i < n; i++)
#define for0(i,n) fora(i, 0, n)
#define _F first
#define _S second
#define _MP make_pair
#define _MT(x, y, z) _MP(x, _MP(y, z))
#define _TL(s) transform(s.begin(), s.end(), s.begin(), ::tolower)
#define _TU(s) transform(s.begin(), s.end(), s.begin(), ::toupper)
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef long long ll;
typedef pair<int, ii> iii;
typedef pair<string, int> si;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<string> vs;
typedef vector< vector<int> > vvi;
class UnionFind {
private:
vi p, rank, setSize;
int numSets;
public:
UnionFind(int N) {
setSize.assign(N, 1); numSets = N; rank.assign(N, 0);
p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; }
int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); }
bool isSameSet(int i, int j) { return findSet(i) == findSet(j); }
void unionSet(int i, int j) {
if (!isSameSet(i, j)) { numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
else { p[x] = y; setSize[y] += setSize[x];
if (rank[x] == rank[y]) rank[y]++; } } }
int numDisjointSets() { return numSets; }
int sizeOfSet(int i) { return setSize[findSet(i)]; }
};
int main(){
int t, n, i, a, b, s, u;
char c, line[1000];
scanf("%d\n", &t);
while(t--){
scanf("%d\n\n", &n);
s = 0; u = 0;
UnionFind UF(n);
while(true){
gets(line);
if((strcmp(line, "") == 0) || feof(stdin)) break;
sscanf(line, "%c %d %d", &c, &a, &b);
a--; b--;
if(c == 'c'){
UF.unionSet(a, b);
} else {
if(UF.isSameSet(a, b))
s++;
else
u++;
}
}
printf("%d,%d\n", s, u);
if(t != 0) prnl();
}
}
| 24.673469 | 73 | 0.563689 | MartinAparicioPons |
ed5fa1a09871813ca7bb89af7f31028f0c040d6e | 3,449 | cpp | C++ | lab4/150101033_3.cpp | mayank-myk/Basic-Datastructure-implementations | 4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356 | [
"MIT"
] | null | null | null | lab4/150101033_3.cpp | mayank-myk/Basic-Datastructure-implementations | 4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356 | [
"MIT"
] | null | null | null | lab4/150101033_3.cpp | mayank-myk/Basic-Datastructure-implementations | 4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356 | [
"MIT"
] | null | null | null | // mayank agrawal
// 150101033
// To complie type: g++ 150101033_3.cpp -std=c++11 in linux
#include <bits/stdc++.h>
#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
struct node{
int row;
int col;
int value;
struct node * right;
struct node * down;
};
struct node *createnode(int row,int col,int value){
struct node *temp = new struct node;
temp->row = row;
temp->col = col;
temp->value = value;
return temp;
}
class sparse_matrix{
struct node *right;
struct node *down;
int row,col;
public:
sparse_matrix(int r,int c){ //row or col value of 0 indicates the node is a pointer to a row or column.
row = r;
col = c;
right = new struct node[c];
down = new struct node[r];
for(int i=0;i<r;i++){
down[i].down = &down[(i+1)%r];
down[i].right = &down[i];
down[i].row = i;
down[i].col = 0;
down[i].value = -1;
}
for(int i=0;i<c;i++){
right[i].right = &right[(i+1)%c];
right[i].down = &right[i];
right[i].row = 0;
right[i].col = i;
right[i].value = -1;
}
//pointer right[0] and down[0] are same struct node
right[0].right = &right[1];
right[0].down = &down[1];
down[0] = right[0];
}
void insert(struct node *temp){
int R = temp->row;
int C = temp->col;
struct node *tempC = &right[C];
struct node *tempR = &down[R];
while( (tempC->row)<R || (tempC->down)->row==0 ){
if((tempC->down)->row==0){
temp->down = tempC->down;
tempC->down = temp;
break;
}else if((tempC->down)->row > R){
temp->down = (tempC->down);
tempC->down = temp;
break;
}else{
tempC = tempC->down;
}
}
while( (tempR->col)<C || (tempR->right)->col==0 ){
if((tempR->right)->col==0){
temp->right = tempR->right;
tempR->right = temp;
break;
}else if((tempR->right)->col > C){
temp->right = (tempR->right);
tempR->right = temp;
break;
}else{
tempR= tempR->right;
}
}
}
void largest(){
int maximum=0;
for(int i=1;i<row;i++){
if(down[i].right->col==0) //if that row has no elements
continue;
struct node * temp = (&down[i])->right;
while (temp->col!=0){
if(temp->value > maximum)
maximum = temp->value;
temp = temp->right;
}
}
printf("Maximum element in the matrix is : %d\n",maximum);
}
//The function to display the value of the matrix row-wise .
void row_print(){
cout<<"\nDisplaying value row-wise : \n";
for(int i=1;i<row;i++){
printf("value in row =>%d\n",i);
struct node * temp = (&down[i])->right;
while (temp->col!=0){
printf("row: %d,Col: %d,value: %d\n",temp->row,temp->col,temp->value);
temp = temp->right;
}
}
}
};
int main(){
int r,c,k;
printf("enter the no. of row, column:\n ");
scanf("%d %d",&r,&c);
printf("Enter the number of non -zero elments : ");
scanf("%d",&k);
int a[k][3],t,x,y,flag;
srand(time(NULL));
for(int i=0;i<k;i++){
x = rand()%r + 1;
y = rand()%c + 1;
a[i][1]=x;
a[i][2]=y;
a[i][0]=rand()%1000;
for(int j=0;j<i;j++){
if( x==a[j][1] && y==a[j][2] ){
j--; // to remove those value of <i,j> which are already been used.
break;
}
}
}
sparse_matrix m(r+1,c+1); //m is the class object
for(int i=0;i<k;i++){
m.insert( createnode (a[i][1],a[i][2],a[i][0]) );
}
// function to print the elements row wise
m.row_print();
m.largest();
return 0;
} | 21.030488 | 108 | 0.551464 | mayank-myk |
ed60a20123146118a0edd7b0e761349a80d128ab | 312 | hpp | C++ | compendium/test_bundles/TestBundleDSTOI12/src/ServiceImpl.hpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 588 | 2015-10-07T15:55:08.000Z | 2022-03-29T00:35:44.000Z | compendium/test_bundles/TestBundleDSTOI12/src/ServiceImpl.hpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 459 | 2015-10-05T23:29:59.000Z | 2022-03-29T14:13:37.000Z | compendium/test_bundles/TestBundleDSTOI12/src/ServiceImpl.hpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 218 | 2015-11-04T08:19:48.000Z | 2022-03-24T02:17:08.000Z | #ifndef SERVICEIMPL_HPP
#define SERVICEIMPL_HPP
#include "TestInterfaces/Interfaces.hpp"
namespace sample {
class ServiceComponent12 : public test::Interface1
{
public:
ServiceComponent12() = default;
~ServiceComponent12() override;
std::string Description() override;
};
}
#endif // _SERVICE_IMPL_HPP_
| 18.352941 | 50 | 0.775641 | fmilano |
ed673c2776dc5598cc3d749d7bc6a8fd1db9a70d | 2,471 | cpp | C++ | src/robot/Constants.cpp | roboFiddle/7405M_TowerTakeover_Code | e16ffab17964ff61a25eac2074da78d0d7577caa | [
"MIT"
] | null | null | null | src/robot/Constants.cpp | roboFiddle/7405M_TowerTakeover_Code | e16ffab17964ff61a25eac2074da78d0d7577caa | [
"MIT"
] | null | null | null | src/robot/Constants.cpp | roboFiddle/7405M_TowerTakeover_Code | e16ffab17964ff61a25eac2074da78d0d7577caa | [
"MIT"
] | null | null | null | #include "Constants.hpp"
namespace constants {
units::QLength RobotConstants::kDriveWheelRadius = 2*units::inch;
units::QMass RobotConstants::kRobotMass = 4*units::kg;
units::QMoment RobotConstants::kRobotMoment = 4*units::kgm2;
units::QAngularDrag RobotConstants::kRobotAngularDrag = 0.0;
units::QLength RobotConstants::kDriveWheelTrackWidth = 10 * units::inch;
units::Number RobotConstants::kTrackScrubFactor = 1.0;
units::QLength RobotConstants::kDeadwheelRadius = 1.375*units::inch;
units::QLength RobotConstants::kDeadwheelBaseWidth = 4.1*units::inch;
units::QLength RobotConstants::kDeadwheelBackTurningRadius = 9.45 * units::inch;
units::QAngularSpeed RobotConstants::kDriveSpeedPerVolt = 1.09; // RADIANS / SECOND / VOTL
units::QTorque RobotConstants::kDriveTorquePerVolt = 0.56; // Nm / VOLT
units::Number RobotConstants::kDriveFrictionVoltage = 1.0; // voltage to overcome friction (V)
double RobotConstants::turnKP = 28;
double RobotConstants::turnKI = 0;
double RobotConstants::turnKD = 0;
int RobotConstants::motor_drive_frontleft = 9;
int RobotConstants::motor_drive_backleft = 10;
int RobotConstants::motor_drive_frontright = 2;
int RobotConstants::motor_drive_backright = 5;
int RobotConstants::motor_intake_left = 12; //bricked 11 on 2/21/2020 changed to 12
int RobotConstants::motor_intake_right = 16; //bricked 17 on 2/22/2020 changed to 16
int RobotConstants::motor_tray = 3;
int RobotConstants::motor_lift = 18;
double RobotConstants::MAX_TRAY_RPM = 100;
double RobotConstants::MAX_LIFT_RPM = 200;
double RobotConstants::LIFT_STAGE[1] = {500};
double RobotConstants::TRAY_LIFT[2] = {75, 1800};
double RobotConstants::LIFT_PRESETS[3] = {340, 2200, 3250};
double RobotConstants::trayErrorBeforeLiftStart = 1000;
double RobotConstants::liftErrorBeforeTrayStart = 100;
double RobotConstants::TRAY_SCORE = 3300;
double RobotConstants::SCORE_START_INTAKE = 1000;
double RobotConstants::SCORE_END_INTAKE = 1400;
double RobotConstants::BACK_WHEELBASE_RADIUS = 20;
int RobotConstants::SIDE_VISION_PORT = 0;
int RobotConstants::FORWARD_VISION_PORT = 0;
int RobotConstants::GREEN_SIG = 0;
int RobotConstants::ORANGE_SIG = 0;
int RobotConstants::PURPLE_SIG = 0;
int RobotConstants::IMU_PORT = 1;
double RobotConstants::IMU_TURN_KP = 30;
double RobotConstants::IMU_TURN_KD = 5;
}
| 43.350877 | 98 | 0.734925 | roboFiddle |
ed6abab59f7433f6de3847922a8fb3045b931481 | 1,004 | cpp | C++ | tests/cpp/integration/test_p2p_apis.cpp | Pandinosaurus/KungFu | 80dfa463450330e920b413f65cc49d8e013b84a9 | [
"Apache-2.0"
] | 291 | 2019-10-25T16:37:59.000Z | 2022-03-17T21:47:09.000Z | tests/cpp/integration/test_p2p_apis.cpp | Pandinosaurus/KungFu | 80dfa463450330e920b413f65cc49d8e013b84a9 | [
"Apache-2.0"
] | 56 | 2019-10-26T08:25:33.000Z | 2021-09-07T11:11:51.000Z | tests/cpp/integration/test_p2p_apis.cpp | Pandinosaurus/KungFu | 80dfa463450330e920b413f65cc49d8e013b84a9 | [
"Apache-2.0"
] | 53 | 2019-10-25T17:45:40.000Z | 2022-02-08T13:09:39.000Z | #include <algorithm>
#include <numeric>
#include <vector>
#include <kungfu.h>
void test_versioned_store(kungfu::Peer &world)
{
const int rank = world.Rank();
const int np = world.Size();
using T = int;
const int n = 10;
std::vector<T> send_buf(n);
std::vector<T> recv_buf(n);
std::iota(send_buf.begin(), send_buf.end(), np);
std::fill(recv_buf.begin(), recv_buf.end(), -1);
if (rank == 0) {
world.Save("v0", "weight", send_buf.data(), send_buf.size(),
kungfu::type_encoder::value<T>());
}
world.Barrier();
world.Request(0, "v0", "weight", recv_buf.data(), recv_buf.size(),
kungfu::type_encoder::value<T>());
for (int i = 0; i < n; ++i) {
if (send_buf[i] != recv_buf[i]) {
printf("%s failed\n", __func__);
exit(1);
}
}
world.Barrier();
}
int main(int argc, char *argv[])
{
kungfu::Peer self;
test_versioned_store(self);
return 0;
}
| 21.826087 | 70 | 0.546813 | Pandinosaurus |
ed6c965bce32a1aed0d2b1aa897fc1e392e61e3e | 2,834 | hpp | C++ | include/codegen/include/System/Text/EncoderFallback.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Text/EncoderFallback.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Text/EncoderFallback.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:42 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Text
namespace System::Text {
// Forward declaring type: EncoderFallbackBuffer
class EncoderFallbackBuffer;
}
// Completed forward declares
// Type namespace: System.Text
namespace System::Text {
// Autogenerated type: System.Text.EncoderFallback
class EncoderFallback : public ::Il2CppObject {
public:
// System.Boolean bIsMicrosoftBestFitFallback
// Offset: 0x10
bool bIsMicrosoftBestFitFallback;
// Get static field: static private System.Text.EncoderFallback replacementFallback
static System::Text::EncoderFallback* _get_replacementFallback();
// Set static field: static private System.Text.EncoderFallback replacementFallback
static void _set_replacementFallback(System::Text::EncoderFallback* value);
// Get static field: static private System.Text.EncoderFallback exceptionFallback
static System::Text::EncoderFallback* _get_exceptionFallback();
// Set static field: static private System.Text.EncoderFallback exceptionFallback
static void _set_exceptionFallback(System::Text::EncoderFallback* value);
// Get static field: static private System.Object s_InternalSyncObject
static ::Il2CppObject* _get_s_InternalSyncObject();
// Set static field: static private System.Object s_InternalSyncObject
static void _set_s_InternalSyncObject(::Il2CppObject* value);
// static private System.Object get_InternalSyncObject()
// Offset: 0x12D8814
static ::Il2CppObject* get_InternalSyncObject();
// static public System.Text.EncoderFallback get_ReplacementFallback()
// Offset: 0x12D2D70
static System::Text::EncoderFallback* get_ReplacementFallback();
// static public System.Text.EncoderFallback get_ExceptionFallback()
// Offset: 0x12D88F8
static System::Text::EncoderFallback* get_ExceptionFallback();
// public System.Text.EncoderFallbackBuffer CreateFallbackBuffer()
// Offset: 0xFFFFFFFF
System::Text::EncoderFallbackBuffer* CreateFallbackBuffer();
// public System.Int32 get_MaxCharCount()
// Offset: 0xFFFFFFFF
int get_MaxCharCount();
// protected System.Void .ctor()
// Offset: 0x12D7F7C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static EncoderFallback* New_ctor();
}; // System.Text.EncoderFallback
}
DEFINE_IL2CPP_ARG_TYPE(System::Text::EncoderFallback*, "System.Text", "EncoderFallback");
#pragma pack(pop)
| 44.984127 | 89 | 0.739238 | Futuremappermydud |
ed70bd97497d987130f6f2f8e57ad2d83f38bd35 | 438 | cpp | C++ | src/boards/mcu/espressif/spi_board.cpp | luisgcu/SX126x-Arduino | 072acaa9f5cdcc8cdf582bd4d2248c232b1c2b08 | [
"MIT"
] | 118 | 2019-10-02T14:30:43.000Z | 2022-03-25T10:31:04.000Z | src/boards/mcu/espressif/spi_board.cpp | luisgcu/SX126x-Arduino | 072acaa9f5cdcc8cdf582bd4d2248c232b1c2b08 | [
"MIT"
] | 58 | 2019-08-21T15:30:41.000Z | 2022-03-04T02:42:14.000Z | src/boards/mcu/espressif/spi_board.cpp | luisgcu/SX126x-Arduino | 072acaa9f5cdcc8cdf582bd4d2248c232b1c2b08 | [
"MIT"
] | 49 | 2019-09-08T15:44:00.000Z | 2022-03-20T22:42:41.000Z | #if defined ESP8266 || defined ESP32
#include <SPI.h>
#include "boards/mcu/board.h"
SPIClass SPI_LORA;
void initSPI(void)
{
#ifdef ESP8266
SPI_LORA.pins(_hwConfig.PIN_LORA_SCLK, _hwConfig.PIN_LORA_MISO, _hwConfig.PIN_LORA_MOSI, _hwConfig.PIN_LORA_NSS);
SPI_LORA.begin();
SPI_LORA.setHwCs(false);
#else
SPI_LORA.begin(_hwConfig.PIN_LORA_SCLK, _hwConfig.PIN_LORA_MISO, _hwConfig.PIN_LORA_MOSI, _hwConfig.PIN_LORA_NSS);
#endif
}
#endif | 25.764706 | 115 | 0.799087 | luisgcu |
ed76770cf59f0fe9c209d72428c36fbf12d46704 | 7,904 | cc | C++ | cpp/core/libcore/net/tcp_conn.cc | cheukw/sample | 602d5d055c3e11e1e0ba385128e64b9c0aa81305 | [
"MIT"
] | null | null | null | cpp/core/libcore/net/tcp_conn.cc | cheukw/sample | 602d5d055c3e11e1e0ba385128e64b9c0aa81305 | [
"MIT"
] | null | null | null | cpp/core/libcore/net/tcp_conn.cc | cheukw/sample | 602d5d055c3e11e1e0ba385128e64b9c0aa81305 | [
"MIT"
] | null | null | null | #include "net/libevent_headers.h"
#include "net/tcp_conn.h"
#include "net/fd_channel.h"
#include "net/event_loop.h"
#include "net/sockets.h"
#include "net/invoke_timer.h"
TCPConn::TCPConn(EventLoop* l, const std::string& n, net_socket_t sockfd, const std::string& laddr, const std::string& raddr)
: loop_(l)
, fd_(sockfd)
, name_(n)
, local_addr_(laddr)
, remote_addr_(raddr)
, type_(kIncoming)
, status_(kDisconnected)
, high_water_mark_(128 * 1024 * 1024)
, close_delay_(3.000001)
{
if (sockfd >= 0) {
chan_.reset(new FdChannel(l, sockfd, false, false));
chan_->SetReadCallback(std::bind(&TCPConn::HandleRead, this));
chan_->SetWriteCallback(std::bind(&TCPConn::HandleWrite, this));
}
}
TCPConn::~TCPConn() {
assert(status_ == kDisconnected);
if (fd_ >= 0) {
assert(chan_);
assert(fd_ == chan_->fd());
assert(chan_->IsNoneEvent());
EVUTIL_CLOSESOCKET(fd_);
fd_ = INVALID_SOCKET;
}
assert(!delay_close_timer_.get());
}
void TCPConn::Close() {
status_ = kDisconnecting;
auto c = shared_from_this();
auto f = [c]() {
assert(c->loop_->IsInLoopThread());
c->HandleClose();
};
// Use QueueInLoop to fix TCPClient::Close bug when the application delete TCPClient in callback
loop_->QueueInLoop(f);
}
void TCPConn::Send(const std::string& d) {
if (status_ != kConnected) {
return;
}
if (loop_->IsInLoopThread()) {
SendInLoop(d);
} else {
loop_->RunInLoop(std::bind(&TCPConn::SendStringInLoop, shared_from_this(), d));
}
}
void TCPConn::Send(const Slice& message) {
if (status_ != kConnected) {
return;
}
if (loop_->IsInLoopThread()) {
SendInLoop(message);
} else {
loop_->RunInLoop(std::bind(&TCPConn::SendStringInLoop, shared_from_this(), message.ToString()));
}
}
void TCPConn::Send(const void* data, size_t len) {
if (loop_->IsInLoopThread()) {
SendInLoop(data, len);
return;
}
Send(Slice(static_cast<const char*>(data), len));
}
void TCPConn::Send(Buffer* buf) {
if (status_ != kConnected) {
return;
}
if (loop_->IsInLoopThread()) {
SendInLoop(buf->Data(), buf->Length());
buf->Reset();
} else {
loop_->RunInLoop(std::bind(&TCPConn::SendStringInLoop, shared_from_this(), buf->NextAllString()));
}
}
void TCPConn::SendInLoop(const Slice& message) {
SendInLoop(message.data(), message.size());
}
void TCPConn::SendStringInLoop(const std::string& message) {
SendInLoop(message.data(), message.size());
}
void TCPConn::SendInLoop(const void* data, size_t len) {
assert(loop_->IsInLoopThread());
if (status_ == kDisconnected) {
return;
}
ssize_t nwritten = 0;
size_t remaining = len;
bool write_error = false;
// if no data in output queue, writing directly
if (!chan_->IsWritable() && output_buffer_.Length() == 0) {
nwritten = ::send(chan_->fd(), static_cast<const char*>(data), static_cast<int>(len), MSG_NOSIGNAL);
if (nwritten >= 0) {
remaining = len - nwritten;
if (remaining == 0 && write_complete_fn_) {
loop_->QueueInLoop(std::bind(write_complete_fn_, shared_from_this()));
}
} else {
int serrno = errno;
nwritten = 0;
if(!EVUTIL_ERR_RW_RETRIABLE(serrno)) {
if (serrno == EPIPE || serrno == ECONNRESET) {
write_error = true;
}
}
}
}
if (write_error) {
HandleError();
return;
}
assert(!write_error);
assert(remaining <= len);
if(remaining > 0) {
size_t old_len = output_buffer_.Length();
if (old_len + remaining >= high_water_mark_ && old_len < high_water_mark_ && high_water_mark_fn_) {
loop_->QueueInLoop(std::bind(high_water_mark_fn_, shared_from_this(), old_len + remaining));
}
output_buffer_.Append(static_cast<const char*>(data) + nwritten, remaining);
if (!chan_->IsWritable()) {
chan_->EnableWriteEvent();
}
}
}
void TCPConn::HandleRead()
{
assert(loop_->IsInLoopThread());
int serrno = 0;
ssize_t n = input_buffer_.ReadFromFD(chan_->fd(), &serrno);
if (n > 0) {
msg_fn_(shared_from_this(), &input_buffer_);
} else if (n == 0) {
if (type() == kOutgoing) {
// This is an outgoing connection, we own it and it's done. so close it
status_ = kDisconnecting;
HandleClose();
} else {
// Fix the half-closing problem : https://github.com/chenshuo/muduo/pull/117
// This is an incoming connection, we need to preserve the connection for a while so that we can reply to it.
// And we set a timer to close the connection eventually.
chan_->DisableReadEvent();
delay_close_timer_ = loop_->RunAfter(close_delay_, std::bind(&TCPConn::DelayClose, shared_from_this())); // TODO leave it to user layer close.
}
} else {
if (EVUTIL_ERR_RW_RETRIABLE(serrno)) {
} else {
HandleError();
}
}
}
void TCPConn::HandleWrite()
{
assert(loop_->IsInLoopThread());
assert(!chan_->attached() || chan_->IsWritable());
ssize_t n = ::send(fd_, output_buffer_.Data(), static_cast<int>(output_buffer_.Length()), MSG_NOSIGNAL);
if (n > 0) {
output_buffer_.Next(n);
if (output_buffer_.Length() == 0) {
chan_->DisableWriteEvent();
if (write_complete_fn_) {
loop_->QueueInLoop(std::bind(write_complete_fn_, shared_from_this()));
}
}
} else {
int serrno = errno;
if (EVUTIL_ERR_RW_RETRIABLE(serrno)) {
} else {
HandleError();
}
}
}
void TCPConn::DelayClose()
{
assert(loop_->IsInLoopThread());
status_ = kDisconnecting;
assert(delay_close_timer_.get());
delay_close_timer_.reset();
HandleClose();
}
void TCPConn::HandleClose()
{
// Avoid multi calling
if (status_ == kDisconnected) {
return;
}
// We call HandleClose() from TCPConn's method, the status_ is kConnected
// But we call HandleClose() from out of TCPConn's method, the status_ is kDisconnecting
assert(status_ == kDisconnecting);
status_ = kDisconnecting;
assert(loop_->IsInLoopThread());
chan_->DisableAllEvent();
chan_->Close();
TCPConnPtr conn(shared_from_this());
if (delay_close_timer_) {
delay_close_timer_->Cancel();
delay_close_timer_.reset();
}
if (conn_fn_) {
// This callback must be invoked at status kDisconnecting
// e.g. when the TCPClient disconnects with remote server,
// the user layer can decide whether to do the reconnection.
assert(status_ == kDisconnecting);
conn_fn_(conn);
}
if (close_fn_) {
close_fn_(conn);
}
status_ = kDisconnected;
}
void TCPConn::HandleError() {
status_ = kDisconnecting;
HandleClose();
}
void TCPConn::OnAttachedToLoop() {
assert(loop_->IsInLoopThread());
status_ = kConnected;
chan_->EnableReadEvent();
if (conn_fn_) {
conn_fn_(shared_from_this());
}
}
void TCPConn::SetHighWaterMarkCallback(const HighWaterMarkCallback& cb, size_t mark) {
high_water_mark_fn_ = cb;
high_water_mark_ = mark;
}
void TCPConn::SetTCPNoDelay(bool on) {
sockets::SetTCPNoDelay(fd_, on);
}
std::string TCPConn::StatusToString() const {
H_CASE_STRING_BIGIN(status_);
H_CASE_STRING(kDisconnected);
H_CASE_STRING(kConnecting);
H_CASE_STRING(kConnected);
H_CASE_STRING(kDisconnecting);
H_CASE_STRING_END();
}
| 26.702703 | 154 | 0.604504 | cheukw |
ed777fc0af8a172c2885b4654977e8876c2fce6d | 1,481 | cc | C++ | cc/test/fake_context_provider.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | cc/test/fake_context_provider.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/test/fake_context_provider.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:19:31.000Z | 2020-11-04T07:19:31.000Z | // Copyright 2013 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 "cc/test/fake_context_provider.h"
#include "cc/test/test_web_graphics_context_3d.h"
namespace cc {
FakeContextProvider::FakeContextProvider()
: destroyed_(false) {
}
FakeContextProvider::FakeContextProvider(
const CreateCallback& create_callback)
: create_callback_(create_callback),
destroyed_(false) {
}
FakeContextProvider::~FakeContextProvider() {}
bool FakeContextProvider::InitializeOnMainThread() {
if (destroyed_)
return false;
if (context3d_)
return true;
if (create_callback_.is_null())
context3d_ = TestWebGraphicsContext3D::Create().Pass();
else
context3d_ = create_callback_.Run();
destroyed_ = !context3d_;
return !!context3d_;
}
bool FakeContextProvider::BindToCurrentThread() {
return context3d_->makeContextCurrent();
}
WebKit::WebGraphicsContext3D* FakeContextProvider::Context3d() {
return context3d_.get();
}
class GrContext* FakeContextProvider::GrContext() {
// TODO(danakj): Make a fake GrContext.
return NULL;
}
void FakeContextProvider::VerifyContexts() {
if (!Context3d() || Context3d()->isContextLost()) {
base::AutoLock lock(destroyed_lock_);
destroyed_ = true;
}
}
bool FakeContextProvider::DestroyedOnMainThread() {
base::AutoLock lock(destroyed_lock_);
return destroyed_;
}
} // namespace cc
| 23.887097 | 73 | 0.740041 | GnorTech |
ed782f71f78615ea0d6b69b6e205495e66e01901 | 2,445 | cpp | C++ | Open3D/cpp/open3d/visualization/gui/Label3D.cpp | xdeng7/redwood_open3d_3dreconstruction | aa1651d3cec1feb00468d548ac2268a3ed17b856 | [
"Apache-2.0"
] | 2 | 2021-03-16T11:36:41.000Z | 2021-03-26T08:52:27.000Z | Open3D/cpp/open3d/visualization/gui/Label3D.cpp | xdeng7/redwood_open3d_3dreconstruction | aa1651d3cec1feb00468d548ac2268a3ed17b856 | [
"Apache-2.0"
] | 1 | 2019-12-15T09:02:38.000Z | 2019-12-15T09:02:38.000Z | Open3D/cpp/open3d/visualization/gui/Label3D.cpp | xdeng7/redwood_open3d_3dreconstruction | aa1651d3cec1feb00468d548ac2268a3ed17b856 | [
"Apache-2.0"
] | 1 | 2021-02-28T15:22:20.000Z | 2021-02-28T15:22:20.000Z | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------------------------------------------------------
#include "open3d/visualization/gui/Label3D.h"
#include <string>
namespace open3d {
namespace visualization {
namespace gui {
static const Color DEFAULT_COLOR(0, 0, 0, 1);
struct Label3D::Impl {
std::string text_;
Eigen::Vector3f position_;
Color color_ = DEFAULT_COLOR;
};
Label3D::Label3D(const Eigen::Vector3f& pos, const char* text /*= nullptr*/)
: impl_(new Label3D::Impl()) {
if (text) {
SetText(text);
}
}
Label3D::~Label3D() {}
const char* Label3D::GetText() const { return impl_->text_.c_str(); }
void Label3D::SetText(const char* text) { impl_->text_ = text; }
Eigen::Vector3f Label3D::GetPosition() const { return impl_->position_; }
void Label3D::SetPosition(const Eigen::Vector3f& pos) {
impl_->position_ = pos;
}
Color Label3D::GetTextColor() const { return impl_->color_; }
void Label3D::SetTextColor(const Color& color) { impl_->color_ = color; }
} // namespace gui
} // namespace visualization
} // namespace open3d
| 35.434783 | 80 | 0.637628 | xdeng7 |
ed7a09e14953f33b3b15f828b3df4233ae1bef45 | 7,296 | cpp | C++ | scopehal/VICPSocketTransport.cpp | x44203/scopehal | 984b38431cdf46c3e9c6055b164e03b4f7336a49 | [
"BSD-3-Clause"
] | null | null | null | scopehal/VICPSocketTransport.cpp | x44203/scopehal | 984b38431cdf46c3e9c6055b164e03b4f7336a49 | [
"BSD-3-Clause"
] | null | null | null | scopehal/VICPSocketTransport.cpp | x44203/scopehal | 984b38431cdf46c3e9c6055b164e03b4f7336a49 | [
"BSD-3-Clause"
] | 1 | 2020-08-02T14:20:52.000Z | 2020-08-02T14:20:52.000Z | /***********************************************************************************************************************
* *
* ANTIKERNEL v0.1 *
* *
* Copyright (c) 2012-2020 Andrew D. Zonenberg *
* 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 author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief Implementation of VICPSocketTransport
*/
#include "scopehal.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
VICPSocketTransport::VICPSocketTransport(string args)
: m_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
{
char hostname[128];
unsigned int port = 0;
if(2 != sscanf(args.c_str(), "%127[^:]:%u", hostname, &port))
{
//default if port not specified
m_hostname = args;
m_port = 1861;
}
else
{
m_hostname = hostname;
m_port = port;
}
LogDebug("Connecting to VICP oscilloscope at %s:%d\n", m_hostname.c_str(), m_port);
if(!m_socket.Connect(m_hostname, m_port))
{
m_socket.Close();
LogError("Couldn't connect to socket\n");
return;
}
if(!m_socket.DisableNagle())
{
m_socket.Close();
LogError("Couldn't disable Nagle\n");
return;
}
}
VICPSocketTransport::~VICPSocketTransport()
{
}
bool VICPSocketTransport::IsConnected()
{
return m_socket.IsValid();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Actual transport code
string VICPSocketTransport::GetTransportName()
{
return "vicp";
}
string VICPSocketTransport::GetConnectionString()
{
char tmp[256];
snprintf(tmp, sizeof(tmp), "%s:%u", m_hostname.c_str(), m_port);
return string(tmp);
}
uint8_t VICPSocketTransport::GetNextSequenceNumber()
{
m_lastSequence = m_nextSequence;
//EOI increments the sequence number.
//Wrap mod 256, but skip zero!
m_nextSequence ++;
if(m_nextSequence == 0)
m_nextSequence = 1;
return m_lastSequence;
}
bool VICPSocketTransport::SendCommand(string cmd)
{
//Operation and flags header
string payload;
uint8_t op = OP_DATA | OP_EOI;
//TODO: remote, clear, poll flags
payload += op;
payload += 0x01; //protocol version number
payload += GetNextSequenceNumber();
payload += '\0'; //reserved
//Next 4 header bytes are the message length (network byte order)
uint32_t len = cmd.length();
payload += (len >> 24) & 0xff;
payload += (len >> 16) & 0xff;
payload += (len >> 8) & 0xff;
payload += (len >> 0) & 0xff;
//Add message data
payload += cmd;
//Actually send it
SendRawData(payload.size(), (const unsigned char*)payload.c_str());
return true;
}
string VICPSocketTransport::ReadReply()
{
string payload;
while(true)
{
//Read the header
unsigned char header[8];
ReadRawData(8, header);
//Sanity check
if(header[1] != 1)
{
LogError("Bad VICP protocol version\n");
return "";
}
if(header[2] != m_lastSequence)
{
//LogError("Bad VICP sequence number %d (expected %d)\n", header[2], m_lastSequence);
//return "";
}
if(header[3] != 0)
{
LogError("Bad VICP reserved field\n");
return "";
}
//Read the message data
uint32_t len = (header[4] << 24) | (header[5] << 16) | (header[6] << 8) | header[7];
string rxbuf;
rxbuf.resize(len);
ReadRawData(len, (unsigned char*)&rxbuf[0]);
//Skip empty blocks, or just newlines
if( (len == 0) || (rxbuf == "\n"))
{
//Special handling needed for EOI.
if(header[0] & OP_EOI)
{
//EOI on an empty block is a stop if we have data from previous blocks.
if(!payload.empty())
break;
//But if we have no data, hold off and wait for the next frame
else
continue;
}
}
//Actual frame data
else
payload += rxbuf;
//Check EOI flag
if(header[0] & OP_EOI)
break;
}
//make sure there's a null terminator
payload += "\0";
return payload;
}
void VICPSocketTransport::SendRawData(size_t len, const unsigned char* buf)
{
m_socket.SendLooped(buf, len);
}
void VICPSocketTransport::ReadRawData(size_t len, unsigned char* buf)
{
m_socket.RecvLooped(buf, len);
}
bool VICPSocketTransport::IsCommandBatchingSupported()
{
return true;
}
| 33.62212 | 120 | 0.497396 | x44203 |
ed7c40908b43202032ee913067216d7c4c9be040 | 3,500 | cpp | C++ | core/src/codecs/default/DefaultIdBloomFilterFormat.cpp | yamasite/milvus | ee3a65a811b5487a92b39418540780fd19f378dc | [
"Apache-2.0"
] | 1 | 2021-10-01T18:16:34.000Z | 2021-10-01T18:16:34.000Z | core/src/codecs/default/DefaultIdBloomFilterFormat.cpp | yamasite/milvus | ee3a65a811b5487a92b39418540780fd19f378dc | [
"Apache-2.0"
] | null | null | null | core/src/codecs/default/DefaultIdBloomFilterFormat.cpp | yamasite/milvus | ee3a65a811b5487a92b39418540780fd19f378dc | [
"Apache-2.0"
] | 2 | 2020-03-02T05:16:57.000Z | 2020-03-04T06:05:55.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "codecs/default/DefaultIdBloomFilterFormat.h"
#include <memory>
#include <string>
#include "utils/Exception.h"
#include "utils/Log.h"
namespace milvus {
namespace codec {
constexpr unsigned int bloom_filter_capacity = 500000;
constexpr double bloom_filter_error_rate = 0.01;
void
DefaultIdBloomFilterFormat::read(const storage::FSHandlerPtr& fs_ptr, segment::IdBloomFilterPtr& id_bloom_filter_ptr) {
const std::lock_guard<std::mutex> lock(mutex_);
std::string dir_path = fs_ptr->operation_ptr_->GetDirectory();
const std::string bloom_filter_file_path = dir_path + "/" + bloom_filter_filename_;
scaling_bloom_t* bloom_filter =
new_scaling_bloom_from_file(bloom_filter_capacity, bloom_filter_error_rate, bloom_filter_file_path.c_str());
if (bloom_filter == nullptr) {
std::string err_msg =
"Failed to read bloom filter from file: " + bloom_filter_file_path + ". " + std::strerror(errno);
ENGINE_LOG_ERROR << err_msg;
throw Exception(SERVER_UNEXPECTED_ERROR, err_msg);
}
id_bloom_filter_ptr = std::make_shared<segment::IdBloomFilter>(bloom_filter);
}
void
DefaultIdBloomFilterFormat::write(const storage::FSHandlerPtr& fs_ptr,
const segment::IdBloomFilterPtr& id_bloom_filter_ptr) {
const std::lock_guard<std::mutex> lock(mutex_);
std::string dir_path = fs_ptr->operation_ptr_->GetDirectory();
const std::string bloom_filter_file_path = dir_path + "/" + bloom_filter_filename_;
if (scaling_bloom_flush(id_bloom_filter_ptr->GetBloomFilter()) == -1) {
std::string err_msg =
"Failed to write bloom filter to file: " + bloom_filter_file_path + ". " + std::strerror(errno);
ENGINE_LOG_ERROR << err_msg;
throw Exception(SERVER_UNEXPECTED_ERROR, err_msg);
}
}
void
DefaultIdBloomFilterFormat::create(const storage::FSHandlerPtr& fs_ptr,
segment::IdBloomFilterPtr& id_bloom_filter_ptr) {
std::string dir_path = fs_ptr->operation_ptr_->GetDirectory();
const std::string bloom_filter_file_path = dir_path + "/" + bloom_filter_filename_;
scaling_bloom_t* bloom_filter =
new_scaling_bloom(bloom_filter_capacity, bloom_filter_error_rate, bloom_filter_file_path.c_str());
if (bloom_filter == nullptr) {
std::string err_msg =
"Failed to read bloom filter from file: " + bloom_filter_file_path + ". " + std::strerror(errno);
ENGINE_LOG_ERROR << err_msg;
throw Exception(SERVER_UNEXPECTED_ERROR, err_msg);
}
id_bloom_filter_ptr = std::make_shared<segment::IdBloomFilter>(bloom_filter);
}
} // namespace codec
} // namespace milvus
| 42.682927 | 119 | 0.722571 | yamasite |
ed7c7062c6784c8205b51a5beed3e2bf783f8d3d | 1,865 | cpp | C++ | CK2ToEU4/Source/Mappers/RulerPersonalitiesMapper/RulerPersonalitiesMapper.cpp | bavbeerhall/CK2ToEU4 | a65edfb895b30e80af5bd7045dbfac7e2c5069e9 | [
"MIT"
] | 2 | 2020-04-25T15:14:10.000Z | 2020-04-25T18:47:00.000Z | CK2ToEU4/Source/Mappers/RulerPersonalitiesMapper/RulerPersonalitiesMapper.cpp | dlbuunk/CK2ToEU4 | 5c1755d17a36950d29a6c0ca13e454cb27b767bf | [
"MIT"
] | null | null | null | CK2ToEU4/Source/Mappers/RulerPersonalitiesMapper/RulerPersonalitiesMapper.cpp | dlbuunk/CK2ToEU4 | 5c1755d17a36950d29a6c0ca13e454cb27b767bf | [
"MIT"
] | null | null | null | #include "RulerPersonalitiesMapper.h"
#include "../../CK2World/Characters/Character.h"
#include "Log.h"
#include "ParserHelpers.h"
mappers::RulerPersonalitiesMapper::RulerPersonalitiesMapper()
{
LOG(LogLevel::Info) << "-> Parsing Ruler Personalities";
registerKeys();
parseFile("configurables/ruler_personalities.txt");
clearRegisteredKeywords();
LOG(LogLevel::Info) << "<> " << theMappings.size() << " personalities loaded.";
}
mappers::RulerPersonalitiesMapper::RulerPersonalitiesMapper(std::istream& theStream)
{
registerKeys();
parseStream(theStream);
clearRegisteredKeywords();
}
void mappers::RulerPersonalitiesMapper::registerKeys()
{
registerRegex("[a-zA-Z0-9_-]+", [this](const std::string& personality, std::istream& theStream) {
const auto newMapping = RulerPersonalitiesMapping(theStream);
theMappings.insert(std::pair(personality, newMapping));
});
registerRegex("[a-zA-Z0-9\\_.:-]+", commonItems::ignoreItem);
}
std::set<std::string> mappers::RulerPersonalitiesMapper::evaluatePersonalities(const std::pair<int, std::shared_ptr<CK2::Character>>& theCharacter) const
{
// In CK2 they are traits. In EU4 they are personalities.
const auto& incTraits = theCharacter.second->getTraits();
std::set<std::string> ck2Traits;
for (const auto& trait: incTraits)
ck2Traits.insert(trait.second);
std::vector<std::pair<int, std::string>> scoreBoard; // personalityscore, personality
std::set<std::string> toReturn;
for (const auto& mapping: theMappings)
{
auto score = mapping.second.evaluatePersonality(ck2Traits);
scoreBoard.emplace_back(std::pair(score, mapping.first));
}
std::sort(scoreBoard.rbegin(), scoreBoard.rend());
// send back first two. EU4 should deal with excess.
for (auto i = 0; i < std::min(2, static_cast<int>(theMappings.size())); i++)
{
toReturn.insert(scoreBoard[i].second);
}
return toReturn;
}
| 33.303571 | 153 | 0.737265 | bavbeerhall |
1431b79db846a46616b69b588bd825b5c88e9056 | 7,415 | cxx | C++ | main/sc/source/ui/view/output3.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sc/source/ui/view/output3.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sc/source/ui/view/output3.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <editeng/eeitem.hxx>
#include <svx/svdograf.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdoutl.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdpagv.hxx>
#include <svx/svdview.hxx>
#include <vcl/svapp.hxx>
#include "output.hxx"
#include "drwlayer.hxx"
#include "document.hxx"
#include "tabvwsh.hxx"
#include "fillinfo.hxx"
#include <svx/fmview.hxx>
//==================================================================
// #i72502#
Point ScOutputData::PrePrintDrawingLayer(long nLogStX, long nLogStY )
{
Rectangle aRect;
SCCOL nCol;
Point aOffset;
long nLayoutSign(bLayoutRTL ? -1 : 1);
for (nCol=0; nCol<nX1; nCol++)
aOffset.X() -= pDoc->GetColWidth( nCol, nTab ) * nLayoutSign;
aOffset.Y() -= pDoc->GetRowHeight( 0, nY1-1, nTab );
long nDataWidth = 0;
long nDataHeight = 0;
for (nCol=nX1; nCol<=nX2; nCol++)
nDataWidth += pDoc->GetColWidth( nCol, nTab );
nDataHeight += pDoc->GetRowHeight( nY1, nY2, nTab );
if ( bLayoutRTL )
aOffset.X() += nDataWidth;
aRect.Left() = aRect.Right() = -aOffset.X();
aRect.Top() = aRect.Bottom() = -aOffset.Y();
Point aMMOffset( aOffset );
aMMOffset.X() = (long)(aMMOffset.X() * HMM_PER_TWIPS);
aMMOffset.Y() = (long)(aMMOffset.Y() * HMM_PER_TWIPS);
if (!bMetaFile)
aMMOffset += Point( nLogStX, nLogStY );
for (nCol=nX1; nCol<=nX2; nCol++)
aRect.Right() += pDoc->GetColWidth( nCol, nTab );
aRect.Bottom() += pDoc->GetRowHeight( nY1, nY2, nTab );
aRect.Left() = (long) (aRect.Left() * HMM_PER_TWIPS);
aRect.Top() = (long) (aRect.Top() * HMM_PER_TWIPS);
aRect.Right() = (long) (aRect.Right() * HMM_PER_TWIPS);
aRect.Bottom() = (long) (aRect.Bottom() * HMM_PER_TWIPS);
if(pViewShell || pDrawView)
{
SdrView* pLocalDrawView = (pDrawView) ? pDrawView : pViewShell->GetSdrView();
if(pLocalDrawView)
{
// #i76114# MapMode has to be set because BeginDrawLayers uses GetPaintRegion
MapMode aOldMode = pDev->GetMapMode();
if (!bMetaFile)
pDev->SetMapMode( MapMode( MAP_100TH_MM, aMMOffset, aOldMode.GetScaleX(), aOldMode.GetScaleY() ) );
// #i74769# work with SdrPaintWindow directly
// #i76114# pass bDisableIntersect = true, because the intersection of the table area
// with the Window's paint region can be empty
Region aRectRegion(aRect);
mpTargetPaintWindow = pLocalDrawView->BeginDrawLayers(pDev, aRectRegion, true);
OSL_ENSURE(mpTargetPaintWindow, "BeginDrawLayers: Got no SdrPaintWindow (!)");
if (!bMetaFile)
pDev->SetMapMode( aOldMode );
}
}
return aMMOffset;
}
// #i72502#
void ScOutputData::PostPrintDrawingLayer(const Point& rMMOffset) // #i74768#
{
// #i74768# just use offset as in PrintDrawingLayer() to also get the form controls
// painted with offset
MapMode aOldMode = pDev->GetMapMode();
if (!bMetaFile)
{
pDev->SetMapMode( MapMode( MAP_100TH_MM, rMMOffset, aOldMode.GetScaleX(), aOldMode.GetScaleY() ) );
}
if(pViewShell || pDrawView)
{
SdrView* pLocalDrawView = (pDrawView) ? pDrawView : pViewShell->GetSdrView();
if(pLocalDrawView)
{
// #i74769# work with SdrPaintWindow directly
pLocalDrawView->EndDrawLayers(*mpTargetPaintWindow, true);
mpTargetPaintWindow = 0;
}
}
// #i74768#
if (!bMetaFile)
{
pDev->SetMapMode( aOldMode );
}
}
// #i72502#
void ScOutputData::PrintDrawingLayer(const sal_uInt16 nLayer, const Point& rMMOffset)
{
bool bHideAllDrawingLayer(false);
if(pViewShell || pDrawView)
{
SdrView* pLocalDrawView = (pDrawView) ? pDrawView : pViewShell->GetSdrView();
if(pLocalDrawView)
{
bHideAllDrawingLayer = pLocalDrawView->getHideOle() && pLocalDrawView->getHideChart()
&& pLocalDrawView->getHideDraw() && pLocalDrawView->getHideFormControl();
}
}
// #109985#
if(bHideAllDrawingLayer || (!pDoc->GetDrawLayer()))
{
return;
}
MapMode aOldMode = pDev->GetMapMode();
if (!bMetaFile)
{
pDev->SetMapMode( MapMode( MAP_100TH_MM, rMMOffset, aOldMode.GetScaleX(), aOldMode.GetScaleY() ) );
}
// #109985#
DrawSelectiveObjects( nLayer );
if (!bMetaFile)
{
pDev->SetMapMode( aOldMode );
}
}
// #109985#
void ScOutputData::DrawSelectiveObjects(const sal_uInt16 nLayer)
{
ScDrawLayer* pModel = pDoc->GetDrawLayer();
if (!pModel)
return;
// #i46362# high contrast mode (and default text direction) must be handled
// by the application, so it's still needed when using DrawLayer().
SdrOutliner& rOutl = pModel->GetDrawOutliner();
rOutl.EnableAutoColor( bUseStyleColor );
rOutl.SetDefaultHorizontalTextDirection(
(EEHorizontalTextDirection)pDoc->GetEditTextDirection( nTab ) );
// #i69767# The hyphenator must be set (used to be before drawing a text shape with hyphenation).
// LinguMgr::GetHyphenator (EditEngine) uses a wrapper now that creates the real hyphenator on demand,
// so it's not a performance problem to call UseHyphenator even when it's not needed.
pModel->UseHyphenator();
sal_uLong nOldDrawMode = pDev->GetDrawMode();
if ( bUseStyleColor && Application::GetSettings().GetStyleSettings().GetHighContrastMode() )
{
pDev->SetDrawMode( nOldDrawMode | DRAWMODE_SETTINGSLINE | DRAWMODE_SETTINGSFILL |
DRAWMODE_SETTINGSTEXT | DRAWMODE_SETTINGSGRADIENT );
}
// #109985#
if(pViewShell || pDrawView)
{
SdrView* pLocalDrawView = (pDrawView) ? pDrawView : pViewShell->GetSdrView();
if(pLocalDrawView)
{
SdrPageView* pPageView = pLocalDrawView->GetSdrPageView();
if(pPageView)
{
pPageView->DrawLayer(sal::static_int_cast<SdrLayerID>(nLayer), pDev);
}
}
}
pDev->SetDrawMode(nOldDrawMode);
// #109985#
return;
}
// Teile nur fuer Bildschirm
// #109985#
void ScOutputData::DrawingSingle(const sal_uInt16 nLayer)
{
sal_Bool bHad = sal_False;
long nPosY = nScrY;
SCSIZE nArrY;
for (nArrY=1; nArrY+1<nArrCount; nArrY++)
{
RowInfo* pThisRowInfo = &pRowInfo[nArrY];
if ( pThisRowInfo->bChanged )
{
if (!bHad)
{
bHad = sal_True;
}
}
else if (bHad)
{
DrawSelectiveObjects( nLayer );
bHad = sal_False;
}
nPosY += pRowInfo[nArrY].nHeight;
}
if (bHad)
DrawSelectiveObjects( nLayer );
}
| 27.565056 | 115 | 0.657047 | Grosskopf |
14338e16675bc71fcc0664b66520f21cb4ae551c | 7,233 | cc | C++ | components/sync_sessions/favicon_cache.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/sync_sessions/favicon_cache.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/sync_sessions/favicon_cache.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 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/sync_sessions/favicon_cache.h"
#include <utility>
#include "base/bind.h"
#include "components/favicon/core/favicon_service.h"
#include "components/history/core/browser/history_types.h"
#include "components/sync/protocol/session_specifics.pb.h"
namespace sync_sessions {
struct FaviconInfo {
explicit FaviconInfo(const GURL& favicon_url)
: favicon_url(favicon_url), last_visit_time(base::Time::Now()) {}
// The URL this favicon was loaded from.
const GURL favicon_url;
// The last time a tab needed this favicon.
const base::Time last_visit_time;
private:
DISALLOW_COPY_AND_ASSIGN(FaviconInfo);
};
namespace {
// Desired size of favicons to load from the cache when translating page url to
// icon url.
const int kDesiredSizeInPx = 16;
// Returns a mask of the supported favicon types.
favicon_base::IconTypeSet SupportedFaviconTypes() {
return {favicon_base::IconType::kFavicon};
}
} // namespace
FaviconCache::FaviconCache(favicon::FaviconService* favicon_service,
history::HistoryService* history_service,
int max_mappings_limit)
: favicon_service_(favicon_service),
max_mappings_limit_(max_mappings_limit) {
if (history_service)
history_service_observer_.Add(history_service);
DVLOG(1) << "Setting mapping limit to " << max_mappings_limit;
}
FaviconCache::~FaviconCache() {}
void FaviconCache::OnPageFaviconUpdated(const GURL& page_url) {
DCHECK(page_url.is_valid());
// If a favicon load is already happening for this url, let it finish.
if (page_task_map_.find(page_url) != page_task_map_.end())
return;
// If a mapping already exists, rely on the cached mapping.
const GURL favicon_url = GetIconUrlForPageUrl(page_url);
if (favicon_url.is_valid()) {
// Reset the same value to update the last visit time.
SetIconUrlForPageUrl(page_url, favicon_url);
return;
}
DVLOG(1) << "Triggering favicon load for url " << page_url.spec();
// Can be nullptr in tests.
if (!favicon_service_)
return;
base::CancelableTaskTracker::TaskId id =
favicon_service_->GetFaviconForPageURL(
page_url, SupportedFaviconTypes(), kDesiredSizeInPx,
base::BindOnce(&FaviconCache::OnFaviconDataAvailable,
weak_ptr_factory_.GetWeakPtr(), page_url),
&cancelable_task_tracker_);
page_task_map_[page_url] = id;
}
void FaviconCache::OnFaviconVisited(const GURL& page_url,
const GURL& favicon_url) {
DCHECK(page_url.is_valid());
if (!favicon_url.is_valid()) {
OnPageFaviconUpdated(page_url);
return;
}
SetIconUrlForPageUrl(page_url, favicon_url);
}
GURL FaviconCache::GetIconUrlForPageUrl(const GURL& page_url) const {
auto iter = page_favicon_map_.find(page_url);
if (iter == page_favicon_map_.end())
return GURL();
return iter->second->favicon_url;
}
void FaviconCache::UpdateMappingsFromForeignTab(
const sync_pb::SessionTab& tab) {
for (const sync_pb::TabNavigation& navigation : tab.navigation()) {
const GURL page_url(navigation.virtual_url());
const GURL icon_url(navigation.favicon_url());
if (!icon_url.is_valid() || !page_url.is_valid() ||
icon_url.SchemeIs("data")) {
continue;
}
SetIconUrlForPageUrl(page_url, icon_url);
}
}
base::WeakPtr<FaviconCache> FaviconCache::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
size_t FaviconCache::NumTasksForTest() const {
return page_task_map_.size();
}
size_t FaviconCache::NumFaviconMappingsForTest() const {
return page_favicon_map_.size();
}
bool FaviconCache::FaviconRecencyFunctor::operator()(
const FaviconInfo* lhs,
const FaviconInfo* rhs) const {
if (lhs->last_visit_time < rhs->last_visit_time)
return true;
else if (lhs->last_visit_time == rhs->last_visit_time)
return lhs->favicon_url.spec() < rhs->favicon_url.spec();
return false;
}
void FaviconCache::OnFaviconDataAvailable(
const GURL& page_url,
const std::vector<favicon_base::FaviconRawBitmapResult>& bitmap_results) {
auto page_iter = page_task_map_.find(page_url);
if (page_iter == page_task_map_.end())
return;
page_task_map_.erase(page_iter);
if (bitmap_results.size() == 0) {
// Either the favicon isn't loaded yet or there is no valid favicon.
// We already cleared the task id, so just return.
DVLOG(1) << "Favicon load failed for page " << page_url.spec();
return;
}
for (size_t i = 0; i < bitmap_results.size(); ++i) {
const favicon_base::FaviconRawBitmapResult& bitmap_result =
bitmap_results[i];
GURL favicon_url = bitmap_result.icon_url;
if (!favicon_url.is_valid() || favicon_url.SchemeIs("data"))
continue; // Can happen if the page is still loading.
SetIconUrlForPageUrl(page_url, favicon_url);
}
}
void FaviconCache::SetIconUrlForPageUrl(const GURL& page_url,
const GURL& favicon_url) {
DCHECK_EQ(recent_mappings_.size(), page_favicon_map_.size());
// If |page_url| is mapped, remove it's current mapping from the recency set.
const auto& iter = page_favicon_map_.find(page_url);
if (iter != page_favicon_map_.end()) {
FaviconInfo* old_info = iter->second.get();
recent_mappings_.erase(old_info);
}
DVLOG(1) << "Associating " << page_url.spec() << " with favicon at "
<< favicon_url.spec();
auto new_info = std::make_unique<FaviconInfo>(favicon_url);
recent_mappings_.insert(new_info.get());
page_favicon_map_[page_url] = std::move(new_info);
DCHECK_EQ(recent_mappings_.size(), page_favicon_map_.size());
// Expire old mappings (if needed).
while (recent_mappings_.size() > max_mappings_limit_) {
FaviconInfo* candidate = *recent_mappings_.begin();
DVLOG(1) << "Expiring favicon " << candidate->favicon_url.spec();
recent_mappings_.erase(recent_mappings_.begin());
base::EraseIf(page_favicon_map_, [candidate](const auto& kv) {
return kv.second.get() == candidate;
});
}
DCHECK_EQ(recent_mappings_.size(), page_favicon_map_.size());
}
void FaviconCache::OnURLsDeleted(history::HistoryService* history_service,
const history::DeletionInfo& deletion_info) {
// We only care about actual user (or sync) deletions.
if (deletion_info.is_from_expiration())
return;
if (!deletion_info.IsAllHistory()) {
for (const GURL& favicon_url : deletion_info.favicon_urls()) {
DVLOG(1) << "Dropping mapping for favicon " << favicon_url;
base::EraseIf(recent_mappings_, [favicon_url](const FaviconInfo* info) {
return info->favicon_url == favicon_url;
});
base::EraseIf(page_favicon_map_, [favicon_url](const auto& kv) {
return kv.second->favicon_url == favicon_url;
});
}
return;
}
// All history was cleared: just delete all mappings.
DVLOG(1) << "History clear detected, deleting all mappings.";
recent_mappings_.clear();
page_favicon_map_.clear();
}
} // namespace sync_sessions
| 32.728507 | 79 | 0.702198 | sarang-apps |
14344357127d3b9c72846d69dab9ecc638811cfc | 54,675 | cpp | C++ | engine/src/execution_kernels/BatchJoinProcessing.cpp | davisusanibar/blazingsql | ee3e7b0150489d6ee21ca680728be40a27f5125c | [
"Apache-2.0"
] | null | null | null | engine/src/execution_kernels/BatchJoinProcessing.cpp | davisusanibar/blazingsql | ee3e7b0150489d6ee21ca680728be40a27f5125c | [
"Apache-2.0"
] | null | null | null | engine/src/execution_kernels/BatchJoinProcessing.cpp | davisusanibar/blazingsql | ee3e7b0150489d6ee21ca680728be40a27f5125c | [
"Apache-2.0"
] | null | null | null | #include <string>
#include "BatchJoinProcessing.h"
#include "ExceptionHandling/BlazingThread.h"
#include "parser/expression_tree.hpp"
#include "utilities/CodeTimer.h"
#include <cudf/partitioning.hpp>
#include <cudf/join.hpp>
#include <cudf/stream_compaction.hpp>
#include <src/execution_kernels/LogicalFilter.h>
#include "execution_graph/executor.h"
#include "cache_machine/CPUCacheData.h"
namespace ral {
namespace batch {
std::tuple<std::string, std::string, std::string, std::string> parseExpressionToGetTypeAndCondition(const std::string & expression) {
std::string modified_expression, condition, filter_statement, join_type, new_join_statement;
modified_expression = expression;
StringUtil::findAndReplaceAll(modified_expression, "IS NOT DISTINCT FROM", "IS_NOT_DISTINCT_FROM");
split_inequality_join_into_join_and_filter(modified_expression, new_join_statement, filter_statement);
// Getting the condition and type of join
condition = get_named_expression(new_join_statement, "condition");
join_type = get_named_expression(new_join_statement, "joinType");
if (condition == "true") {
join_type = CROSS_JOIN;
}
return std::make_tuple(modified_expression, condition, filter_statement, join_type);
}
void parseJoinConditionToColumnIndices(const std::string & condition, std::vector<int> & columnIndices) {
// TODO: right now this only works for equijoins
// since this is all that is implemented at the time
// TODO: for this to work properly we can only do multi column join
// when we have `ands`, when we have `ors` we have to perform the join seperately then
// do a unique merge of the indices
// right now with pred push down the join codnition takes the filters as the second argument to condition
std::string clean_expression = clean_calcite_expression(condition);
int operator_count = 0;
std::stack<std::string> operand;
std::vector<std::string> tokens = get_tokens_in_reverse_order(clean_expression);
for(std::string token : tokens) {
if(is_operator_token(token)) {
if(token == "=" || token == "IS_NOT_DISTINCT_FROM") {
// so far only equijoins are supported in libgdf
operator_count++;
} else if(token != "AND") {
throw std::runtime_error("In evaluate_join function: unsupported non-equijoins operator");
}
} else {
operand.push(token);
}
}
columnIndices.resize(2 * operator_count);
for(int i = 0; i < operator_count; i++) {
int right_index = get_index(operand.top());
operand.pop();
int left_index = get_index(operand.top());
operand.pop();
if(right_index < left_index) {
std::swap(left_index, right_index);
}
columnIndices[2 * i] = left_index;
columnIndices[2 * i + 1] = right_index;
}
}
cudf::null_equality parseJoinConditionToEqualityTypes(const std::string & condition) {
// TODO: right now this only works for equijoins
// since this is all that is implemented at the time
std::string clean_expression = clean_calcite_expression(condition);
std::vector<std::string> tokens = get_tokens_in_reverse_order(clean_expression);
std::vector<cudf::null_equality> joinEqualityTypes;
for(std::string token : tokens) {
if(is_operator_token(token)) {
// so far only equijoins are supported in libgdf
if(token == "="){
joinEqualityTypes.push_back(cudf::null_equality::UNEQUAL);
} else if(token == "IS_NOT_DISTINCT_FROM") {
joinEqualityTypes.push_back(cudf::null_equality::EQUAL);
} else if(token != "AND") {
throw std::runtime_error("In evaluate_join function: unsupported non-equijoins operator");
}
}
}
if(joinEqualityTypes.empty()){
throw std::runtime_error("In evaluate_join function: unrecognized joining type operators");
}
// TODO: There may be cases where there is a mixture of
// equality operators (not for IS NOT DISTINCT FROM). We do not support it for now,
// since that is not supported in cudf.
// We only rely on the first equality type found.
bool all_types_are_equal = std::all_of(joinEqualityTypes.begin(), joinEqualityTypes.end(), [&](const cudf::null_equality & elem) {return elem == joinEqualityTypes.front();});
if(!all_types_are_equal){
throw std::runtime_error("In evaluate_join function: unsupported different equijoins operators");
}
return joinEqualityTypes[0];
}
/*
This function will take a join_statement and if it contains anything that is not an equijoin, it will try to break it up into an equijoin (new_join_statement) and a filter (filter_statement)
If its just an equijoin, then the new_join_statement will just be join_statement and filter_statement will be empty
Examples:
Basic case:
join_statement = LogicalJoin(condition=[=($3, $0)], joinType=[inner])
new_join_statement = LogicalJoin(condition=[=($3, $0)], joinType=[inner])
filter_statement = ""
Simple case:
join_statement = LogicalJoin(condition=[AND(=($3, $0), >($5, $2))], joinType=[inner])
new_join_statement = LogicalJoin(condition=[=($3, $0)], joinType=[inner])
filter_statement = LogicalFilter(condition=[>($5, $2)])
Complex case:
join_statement = LogicalJoin(condition=[AND(=($7, $0), OR(AND($8, $9, $2, $3), AND($8, $9, $4, $5), AND($8, $9, $6, $5)))], joinType=[inner])
new_join_statement = LogicalJoin(condition=[=($7, $0)], joinType=[inner])
filter_statement = LogicalFilter(condition=[OR(AND($8, $9, $2, $3), AND($8, $9, $4, $5), AND($8, $9, $6, $5))])
IS NOT DISTINCT FROM case:
join_statement = LogicalJoin(condition=[AND(=($0, $3), IS_NOT_DISTINCT_FROM($1, $3))], joinType=[inner])
new_join_statement = LogicalJoin(condition=[=($0, $3)], joinType=[inner])
filter_statement = LogicalFilter(condition=[OR(AND(IS NULL($1), IS NULL($3)), IS TRUE(=($1 , $3)))])
Error case:
join_statement = LogicalJoin(condition=[OR(=($7, $0), AND($8, $9, $2, $3), AND($8, $9, $4, $5), AND($8, $9, $6, $5))], joinType=[inner])
Should throw an error
Error case:
join_statement = LogicalJoin(condition=[AND(<($7, $0), >($7, $1)], joinType=[inner])
Should throw an error
*/
void split_inequality_join_into_join_and_filter(const std::string & join_statement, std::string & new_join_statement, std::string & filter_statement){
new_join_statement = join_statement;
filter_statement = "";
std::string condition = get_named_expression(join_statement, "condition");
condition = replace_calcite_regex(condition);
std::string join_type = get_named_expression(join_statement, "joinType");
ral::parser::parse_tree tree;
tree.build(condition);
std::string new_join_statement_expression, filter_statement_expression;
assert(tree.root().type == ral::parser::node_type::OPERATOR or
tree.root().type == ral::parser::node_type::LITERAL); // condition=[true] (for cross join)
if (tree.root().value == "=" || tree.root().value == "IS_NOT_DISTINCT_FROM") {
// this would be a regular single equality join
new_join_statement_expression = condition; // the join_out is the same as the original input
filter_statement_expression = ""; // no filter out
} else if (tree.root().value == "AND") {
size_t num_equalities = 0;
size_t num_equal_due_is_not_dist = 0;
for (auto&& c : tree.root().children) {
if (c->value == "=") {
num_equalities++;
} else if (c->value == "IS_NOT_DISTINCT_FROM") {
num_equalities++;
num_equal_due_is_not_dist++;
}
}
if (num_equalities == tree.root().children.size()) { // all are equalities. this would be a regular multiple equality join
if (num_equal_due_is_not_dist > 0) {
std::tie(new_join_statement_expression, filter_statement_expression) = update_join_and_filter_expressions_from_is_not_distinct_expr(condition);
} else {
new_join_statement_expression = condition;
filter_statement_expression = "";
}
} else if (num_equalities > 0) { // i can split this into an equality join and a filter
if (num_equalities == 1) { // if there is only one equality, then the root_ for join_out wont be an AND,
// and we will just have this equality as the root_
if (tree.root().children.size() == 2) {
for (auto&& c : tree.root().children) {
if (c->value == "=" || c->value == "IS_NOT_DISTINCT_FROM") {
new_join_statement_expression = ral::parser::detail::rebuild_helper(c.get());
} else {
filter_statement_expression = ral::parser::detail::rebuild_helper(c.get());
}
}
} else {
auto filter_root = std::make_unique<ral::parser::operator_node>("AND");
for (auto&& c : tree.root().children) {
if (c->value == "=" || c->value == "IS_NOT_DISTINCT_FROM") {
new_join_statement_expression = ral::parser::detail::rebuild_helper(c.get());
} else {
filter_root->children.push_back(std::unique_ptr<ral::parser::node>(c->clone()));
}
}
filter_statement_expression = ral::parser::detail::rebuild_helper(filter_root.get());
}
} else if (num_equalities == tree.root().children.size() - 1) {
// only one that does not have an inequality and therefore will be
// in the filter (without an and at the root_)
auto join_out_root = std::make_unique<ral::parser::operator_node>("AND");
for (auto&& c : tree.root().children) {
if (c->value == "=" || c->value == "IS_NOT_DISTINCT_FROM") {
join_out_root->children.push_back(std::unique_ptr<ral::parser::node>(c->clone()));
} else {
filter_statement_expression = ral::parser::detail::rebuild_helper(c.get());
}
}
new_join_statement_expression = ral::parser::detail::rebuild_helper(join_out_root.get());
// Now that we support IS_NOT_DISTINCT_FROM for join let's update if it is needed
if (new_join_statement_expression.find("IS_NOT_DISTINCT_FROM") != new_join_statement_expression.npos) {
std::tie(new_join_statement_expression, filter_statement_expression) = update_join_and_filter_expressions_from_is_not_distinct_expr(condition);
}
} else {
auto join_out_root = std::make_unique<ral::parser::operator_node>("AND");
auto filter_root = std::make_unique<ral::parser::operator_node>("AND");
for (auto&& c : tree.root().children) {
if (c->value == "=" || c->value == "IS_NOT_DISTINCT_FROM") {
join_out_root->children.push_back(std::unique_ptr<ral::parser::node>(c->clone()));
} else {
filter_root->children.push_back(std::unique_ptr<ral::parser::node>(c->clone()));
}
}
new_join_statement_expression = ral::parser::detail::rebuild_helper(join_out_root.get());
filter_statement_expression = ral::parser::detail::rebuild_helper(filter_root.get());
}
} else {
RAL_FAIL("Join condition is currently not supported");
}
} else if (tree.root().value == "true") { // cross join case
new_join_statement_expression = "true";
}
else {
RAL_FAIL("Join condition is currently not supported");
}
new_join_statement = "LogicalJoin(condition=[" + new_join_statement_expression + "], joinType=[" + join_type + "])";
if (filter_statement_expression != ""){
filter_statement = "LogicalFilter(condition=[" + filter_statement_expression + "])";
} else {
filter_statement = "";
}
}
// BEGIN PartwiseJoin
PartwiseJoin::PartwiseJoin(std::size_t kernel_id, const std::string & queryString, std::shared_ptr<Context> context, std::shared_ptr<ral::cache::graph> query_graph)
: kernel{kernel_id, queryString, context, kernel_type::PartwiseJoinKernel} {
this->query_graph = query_graph;
this->input_.add_port("input_a", "input_b");
this->max_left_ind = -1;
this->max_right_ind = -1;
ral::cache::cache_settings cache_machine_config;
cache_machine_config.type = ral::cache::CacheType::SIMPLE;
cache_machine_config.context = context->clone();
std::string left_array_cache_name = std::to_string(this->get_id()) + "_left_array";
this->leftArrayCache = ral::cache::create_cache_machine(cache_machine_config, left_array_cache_name);
std::string right_array_cache_name = std::to_string(this->get_id()) + "_right_array";
this->rightArrayCache = ral::cache::create_cache_machine(cache_machine_config, right_array_cache_name);
std::tie(this->expression, this->condition, this->filter_statement, this->join_type) = parseExpressionToGetTypeAndCondition(this->expression);
if (this->filter_statement != "" && this->join_type != INNER_JOIN){
throw std::runtime_error("Outer joins with inequalities are not currently supported");
}
}
std::unique_ptr<ral::cache::CacheData> PartwiseJoin::load_left_set(){
this->max_left_ind++;
auto cache_data = this->left_input->pullCacheData();
RAL_EXPECTS(cache_data != nullptr, "In PartwiseJoin: The left input cache data cannot be null");
return cache_data;
}
std::unique_ptr<ral::cache::CacheData> PartwiseJoin::load_right_set(){
this->max_right_ind++;
auto cache_data = this->right_input->pullCacheData();
RAL_EXPECTS(cache_data != nullptr, "In PartwiseJoin: The right input cache data cannot be null");
return cache_data;
}
void PartwiseJoin::mark_set_completed(int left_ind, int right_ind){
assert(left_ind >=0 && right_ind >=0 );
if (completion_matrix.size() <= static_cast<size_t>(left_ind)){
size_t old_row_size = completion_matrix.size();
completion_matrix.resize(left_ind + 1);
if (old_row_size > 0) {
size_t column_size = completion_matrix[0].size();
for (size_t i = old_row_size; i < completion_matrix.size(); i++) {
completion_matrix[i].resize(column_size, false);
}
}
}
if (completion_matrix[left_ind].size() <= static_cast<size_t>(right_ind)){ // if we need to resize, lets resize the whole matrix, making sure that the default is false
for (std::size_t i = 0; i < completion_matrix.size(); i++){
completion_matrix[i].resize(right_ind + 1, false);
}
}
completion_matrix[left_ind][right_ind] = true;
}
// This function checks to see if there is a set from our current completion_matix (data we have already loaded once)
// that we have not completed that uses one of our current indices, otherwise it returns [-1, -1]
std::tuple<int, int> PartwiseJoin::check_for_another_set_to_do_with_data_we_already_have(int left_ind, int right_ind) {
assert(left_ind == -1 || right_ind == -1);
auto left_indices = leftArrayCache->get_all_indexes();
auto right_indices = rightArrayCache->get_all_indexes();
if (left_ind >= 0 ) {
assert(left_ind >= completion_matrix.size());
return {left_ind, (!right_indices.empty() ? right_indices[0] : 0)};
}
if (right_ind >= 0 ) {
assert(right_ind >= completion_matrix[0].size());
return {(!left_indices.empty() ? left_indices[0] : 0), right_ind};
}
for (auto &&i : left_indices) {
for (auto &&j : right_indices) {
if (!completion_matrix[i][j]) {
return {i, j};
}
}
}
return {-1, -1};
}
// This function returns the first not completed set, otherwise it returns [-1, -1]
std::tuple<int, int> PartwiseJoin::check_for_set_that_has_not_been_completed(){
for (size_t i = 0; i < completion_matrix.size(); i++){
for (size_t j = 0; j < completion_matrix[i].size(); j++){
if (!completion_matrix[i][j]){
return {i, j};
}
}
}
return {-1, -1};
}
// this function makes sure that the columns being joined are of the same type so that we can join them properly
void PartwiseJoin::computeNormalizationData(const std::vector<cudf::data_type> & left_types, const std::vector<cudf::data_type> & right_types){
std::vector<cudf::data_type> left_join_types, right_join_types;
for (size_t i = 0; i < this->left_column_indices.size(); i++){
left_join_types.push_back(left_types[this->left_column_indices[i]]);
right_join_types.push_back(right_types[this->right_column_indices[i]]);
}
bool strict = true;
this->join_column_common_types = ral::utilities::get_common_types(left_join_types, right_join_types, strict);
this->normalize_left = !std::equal(this->join_column_common_types.cbegin(), this->join_column_common_types.cend(),
left_join_types.cbegin(), left_join_types.cend());
this->normalize_right = !std::equal(this->join_column_common_types.cbegin(), this->join_column_common_types.cend(),
right_join_types.cbegin(), right_join_types.cend());
}
std::unique_ptr<cudf::table> reordering_columns_due_to_right_join(std::unique_ptr<cudf::table> table_ptr, size_t right_columns) {
std::vector<std::unique_ptr<cudf::column>> columns_ptr = table_ptr->release();
std::vector<std::unique_ptr<cudf::column>> columns_right_pos;
// First let's put all the left columns
for (size_t index = right_columns; index < columns_ptr.size(); ++index) {
columns_right_pos.push_back(std::move(columns_ptr[index]));
}
// Now let's append right columns
for (size_t index = 0; index < right_columns; ++index) {
columns_right_pos.push_back(std::move(columns_ptr[index]));
}
return std::make_unique<cudf::table>(std::move(columns_right_pos));
}
std::unique_ptr<ral::frame::BlazingTable> PartwiseJoin::join_set(
const ral::frame::BlazingTableView & table_left,
const ral::frame::BlazingTableView & table_right)
{
std::unique_ptr<CudfTable> result_table;
if (this->join_type == CROSS_JOIN) {
result_table = cudf::cross_join(
table_left.view(),
table_right.view());
} else {
bool has_nulls_left = ral::processor::check_if_has_nulls(table_left.view(), left_column_indices);
bool has_nulls_right = ral::processor::check_if_has_nulls(table_right.view(), right_column_indices);
if(this->join_type == INNER_JOIN) {
cudf::null_equality equalityType = parseJoinConditionToEqualityTypes(this->condition);
result_table = cudf::inner_join(
table_left.view(),
table_right.view(),
this->left_column_indices,
this->right_column_indices,
equalityType);
} else if(this->join_type == LEFT_JOIN) {
//Removing nulls on right key columns before joining
std::unique_ptr<CudfTable> table_right_dropna;
bool has_nulls_right = ral::processor::check_if_has_nulls(table_right.view(), right_column_indices);
if(has_nulls_right){
table_right_dropna = cudf::drop_nulls(table_right.view(), right_column_indices);
}
result_table = cudf::left_join(
table_left.view(),
has_nulls_right ? table_right_dropna->view() : table_right.view(),
this->left_column_indices,
this->right_column_indices);
} else if(this->join_type == RIGHT_JOIN) {
//Removing nulls on left key columns before joining
std::unique_ptr<CudfTable> table_left_dropna;
bool has_nulls_left = ral::processor::check_if_has_nulls(table_left.view(), left_column_indices);
if(has_nulls_left){
table_left_dropna = cudf::drop_nulls(table_left.view(), left_column_indices);
}
result_table = cudf::left_join(
table_right.view(),
has_nulls_left ? table_left_dropna->view() : table_left.view(),
this->right_column_indices,
this->left_column_indices);
// After a right join is performed, we want to make sure the left column keep on the left side of result_table
result_table = reordering_columns_due_to_right_join(std::move(result_table), table_right.num_columns());
} else if(this->join_type == OUTER_JOIN) {
result_table = cudf::full_join(
table_left.view(),
table_right.view(),
this->left_column_indices,
this->right_column_indices,
(has_nulls_left && has_nulls_right) ? cudf::null_equality::UNEQUAL : cudf::null_equality::EQUAL);
} else {
RAL_FAIL("Unsupported join operator");
}
}
return std::make_unique<ral::frame::BlazingTable>(std::move(result_table), this->result_names);
}
ral::execution::task_result PartwiseJoin::do_process(std::vector<std::unique_ptr<ral::frame::BlazingTable>> inputs,
std::shared_ptr<ral::cache::CacheMachine> /*output*/,
cudaStream_t /*stream*/, const std::map<std::string, std::string>& args) {
CodeTimer eventTimer;
auto & left_batch = inputs[0];
auto & right_batch = inputs[1];
try{
if (this->normalize_left){
ral::utilities::normalize_types(left_batch, this->join_column_common_types, this->left_column_indices);
}
if (this->normalize_right){
ral::utilities::normalize_types(right_batch, this->join_column_common_types, this->right_column_indices);
}
auto log_input_num_rows = left_batch->num_rows() + right_batch->num_rows();
auto log_input_num_bytes = left_batch->sizeInBytes() + right_batch->sizeInBytes();
std::unique_ptr<ral::frame::BlazingTable> joined = join_set(left_batch->toBlazingTableView(), right_batch->toBlazingTableView());
auto log_output_num_rows = joined->num_rows();
auto log_output_num_bytes = joined->sizeInBytes();
if (filter_statement != "") {
auto filter_table = ral::processor::process_filter(joined->toBlazingTableView(), filter_statement, this->context.get());
eventTimer.stop();
log_output_num_rows = filter_table->num_rows();
log_output_num_bytes = filter_table->sizeInBytes();
this->add_to_output_cache(std::move(filter_table));
} else{
eventTimer.stop();
this->add_to_output_cache(std::move(joined));
}
}catch(const rmm::bad_alloc& e){
return {ral::execution::task_status::RETRY, std::string(e.what()), std::move(inputs)};
}catch(const std::exception& e){
return {ral::execution::task_status::FAIL, std::string(e.what()), std::vector< std::unique_ptr<ral::frame::BlazingTable> > ()};
}
try{
this->leftArrayCache->put(std::stoi(args.at("left_idx")), std::move(left_batch));
this->rightArrayCache->put(std::stoi(args.at("right_idx")), std::move(right_batch));
}catch(const rmm::bad_alloc& e){
//can still recover if the input was not a GPUCacheData
return {ral::execution::task_status::RETRY, std::string(e.what()), std::move(inputs)};
}catch(const std::exception& e){
return {ral::execution::task_status::FAIL, std::string(e.what()), std::vector< std::unique_ptr<ral::frame::BlazingTable> > ()};
}
return {ral::execution::task_status::SUCCESS, std::string(), std::vector< std::unique_ptr<ral::frame::BlazingTable> > ()};
}
kstatus PartwiseJoin::run() {
CodeTimer timer;
left_input = this->input_.get_cache("input_a");
right_input = this->input_.get_cache("input_b");
bool done = false;
while (!done) {
std::unique_ptr<ral::cache::CacheData> left_cache_data, right_cache_data;
int left_ind, right_ind;
if (max_left_ind == -1 && max_right_ind == -1){
// before we load anything, lets make sure each side has data to process
left_input->wait_for_next();
right_input->wait_for_next();
left_cache_data = load_left_set();
right_cache_data = load_right_set();
left_ind = this->max_left_ind = 0; // we have loaded just once. This is the highest index for now
right_ind = this->max_right_ind = 0; // we have loaded just once. This is the highest index for now
// parsing more of the expression here because we need to have the number of columns of the tables
std::vector<int> column_indices;
parseJoinConditionToColumnIndices(this->condition, column_indices);
for(std::size_t i = 0; i < column_indices.size();i++){
if(column_indices[i] >= static_cast<int>(left_cache_data->num_columns())){
this->right_column_indices.push_back(column_indices[i] - left_cache_data->num_columns());
}else{
this->left_column_indices.push_back(column_indices[i]);
}
}
std::vector<std::string> left_names = left_cache_data->names();
std::vector<std::string> right_names = right_cache_data->names();
this->result_names.reserve(left_names.size() + right_names.size());
this->result_names.insert(this->result_names.end(), left_names.begin(), left_names.end());
this->result_names.insert(this->result_names.end(), right_names.begin(), right_names.end());
computeNormalizationData(left_cache_data->get_schema(), right_cache_data->get_schema());
} else {
// Not first load, so we have joined a set pair. Now lets see if there is another set pair we can do, but keeping one of the two sides we already have
std::tie(left_ind, right_ind) = check_for_another_set_to_do_with_data_we_already_have();
if (left_ind >= 0 && right_ind >= 0) {
left_cache_data = this->leftArrayCache->get_or_wait_CacheData(left_ind);
right_cache_data = this->rightArrayCache->get_or_wait_CacheData(right_ind);
} else {
if (this->left_input->wait_for_next()){
left_cache_data = load_left_set();
left_ind = this->max_left_ind;
}
if (this->right_input->wait_for_next()){
right_cache_data = load_right_set();
right_ind = this->max_right_ind;
}
if (left_ind >= 0 && right_ind >= 0) {
// We pulled new data from left and right
} else if (left_ind >= 0) {
std::tie(std::ignore, right_ind) = check_for_another_set_to_do_with_data_we_already_have(left_ind, -1);
right_cache_data = this->rightArrayCache->get_or_wait_CacheData(right_ind);
} else if (right_ind >= 0) {
std::tie(left_ind, std::ignore) = check_for_another_set_to_do_with_data_we_already_have(-1, right_ind);
left_cache_data = this->leftArrayCache->get_or_wait_CacheData(left_ind);
} else {
// Both inputs are finished, check any remaining pairs to process
std::tie(left_ind, right_ind) = check_for_set_that_has_not_been_completed();
if (left_ind >= 0 && right_ind >= 0) {
left_cache_data = this->leftArrayCache->get_or_wait_CacheData(left_ind);
right_cache_data = this->rightArrayCache->get_or_wait_CacheData(right_ind);
} else {
done = true;
}
}
}
}
if (!done) {
std::vector<std::unique_ptr<ral::cache::CacheData>> inputs;
inputs.push_back(std::move(left_cache_data));
inputs.push_back(std::move(right_cache_data));
ral::execution::executor::get_instance()->add_task(
std::move(inputs),
this->output_cache(),
this,
{{"left_idx", std::to_string(left_ind)}, {"right_idx", std::to_string(right_ind)}});
mark_set_completed(left_ind, right_ind);
}
}
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="Compute Aggregate Kernel tasks created",
"duration"_a=timer.elapsed_time(),
"kernel_id"_a=this->get_id());
}
std::unique_lock<std::mutex> lock(kernel_mutex);
kernel_cv.wait(lock,[this]{
return this->tasks.empty() || ral::execution::executor::get_instance()->has_exception();
});
if(auto ep = ral::execution::executor::get_instance()->last_exception()){
std::rethrow_exception(ep);
}
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="PartwiseJoin Kernel Completed",
"duration"_a=timer.elapsed_time(),
"kernel_id"_a=this->get_id());
}
// these are intra kernel caches. We want to make sure they are empty before we finish.
this->leftArrayCache->clear();
this->rightArrayCache->clear();
return kstatus::proceed;
}
std::string PartwiseJoin::get_join_type() {
return join_type;
}
// END PartwiseJoin
// BEGIN JoinPartitionKernel
JoinPartitionKernel::JoinPartitionKernel(std::size_t kernel_id, const std::string & queryString, std::shared_ptr<Context> context, std::shared_ptr<ral::cache::graph> query_graph)
: distributing_kernel{kernel_id, queryString, context, kernel_type::JoinPartitionKernel} {
this->query_graph = query_graph;
set_number_of_message_trackers(2); //default for left and right partitions
this->input_.add_port("input_a", "input_b");
this->output_.add_port("output_a", "output_b");
std::tie(this->expression, this->condition, this->filter_statement, this->join_type) = parseExpressionToGetTypeAndCondition(this->expression);
}
// this function makes sure that the columns being joined are of the same type so that we can join them properly
void JoinPartitionKernel::computeNormalizationData(const std::vector<cudf::data_type> & left_types, const std::vector<cudf::data_type> & right_types){
std::vector<cudf::data_type> left_join_types, right_join_types;
for (size_t i = 0; i < this->left_column_indices.size(); i++){
left_join_types.push_back(left_types[this->left_column_indices[i]]);
right_join_types.push_back(right_types[this->right_column_indices[i]]);
}
bool strict = true;
this->join_column_common_types = ral::utilities::get_common_types(left_join_types, right_join_types, strict);
this->normalize_left = !std::equal(this->join_column_common_types.cbegin(), this->join_column_common_types.cend(),
left_join_types.cbegin(), left_join_types.cend());
this->normalize_right = !std::equal(this->join_column_common_types.cbegin(), this->join_column_common_types.cend(),
right_join_types.cbegin(), right_join_types.cend());
}
std::pair<bool, bool> JoinPartitionKernel::determine_if_we_are_scattering_a_small_table(const ral::cache::CacheData& left_cache_data,
const ral::cache::CacheData& right_cache_data){
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="determine_if_we_are_scattering_a_small_table start",
"duration"_a="",
"kernel_id"_a=this->get_id());
}
std::pair<bool, uint64_t> left_num_rows_estimate = this->query_graph->get_estimated_input_rows_to_cache(this->kernel_id, "input_a");
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}|rows|{rows}",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a=left_num_rows_estimate.first ? "left_num_rows_estimate was valid" : "left_num_rows_estimate was invalid",
"duration"_a="",
"kernel_id"_a=this->get_id(),
"rows"_a=left_num_rows_estimate.second);
}
std::pair<bool, uint64_t> right_num_rows_estimate = this->query_graph->get_estimated_input_rows_to_cache(this->kernel_id, "input_b");
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}|rows|{rows}",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a=right_num_rows_estimate.first ? "right_num_rows_estimate was valid" : "right_num_rows_estimate was invalid",
"duration"_a="",
"kernel_id"_a=this->get_id(),
"rows"_a=right_num_rows_estimate.second);
}
double left_batch_rows = (double)left_cache_data.num_rows();
double left_batch_bytes = (double)left_cache_data.sizeInBytes();
double right_batch_rows = (double)right_cache_data.num_rows();
double right_batch_bytes = (double)right_cache_data.sizeInBytes();
int64_t left_bytes_estimate;
if (!left_num_rows_estimate.first){
// if we cant get a good estimate of current bytes, then we will set to -1 to signify that
left_bytes_estimate = -1;
} else {
left_bytes_estimate = left_batch_rows == 0 ? 0 : (int64_t)(left_batch_bytes*(((double)left_num_rows_estimate.second)/left_batch_rows));
}
int64_t right_bytes_estimate;
if (!right_num_rows_estimate.first){
// if we cant get a good estimate of current bytes, then we will set to -1 to signify that
right_bytes_estimate = -1;
} else {
right_bytes_estimate = right_batch_rows == 0 ? 0 : (int64_t)(right_batch_bytes*(((double)right_num_rows_estimate.second)/right_batch_rows));
}
context->incrementQuerySubstep();
auto& self_node = ral::communication::CommunicationData::getInstance().getSelfNode();
int self_node_idx = context->getNodeIndex(self_node);
auto nodes_to_send = context->getAllOtherNodes(self_node_idx);
ral::cache::MetadataDictionary extra_metadata;
extra_metadata.add_value(ral::cache::JOIN_LEFT_BYTES_METADATA_LABEL, std::to_string(left_bytes_estimate));
extra_metadata.add_value(ral::cache::JOIN_RIGHT_BYTES_METADATA_LABEL, std::to_string(right_bytes_estimate));
std::vector<std::string> determination_messages_to_wait_for;
std::vector<std::string> target_ids;
for (auto & node_to_send : nodes_to_send) {
target_ids.push_back(node_to_send.id());
determination_messages_to_wait_for.push_back(
"determine_if_we_are_scattering_a_small_table_" + std::to_string(this->context->getContextToken()) + "_" + std::to_string(this->get_id()) + "_" + node_to_send.id());
}
send_message(nullptr,
false, //specific_cache
"", //cache_id
target_ids, //target_ids
"determine_if_we_are_scattering_a_small_table_", //message_id_prefix
true, //always_add
false, //wait_for
0, //message_tracker_idx
extra_metadata);
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="determine_if_we_are_scattering_a_small_table about to collectLeftRightTableSizeBytes",
"duration"_a="",
"kernel_id"_a=this->get_id());
}
std::vector<int64_t> nodes_num_bytes_left(this->context->getTotalNodes());
std::vector<int64_t> nodes_num_bytes_right(this->context->getTotalNodes());
for (auto & message_id : determination_messages_to_wait_for) {
auto message = this->query_graph->get_input_message_cache()->pullCacheData(message_id);
auto *message_with_metadata = dynamic_cast<ral::cache::CPUCacheData*>(message.get());
int node_idx = context->getNodeIndex(context->getNode(message_with_metadata->getMetadata().get_values()[ral::cache::SENDER_WORKER_ID_METADATA_LABEL]));
nodes_num_bytes_left[node_idx] = std::stoll(message_with_metadata->getMetadata().get_values()[ral::cache::JOIN_LEFT_BYTES_METADATA_LABEL]);
nodes_num_bytes_right[node_idx] = std::stoll(message_with_metadata->getMetadata().get_values()[ral::cache::JOIN_RIGHT_BYTES_METADATA_LABEL]);
}
nodes_num_bytes_left[self_node_idx] = left_bytes_estimate;
nodes_num_bytes_right[self_node_idx] = right_bytes_estimate;
std::string collectLeftRightTableSizeBytesInfo = "nodes_num_bytes_left: ";
for (auto num_bytes : nodes_num_bytes_left){
collectLeftRightTableSizeBytesInfo += std::to_string(num_bytes) + ", ";
}
collectLeftRightTableSizeBytesInfo += "; nodes_num_bytes_right: ";
for (auto num_bytes : nodes_num_bytes_right){
collectLeftRightTableSizeBytesInfo += std::to_string(num_bytes) + ", ";
}
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="determine_if_we_are_scattering_a_small_table collected " + collectLeftRightTableSizeBytesInfo,
"duration"_a="",
"kernel_id"_a=this->get_id());
}
bool any_unknowns_left = std::any_of(nodes_num_bytes_left.begin(), nodes_num_bytes_left.end(), [](int64_t bytes){return bytes == -1;});
bool any_unknowns_right = std::any_of(nodes_num_bytes_right.begin(), nodes_num_bytes_right.end(), [](int64_t bytes){return bytes == -1;});
int64_t total_bytes_left = std::accumulate(nodes_num_bytes_left.begin(), nodes_num_bytes_left.end(), int64_t(0));
int64_t total_bytes_right = std::accumulate(nodes_num_bytes_right.begin(), nodes_num_bytes_right.end(), int64_t(0));
bool scatter_left = false;
bool scatter_right = false;
if (any_unknowns_left || any_unknowns_right){
// with CROSS_JOIN we want to scatter or or the other, no matter what, even with unknowns
if (this->join_type == CROSS_JOIN){
if(total_bytes_left < total_bytes_right) {
scatter_left = true;
} else {
scatter_right = true;
}
return std::make_pair(scatter_left, scatter_right);
} else {
return std::make_pair(false, false); // we wont do any small table scatter if we have unknowns
}
}
int num_nodes = context->getTotalNodes();
int64_t estimate_regular_distribution = (total_bytes_left + total_bytes_right) * (num_nodes - 1) / num_nodes;
int64_t estimate_scatter_left = (total_bytes_left) * (num_nodes - 1);
int64_t estimate_scatter_right = (total_bytes_right) * (num_nodes - 1);
unsigned long long max_join_scatter_mem_overhead = 500000000; // 500Mb how much extra memory consumption per node are we ok with
std::map<std::string, std::string> config_options = context->getConfigOptions();
auto it = config_options.find("MAX_JOIN_SCATTER_MEM_OVERHEAD");
if (it != config_options.end()){
max_join_scatter_mem_overhead = std::stoull(config_options["MAX_JOIN_SCATTER_MEM_OVERHEAD"]);
}
// with CROSS_JOIN we want to scatter or or the other
if (this->join_type == CROSS_JOIN){
if(estimate_scatter_left < estimate_scatter_right) {
scatter_left = true;
} else {
scatter_right = true;
}
// with LEFT_JOIN we cant scatter the left side
} else if (this->join_type == LEFT_JOIN) {
if(estimate_scatter_right < estimate_regular_distribution &&
static_cast<unsigned long long>(total_bytes_right) < max_join_scatter_mem_overhead) {
scatter_right = true;
}
} else {
if(estimate_scatter_left < estimate_regular_distribution ||
estimate_scatter_right < estimate_regular_distribution) {
if(estimate_scatter_left < estimate_scatter_right &&
static_cast<unsigned long long>(total_bytes_left) < max_join_scatter_mem_overhead) {
scatter_left = true;
} else if(estimate_scatter_right < estimate_scatter_left &&
static_cast<unsigned long long>(total_bytes_right) < max_join_scatter_mem_overhead) {
scatter_right = true;
}
}
}
return std::make_pair(scatter_left, scatter_right);
}
void JoinPartitionKernel::perform_standard_hash_partitioning(
std::unique_ptr<ral::cache::CacheData> left_cache_data,
std::unique_ptr<ral::cache::CacheData> right_cache_data,
std::shared_ptr<ral::cache::CacheMachine> left_input,
std::shared_ptr<ral::cache::CacheMachine> right_input){
this->context->incrementQuerySubstep();
// parsing more of the expression here because we need to have the number of columns of the tables
std::vector<int> column_indices;
parseJoinConditionToColumnIndices(condition, column_indices);
for(std::size_t i = 0; i < column_indices.size();i++){
if(column_indices[i] >= static_cast<int>(left_cache_data->num_columns())){
this->right_column_indices.push_back(column_indices[i] - left_cache_data->num_columns());
}else{
this->left_column_indices.push_back(column_indices[i]);
}
}
computeNormalizationData(left_cache_data->get_schema(), right_cache_data->get_schema());
BlazingThread left_thread([this, &left_input, &left_cache_data](){
while(left_cache_data != nullptr) {
std::vector<std::unique_ptr<ral::cache::CacheData>> inputs;
inputs.push_back(std::move(left_cache_data));
ral::execution::executor::get_instance()->add_task(
std::move(inputs),
this->output_cache("output_a"),
this,
{{"operation_type", "hash_partition"}, {"side", "left"}});
left_cache_data = left_input->pullCacheData();
}
});
BlazingThread right_thread([this, &right_input, &right_cache_data](){
while(right_cache_data != nullptr) {
std::vector<std::unique_ptr<ral::cache::CacheData>> inputs;
inputs.push_back(std::move(right_cache_data));
ral::execution::executor::get_instance()->add_task(
std::move(inputs),
this->output_cache("output_b"),
this,
{{"operation_type", "hash_partition"}, {"side", "right"}});
right_cache_data = right_input->pullCacheData();
}
});
left_thread.join();
right_thread.join();
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}||kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartitionKernel Kernel tasks created",
"kernel_id"_a=this->get_id());
}
std::unique_lock<std::mutex> lock(kernel_mutex);
kernel_cv.wait(lock,[this]{
return this->tasks.empty() || ral::execution::executor::get_instance()->has_exception();
});
if(auto ep = ral::execution::executor::get_instance()->last_exception()){
std::rethrow_exception(ep);
}
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}||kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartitionKernel Kernel tasks executed",
"kernel_id"_a=this->get_id());
}
send_total_partition_counts("", "output_a", LEFT_TABLE_IDX);
send_total_partition_counts("", "output_b", RIGHT_TABLE_IDX);
int total_count_left = get_total_partition_counts(LEFT_TABLE_IDX); //left
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}||kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartitionKernel Kernel got total_partition_counts left: " + std::to_string(total_count_left),
"kernel_id"_a=this->get_id());
}
this->output_.get_cache("output_a")->wait_for_count(total_count_left);
int total_count_right = get_total_partition_counts(RIGHT_TABLE_IDX); //right
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}||kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartitionKernel Kernel got total_partition_counts right " + std::to_string(total_count_right),
"kernel_id"_a=this->get_id());
}
this->output_.get_cache("output_b")->wait_for_count(total_count_right);
}
void JoinPartitionKernel::small_table_scatter_distribution(std::unique_ptr<ral::cache::CacheData> small_cache_data,
std::unique_ptr<ral::cache::CacheData> big_cache_data,
std::shared_ptr<ral::cache::CacheMachine> small_input,
std::shared_ptr<ral::cache::CacheMachine> big_input){
this->context->incrementQuerySubstep();
// In this function we are assuming that one and only one of the two bools in scatter_left_right is true
assert((scatter_left_right.first || scatter_left_right.second) && not (scatter_left_right.first && scatter_left_right.second));
std::string small_output_cache_name = scatter_left_right.first ? "output_a" : "output_b";
int small_table_idx = scatter_left_right.first ? LEFT_TABLE_IDX : RIGHT_TABLE_IDX;
std::string big_output_cache_name = scatter_left_right.first ? "output_b" : "output_a";
int big_table_idx = scatter_left_right.first ? RIGHT_TABLE_IDX : LEFT_TABLE_IDX;
BlazingThread left_thread([this, &small_input, &small_cache_data, small_output_cache_name](){
while(small_cache_data != nullptr ) {
std::vector<std::unique_ptr<ral::cache::CacheData>> inputs;
inputs.push_back(std::move(small_cache_data));
ral::execution::executor::get_instance()->add_task(
std::move(inputs),
this->output_cache(small_output_cache_name),
this,
{{"operation_type", "small_table_scatter"}});
small_cache_data = small_input->pullCacheData();
}
});
BlazingThread right_thread([this, &big_input, &big_cache_data, big_output_cache_name, big_table_idx](){
while (big_cache_data != nullptr) {
bool added = this->add_to_output_cache(std::move(big_cache_data), big_output_cache_name);
if (added) {
auto& self_node = ral::communication::CommunicationData::getInstance().getSelfNode();
increment_node_count(self_node.id(), big_table_idx);
}
big_cache_data = big_input->pullCacheData();
}
});
left_thread.join();
right_thread.join();
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}||kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartitionKernel Kernel tasks created",
"kernel_id"_a=this->get_id());
}
std::unique_lock<std::mutex> lock(kernel_mutex);
kernel_cv.wait(lock,[this]{
return this->tasks.empty() || ral::execution::executor::get_instance()->has_exception();
});
if(auto ep = ral::execution::executor::get_instance()->last_exception()){
std::rethrow_exception(ep);
}
if(logger) {
logger->debug("{query_id}|{step}|{substep}|{info}||kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartitionKernel Kernel tasks executed",
"kernel_id"_a=this->get_id());
}
send_total_partition_counts(
"", //message_prefix
small_output_cache_name, //cache_id
small_table_idx //message_tracker_idx
);
int total_count = get_total_partition_counts(small_table_idx);
this->output_cache(small_output_cache_name)->wait_for_count(total_count);
}
ral::execution::task_result JoinPartitionKernel::do_process(std::vector<std::unique_ptr<ral::frame::BlazingTable>> inputs,
std::shared_ptr<ral::cache::CacheMachine> /*output*/,
cudaStream_t /*stream*/, const std::map<std::string, std::string>& args) {
bool input_consumed = false;
try{
auto& operation_type = args.at("operation_type");
auto & input = inputs[0];
if (operation_type == "small_table_scatter") {
input_consumed = true;
std::string small_output_cache_name = scatter_left_right.first ? "output_a" : "output_b";
int small_table_idx = scatter_left_right.first ? LEFT_TABLE_IDX : RIGHT_TABLE_IDX;
broadcast(std::move(input),
this->output_.get_cache(small_output_cache_name).get(),
"", //message_id_prefix
small_output_cache_name, //cache_id
small_table_idx //message_tracker_idx
);
} else if (operation_type == "hash_partition") {
bool normalize_types;
int table_idx;
std::string cache_id;
std::vector<cudf::size_type> column_indices;
if(args.at("side") == "left"){
normalize_types = this->normalize_left;
table_idx = LEFT_TABLE_IDX;
cache_id = "output_a";
column_indices = this->left_column_indices;
} else {
normalize_types = this->normalize_right;
table_idx = RIGHT_TABLE_IDX;
cache_id = "output_b";
column_indices = this->right_column_indices;
}
if (normalize_types) {
ral::utilities::normalize_types(input, join_column_common_types, column_indices);
}
auto batch_view = input->view();
std::unique_ptr<cudf::table> hashed_data;
std::vector<cudf::table_view> partitioned;
if (input->num_rows() > 0) {
// When is cross_join. `column_indices` is equal to 0, so we need all `batch` columns to apply cudf::hash_partition correctly
if (column_indices.size() == 0) {
column_indices.resize(input->num_columns());
std::iota(std::begin(column_indices), std::end(column_indices), 0);
}
int num_partitions = context->getTotalNodes();
std::vector<cudf::size_type> hased_data_offsets;
std::tie(hashed_data, hased_data_offsets) = cudf::hash_partition(batch_view, column_indices, num_partitions);
assert(hased_data_offsets.begin() != hased_data_offsets.end());
// the offsets returned by hash_partition will always start at 0, which is a value we want to ignore for cudf::split
std::vector<cudf::size_type> split_indexes(hased_data_offsets.begin() + 1, hased_data_offsets.end());
partitioned = cudf::split(hashed_data->view(), split_indexes);
} else {
for(int i = 0; i < context->getTotalNodes(); i++){
partitioned.push_back(batch_view);
}
}
std::vector<ral::frame::BlazingTableView> partitions;
for(auto partition : partitioned) {
partitions.push_back(ral::frame::BlazingTableView(partition, input->names()));
}
scatter(partitions,
this->output_.get_cache(cache_id).get(),
"", //message_id_prefix
cache_id, //cache_id
table_idx //message_tracker_idx
);
} else { // not an option! error
if (logger) {
logger->error("{query_id}|{step}|{substep}|{info}|{duration}||||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="In JoinPartitionKernel::do_process Invalid operation_type: {}"_format(operation_type),
"duration"_a="");
}
return {ral::execution::task_status::FAIL, std::string("In JoinPartitionKernel::do_process Invalid operation_type"), std::vector< std::unique_ptr<ral::frame::BlazingTable> > ()};
}
}catch(const rmm::bad_alloc& e){
return {ral::execution::task_status::RETRY, std::string(e.what()), input_consumed ? std::vector< std::unique_ptr<ral::frame::BlazingTable> > () : std::move(inputs)};
}catch(const std::exception& e){
return {ral::execution::task_status::FAIL, std::string(e.what()), std::vector< std::unique_ptr<ral::frame::BlazingTable> > ()};
}
return {ral::execution::task_status::SUCCESS, std::string(), std::vector< std::unique_ptr<ral::frame::BlazingTable> > ()};
}
kstatus JoinPartitionKernel::run() {
CodeTimer timer;
auto left_input = this->input_.get_cache("input_a");
auto right_input = this->input_.get_cache("input_b");
auto left_cache_data = left_input->pullCacheData();
auto right_cache_data = right_input->pullCacheData();
if (left_cache_data == nullptr || left_cache_data->num_columns() == 0){
while (left_input->wait_for_next()){
left_cache_data = left_input->pullCacheData();
if (left_cache_data != nullptr && left_cache_data->num_columns() > 0){
break;
}
}
}
if (left_cache_data == nullptr || left_cache_data->num_columns() == 0){
RAL_FAIL("In JoinPartitionKernel left side is empty and cannot determine join column indices");
}
if (this->join_type != OUTER_JOIN){
// can't scatter a full outer join
scatter_left_right = determine_if_we_are_scattering_a_small_table(*left_cache_data, *right_cache_data);
}
if (scatter_left_right.first) {
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartition Scattering left table",
"duration"_a="",
"kernel_id"_a=this->get_id());
}
small_table_scatter_distribution(std::move(left_cache_data), std::move(right_cache_data),
left_input, right_input);
} else if (scatter_left_right.second) {
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartition Scattering right table",
"duration"_a="",
"kernel_id"_a=this->get_id());
}
small_table_scatter_distribution(std::move(right_cache_data), std::move(left_cache_data),
right_input, left_input);
} else {
if(logger){
logger->trace("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartition Standard hash partition",
"duration"_a="",
"kernel_id"_a=this->get_id());
}
perform_standard_hash_partitioning(std::move(left_cache_data), std::move(right_cache_data),
left_input, right_input);
}
if(logger){
logger->debug("{query_id}|{step}|{substep}|{info}|{duration}|kernel_id|{kernel_id}||",
"query_id"_a=context->getContextToken(),
"step"_a=context->getQueryStep(),
"substep"_a=context->getQuerySubstep(),
"info"_a="JoinPartition Kernel Completed",
"duration"_a=timer.elapsed_time(),
"kernel_id"_a=this->get_id());
}
return kstatus::proceed;
}
std::string JoinPartitionKernel::get_join_type() {
return join_type;
}
// END JoinPartitionKernel
} // namespace batch
} // namespace ral
| 44.379058 | 190 | 0.681536 | davisusanibar |
143b49ce98020dd1388d8a56d385721003bf40b5 | 1,573 | cpp | C++ | src/blockManagement/block.cpp | ivomachado/Trabalho1BD | 291a52ae8a24c7dc0ec2a87543b8260e1953c354 | [
"MIT"
] | 2 | 2019-05-16T13:52:40.000Z | 2019-05-31T20:05:18.000Z | src/blockManagement/block.cpp | ivomachado/Trabalho1BD | 291a52ae8a24c7dc0ec2a87543b8260e1953c354 | [
"MIT"
] | null | null | null | src/blockManagement/block.cpp | ivomachado/Trabalho1BD | 291a52ae8a24c7dc0ec2a87543b8260e1953c354 | [
"MIT"
] | null | null | null | #include "block.hpp"
#include "field.hpp"
#include "utils.hpp"
#include <cstdio>
#include <vector>
DiskBlock::DiskBlock(std::vector<Field>& recordFields)
{
m_header.m_data.emplace_back(Field::asInteger(0)); //Registros no bloco
m_header.m_data.emplace_back(Field::asInteger(0)); //Apontador para o de overflow
m_recordFields = recordFields;
for (auto& field : m_recordFields) {
m_recordSize += field.size();
}
}
void DiskBlock::readFromFile(FILE* file)
{
fread(m_buffer, sizeof(char), DiskBlock::SIZE, file);
readFromBuffer();
}
void DiskBlock::writeToFile(FILE* file)
{
writeToBuffer();
fwrite(m_buffer, sizeof(char), DiskBlock::SIZE, file);
}
void DiskBlock::writeToBuffer()
{
m_header.m_data[0].m_integer = static_cast<int>(m_records.size());
m_bufferPos = m_header.writeToBuffer(m_buffer, 0);
m_bufferPos = Utils::writeVectorToBuffer(m_buffer, m_records, m_bufferPos);
}
void DiskBlock::readFromBuffer()
{
m_bufferPos = m_header.readFromBuffer(m_buffer, 0);
int numberOfRecords = m_header.m_data[0].m_integer;
m_records.resize(0);
for (int i = 0; i < numberOfRecords; i++) {
m_records.emplace_back(m_recordFields);
}
m_bufferPos = Utils::readVectorFromBuffer(m_buffer, m_records, m_bufferPos);
}
bool DiskBlock::fitOneMoreRecord() {
return (m_records.size() + 1) * m_recordSize <= DiskBlock::AVAILABLE_SIZE;
}
bool DiskBlock::insert(const Record& record)
{
if(fitOneMoreRecord()) {
m_records.push_back(record);
return true;
}
return false;
}
| 26.661017 | 85 | 0.698029 | ivomachado |
143b6b698831ee4bf8d154e9568860a5354cbb5c | 2,764 | cc | C++ | shared/ortcustomops.cc | vvchernov/onnxruntime-extensions | cc858e831b719d31e4f34ee9adb391105b4ce26b | [
"MIT"
] | 59 | 2021-04-29T07:39:42.000Z | 2022-03-29T21:12:05.000Z | shared/ortcustomops.cc | vvchernov/onnxruntime-extensions | cc858e831b719d31e4f34ee9adb391105b4ce26b | [
"MIT"
] | 45 | 2021-05-12T08:32:58.000Z | 2022-03-29T21:11:59.000Z | shared/ortcustomops.cc | vvchernov/onnxruntime-extensions | cc858e831b719d31e4f34ee9adb391105b4ce26b | [
"MIT"
] | 18 | 2021-05-10T10:15:46.000Z | 2022-03-22T10:46:36.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <set>
#include "onnxruntime_extensions.h"
#include "ocos.h"
class ExternalCustomOps {
public:
ExternalCustomOps() {
}
static ExternalCustomOps& instance() {
static ExternalCustomOps g_instance;
return g_instance;
}
void Add(const OrtCustomOp* c_op) {
op_array_.push_back(c_op);
}
const OrtCustomOp* GetNextOp(size_t& idx) {
if (idx >= op_array_.size()) {
return nullptr;
}
return op_array_[idx++];
}
ExternalCustomOps(ExternalCustomOps const&) = delete;
void operator=(ExternalCustomOps const&) = delete;
private:
std::vector<const OrtCustomOp*> op_array_;
};
extern "C" bool ORT_API_CALL AddExternalCustomOp(const OrtCustomOp* c_op) {
ExternalCustomOps::instance().Add(c_op);
return true;
}
extern "C" OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api) {
OrtCustomOpDomain* domain = nullptr;
const OrtApi* ortApi = api->GetApi(ORT_API_VERSION);
std::set<std::string> pyop_nameset;
OrtStatus* status = nullptr;
#if defined(PYTHON_OP_SUPPORT)
if (status = RegisterPythonDomainAndOps(options, ortApi)){
return status;
}
#endif // PYTHON_OP_SUPPORT
if (status = ortApi->CreateCustomOpDomain(c_OpDomain, &domain)) {
return status;
}
#if defined(PYTHON_OP_SUPPORT)
size_t count = 0;
const OrtCustomOp* c_ops = FetchPyCustomOps(count);
while (c_ops != nullptr) {
if (status = ortApi->CustomOpDomain_Add(domain, c_ops)) {
return status;
} else {
pyop_nameset.emplace(c_ops->GetName(c_ops));
}
++count;
c_ops = FetchPyCustomOps(count);
}
#endif
static std::vector<FxLoadCustomOpFactory> c_factories = {
LoadCustomOpClasses<CustomOpClassBegin>
#if defined(ENABLE_TF_STRING)
, LoadCustomOpClasses_Text
#endif // ENABLE_TF_STRING
#if defined(ENABLE_MATH)
, LoadCustomOpClasses_Math
#endif
#if defined(ENABLE_TOKENIZER)
, LoadCustomOpClasses_Tokenizer
#endif
};
for (auto fx : c_factories) {
auto ops = fx();
while (*ops != nullptr) {
if (pyop_nameset.find((*ops)->GetName(*ops)) == pyop_nameset.end()) {
if (status = ortApi->CustomOpDomain_Add(domain, *ops)) {
return status;
}
}
++ops;
}
}
size_t idx = 0;
const OrtCustomOp* e_ops = ExternalCustomOps::instance().GetNextOp(idx);
while (e_ops != nullptr) {
if (pyop_nameset.find(e_ops->GetName(e_ops)) == pyop_nameset.end()) {
if (status = ortApi->CustomOpDomain_Add(domain, e_ops)) {
return status;
}
e_ops = ExternalCustomOps::instance().GetNextOp(idx);
}
}
return ortApi->AddCustomOpDomain(options, domain);
}
| 24.678571 | 105 | 0.686686 | vvchernov |
143ca63aa83dc435341cc33e07f47564e0b7c809 | 8,593 | cpp | C++ | viceplugins/retrojsvice/src/vice_plugin_api.cpp | hackyannick/browservice | 10022849a15683e0f72a14aaee475b8daf13dbb1 | [
"MIT"
] | null | null | null | viceplugins/retrojsvice/src/vice_plugin_api.cpp | hackyannick/browservice | 10022849a15683e0f72a14aaee475b8daf13dbb1 | [
"MIT"
] | null | null | null | viceplugins/retrojsvice/src/vice_plugin_api.cpp | hackyannick/browservice | 10022849a15683e0f72a14aaee475b8daf13dbb1 | [
"MIT"
] | null | null | null | #include "context.hpp"
#include "../../../vice_plugin_api.h"
namespace {
using namespace retrojsvice;
const char* RetrojsviceVersion = "0.9.2.1";
template <typename T>
class GlobalCallback {
private:
struct Inner {
T callback;
void* data;
void (*destructorCallback)(void* data);
Inner(
T callback,
void* data,
void (*destructorCallback)(void* data)
) :
callback(callback),
data(data),
destructorCallback(destructorCallback)
{}
DISABLE_COPY_MOVE(Inner);
~Inner() {
if(destructorCallback != nullptr) {
destructorCallback(data);
}
}
};
shared_ptr<Inner> inner_;
public:
template <typename... Arg>
GlobalCallback(Arg... arg) : inner_(make_shared<Inner>(arg...)) {}
template <typename... Arg>
void operator()(Arg... arg) const {
inner_->callback(inner_->data, arg...);
}
};
void setOutString(char** out, string val) {
if(out != nullptr) {
*out = createMallocString(val);
}
}
#define API_EXPORT __attribute__((visibility("default")))
#define API_FUNC_START \
try {
#define API_FUNC_END \
} catch(const exception& e) { \
PANIC("Unhandled exception traversing the vice plugin API: ", e.what()); \
abort(); \
} catch(...) { \
PANIC("Unhandled exception traversing the vice plugin API"); \
abort(); \
}
}
extern "C" {
struct VicePluginAPI_Context {
shared_ptr<Context> impl;
};
API_EXPORT int vicePluginAPI_isAPIVersionSupported(uint64_t apiVersion) {
API_FUNC_START
return (int)(apiVersion == (uint64_t)1000000);
API_FUNC_END
}
API_EXPORT char* vicePluginAPI_getVersionString() {
API_FUNC_START
return createMallocString(string("Retrojsvice ") + RetrojsviceVersion);
API_FUNC_END
}
API_EXPORT VicePluginAPI_Context* vicePluginAPI_initContext(
uint64_t apiVersion,
const char** optionNames,
const char** optionValues,
size_t optionCount,
const char* programName,
char** initErrorMsgOut
) {
API_FUNC_START
REQUIRE(apiVersion == (uint64_t)1000000);
REQUIRE(programName != nullptr);
vector<pair<string, string>> options;
for(size_t i = 0; i < optionCount; ++i) {
REQUIRE(optionNames != nullptr);
REQUIRE(optionValues != nullptr);
REQUIRE(optionNames[i] != nullptr);
REQUIRE(optionValues[i] != nullptr);
options.emplace_back(optionNames[i], optionValues[i]);
}
variant<shared_ptr<Context>, string> result =
Context::init(options, programName);
shared_ptr<Context> impl;
if(shared_ptr<Context>* implPtr = get_if<shared_ptr<Context>>(&result)) {
impl = *implPtr;
} else {
string msg = get<string>(result);
setOutString(initErrorMsgOut, msg);
return nullptr;
}
VicePluginAPI_Context* ctx = new VicePluginAPI_Context;
ctx->impl = impl;
return ctx;
API_FUNC_END
}
API_EXPORT void vicePluginAPI_destroyContext(VicePluginAPI_Context* ctx) {
API_FUNC_START
REQUIRE(ctx != nullptr);
delete ctx;
API_FUNC_END
}
// Convenience macro for creating implementations of API functions that forward
// their arguments to corresponding member functions of the Context
#define WRAP_CTX_API(funcName, ...) \
{ \
API_FUNC_START \
REQUIRE(ctx != nullptr); \
return ctx->impl->funcName(__VA_ARGS__); \
API_FUNC_END \
}
API_EXPORT void vicePluginAPI_start(
VicePluginAPI_Context* ctx,
VicePluginAPI_Callbacks callbacks,
void* callbackData
)
WRAP_CTX_API(start, callbacks, callbackData)
API_EXPORT void vicePluginAPI_shutdown(VicePluginAPI_Context* ctx)
WRAP_CTX_API(shutdown)
API_EXPORT void vicePluginAPI_pumpEvents(VicePluginAPI_Context* ctx)
WRAP_CTX_API(pumpEvents)
API_EXPORT int vicePluginAPI_createPopupWindow(
VicePluginAPI_Context* ctx,
uint64_t parentWindow,
uint64_t popupWindow,
char** msg
)
WRAP_CTX_API(createPopupWindow, parentWindow, popupWindow, msg)
API_EXPORT void vicePluginAPI_closeWindow(
VicePluginAPI_Context* ctx,
uint64_t window
)
WRAP_CTX_API(closeWindow, window)
API_EXPORT void vicePluginAPI_notifyWindowViewChanged(
VicePluginAPI_Context* ctx,
uint64_t window
)
WRAP_CTX_API(notifyWindowViewChanged, window)
API_EXPORT void vicePluginAPI_setWindowCursor(
VicePluginAPI_Context* ctx,
uint64_t window,
VicePluginAPI_MouseCursor cursor
)
WRAP_CTX_API(setWindowCursor, window, cursor)
API_EXPORT int vicePluginAPI_windowQualitySelectorQuery(
VicePluginAPI_Context* ctx,
uint64_t window,
char** qualityListOut,
size_t* currentQualityOut
)
WRAP_CTX_API(
windowQualitySelectorQuery, window, qualityListOut, currentQualityOut
)
API_EXPORT void vicePluginAPI_windowQualityChanged(
VicePluginAPI_Context* ctx,
uint64_t window,
size_t qualityIdx
)
WRAP_CTX_API(windowQualityChanged, window, qualityIdx)
API_EXPORT int vicePluginAPI_windowNeedsClipboardButtonQuery(
VicePluginAPI_Context* ctx,
uint64_t window
)
WRAP_CTX_API(windowNeedsClipboardButtonQuery, window)
API_EXPORT void vicePluginAPI_windowClipboardButtonPressed(
VicePluginAPI_Context* ctx,
uint64_t window
)
WRAP_CTX_API(windowClipboardButtonPressed, window)
API_EXPORT void vicePluginAPI_putClipboardContent(
VicePluginAPI_Context* ctx,
const char* text
)
WRAP_CTX_API(putClipboardContent, text)
API_EXPORT void vicePluginAPI_putFileDownload(
VicePluginAPI_Context* ctx,
uint64_t window,
const char* name,
const char* path,
void (*cleanup)(void*),
void* cleanupData
)
WRAP_CTX_API(putFileDownload, window, name, path, cleanup, cleanupData)
API_EXPORT int vicePluginAPI_startFileUpload(
VicePluginAPI_Context* ctx,
uint64_t window
)
WRAP_CTX_API(startFileUpload, window)
API_EXPORT void vicePluginAPI_cancelFileUpload(
VicePluginAPI_Context* ctx,
uint64_t window
)
WRAP_CTX_API(cancelFileUpload, window)
API_EXPORT void vicePluginAPI_getOptionDocs(
uint64_t apiVersion,
void (*callback)(
void* data,
const char* name,
const char* valSpec,
const char* desc,
const char* defaultValStr
),
void* data
) {
API_FUNC_START
REQUIRE(apiVersion == (uint64_t)1000000);
REQUIRE(callback != nullptr);
vector<tuple<string, string, string, string>> docs =
Context::getOptionDocs();
for(const tuple<string, string, string, string>& doc : docs) {
string name, valSpec, desc, defaultValStr;
tie(name, valSpec, desc, defaultValStr) = doc;
callback(
data,
name.c_str(),
valSpec.c_str(),
desc.c_str(),
defaultValStr.c_str()
);
}
API_FUNC_END
}
API_EXPORT void vicePluginAPI_setGlobalLogCallback(
uint64_t apiVersion,
void (*callback)(
void* data,
VicePluginAPI_LogLevel logLevel,
const char* location,
const char* msg
),
void* data,
void (*destructorCallback)(void* data)
) {
API_FUNC_START
REQUIRE(apiVersion == (uint64_t)1000000);
if(callback == nullptr) {
setLogCallback({});
} else {
GlobalCallback<decltype(callback)> func(
callback, data, destructorCallback
);
setLogCallback(
[func](
LogLevel logLevel,
const char* location,
const char* msg
) {
VicePluginAPI_LogLevel apiLogLevel;
if(logLevel == LogLevel::Error) {
apiLogLevel = VICE_PLUGIN_API_LOG_LEVEL_ERROR;
} else if(logLevel == LogLevel::Warning) {
apiLogLevel = VICE_PLUGIN_API_LOG_LEVEL_WARNING;
} else {
REQUIRE(logLevel == LogLevel::Info);
apiLogLevel = VICE_PLUGIN_API_LOG_LEVEL_INFO;
}
func(apiLogLevel, location, msg);
}
);
}
API_FUNC_END
}
API_EXPORT void vicePluginAPI_setGlobalPanicCallback(
uint64_t apiVersion,
void (*callback)(void* data, const char* location, const char* msg),
void* data,
void (*destructorCallback)(void* data)
) {
API_FUNC_START
REQUIRE(apiVersion == (uint64_t)1000000);
if(callback == nullptr) {
setPanicCallback({});
} else {
setPanicCallback(
GlobalCallback<decltype(callback)>(callback, data, destructorCallback)
);
}
API_FUNC_END
}
}
| 24.481481 | 82 | 0.669615 | hackyannick |
143d80b09390681feecdc7626536dd75e5a15255 | 888 | cpp | C++ | libs/renderer/src/renderer/state/ffp/lighting/light/scoped.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/renderer/src/renderer/state/ffp/lighting/light/scoped.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/renderer/src/renderer/state/ffp/lighting/light/scoped.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/renderer/context/ffp.hpp>
#include <sge/renderer/context/ffp_ref.hpp>
#include <sge/renderer/state/ffp/lighting/light/const_object_ref_vector.hpp>
#include <sge/renderer/state/ffp/lighting/light/scoped.hpp>
sge::renderer::state::ffp::lighting::light::scoped::scoped(
sge::renderer::context::ffp_ref const _context,
sge::renderer::state::ffp::lighting::light::const_object_ref_vector const &_states)
: context_(_context)
{
context_.get().lights_state(_states);
}
sge::renderer::state::ffp::lighting::light::scoped::~scoped()
{
context_.get().lights_state(
sge::renderer::state::ffp::lighting::light::const_object_ref_vector());
}
| 37 | 87 | 0.726351 | cpreh |
143e49499bb3d2d02291ec8c84b33f38a67501e8 | 4,858 | cpp | C++ | modules/task_4/gushchin_a_simpson_method/simsponMethod.cpp | vla5924-practice/parallel-programming-2 | 4657fd9c02fdd11bbb64614f2aca04356ff45a60 | [
"BSD-3-Clause"
] | null | null | null | modules/task_4/gushchin_a_simpson_method/simsponMethod.cpp | vla5924-practice/parallel-programming-2 | 4657fd9c02fdd11bbb64614f2aca04356ff45a60 | [
"BSD-3-Clause"
] | null | null | null | modules/task_4/gushchin_a_simpson_method/simsponMethod.cpp | vla5924-practice/parallel-programming-2 | 4657fd9c02fdd11bbb64614f2aca04356ff45a60 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 Gushchin Artem
#include <algorithm>
#include <functional>
#include <numeric>
#include <vector>
#include "../../../3rdparty/unapproved/unapproved.h"
#include "../../../modules/task_4/gushchin_a_simpson_method/simpsonMethod.h"
namespace {
constexpr auto numOfThreads = 4;
}
double parallelSimpsonsMethod(
const std::function<double(const std::vector<double>&)>& func,
const std::vector<std::pair<double, double>>& segments,
int stepsCount) {
if (segments.empty())
throw "Segments vector should contain positive number of segments";
if (stepsCount < 1)
throw "Steps count should be a positive value";
if (!func)
throw "Function is incorrect";
if (stepsCount % 2 == 1)
++stepsCount;
const auto segmentsSize = segments.size();
std::vector<double> segmentsDiffs(segmentsSize);
std::vector<double> segmentsSteps(segmentsSize);
std::vector<double> firstPoint(segmentsSize);
std::vector<double> lastPoint(segmentsSize);
double diffsProduct = 1;
for (int i = 0; i < static_cast<int>(segmentsSize); ++i) {
firstPoint[i] = segments[i].first;
lastPoint[i] = segments[i].second;
segmentsDiffs[i] = segments[i].second - segments[i].first;
segmentsSteps[i] = segmentsDiffs[i] / stepsCount;
diffsProduct *= segmentsDiffs[i];
}
diffsProduct /= stepsCount;
using valuesPair = std::pair<double, double>;
auto sum = [&](const int begin, const int end) {
std::vector<double> currentPoint(segmentsSize);
valuesPair values = { 0, 0 };
for (auto i = begin; i < end; ++i) {
for (size_t j = 0; j < segmentsSize; ++j)
currentPoint[j] = firstPoint[j] + i * segmentsSteps[j];
if (i % 2 == 0)
values.first += func(currentPoint);
else
values.second += func(currentPoint);
}
return values;
};
std::vector<std::future<valuesPair>> results(numOfThreads);
const int delta = (stepsCount - 1) / numOfThreads;
const int remainder = (stepsCount - 1) % numOfThreads;
int currentBegin = 1, currentEnd = 0;
int rootBegin = 1, rootEnd = 0;
for (int i = 0; i < numOfThreads; ++i) {
if (i < remainder) {
currentEnd = currentBegin + delta + 1;
} else {
currentEnd = currentBegin + delta;
}
if (i == 0) {
rootBegin = currentBegin;
rootEnd = currentEnd;
} else {
results[i] = std::async(std::launch::async,
sum, currentBegin,
currentEnd);
}
currentBegin = currentEnd;
}
auto values = sum(rootBegin, rootEnd);
double evenValues = values.first, oddValues = values.second;
for (int i = 1; i < numOfThreads; ++i) {
results[i].wait();
auto taskResult = results[i].get();
evenValues += taskResult.first;
oddValues += taskResult.second;
}
double coeff = diffsProduct / 3.0;
double result = coeff * (func(firstPoint) + 2 * evenValues
+ 4 * oddValues + func(lastPoint));
return result;
}
double simpsonsMethod(
const std::function<double(const std::vector<double>&)>& func,
const std::vector<std::pair<double, double>>& segments,
int stepsCount) {
if (segments.empty())
throw "Segments vector should contain positive number of segments";
if (stepsCount < 1)
throw "Steps count should be a positive value";
if (!func)
throw "Function is incorrect";
if (stepsCount % 2 == 1)
++stepsCount;
std::vector<double> segmentsDiffs(segments.size());
std::vector<double> segmentsSteps(segments.size());
std::vector<double> firstPoint(segments.size());
std::vector<double> lastPoint(segments.size());
double diffsProduct = 1;
for (size_t i = 0; i < segments.size(); ++i) {
firstPoint[i] = segments[i].first;
lastPoint[i] = segments[i].second;
segmentsDiffs[i] = segments[i].second - segments[i].first;
segmentsSteps[i] = segmentsDiffs[i] / stepsCount;
diffsProduct *= segmentsDiffs[i];
}
diffsProduct /= stepsCount;
double evenValues = 0, oddValues = 0;
std::vector<double> currentPoint = firstPoint;
for (int i = 1; i < stepsCount; ++i) {
for (int i = 0; i < static_cast<int>(segments.size()); ++i)
currentPoint[i] += segmentsSteps[i];
if (i % 2 == 0)
evenValues += func(currentPoint);
else
oddValues += func(currentPoint);
}
double coeff = diffsProduct / 3.0;
double result = coeff * (func(firstPoint) + 2 * evenValues
+ 4 * oddValues + func(lastPoint));
return result;
}
| 29.987654 | 76 | 0.591601 | vla5924-practice |
1444e3d97396e6cdfa54f9f2bc84a35e5748a8af | 753 | hpp | C++ | include/RED4ext/Types/generated/AI/ArgumentSerializableValue.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/AI/ArgumentSerializableValue.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/AI/ArgumentSerializableValue.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Types/generated/AI/ArgumentDefinition.hpp>
#include <RED4ext/Types/generated/AI/ArgumentType.hpp>
namespace RED4ext
{
struct ISerializable;
namespace AI {
struct ArgumentSerializableValue : AI::ArgumentDefinition
{
static constexpr const char* NAME = "AIArgumentSerializableValue";
static constexpr const char* ALIAS = NAME;
Handle<ISerializable> defaultValue; // 48
AI::ArgumentType type; // 58
uint8_t unk5C[0x60 - 0x5C]; // 5C
};
RED4EXT_ASSERT_SIZE(ArgumentSerializableValue, 0x60);
} // namespace AI
} // namespace RED4ext
| 25.965517 | 70 | 0.756972 | Cyberpunk-Extended-Development-Team |
14482f5853be44047d53bea9e416a8aa68add96f | 1,871 | cpp | C++ | kuangbin/1/i.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 2 | 2021-06-09T12:27:07.000Z | 2021-06-11T12:02:03.000Z | kuangbin/1/i.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 1 | 2021-09-08T12:00:05.000Z | 2021-09-08T14:52:30.000Z | kuangbin/1/i.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int x, y, vis, step;
char ch;
void init(){
vis = step = 0;
return;
}
}mp[12][12], temp;
int n, m;
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int main(){
int T, ans, flag;
scanf("%d", &T);
for(int iiiii = 1; iiiii<=T; iiiii++){
printf("Case %d: ", iiiii);
ans = 10000;
scanf("%d %d", &n, &m);
getchar();
for(int i = 1; i<=n; i++){
for(int j = 1; j<=m; j++){
mp[i][j].x = i;
mp[i][j].y = j;
mp[i][j].ch = getchar();
mp[i][j].init();
}
getchar();
}
queue<node> bfs;
for(int i1 = 1; i1<=n; i1++){
for(int j1 = 1; j1<=m; j1++){
if(mp[i1][j1].ch == '#'){
for(int i2 = 1; i2<=n; i2++){
for(int j2 = 1; j2<=m; j2++){
if(mp[i2][j2].ch == '#'){
for(int u = 1; u<=n; u++) for(int v = 1; v<=m; v++) mp[u][v].vis = 0;
mp[i1][j1].vis = 1;
mp[i1][j1].step = 0;
mp[i2][j2].vis = 1;
mp[i2][j2].step = 0;
bfs.push(mp[i1][j1]);
bfs.push(mp[i2][j2]);
flag = 0;
while(!bfs.empty()){
temp = bfs.front();
bfs.pop();
for(int k = 0; k<4; k++){
int nx = temp.x + dir[k][0], ny = temp.y + dir[k][1];
if(nx > 0 && nx <= n && ny > 0 && ny <=m && mp[nx][ny].ch == '#' && mp[nx][ny].vis == 0){
mp[nx][ny].vis = 1;
mp[nx][ny].step = temp.step + 1;
bfs.push(mp[nx][ny]);
}
}
}
for(int i = 1; i<=n; i++){
for(int j = 1; j<=m; j++){
if(mp[i][j].ch == '#' && mp[i][j].vis == 0)
flag = 1;
mp[i][j].init();
}
}
if(flag == 0)
ans = min(ans, temp.step);
}
}
}
}
}
}
if(ans == 10000) ans = -1;
printf("%d\n", ans);
}
return 0;
} | 22.817073 | 99 | 0.397648 | tusikalanse |
14496db05408da977026af636f9ad71da45cec96 | 6,333 | cpp | C++ | deps/bcd-1.1/src/core/SamplesAccumulator.cpp | julescmay/LuxCore | 3a6233f37afaf064300f52854715c0ab9ca2103e | [
"Apache-2.0"
] | 826 | 2017-12-12T15:38:16.000Z | 2022-03-28T07:12:40.000Z | deps/bcd-1.1/src/core/SamplesAccumulator.cpp | julescmay/LuxCore | 3a6233f37afaf064300f52854715c0ab9ca2103e | [
"Apache-2.0"
] | 531 | 2017-12-03T17:21:06.000Z | 2022-03-20T19:22:11.000Z | deps/bcd-1.1/src/core/SamplesAccumulator.cpp | julescmay/LuxCore | 3a6233f37afaf064300f52854715c0ab9ca2103e | [
"Apache-2.0"
] | 133 | 2017-12-13T18:46:10.000Z | 2022-03-27T16:21:00.000Z | // This file is part of the reference implementation for the paper
// Bayesian Collaborative Denoising for Monte-Carlo Rendering
// Malik Boughida and Tamy Boubekeur.
// Computer Graphics Forum (Proc. EGSR 2017), vol. 36, no. 4, p. 137-153, 2017
//
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE.txt file.
#include "SamplesAccumulator.h"
#include "CovarianceMatrix.h"
#include <cassert>
#include <cmath>
using namespace std;
namespace bcd
{
SamplesStatisticsImages::SamplesStatisticsImages(int i_width, int i_height, int i_nbOfBins) :
m_nbOfSamplesImage(i_width, i_height, 1),
m_meanImage(i_width, i_height, 3),
m_covarImage(i_width, i_height, 6),
m_histoImage(i_width, i_height, 3 * i_nbOfBins)
{
}
SamplesAccumulator::SamplesAccumulator(
int i_width, int i_height,
const HistogramParameters& i_rHistogramParameters) :
m_width(i_width), m_height(i_height),
m_histogramParameters(i_rHistogramParameters),
m_samplesStatisticsImages(i_width, i_height, i_rHistogramParameters.m_nbOfBins),
m_squaredWeightSumsImage(i_width, i_height, 1),
m_isValid(true)
{
m_samplesStatisticsImages.m_nbOfSamplesImage.fill(0.f);
m_samplesStatisticsImages.m_meanImage.fill(0.f);
m_samplesStatisticsImages.m_covarImage.fill(0.f);
m_samplesStatisticsImages.m_histoImage.fill(0.f);
m_squaredWeightSumsImage.fill(0.f);
}
void SamplesAccumulator::addSample(
int i_line, int i_column,
float i_sampleR, float i_sampleG, float i_sampleB,
float i_weight)
{
assert(m_isValid);
const float sample[3] = { i_sampleR, i_sampleG, i_sampleB };
const float satureLevelGamma = 2.f; // used for determining the weight to give to the sample in the highest two bins, when the sample is saturated
m_samplesStatisticsImages.m_nbOfSamplesImage.get(i_line, i_column, 0) += i_weight;
m_squaredWeightSumsImage.get(i_line, i_column, 0) += i_weight * i_weight;
PixelPosition p(i_line, i_column);
DeepImage<float>& rSum = m_samplesStatisticsImages.m_meanImage;
rSum.get(i_line, i_column, 0) += i_weight * i_sampleR;
rSum.get(i_line, i_column, 1) += i_weight * i_sampleG;
rSum.get(i_line, i_column, 2) += i_weight * i_sampleB;
DeepImage<float>& rCovSum = m_samplesStatisticsImages.m_covarImage;
rCovSum.get(i_line, i_column, int(ESymMatData::e_xx)) += i_weight * i_sampleR * i_sampleR;
rCovSum.get(i_line, i_column, int(ESymMatData::e_yy)) += i_weight * i_sampleG * i_sampleG;
rCovSum.get(i_line, i_column, int(ESymMatData::e_zz)) += i_weight * i_sampleB * i_sampleB;
rCovSum.get(i_line, i_column, int(ESymMatData::e_yz)) += i_weight * i_sampleG * i_sampleB;
rCovSum.get(i_line, i_column, int(ESymMatData::e_xz)) += i_weight * i_sampleR * i_sampleB;
rCovSum.get(i_line, i_column, int(ESymMatData::e_xy)) += i_weight * i_sampleR * i_sampleG;
int floorBinIndex;
int ceilBinIndex;
float binFloatIndex;
float floorBinWeight;
float ceilBinWeight;
for(int32_t channelIndex = 0; channelIndex < 3; ++channelIndex)
{ // fill histogram; code refactored from Ray Histogram Fusion PBRT code
float value = sample[channelIndex];
value = (value > 0 ? value : 0);
if(m_histogramParameters.m_gamma > 1)
value = pow(value, 1.f / m_histogramParameters.m_gamma); // exponential scaling
if(m_histogramParameters.m_maxValue > 0)
value = (value / m_histogramParameters.m_maxValue); // normalize to the maximum value
value = value > satureLevelGamma ? satureLevelGamma : value;
binFloatIndex = value * (m_histogramParameters.m_nbOfBins - 2);
floorBinIndex = int(binFloatIndex);
if(floorBinIndex < m_histogramParameters.m_nbOfBins - 2) // in bounds
{
ceilBinIndex = floorBinIndex + 1;
ceilBinWeight = binFloatIndex - floorBinIndex;
floorBinWeight = 1.0f - ceilBinWeight;
}
else
{ //out of bounds... v >= 1
floorBinIndex = m_histogramParameters.m_nbOfBins - 2;
ceilBinIndex = floorBinIndex + 1;
ceilBinWeight = (value - 1.0f) / (satureLevelGamma - 1.f);
floorBinWeight = 1.0f - ceilBinWeight;
}
m_samplesStatisticsImages.m_histoImage.get(i_line, i_column, channelIndex * m_histogramParameters.m_nbOfBins + floorBinIndex) += i_weight * floorBinWeight;
m_samplesStatisticsImages.m_histoImage.get(i_line, i_column, channelIndex * m_histogramParameters.m_nbOfBins + ceilBinIndex) += i_weight * ceilBinWeight;
}
}
void SamplesAccumulator::computeSampleStatistics(SamplesStatisticsImages& io_sampleStats) const
{
float mean[3];
float cov[6];
for(int line = 0; line < m_height; ++line)
for(int column = 0; column < m_width; ++column)
{
float weightSum = io_sampleStats.m_nbOfSamplesImage.get(line, column, 0);
float squaredWeightSum = m_squaredWeightSumsImage.get(line, column, 0);
float invWeightSum = 1.f / weightSum;
for(int i = 0; i < 3; ++i)
{
mean[i] = invWeightSum * io_sampleStats.m_meanImage.get(line, column, i);
io_sampleStats.m_meanImage.set(line, column, i, mean[i]);
}
for(int i = 0; i < 6; ++i)
cov[i] = io_sampleStats.m_covarImage.get(line, column, i) * invWeightSum;
cov[int(ESymMatData::e_xx)] -= mean[0] * mean[0];
cov[int(ESymMatData::e_yy)] -= mean[1] * mean[1];
cov[int(ESymMatData::e_zz)] -= mean[2] * mean[2];
cov[int(ESymMatData::e_yz)] -= mean[1] * mean[2];
cov[int(ESymMatData::e_xz)] -= mean[0] * mean[2];
cov[int(ESymMatData::e_xy)] -= mean[0] * mean[1];
float biasCorrectionFactor = 1.f / (1 - squaredWeightSum / (weightSum * weightSum));
for(int i = 0; i < 6; ++i)
io_sampleStats.m_covarImage.set(line, column, i, cov[i] * biasCorrectionFactor);
}
}
SamplesStatisticsImages SamplesAccumulator::getSamplesStatistics() const
{
SamplesStatisticsImages stats(m_samplesStatisticsImages);
computeSampleStatistics(stats);
return move(stats);
}
SamplesStatisticsImages SamplesAccumulator::extractSamplesStatistics()
{
computeSampleStatistics(m_samplesStatisticsImages);
return move(m_samplesStatisticsImages);
}
void SamplesAccumulatorThreadSafe::addSampleThreadSafely(
int i_line, int i_column,
float i_sampleR, float i_sampleG, float i_sampleB,
float i_weight)
{
// lock
addSample(i_line, i_column, i_sampleR, i_sampleG, i_sampleB, i_weight);
}
} // namespace bcd
| 37.473373 | 158 | 0.730144 | julescmay |
144a15106536480fac3c3a2f7bd5bca269c4dd10 | 3,760 | hpp | C++ | include/np/ndarray/static/NDArrayStaticIndexImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | include/np/ndarray/static/NDArrayStaticIndexImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | include/np/ndarray/static/NDArrayStaticIndexImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | /*
C++ numpy-like template-based array implementation
Copyright (c) 2022 Mikhail Gorshkov (mikhail.gorshkov@gmail.com)
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.
*/
#pragma once
#include <np/ndarray/static/NDArrayStaticDecl.hpp>
namespace np::ndarray::array_static {
// Subsetting
template<typename DType, Size SizeT, Size... SizeTs>
inline void
set(NDArrayStatic<DType, SizeT, SizeTs...>& array, Size i, const typename NDArrayStatic<DType, SizeT, SizeTs...>::ReducedType& data) {
array.m_ArrayImpl.set(i, data.m_ArrayImpl);
}
// Select an element at an index
// a[2]
template<typename DType, Size SizeT, Size... SizeTs>
inline typename NDArrayStatic<DType, SizeT, SizeTs...>::ReducedType
NDArrayStatic<DType, SizeT, SizeTs...>::operator[](Size i) const {
return ReducedType{m_ArrayImpl[i]};
}
// a[1,2] Select the element at row and column (same as a[1][2])
// Slicing
// a[0:2] Select items at index 0 and 1
// b[0:2,1] Select items at rows 0 and 1 in column 1
// b[:1] Select all items at row 0 (equivalent to b[0:1,:])
// c[1,...] Same as [1,:,:]
// a[::-1] Reversed array
// Boolean indexing
// a[a < 2] Select elements from a less than 2
// Fancy indexing
// b[[1, 0, 1, 0], [0, 1, 2, 0]] Select elements (1,0),(0,1),(1,2) and (0,0)
// b[[1, 0, 1, 0]][: ,[0, 1, 2, 0]] Select a subset of the matrix’s rows and columns
/* TODO
template <typename DType, Size SizeT, Size... SizeTs>
inline ReducedType&
NDArrayStatic<DType, SizeT, SizeTs...>::operator [] (const std::string& i) {
return ReducedType{m_ArrayImpl[i]};
}
template <typename DType, Size SizeT, Size... SizeTs>
inline ReducedType
NDArrayStatic<DType, SizeT, SizeTs...>::operator [] (const std::string& i) const {
return ReducedType{m_ArrayImpl[i]};
}
*/
template<typename DType, Size SizeT, Size... SizeTs>
inline typename NDArrayStatic<DType, SizeT, SizeTs...>::ReducedType NDArrayStatic<DType, SizeT, SizeTs...>::at(Size i) const {
return ReducedType(m_ArrayImpl[i]);
}
/* TODO
template <typename DType, Size SizeT, Size... SizeTs>
inline ReducedType&
NDArrayStatic<DType, SizeT, SizeTs...>::at(const std::string& i) {
return ReducedType{m_ArrayImpl[i]};
}
template <typename DType, Size SizeT, Size... SizeTs>
inline ReducedType
NDArrayStatic<DType, SizeT, SizeTs...>::at(const std::string& i) const {
return ReducedType{m_ArrayImpl[i]};
}
*/
}
| 41.777778 | 138 | 0.645213 | mgorshkov |
144a8f33863d0db6051f4bb1d962e1b188d68554 | 19,987 | cpp | C++ | externals/skia/third_party/externals/angle2/src/libANGLE/ContextState.cpp | terrajobst/linux-packaging-skiasharp | 47dbb2ff9ae01305b190f409ccea00b3b4f0bc79 | [
"MIT"
] | 1 | 2019-10-29T14:36:32.000Z | 2019-10-29T14:36:32.000Z | externals/skia/third_party/externals/angle2/src/libANGLE/ContextState.cpp | terrajobst/linux-packaging-skiasharp | 47dbb2ff9ae01305b190f409ccea00b3b4f0bc79 | [
"MIT"
] | 1 | 2017-06-18T00:25:03.000Z | 2017-11-29T16:01:48.000Z | externals/skia/third_party/externals/angle2/src/libANGLE/ContextState.cpp | terrajobst/linux-packaging-skiasharp | 47dbb2ff9ae01305b190f409ccea00b3b4f0bc79 | [
"MIT"
] | 5 | 2017-11-30T06:06:50.000Z | 2022-03-31T21:48:49.000Z | //
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Data.cpp: Container class for all GL relevant state, caps and objects
#include "libANGLE/ContextState.h"
#include "libANGLE/Framebuffer.h"
#include "libANGLE/ResourceManager.h"
namespace gl
{
ContextState::ContextState(uintptr_t contextIn,
const Version &clientVersion,
State *stateIn,
const Caps &capsIn,
const TextureCapsMap &textureCapsIn,
const Extensions &extensionsIn,
const ResourceManager *resourceManagerIn,
const Limitations &limitationsIn,
const ResourceMap<Framebuffer> &framebufferMap)
: mClientVersion(clientVersion),
mContext(contextIn),
mState(stateIn),
mCaps(capsIn),
mTextureCaps(textureCapsIn),
mExtensions(extensionsIn),
mResourceManager(resourceManagerIn),
mLimitations(limitationsIn),
mFramebufferMap(framebufferMap)
{
}
ContextState::~ContextState()
{
}
const TextureCaps &ContextState::getTextureCap(GLenum internalFormat) const
{
return mTextureCaps.get(internalFormat);
}
ValidationContext::ValidationContext(const Version &clientVersion,
State *state,
const Caps &caps,
const TextureCapsMap &textureCaps,
const Extensions &extensions,
const ResourceManager *resourceManager,
const Limitations &limitations,
const ResourceMap<Framebuffer> &framebufferMap,
bool skipValidation)
: mState(reinterpret_cast<uintptr_t>(this),
clientVersion,
state,
caps,
textureCaps,
extensions,
resourceManager,
limitations,
framebufferMap),
mSkipValidation(skipValidation)
{
}
bool ValidationContext::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams)
{
if (pname >= GL_DRAW_BUFFER0_EXT && pname <= GL_DRAW_BUFFER15_EXT)
{
*type = GL_INT;
*numParams = 1;
return true;
}
// Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
// is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
// to the fact that it is stored internally as a float, and so would require conversion
// if returned from Context::getIntegerv. Since this conversion is already implemented
// in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
// place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
// application.
switch (pname)
{
case GL_COMPRESSED_TEXTURE_FORMATS:
{
*type = GL_INT;
*numParams = static_cast<unsigned int>(getCaps().compressedTextureFormats.size());
return true;
}
case GL_PROGRAM_BINARY_FORMATS_OES:
{
*type = GL_INT;
*numParams = static_cast<unsigned int>(getCaps().programBinaryFormats.size());
return true;
}
case GL_SHADER_BINARY_FORMATS:
{
*type = GL_INT;
*numParams = static_cast<unsigned int>(getCaps().shaderBinaryFormats.size());
return true;
}
case GL_MAX_VERTEX_ATTRIBS:
case GL_MAX_VERTEX_UNIFORM_VECTORS:
case GL_MAX_VARYING_VECTORS:
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
case GL_MAX_TEXTURE_IMAGE_UNITS:
case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
case GL_MAX_RENDERBUFFER_SIZE:
case GL_MAX_COLOR_ATTACHMENTS_EXT:
case GL_MAX_DRAW_BUFFERS_EXT:
case GL_NUM_SHADER_BINARY_FORMATS:
case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
case GL_ARRAY_BUFFER_BINDING:
// case GL_FRAMEBUFFER_BINDING: // equivalent to DRAW_FRAMEBUFFER_BINDING_ANGLE
case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE:
case GL_READ_FRAMEBUFFER_BINDING_ANGLE:
case GL_RENDERBUFFER_BINDING:
case GL_CURRENT_PROGRAM:
case GL_PACK_ALIGNMENT:
case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
case GL_UNPACK_ALIGNMENT:
case GL_GENERATE_MIPMAP_HINT:
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
case GL_RED_BITS:
case GL_GREEN_BITS:
case GL_BLUE_BITS:
case GL_ALPHA_BITS:
case GL_DEPTH_BITS:
case GL_STENCIL_BITS:
case GL_ELEMENT_ARRAY_BUFFER_BINDING:
case GL_CULL_FACE_MODE:
case GL_FRONT_FACE:
case GL_ACTIVE_TEXTURE:
case GL_STENCIL_FUNC:
case GL_STENCIL_VALUE_MASK:
case GL_STENCIL_REF:
case GL_STENCIL_FAIL:
case GL_STENCIL_PASS_DEPTH_FAIL:
case GL_STENCIL_PASS_DEPTH_PASS:
case GL_STENCIL_BACK_FUNC:
case GL_STENCIL_BACK_VALUE_MASK:
case GL_STENCIL_BACK_REF:
case GL_STENCIL_BACK_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_PASS:
case GL_DEPTH_FUNC:
case GL_BLEND_SRC_RGB:
case GL_BLEND_SRC_ALPHA:
case GL_BLEND_DST_RGB:
case GL_BLEND_DST_ALPHA:
case GL_BLEND_EQUATION_RGB:
case GL_BLEND_EQUATION_ALPHA:
case GL_STENCIL_WRITEMASK:
case GL_STENCIL_BACK_WRITEMASK:
case GL_STENCIL_CLEAR_VALUE:
case GL_SUBPIXEL_BITS:
case GL_MAX_TEXTURE_SIZE:
case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
case GL_SAMPLE_BUFFERS:
case GL_SAMPLES:
case GL_IMPLEMENTATION_COLOR_READ_TYPE:
case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
case GL_TEXTURE_BINDING_2D:
case GL_TEXTURE_BINDING_CUBE_MAP:
case GL_RESET_NOTIFICATION_STRATEGY_EXT:
case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
{
*type = GL_INT;
*numParams = 1;
return true;
}
case GL_MAX_SAMPLES_ANGLE:
{
if (!getExtensions().framebufferMultisample)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
}
case GL_MAX_VIEWPORT_DIMS:
{
*type = GL_INT;
*numParams = 2;
return true;
}
case GL_VIEWPORT:
case GL_SCISSOR_BOX:
{
*type = GL_INT;
*numParams = 4;
return true;
}
case GL_SHADER_COMPILER:
case GL_SAMPLE_COVERAGE_INVERT:
case GL_DEPTH_WRITEMASK:
case GL_CULL_FACE: // CULL_FACE through DITHER are natural to IsEnabled,
case GL_POLYGON_OFFSET_FILL: // but can be retrieved through the Get{Type}v queries.
case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as
// bool-natural
case GL_SAMPLE_COVERAGE:
case GL_SCISSOR_TEST:
case GL_STENCIL_TEST:
case GL_DEPTH_TEST:
case GL_BLEND:
case GL_DITHER:
case GL_CONTEXT_ROBUST_ACCESS_EXT:
{
*type = GL_BOOL;
*numParams = 1;
return true;
}
case GL_COLOR_WRITEMASK:
{
*type = GL_BOOL;
*numParams = 4;
return true;
}
case GL_POLYGON_OFFSET_FACTOR:
case GL_POLYGON_OFFSET_UNITS:
case GL_SAMPLE_COVERAGE_VALUE:
case GL_DEPTH_CLEAR_VALUE:
case GL_LINE_WIDTH:
{
*type = GL_FLOAT;
*numParams = 1;
return true;
}
case GL_ALIASED_LINE_WIDTH_RANGE:
case GL_ALIASED_POINT_SIZE_RANGE:
case GL_DEPTH_RANGE:
{
*type = GL_FLOAT;
*numParams = 2;
return true;
}
case GL_COLOR_CLEAR_VALUE:
case GL_BLEND_COLOR:
{
*type = GL_FLOAT;
*numParams = 4;
return true;
}
case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
if (!getExtensions().maxTextureAnisotropy)
{
return false;
}
*type = GL_FLOAT;
*numParams = 1;
return true;
case GL_TIMESTAMP_EXT:
if (!getExtensions().disjointTimerQuery)
{
return false;
}
*type = GL_INT_64_ANGLEX;
*numParams = 1;
return true;
case GL_GPU_DISJOINT_EXT:
if (!getExtensions().disjointTimerQuery)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
case GL_COVERAGE_MODULATION_CHROMIUM:
if (!getExtensions().framebufferMixedSamples)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
case GL_TEXTURE_BINDING_EXTERNAL_OES:
if (!getExtensions().eglStreamConsumerExternal && !getExtensions().eglImageExternal)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
}
if (getExtensions().debug)
{
switch (pname)
{
case GL_DEBUG_LOGGED_MESSAGES:
case GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH:
case GL_DEBUG_GROUP_STACK_DEPTH:
case GL_MAX_DEBUG_MESSAGE_LENGTH:
case GL_MAX_DEBUG_LOGGED_MESSAGES:
case GL_MAX_DEBUG_GROUP_STACK_DEPTH:
case GL_MAX_LABEL_LENGTH:
*type = GL_INT;
*numParams = 1;
return true;
case GL_DEBUG_OUTPUT_SYNCHRONOUS:
case GL_DEBUG_OUTPUT:
*type = GL_BOOL;
*numParams = 1;
return true;
}
}
if (getExtensions().multisampleCompatibility)
{
switch (pname)
{
case GL_MULTISAMPLE_EXT:
case GL_SAMPLE_ALPHA_TO_ONE_EXT:
*type = GL_BOOL;
*numParams = 1;
return true;
}
}
if (getExtensions().pathRendering)
{
switch (pname)
{
case GL_PATH_MODELVIEW_MATRIX_CHROMIUM:
case GL_PATH_PROJECTION_MATRIX_CHROMIUM:
*type = GL_FLOAT;
*numParams = 16;
return true;
}
}
if (getExtensions().bindGeneratesResource)
{
switch (pname)
{
case GL_BIND_GENERATES_RESOURCE_CHROMIUM:
*type = GL_BOOL;
*numParams = 1;
return true;
}
}
if (getExtensions().sRGBWriteControl)
{
switch (pname)
{
case GL_FRAMEBUFFER_SRGB_EXT:
*type = GL_BOOL;
*numParams = 1;
return true;
}
}
// Check for ES3.0+ parameter names which are also exposed as ES2 extensions
switch (pname)
{
case GL_PACK_ROW_LENGTH:
case GL_PACK_SKIP_ROWS:
case GL_PACK_SKIP_PIXELS:
if ((getClientMajorVersion() < 3) && !getExtensions().packSubimage)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
case GL_UNPACK_ROW_LENGTH:
case GL_UNPACK_SKIP_ROWS:
case GL_UNPACK_SKIP_PIXELS:
if ((getClientMajorVersion() < 3) && !getExtensions().unpackSubimage)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
case GL_VERTEX_ARRAY_BINDING:
if ((getClientMajorVersion() < 3) && !getExtensions().vertexArrayObject)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
case GL_PIXEL_PACK_BUFFER_BINDING:
case GL_PIXEL_UNPACK_BUFFER_BINDING:
if ((getClientMajorVersion() < 3) && !getExtensions().pixelBufferObject)
{
return false;
}
*type = GL_INT;
*numParams = 1;
return true;
}
if (getClientVersion() < Version(3, 0))
{
return false;
}
// Check for ES3.0+ parameter names
switch (pname)
{
case GL_MAX_UNIFORM_BUFFER_BINDINGS:
case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
case GL_UNIFORM_BUFFER_BINDING:
case GL_TRANSFORM_FEEDBACK_BINDING:
case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
case GL_COPY_READ_BUFFER_BINDING:
case GL_COPY_WRITE_BUFFER_BINDING:
case GL_SAMPLER_BINDING:
case GL_READ_BUFFER:
case GL_TEXTURE_BINDING_3D:
case GL_TEXTURE_BINDING_2D_ARRAY:
case GL_MAX_3D_TEXTURE_SIZE:
case GL_MAX_ARRAY_TEXTURE_LAYERS:
case GL_MAX_VERTEX_UNIFORM_BLOCKS:
case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:
case GL_MAX_COMBINED_UNIFORM_BLOCKS:
case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
case GL_MAX_VARYING_COMPONENTS:
case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
case GL_MIN_PROGRAM_TEXEL_OFFSET:
case GL_MAX_PROGRAM_TEXEL_OFFSET:
case GL_NUM_EXTENSIONS:
case GL_MAJOR_VERSION:
case GL_MINOR_VERSION:
case GL_MAX_ELEMENTS_INDICES:
case GL_MAX_ELEMENTS_VERTICES:
case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:
case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:
case GL_UNPACK_IMAGE_HEIGHT:
case GL_UNPACK_SKIP_IMAGES:
{
*type = GL_INT;
*numParams = 1;
return true;
}
case GL_MAX_ELEMENT_INDEX:
case GL_MAX_UNIFORM_BLOCK_SIZE:
case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:
case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:
case GL_MAX_SERVER_WAIT_TIMEOUT:
{
*type = GL_INT_64_ANGLEX;
*numParams = 1;
return true;
}
case GL_TRANSFORM_FEEDBACK_ACTIVE:
case GL_TRANSFORM_FEEDBACK_PAUSED:
case GL_PRIMITIVE_RESTART_FIXED_INDEX:
case GL_RASTERIZER_DISCARD:
{
*type = GL_BOOL;
*numParams = 1;
return true;
}
case GL_MAX_TEXTURE_LOD_BIAS:
{
*type = GL_FLOAT;
*numParams = 1;
return true;
}
}
if (getExtensions().requestExtension)
{
switch (pname)
{
case GL_NUM_REQUESTABLE_EXTENSIONS_ANGLE:
*type = GL_INT;
*numParams = 1;
return true;
}
}
if (getClientVersion() < Version(3, 1))
{
return false;
}
switch (pname)
{
case GL_DRAW_INDIRECT_BUFFER_BINDING:
case GL_MAX_FRAMEBUFFER_WIDTH:
case GL_MAX_FRAMEBUFFER_HEIGHT:
case GL_MAX_FRAMEBUFFER_SAMPLES:
case GL_MAX_SAMPLE_MASK_WORDS:
case GL_MAX_COLOR_TEXTURE_SAMPLES:
case GL_MAX_DEPTH_TEXTURE_SAMPLES:
case GL_MAX_INTEGER_SAMPLES:
case GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET:
case GL_MAX_VERTEX_ATTRIB_BINDINGS:
case GL_MAX_VERTEX_ATTRIB_STRIDE:
case GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS:
case GL_MAX_VERTEX_ATOMIC_COUNTERS:
case GL_MAX_VERTEX_IMAGE_UNIFORMS:
case GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS:
case GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS:
case GL_MAX_FRAGMENT_ATOMIC_COUNTERS:
case GL_MAX_FRAGMENT_IMAGE_UNIFORMS:
case GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS:
case GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET:
case GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET:
case GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS:
case GL_MAX_COMPUTE_UNIFORM_BLOCKS:
case GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS:
case GL_MAX_COMPUTE_SHARED_MEMORY_SIZE:
case GL_MAX_COMPUTE_UNIFORM_COMPONENTS:
case GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS:
case GL_MAX_COMPUTE_ATOMIC_COUNTERS:
case GL_MAX_COMPUTE_IMAGE_UNIFORMS:
case GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS:
case GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS:
case GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES:
case GL_MAX_UNIFORM_LOCATIONS:
case GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS:
case GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE:
case GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS:
case GL_MAX_COMBINED_ATOMIC_COUNTERS:
case GL_MAX_IMAGE_UNITS:
case GL_MAX_COMBINED_IMAGE_UNIFORMS:
case GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS:
case GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS:
case GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT:
*type = GL_INT;
*numParams = 1;
return true;
case GL_MAX_SHADER_STORAGE_BLOCK_SIZE:
*type = GL_INT_64_ANGLEX;
*numParams = 1;
return true;
}
return false;
}
bool ValidationContext::getIndexedQueryParameterInfo(GLenum target,
GLenum *type,
unsigned int *numParams)
{
if (getClientVersion() < Version(3, 0))
{
return false;
}
switch (target)
{
case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
case GL_UNIFORM_BUFFER_BINDING:
{
*type = GL_INT;
*numParams = 1;
return true;
}
case GL_TRANSFORM_FEEDBACK_BUFFER_START:
case GL_TRANSFORM_FEEDBACK_BUFFER_SIZE:
case GL_UNIFORM_BUFFER_START:
case GL_UNIFORM_BUFFER_SIZE:
{
*type = GL_INT_64_ANGLEX;
*numParams = 1;
return true;
}
}
if (getClientVersion() < Version(3, 1))
{
return false;
}
switch (target)
{
case GL_MAX_COMPUTE_WORK_GROUP_COUNT:
case GL_MAX_COMPUTE_WORK_GROUP_SIZE:
{
*type = GL_INT;
*numParams = 1;
return true;
}
}
return false;
}
Program *ValidationContext::getProgram(GLuint handle) const
{
return mState.mResourceManager->getProgram(handle);
}
Shader *ValidationContext::getShader(GLuint handle) const
{
return mState.mResourceManager->getShader(handle);
}
bool ValidationContext::isTextureGenerated(GLuint texture) const
{
return mState.mResourceManager->isTextureGenerated(texture);
}
bool ValidationContext::isBufferGenerated(GLuint buffer) const
{
return mState.mResourceManager->isBufferGenerated(buffer);
}
bool ValidationContext::isRenderbufferGenerated(GLuint renderbuffer) const
{
return mState.mResourceManager->isRenderbufferGenerated(renderbuffer);
}
bool ValidationContext::isFramebufferGenerated(GLuint framebuffer) const
{
ASSERT(mState.mFramebufferMap.find(0) != mState.mFramebufferMap.end());
return mState.mFramebufferMap.find(framebuffer) != mState.mFramebufferMap.end();
}
} // namespace gl
| 31.675119 | 98 | 0.593986 | terrajobst |
144c4dcff9515405e869ec9fd60e94b33c61d40b | 5,771 | hpp | C++ | Engine/UserInterface/UICommon.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | Engine/UserInterface/UICommon.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | Engine/UserInterface/UICommon.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | //==============================================================================================================
//UserInterfaceCommon.hpp
//by Albert Chen Apr-18-2016.
//==============================================================================================================
#pragma once
#ifndef _included_UserInterfaceCommon__
#define _included_UserInterfaceCommon__
#include "Engine/Math/Vector2.hpp"
#include "Engine/Renderer/OpenGLRenderer.hpp"
#include "Engine/Input//InputCommon.hpp"
#include "Engine/Core/Clock.hpp"
//===========================================================================================================
extern Clock* g_UIClock;
void AllocUIClock();
double GetUIDeltaSeconds();
//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///UI constants
//anchor points
static const Vector2 UI_SCREEN_SIZE = Vector2(1600, 900);
static const Vector2 UI_ANCHOR_SCREEN_CENTER = UI_SCREEN_SIZE * 0.5f;
static const Vector2 UI_ANCHOR_SCREEN_LEFT_CENTER = Vector2(0.0f, UI_SCREEN_SIZE.y * 0.5f);
static const Vector2 UI_ANCHOR_SCREEN_RIGHT_CENTER = Vector2(UI_SCREEN_SIZE.x * 0.5f, UI_SCREEN_SIZE.y * 0.5f);
static const Vector2 UI_ANCHOR_SCREEN_TOP_CENTER = Vector2(UI_SCREEN_SIZE.x * 0.5f, UI_SCREEN_SIZE.y);
static const Vector2 UI_ANCHOR_SCREEN_BOTTOM_CENTER = Vector2(UI_SCREEN_SIZE.x * 0.5f, 0.0f);
static const Vector2 UI_ANCHOR_SCREEN_TOP_LEFT = Vector2(0.0f, UI_SCREEN_SIZE.y);
static const Vector2 UI_ANCHOR_SCREEN_TOP_RIGHT = Vector2(UI_SCREEN_SIZE.x, UI_SCREEN_SIZE.y);
static const Vector2 UI_ANCHOR_SCREEN_BOTTOM_LEFT = Vector2(0.0f, 0.0f);
static const Vector2 UI_ANCHOR_SCREEN_BOTTOM_RIGHT = Vector2(UI_SCREEN_SIZE.x, 0.0f);
//===========================================================================================================
enum UIAnchorID {
UI_ANCHOR_CENTER,
UI_ANCHOR_LEFT_CENTER,
UI_ANCHOR_RIGHT_CENTER,
UI_ANCHOR_TOP_CENTER,
UI_ANCHOR_BOTTOM_CENTER,
UI_ANCHOR_TOP_LEFT,
UI_ANCHOR_TOP_RIGHT,
UI_ANCHOR_BOTTOM_LEFT,
UI_ANCHOR_BOTTOM_RIGHT,
NUM_UI_ANCHORS,
UI_ANCHOR_INVALID
};
///----------------------------------------------------------------------------------------------------------
///global helpers
const Vector2 GetUIAnchorForScreen(const UIAnchorID& anchorEnum);
const Vector2 GetPositionForUIAnchorInAABB2(const UIAnchorID&, const AABB2& anchorBounds);
const UIAnchorID GetUIAnchorForString(const std::string& anchorString);
///----------------------------------------------------------------------------------------------------------
///inline globals
inline const Vector2 GetUIAnchorForScreen(const UIAnchorID& anchorEnum) {
switch(anchorEnum){
case UI_ANCHOR_CENTER:
return UI_ANCHOR_SCREEN_CENTER;
case UI_ANCHOR_LEFT_CENTER:
return UI_ANCHOR_SCREEN_LEFT_CENTER;
case UI_ANCHOR_RIGHT_CENTER:
return UI_ANCHOR_SCREEN_RIGHT_CENTER;
case UI_ANCHOR_TOP_CENTER:
return UI_ANCHOR_SCREEN_TOP_CENTER;
case UI_ANCHOR_BOTTOM_CENTER:
return UI_ANCHOR_SCREEN_BOTTOM_CENTER;
case UI_ANCHOR_TOP_LEFT:
return UI_ANCHOR_SCREEN_TOP_LEFT;
case UI_ANCHOR_TOP_RIGHT:
return UI_ANCHOR_SCREEN_TOP_RIGHT;
case UI_ANCHOR_BOTTOM_LEFT:
return UI_ANCHOR_SCREEN_BOTTOM_LEFT;
case UI_ANCHOR_BOTTOM_RIGHT:
return UI_ANCHOR_SCREEN_BOTTOM_RIGHT;
}
return Vector2::ZERO;
}
//-----------------------------------------------------------------------------------------------------------
inline const Vector2 GetPositionForUIAnchorInAABB2(const UIAnchorID& anchorID , const AABB2& anchorBounds) {
switch (anchorID) {
case UI_ANCHOR_CENTER:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.5f, 0.5f));
case UI_ANCHOR_LEFT_CENTER:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.0f, 0.5f));
case UI_ANCHOR_RIGHT_CENTER:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(1.0f, 0.5f));
case UI_ANCHOR_TOP_CENTER:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.5f, 1.0f));
case UI_ANCHOR_BOTTOM_CENTER:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.5f, 0.0f));
case UI_ANCHOR_TOP_LEFT:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.0f, 1.0f));
case UI_ANCHOR_TOP_RIGHT:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(1.0f, 1.0f));
case UI_ANCHOR_BOTTOM_LEFT:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.0f, 0.0f));
case UI_ANCHOR_BOTTOM_RIGHT:
return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(1.0f, 0.0f));
}
return Vector2::ZERO;
}
//-----------------------------------------------------------------------------------------------------------
inline const UIAnchorID GetUIAnchorForString(const std::string& anchorString){
if (anchorString == "center") {
return UI_ANCHOR_CENTER;
}
else if (anchorString == "left center") {
return UI_ANCHOR_LEFT_CENTER;
}
else if (anchorString == "right center") {
return UI_ANCHOR_RIGHT_CENTER;
}
else if (anchorString == "top center") {
return UI_ANCHOR_TOP_CENTER;
}
else if (anchorString == "bottom center") {
return UI_ANCHOR_BOTTOM_CENTER;
}
else if (anchorString == "top left") {
return UI_ANCHOR_TOP_LEFT;
}
else if (anchorString == "top right") {
return UI_ANCHOR_TOP_RIGHT;
}
else if (anchorString == "bottom left") {
return UI_ANCHOR_BOTTOM_LEFT;
}
else if (anchorString == "bottom right") {
return UI_ANCHOR_BOTTOM_RIGHT;
}
return UI_ANCHOR_INVALID;
}
//===========================================================================================================
#endif //__includedUserInterfaceCommon__
| 34.556886 | 112 | 0.634032 | achen889 |
144ed7f11ac26f0182a4b081598643bb3c088ece | 18,652 | cc | C++ | src/swig_siqadconn/siqadconn.cc | samuelngsh/qpuanneal-sidb | ba0341a0ba852241de7c9a4e45f6a0a252bc48b4 | [
"Apache-2.0"
] | null | null | null | src/swig_siqadconn/siqadconn.cc | samuelngsh/qpuanneal-sidb | ba0341a0ba852241de7c9a4e45f6a0a252bc48b4 | [
"Apache-2.0"
] | null | null | null | src/swig_siqadconn/siqadconn.cc | samuelngsh/qpuanneal-sidb | ba0341a0ba852241de7c9a4e45f6a0a252bc48b4 | [
"Apache-2.0"
] | null | null | null | // @file: siqadconn.cc
// @author: Samuel
// @created: 2017.08.23
// @editted: 2019.01.23 - Nathan
// @license: Apache License 2.0
//
// @desc: Convenient functions for interacting with SiQAD
#include "siqadconn.h"
#include <iostream>
#include <stdexcept>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using namespace phys;
//CONSTRUCTOR
SiQADConnector::SiQADConnector(const std::string &eng_name,
const std::string &input_path, const std::string &output_path)
: eng_name(eng_name), input_path(input_path), output_path(output_path)
{
// initialize variables
item_tree = std::make_shared<Aggregate>();
start_time = std::chrono::system_clock::now();
elec_col = new ElectrodeCollection(item_tree);
elec_poly_col = new ElectrodePolyCollection(item_tree);
db_col = new DBCollection(item_tree);
// read problem from input_path
readProblem(input_path);
}
void SiQADConnector::setExport(std::string type, std::vector< std::pair< std::string, std::string > > &data_in)
{
if (type == "db_loc")
dbl_data = data_in;
else
throw std::invalid_argument(std::string("No candidate for export type '") +
type + std::string("' with class std::vector<std::pair<std::string, std::string>>"));
}
void SiQADConnector::setExport(std::string type, std::vector< std::vector< std::string > > &data_in)
{
if (type == "potential")
pot_data = data_in;
else if (type == "electrodes")
elec_data = data_in;
else if (type == "db_pot")
db_pot_data = data_in;
else if (type == "db_charge")
db_charge_data = data_in;
else
throw std::invalid_argument(std::string("No candidate for export type '") +
type + std::string("' with class std::vector<std::vector<std::string>>"));
}
// FILE HANDLING
// parse problem XML, return true if successful
void SiQADConnector::readProblem(const std::string &path)
{
std::cout << "Reading problem file: " << input_path << std::endl;
bpt::ptree tree; // create empty property tree object
bpt::read_xml(path, tree, bpt::xml_parser::no_comments); // parse the input file into property tree
// parse XML
// read program properties
// TODO read program node
// read simulation parameters
std::cout << "Read simulation parameters" << std::endl;
readSimulationParam(tree.get_child("siqad.sim_params"));
// read layer properties
std::cout << "Read layer properties" << std::endl;
readLayers(tree.get_child("siqad.layers"));
// read items
std::cout << "Read items tree" << std::endl;
readDesign(tree.get_child("siqad.design"), item_tree);
}
void SiQADConnector::readProgramProp(const bpt::ptree &program_prop_tree)
{
for (bpt::ptree::value_type const &v : program_prop_tree) {
program_props.insert(std::map<std::string, std::string>::value_type(v.first, v.second.data()));
std::cout << "ProgramProp: Key=" << v.first << ", Value=" << program_props[v.first] << std::endl;
}
}
void SiQADConnector::readLayers(const bpt::ptree &layer_prop_tree)
{
// if this were structured the same way as readDesign, then only the first layer_prop subtree would be read.
// TODO: make this more general.
for (bpt::ptree::value_type const &v : layer_prop_tree)
readLayerProp(v.second);
}
void SiQADConnector::readLayerProp(const bpt::ptree &layer_node)
{
Layer lay;
lay.name = layer_node.get<std::string>("name");
lay.type = layer_node.get<std::string>("type");
lay.zoffset = layer_node.get<float>("zoffset");
lay.zheight = layer_node.get<float>("zheight");
layers.push_back(lay);
std::cout << "Retrieved layer " << lay.name << " of type " << lay.type << std::endl;
}
void SiQADConnector::readSimulationParam(const bpt::ptree &sim_params_tree)
{
for (bpt::ptree::value_type const &v : sim_params_tree) {
sim_params.insert(std::map<std::string, std::string>::value_type(v.first, v.second.data()));
std::cout << "SimParam: Key=" << v.first << ", Value=" << sim_params[v.first] << std::endl;
}
}
void SiQADConnector::readDesign(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent)
{
std::cout << "Beginning to read design" << std::endl;
for (bpt::ptree::value_type const &layer_tree : subtree) {
std::string layer_type = layer_tree.second.get<std::string>("<xmlattr>.type");
if ((!layer_type.compare("DB"))) {
std::cout << "Encountered node " << layer_tree.first << " with type " << layer_type << ", entering" << std::endl;
readItemTree(layer_tree.second, agg_parent);
} else if ( (!layer_type.compare("Electrode"))) {
std::cout << "Encountered node " << layer_tree.first << " with type " << layer_type << ", entering" << std::endl;
readItemTree(layer_tree.second, agg_parent);
} else {
std::cout << "Encountered node " << layer_tree.first << " with type " << layer_type << ", no defined action for this layer. Skipping." << std::endl;
}
}
}
void SiQADConnector::readItemTree(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent)
{
for (bpt::ptree::value_type const &item_tree : subtree) {
std::string item_name = item_tree.first;
std::cout << "item_name: " << item_name << std::endl;
if (!item_name.compare("aggregate")) {
// add aggregate child to tree
agg_parent->aggs.push_back(std::make_shared<Aggregate>());
readItemTree(item_tree.second, agg_parent->aggs.back());
} else if (!item_name.compare("dbdot")) {
// add DBDot to tree
readDBDot(item_tree.second, agg_parent);
} else if (!item_name.compare("electrode")) {
// add Electrode to tree
readElectrode(item_tree.second, agg_parent);
} else if (!item_name.compare("electrode_poly")) {
// add Electrode to tree
readElectrodePoly(item_tree.second, agg_parent);
} else {
std::cout << "Encountered unknown item node: " << item_tree.first << std::endl;
}
}
}
void SiQADConnector::readElectrode(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent)
{
double x1, x2, y1, y2, pixel_per_angstrom, potential, phase, angle;
int layer_id, electrode_type, net;
// read values from XML stream
layer_id = subtree.get<int>("layer_id");
angle = subtree.get<double>("angle");
potential = subtree.get<double>("property_map.potential.val");
phase = subtree.get<double>("property_map.phase.val");
std::string electrode_type_s = subtree.get<std::string>("property_map.type.val");
if (!electrode_type_s.compare("fixed")){
electrode_type = 0;
} else if (!electrode_type_s.compare("clocked")) {
electrode_type = 1;
}
net = subtree.get<int>("property_map.net.val");
pixel_per_angstrom = subtree.get<double>("pixel_per_angstrom");
x1 = subtree.get<double>("dim.<xmlattr>.x1");
x2 = subtree.get<double>("dim.<xmlattr>.x2");
y1 = subtree.get<double>("dim.<xmlattr>.y1");
y2 = subtree.get<double>("dim.<xmlattr>.y2");
agg_parent->elecs.push_back(std::make_shared<Electrode>(layer_id,x1,x2,y1,y2,potential,phase,electrode_type,pixel_per_angstrom,net,angle));
std::cout << "Electrode created with x1=" << agg_parent->elecs.back()->x1 << ", y1=" << agg_parent->elecs.back()->y1 <<
", x2=" << agg_parent->elecs.back()->x2 << ", y2=" << agg_parent->elecs.back()->y2 <<
", potential=" << agg_parent->elecs.back()->potential << std::endl;
}
void SiQADConnector::readElectrodePoly(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent)
{
double pixel_per_angstrom, potential, phase;
std::vector<std::pair<double, double>> vertices;
int layer_id, electrode_type, net;
// read values from XML stream
layer_id = subtree.get<int>("layer_id");
potential = subtree.get<double>("property_map.potential.val");
phase = subtree.get<double>("property_map.phase.val");
std::string electrode_type_s = subtree.get<std::string>("property_map.type.val");
if (!electrode_type_s.compare("fixed")){
electrode_type = 0;
} else if (!electrode_type_s.compare("clocked")) {
electrode_type = 1;
}
pixel_per_angstrom = subtree.get<double>("pixel_per_angstrom");
net = subtree.get<int>("property_map.net.val");
//cycle through the vertices
std::pair<double, double> point;
for (auto val: subtree) {
if(val.first == "vertex") {
double x = std::stod(val.second.get_child("<xmlattr>.x").data());
double y = std::stod(val.second.get_child("<xmlattr>.y").data());
point = std::make_pair(x, y);
vertices.push_back(point);
}
}
agg_parent->elec_polys.push_back(std::make_shared<ElectrodePoly>(layer_id,vertices,potential,phase,electrode_type,pixel_per_angstrom,net));
std::cout << "ElectrodePoly created with " << agg_parent->elec_polys.back()->vertices.size() <<
" vertices, potential=" << agg_parent->elec_polys.back()->potential << std::endl;
}
void SiQADConnector::readDBDot(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent)
{
float x, y;
int n, m, l;
// read x and y physical locations
x = subtree.get<float>("physloc.<xmlattr>.x");
y = subtree.get<float>("physloc.<xmlattr>.y");
// read n, m and l lattice coordinates
n = subtree.get<int>("latcoord.<xmlattr>.n");
m = subtree.get<int>("latcoord.<xmlattr>.m");
l = subtree.get<int>("latcoord.<xmlattr>.l");
agg_parent->dbs.push_back(std::make_shared<DBDot>(x, y, n, m, l));
std::cout << "DBDot created with x=" << agg_parent->dbs.back()->x
<< ", y=" << agg_parent->dbs.back()->y
<< ", n=" << agg_parent->dbs.back()->n
<< ", m=" << agg_parent->dbs.back()->m
<< ", l=" << agg_parent->dbs.back()->l
<< std::endl;
}
void SiQADConnector::writeResultsXml()
{
std::cout << "SiQADConnector::writeResultsXml()" << std::endl;
boost::property_tree::ptree node_root;
std::cout << "Write results to XML..." << std::endl;
// eng_info
node_root.add_child("eng_info", engInfoPropertyTree());
// sim_params
node_root.add_child("sim_params", simParamsPropertyTree());
// DB locations
if (!dbl_data.empty())
node_root.add_child("physloc", dbLocPropertyTree());
// DB electron distributions
if(!db_charge_data.empty())
node_root.add_child("elec_dist", dbChargePropertyTree());
// electrode
if (!elec_data.empty())
node_root.add_child("electrode", electrodePropertyTree());
//electric potentials
if (!pot_data.empty())
node_root.add_child("potential_map", potentialPropertyTree());
//potentials at db locations
if (!db_pot_data.empty())
node_root.add_child("dbdots", dbPotentialPropertyTree());
// write full tree to file
boost::property_tree::ptree tree;
tree.add_child("sim_out", node_root);
boost::property_tree::write_xml(output_path, tree, std::locale(), boost::property_tree::xml_writer_make_settings<std::string>(' ',4));
std::cout << "Write to XML complete." << std::endl;
}
bpt::ptree SiQADConnector::engInfoPropertyTree()
{
boost::property_tree::ptree node_eng_info;
node_eng_info.put("engine", eng_name);
node_eng_info.put("version", "TBD"); // TODO real version
node_eng_info.put("return_code", std::to_string(return_code).c_str());
//get timing information
end_time = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end_time-start_time;
std::time_t end = std::chrono::system_clock::to_time_t(end_time);
char* end_c_str = std::ctime(&end);
*std::remove(end_c_str, end_c_str+strlen(end_c_str), '\n') = '\0'; // removes _all_ new lines from the cstr
node_eng_info.put("timestamp", end_c_str);
node_eng_info.put("time_elapsed_s", std::to_string(elapsed_seconds.count()).c_str());
return node_eng_info;
}
bpt::ptree SiQADConnector::simParamsPropertyTree()
{
bpt::ptree node_sim_params;
for (std::pair<std::string, std::string> param : sim_params)
node_sim_params.put(param.first, param.second);
return node_sim_params;
}
bpt::ptree SiQADConnector::dbLocPropertyTree()
{
bpt::ptree node_physloc;
for (unsigned int i = 0; i < dbl_data.size(); i++){
bpt::ptree node_dbdot;
node_dbdot.put("<xmlattr>.x", dbl_data[i].first.c_str());
node_dbdot.put("<xmlattr>.y", dbl_data[i].second.c_str());
node_physloc.add_child("dbdot", node_dbdot);
}
return node_physloc;
}
bpt::ptree SiQADConnector::dbChargePropertyTree()
{
bpt::ptree node_elec_dist;
for (unsigned int i = 0; i < db_charge_data.size(); i++){
bpt::ptree node_dist;
node_dist.put("", db_charge_data[i][0]);
node_dist.put("<xmlattr>.energy", db_charge_data[i][1]);
node_dist.put("<xmlattr>.count", db_charge_data[i][2]);
node_elec_dist.add_child("dist", node_dist);
}
return node_elec_dist;
}
bpt::ptree SiQADConnector::electrodePropertyTree()
{
bpt::ptree node_electrode;
for (unsigned int i = 0; i < elec_data.size(); i++){
boost::property_tree::ptree node_dim;
node_dim.put("<xmlattr>.x1", elec_data[i][0].c_str());
node_dim.put("<xmlattr>.y1", elec_data[i][1].c_str());
node_dim.put("<xmlattr>.x2", elec_data[i][2].c_str());
node_dim.put("<xmlattr>.y2", elec_data[i][3].c_str());
node_electrode.add_child("dim", node_dim);
boost::property_tree::ptree node_pot;
node_pot.put("", elec_data[i][4].c_str());
node_electrode.add_child("potential", node_pot);
}
return node_electrode;
}
bpt::ptree SiQADConnector::potentialPropertyTree()
{
bpt::ptree node_potential_map;
for (unsigned int i = 0; i < pot_data.size(); i++){
boost::property_tree::ptree node_potential_val;
node_potential_val.put("<xmlattr>.x", pot_data[i][0].c_str());
node_potential_val.put("<xmlattr>.y", pot_data[i][1].c_str());
node_potential_val.put("<xmlattr>.val", pot_data[i][2].c_str());
node_potential_map.add_child("potential_val", node_potential_val);
}
return node_potential_map;
}
bpt::ptree SiQADConnector::dbPotentialPropertyTree()
{
bpt::ptree node_dbdots;
for (unsigned int i = 0; i < db_pot_data.size(); i++){
bpt::ptree node_dbdot;
bpt::ptree node_physloc;
node_physloc.put("<xmlattr>.x", db_pot_data[i][0].c_str());
node_physloc.put("<xmlattr>.y", db_pot_data[i][1].c_str());
node_dbdot.add_child("physloc", node_physloc);
boost::property_tree::ptree node_db_pot;
node_db_pot.put("", db_pot_data[i][2].c_str());
node_dbdot.add_child("potential", node_db_pot);
node_dbdots.add_child("dbdot", node_dbdot);
}
return node_dbdots;
}
//DB ITERATOR
DBIterator::DBIterator(std::shared_ptr<Aggregate> root, bool begin)
{
if(begin){
// keep finding deeper aggregates until one that contains dbs is found
while(root->dbs.empty() && !root->aggs.empty()) {
push(root);
root = root->aggs.front();
}
push(root);
}
else{
db_iter = root->dbs.cend();
}
}
DBIterator& DBIterator::operator++()
{
// exhaust the current Aggregate DBs first
if(db_iter != curr->dbs.cend())
return ++db_iter != curr->dbs.cend() ? *this : ++(*this);
// if available, push the next aggregate onto the stack
if(agg_stack.top().second != curr->aggs.cend()){
push(*agg_stack.top().second);
return db_iter != curr->dbs.cend() ? *this : ++(*this);
}
// aggregate is complete, pop off stack
pop();
return agg_stack.size() == 0 ? *this : ++(*this);
}
void DBIterator::push(std::shared_ptr<Aggregate> agg)
{
if(!agg_stack.empty())
++agg_stack.top().second;
agg_stack.push(std::make_pair(agg, agg->aggs.cbegin()));
db_iter = agg->dbs.cbegin();
curr = agg;
}
void DBIterator::pop()
{
agg_stack.pop(); // pop complete aggregate off stack
if(agg_stack.size() > 0){
curr = agg_stack.top().first; // update current to new top
db_iter = curr->dbs.cend(); // don't reread dbs
}
}
// ELEC ITERATOR
ElecIterator::ElecIterator(std::shared_ptr<Aggregate> root, bool begin)
{
if(begin){
// keep finding deeper aggregates until one that contains dbs is found
while(root->elecs.empty() && !root->aggs.empty()) {
push(root);
root = root->aggs.front();
}
push(root);
}
else{
elec_iter = root->elecs.cend();
}
}
ElecIterator& ElecIterator::operator++()
{
// exhaust the current Aggregate DBs first
if(elec_iter != curr->elecs.cend())
return ++elec_iter != curr->elecs.cend() ? *this : ++(*this);
// if available, push the next aggregate onto the stack
if(agg_stack.top().second != curr->aggs.cend()){
push(*agg_stack.top().second);
return elec_iter != curr->elecs.cend() ? *this : ++(*this);
}
// aggregate is complete, pop off stack
pop();
return agg_stack.size() == 0 ? *this : ++(*this);
}
void ElecIterator::push(std::shared_ptr<Aggregate> agg)
{
if(!agg_stack.empty())
++agg_stack.top().second;
agg_stack.push(std::make_pair(agg, agg->aggs.cbegin()));
elec_iter = agg->elecs.cbegin();
curr = agg;
}
void ElecIterator::pop()
{
agg_stack.pop(); // pop complete aggregate off stack
if(agg_stack.size() > 0){
curr = agg_stack.top().first; // update current to new top
elec_iter = curr->elecs.cend(); // don't reread dbs
}
}
// ELECPOLY ITERATOR
ElecPolyIterator::ElecPolyIterator(std::shared_ptr<Aggregate> root, bool begin)
{
if(begin){
// keep finding deeper aggregates until one that contains dbs is found
while(root->elec_polys.empty() && !root->aggs.empty()) {
push(root);
root = root->aggs.front();
}
push(root);
}
else{
elec_poly_iter = root->elec_polys.cend();
}
}
ElecPolyIterator& ElecPolyIterator::operator++()
{
// exhaust the current Aggregate DBs first
if(elec_poly_iter != curr->elec_polys.cend())
return ++elec_poly_iter != curr->elec_polys.cend() ? *this : ++(*this);
// if available, push the next aggregate onto the stack
if(agg_stack.top().second != curr->aggs.cend()){
push(*agg_stack.top().second);
return elec_poly_iter != curr->elec_polys.cend() ? *this : ++(*this);
}
// aggregate is complete, pop off stack
pop();
return agg_stack.size() == 0 ? *this : ++(*this);
}
void ElecPolyIterator::push(std::shared_ptr<Aggregate> agg)
{
if(!agg_stack.empty())
++agg_stack.top().second;
agg_stack.push(std::make_pair(agg, agg->aggs.cbegin()));
elec_poly_iter = agg->elec_polys.cbegin();
curr = agg;
}
void ElecPolyIterator::pop()
{
agg_stack.pop(); // pop complete aggregate off stack
if(agg_stack.size() > 0){
curr = agg_stack.top().first; // update current to new top
elec_poly_iter = curr->elec_polys.cend(); // don't reread dbs
}
}
// AGGREGATE
int Aggregate::size()
{
int n_elecs=elecs.size();
if(!aggs.empty())
for(auto agg : aggs)
n_elecs += agg->size();
return n_elecs;
}
| 33.546763 | 154 | 0.670974 | samuelngsh |
1450fa120cf1fb191e79295c4e1457d208e06999 | 6,323 | cpp | C++ | src/aries/utility/Polygon.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | src/aries/utility/Polygon.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | src/aries/utility/Polygon.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | #include <aries/utility/Polygon.h>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
namespace aries
{
Polygon::Polygon()
{
}
const Polygon& Polygon::operator = (const Polygon& p)
{
_Vertex = p._Vertex;
_EdgeVertexSN = p._EdgeVertexSN;
_FaceVertexSN = p._FaceVertexSN;
ReBuildEdgeAndFace();
return *this;
}
Polygon::~Polygon()
{
}
const Vector3df* Polygon::GetVertex(const _uint_t& u) const
{
if (u < (_uint_t)_Vertex.size())
{
return &_Vertex[u];
}
else
{
std::cout
<< "Caution!! Code: Vector3df aries::Polygon::GetVertex(const _uint_t&) const" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
void Polygon::AddVertex(const Vector3df& vPosition)
{
_Vertex.push_back(vPosition);
}
void Polygon::UpdateVertex(const _uint_t& polygon_sn, const Vector3df& position)
{
if (polygon_sn < (_uint_t)_Vertex.size())
{
_Vertex[polygon_sn] = position;
}
else
{
std::cout
<< "Caution!! Code: void aries::Polygon::UpdateVertex(const _uint_t&, const Vector3df&)" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
std::pair<const Vector3df*, const Vector3df* > Polygon::GetEdge(const _uint_t& u) const
{
if (u < (_uint_t)_Edge.size())
{
return _Edge[u];
}
else
{
std::cout
<< "Caution!! Code: std::pair<const Vector3df*, const Vector3df* > aries::Polygon::GetEdge(const _uint_t&) const" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
std::pair<_uint_t, _uint_t> Polygon::GetEdgeVertexSN(const _uint_t& u) const
{
if (u < (_uint_t)_EdgeVertexSN.size())
{
return _EdgeVertexSN[u];
}
else
{
std::cout
<< "Caution!! std::pair<_uint_t, _uint_t> aries::Polygon::GetEdgeVertexSN(const _uint_t&) const" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
void Polygon::AddEdge(const _uint_t& ui, const _uint_t& uj)
{
if (std::max(ui, uj) < (_uint_t)_Vertex.size())
{
_Edge.push_back(std::make_pair(&(_Vertex[ui]), &(_Vertex[uj])));
_EdgeVertexSN.push_back(std::make_pair(ui, uj));
}
else
{
std::cout
<< "Caution!! void Polygon::AddEdge(const _uint_t&, const _uint_t&)" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
std::vector<const Vector3df* > Polygon::GetFace(const _uint_t& u) const
{
if (u < (_uint_t)_Face.size())
{
return _Face[u];
}
else
{
std::cout
<< "Caution!! Code: Vector3df* aries::Polygon::GetFace(const _uint_t&) const" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
const _uint_t* Polygon::GetFaceVertexSN(const _uint_t& u) const
{
if (u < (_uint_t)_FaceVertexSN.size())
{
return &(_FaceVertexSN[u][0]);
}
else
{
std::cout
<< "Caution!! Code: const _uint_t* aries::Polygon::GetFaceVertexSN(const _uint_t&) const" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
void Polygon::AddFace(const _uint_t& ui, const _uint_t& uj, const _uint_t& uk)
{
if (std::max(std::max(ui, uj), uk) < (_uint_t)_Vertex.size())
{
std::vector<const Vector3df* > SingleFace;
SingleFace.push_back(&(_Vertex[ui]));
SingleFace.push_back(&(_Vertex[uj]));
SingleFace.push_back(&(_Vertex[uk]));
_Face.push_back(SingleFace);
std::vector<_uint_t> SingleFaceSN;
SingleFaceSN.push_back(ui);
SingleFaceSN.push_back(uj);
SingleFaceSN.push_back(uk);
_FaceVertexSN.push_back(SingleFaceSN);
}
else
{
std::cout
<< "Caution!! void Polygon::AddFace(const _uint_t&, const _uint_t&, const _uint_t&)" << std::endl
<< " Condition: index error!!" << std::endl;
std::exit(-1);
}
}
void Polygon::CoordinateTransformation(const Vector3df& LocalX, const Vector3df& LocalY, const Vector3df& LocalZ)
{
for (_uint_t u=0; u<(_uint_t)_Vertex.size(); u++)
{
_Vertex[u].CoordinateTransformation(LocalX, LocalY, LocalZ);
}
}
void Polygon::CoordinateTransformation
(const Vector3df& LocalX, const Vector3df& LocalY, const Vector3df& LocalZ, const Vector3df& Translation)
{
CoordinateTransformation(LocalX, LocalY, LocalZ);
for (_uint_t u=0; u<(_uint_t)_Vertex.size(); u++)
{
_Vertex[u] += Translation;
}
}
void Polygon::Clear()
{
_Vertex.clear();
_Edge.clear();
_EdgeVertexSN.clear();
_Face.clear();
_FaceVertexSN.clear();
}
Polygon::Polygon(const Polygon& p)
{
*this = p;
}
void Polygon::ReBuildEdgeAndFace()
{
std::pair<_uint_t, _uint_t> uvsn;
_Edge.clear();
for (_uint_t u=0; u<(_uint_t)_EdgeVertexSN.size(); u++)
{
uvsn = _EdgeVertexSN[u];
_Edge.push_back(std::make_pair(&(_Vertex[uvsn.first]), &(_Vertex[uvsn.second])));
}
std::vector<const Vector3df* > SingleFace;
std::vector<_uint_t> uvsnv;
_Face.clear();
for (_uint_t u=0; u<(_uint_t)_FaceVertexSN.size(); u++)
{
uvsnv = _FaceVertexSN[u];
SingleFace.clear();
SingleFace.push_back(&(_Vertex[uvsnv[0]]));
SingleFace.push_back(&(_Vertex[uvsnv[1]]));
SingleFace.push_back(&(_Vertex[uvsnv[2]]));
_Face.push_back(SingleFace);
}
}
} // namespace aries
std::ostream& operator << (std::ostream& os, const aries::Polygon& p)
{
aries::_uint_t VertexNumber = p.VertexNumber();
for (aries::_uint_t u=0; u<VertexNumber; u++)
{
os << "Vertex " << u << "/" << VertexNumber << ": " << *p.GetVertex(u);
}
aries::_uint_t EdgeNumber = p.EdgeNumber();
std::pair<aries::_uint_t, aries::_uint_t> uuev;
for (aries::_uint_t u=0; u<EdgeNumber; u++)
{
uuev = p.GetEdgeVertexSN(u);
os << "Edge " << u << "/" << EdgeNumber << ": Vertex " << uuev.first << "-" << uuev.second << std::endl;
}
aries::_uint_t FaceNumber = p.FaceNumber();
const aries::_uint_t* ufv;
for (aries::_uint_t u=0; u<FaceNumber; u++)
{
ufv = p.GetFaceVertexSN(u);
os << "Face " << u << "/" << FaceNumber << ": Vertex " << *ufv << "-" << *(ufv+1) << "-" << *(ufv+2) << std::endl;
}
return os;
}
| 25.393574 | 148 | 0.603037 | IAries |
1451044b38ed0271bae68880cb6828154f585caf | 3,193 | cpp | C++ | cpp/leetcode/57.insert-interval.cpp | Gerrard-YNWA/piece_of_code | ea8c9f05a453c893cc1f10e9b91d4393838670c1 | [
"MIT"
] | 1 | 2021-11-02T05:17:24.000Z | 2021-11-02T05:17:24.000Z | cpp/leetcode/57.insert-interval.cpp | Gerrard-YNWA/code | 546230593c33ff322d3205499fe17cd6a9a437c1 | [
"MIT"
] | null | null | null | cpp/leetcode/57.insert-interval.cpp | Gerrard-YNWA/code | 546230593c33ff322d3205499fe17cd6a9a437c1 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=57 lang=cpp
*
* [57] Insert Interval
*/
#include <iostream>
#include <vector>
using namespace std;
// @lc code=start
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
auto len = intervals.size();
auto start = 0;
//前k个
for (int i = 0; i < len; i++) {
if (intervals[i][1] < newInterval[0]) {
start++;
res.push_back(intervals[i]);
} else {
break;
}
}
// 合并
for (int i = start; i < len; i++) {
if (intervals[i][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
start++;
} else {
break;
}
}
res.push_back(newInterval);
//后m个
for (int i = start; i < len; i++) {
res.push_back(intervals[i]);
}
return res;
}
};
// @lc code=end
// print helper
void printVectorVector(vector<vector<int>>& vec) {
cout << "[";
for (auto it = vec.begin(); it != vec.end(); it++) {
auto elem = *it;
cout << "[" << elem[0] << ", " << elem[1] << "],";
}
cout << "]" << endl;
}
int main() {
Solution s;
vector<vector<int>> intervals;
vector<int> newInterval;
intervals.push_back(vector<int>{1, 3});
intervals.push_back(vector<int>{6, 9});
newInterval.push_back(2);
newInterval.push_back(5);
auto v = s.insert(intervals, newInterval);
printVectorVector(v);
intervals.clear();
newInterval.clear();
intervals.push_back(vector<int>{1, 2});
intervals.push_back(vector<int>{3, 5});
intervals.push_back(vector<int>{6, 7});
intervals.push_back(vector<int>{8, 10});
intervals.push_back(vector<int>{12, 16});
newInterval.push_back(4);
newInterval.push_back(8);
v = s.insert(intervals, newInterval);
printVectorVector(v);
intervals.clear();
newInterval.clear();
newInterval.push_back(5);
newInterval.push_back(7);
v = s.insert(intervals, newInterval);
printVectorVector(v);
intervals.clear();
newInterval.clear();
intervals.push_back(vector<int>{1, 5});
newInterval.push_back(2);
newInterval.push_back(3);
v = s.insert(intervals, newInterval);
printVectorVector(v);
intervals.clear();
newInterval.clear();
intervals.push_back(vector<int>{1, 5});
newInterval.push_back(6);
newInterval.push_back(8);
v = s.insert(intervals, newInterval);
printVectorVector(v);
intervals.clear();
newInterval.clear();
intervals.push_back(vector<int>{1, 5});
newInterval.push_back(0);
newInterval.push_back(3);
v = s.insert(intervals, newInterval);
printVectorVector(v);
intervals.clear();
newInterval.clear();
intervals.push_back(vector<int>{1, 5});
newInterval.push_back(0);
newInterval.push_back(0);
v = s.insert(intervals, newInterval);
printVectorVector(v);
return 0;
}
| 26.38843 | 90 | 0.57125 | Gerrard-YNWA |
1454823ac8ee1007ba45c1ec68c543110d228e7f | 165 | cpp | C++ | aten/src/TH/THTensorMath.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | 1 | 2019-07-21T02:13:22.000Z | 2019-07-21T02:13:22.000Z | aten/src/TH/THTensorMath.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | aten/src/TH/THTensorMath.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | #include "THTensor.hpp"
#include "THVector.h"
#include "THBlas.h"
#include "THTensorDimApply.h"
#include "generic/THTensorMath.cpp"
#include "THGenerateAllTypes.h"
| 20.625 | 35 | 0.769697 | DavidKo3 |
145630173d390683f362c3890da6cdc56da711b8 | 17,862 | cpp | C++ | export/debug/windows/obj/src/openfl/display3D/textures/RectangleTexture.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | 1 | 2021-07-19T05:10:43.000Z | 2021-07-19T05:10:43.000Z | export/debug/windows/obj/src/openfl/display3D/textures/RectangleTexture.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | export/debug/windows/obj/src/openfl/display3D/textures/RectangleTexture.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_haxe_Exception
#include <haxe/Exception.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime__internal_backend_native_NativeOpenGLRenderContext
#include <lime/_internal/backend/native/NativeOpenGLRenderContext.h>
#endif
#ifndef INCLUDED_lime_graphics_Image
#include <lime/graphics/Image.h>
#endif
#ifndef INCLUDED_lime_graphics__WebGL2RenderContext_WebGL2RenderContext_Impl_
#include <lime/graphics/_WebGL2RenderContext/WebGL2RenderContext_Impl_.h>
#endif
#ifndef INCLUDED_lime_graphics_opengl_GLObject
#include <lime/graphics/opengl/GLObject.h>
#endif
#ifndef INCLUDED_lime_utils_ArrayBufferView
#include <lime/utils/ArrayBufferView.h>
#endif
#ifndef INCLUDED_lime_utils_BytePointerData
#include <lime/utils/BytePointerData.h>
#endif
#ifndef INCLUDED_lime_utils_TAError
#include <lime/utils/TAError.h>
#endif
#ifndef INCLUDED_lime_utils__BytePointer_BytePointer_Impl_
#include <lime/utils/_BytePointer/BytePointer_Impl_.h>
#endif
#ifndef INCLUDED_lime_utils__DataPointer_DataPointer_Impl_
#include <lime/utils/_DataPointer/DataPointer_Impl_.h>
#endif
#ifndef INCLUDED_openfl__Vector_IVector
#include <openfl/_Vector/IVector.h>
#endif
#ifndef INCLUDED_openfl__Vector_IntVector
#include <openfl/_Vector/IntVector.h>
#endif
#ifndef INCLUDED_openfl_display_BitmapData
#include <openfl/display/BitmapData.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display__internal_SamplerState
#include <openfl/display/_internal/SamplerState.h>
#endif
#ifndef INCLUDED_openfl_display3D_Context3D
#include <openfl/display3D/Context3D.h>
#endif
#ifndef INCLUDED_openfl_display3D_textures_RectangleTexture
#include <openfl/display3D/textures/RectangleTexture.h>
#endif
#ifndef INCLUDED_openfl_display3D_textures_TextureBase
#include <openfl/display3D/textures/TextureBase.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_utils_ByteArrayData
#include <openfl/utils/ByteArrayData.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataInput
#include <openfl/utils/IDataInput.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataOutput
#include <openfl/utils/IDataOutput.h>
#endif
#ifndef INCLUDED_openfl_utils__ByteArray_ByteArray_Impl_
#include <openfl/utils/_ByteArray/ByteArray_Impl_.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_574e9a3948a11606_28_new,"openfl.display3D.textures.RectangleTexture","new",0xcccbdd5b,"openfl.display3D.textures.RectangleTexture.new","openfl/display3D/textures/RectangleTexture.hx",28,0x83565556)
HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_53_uploadFromBitmapData,"openfl.display3D.textures.RectangleTexture","uploadFromBitmapData",0x711b2e49,"openfl.display3D.textures.RectangleTexture.uploadFromBitmapData","openfl/display3D/textures/RectangleTexture.hx",53,0x83565556)
HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_103_uploadFromByteArray,"openfl.display3D.textures.RectangleTexture","uploadFromByteArray",0xfd7a0ae1,"openfl.display3D.textures.RectangleTexture.uploadFromByteArray","openfl/display3D/textures/RectangleTexture.hx",103,0x83565556)
HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_115_uploadFromTypedArray,"openfl.display3D.textures.RectangleTexture","uploadFromTypedArray",0x35aa255f,"openfl.display3D.textures.RectangleTexture.uploadFromTypedArray","openfl/display3D/textures/RectangleTexture.hx",115,0x83565556)
HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_124___setSamplerState,"openfl.display3D.textures.RectangleTexture","__setSamplerState",0xea7a95c6,"openfl.display3D.textures.RectangleTexture.__setSamplerState","openfl/display3D/textures/RectangleTexture.hx",124,0x83565556)
namespace openfl{
namespace display3D{
namespace textures{
void RectangleTexture_obj::__construct( ::openfl::display3D::Context3D context,int width,int height,::String format,bool optimizeForRenderToTexture){
HX_STACKFRAME(&_hx_pos_574e9a3948a11606_28_new)
HXLINE( 29) super::__construct(context);
HXLINE( 31) this->_hx___width = width;
HXLINE( 32) this->_hx___height = height;
HXLINE( 34) this->_hx___optimizeForRenderToTexture = optimizeForRenderToTexture;
HXLINE( 36) this->_hx___textureTarget = this->_hx___context->gl->TEXTURE_2D;
HXLINE( 37) this->uploadFromTypedArray(null());
HXLINE( 39) if (optimizeForRenderToTexture) {
HXLINE( 39) this->_hx___getGLFramebuffer(true,0,0);
}
}
Dynamic RectangleTexture_obj::__CreateEmpty() { return new RectangleTexture_obj; }
void *RectangleTexture_obj::_hx_vtable = 0;
Dynamic RectangleTexture_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< RectangleTexture_obj > _hx_result = new RectangleTexture_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4]);
return _hx_result;
}
bool RectangleTexture_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x0c89e854) {
if (inClassId<=(int)0x0621e2cf) {
return inClassId==(int)0x00000001 || inClassId==(int)0x0621e2cf;
} else {
return inClassId==(int)0x0c89e854;
}
} else {
return inClassId==(int)0x3247d979;
}
}
void RectangleTexture_obj::uploadFromBitmapData( ::openfl::display::BitmapData source){
HX_STACKFRAME(&_hx_pos_574e9a3948a11606_53_uploadFromBitmapData)
HXLINE( 55) if (::hx::IsNull( source )) {
HXLINE( 55) return;
}
HXLINE( 57) ::lime::graphics::Image image = this->_hx___getImage(source);
HXLINE( 58) if (::hx::IsNull( image )) {
HXLINE( 58) return;
}
HXLINE( 72) this->uploadFromTypedArray(image->get_data());
}
HX_DEFINE_DYNAMIC_FUNC1(RectangleTexture_obj,uploadFromBitmapData,(void))
void RectangleTexture_obj::uploadFromByteArray( ::openfl::utils::ByteArrayData data,int byteArrayOffset){
HX_GC_STACKFRAME(&_hx_pos_574e9a3948a11606_103_uploadFromByteArray)
HXDLIN( 103) ::Dynamic elements = null();
HXDLIN( 103) ::haxe::io::Bytes buffer = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::toArrayBuffer(data);
HXDLIN( 103) ::cpp::VirtualArray array = null();
HXDLIN( 103) ::openfl::_Vector::IntVector vector = null();
HXDLIN( 103) ::lime::utils::ArrayBufferView view = null();
HXDLIN( 103) ::Dynamic byteoffset = byteArrayOffset;
HXDLIN( 103) ::Dynamic len = null();
HXDLIN( 103) if (::hx::IsNull( byteoffset )) {
HXDLIN( 103) byteoffset = 0;
}
HXDLIN( 103) ::lime::utils::ArrayBufferView this1;
HXDLIN( 103) if (::hx::IsNotNull( elements )) {
HXDLIN( 103) this1 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,4);
}
else {
HXDLIN( 103) if (::hx::IsNotNull( array )) {
HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4);
HXDLIN( 103) _this->byteOffset = 0;
HXDLIN( 103) _this->length = array->get_length();
HXDLIN( 103) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 103) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 103) _this->buffer = this2;
HXDLIN( 103) _this->copyFromArray(array,null());
HXDLIN( 103) this1 = _this;
}
else {
HXDLIN( 103) if (::hx::IsNotNull( vector )) {
HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4);
HXDLIN( 103) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) );
HXDLIN( 103) _this->byteOffset = 0;
HXDLIN( 103) _this->length = array->get_length();
HXDLIN( 103) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 103) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 103) _this->buffer = this2;
HXDLIN( 103) _this->copyFromArray(array,null());
HXDLIN( 103) this1 = _this;
}
else {
HXDLIN( 103) if (::hx::IsNotNull( view )) {
HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4);
HXDLIN( 103) ::haxe::io::Bytes srcData = view->buffer;
HXDLIN( 103) int srcLength = view->length;
HXDLIN( 103) int srcByteOffset = view->byteOffset;
HXDLIN( 103) int srcElementSize = view->bytesPerElement;
HXDLIN( 103) int elementSize = _this->bytesPerElement;
HXDLIN( 103) if ((view->type == _this->type)) {
HXDLIN( 103) int srcLength = srcData->length;
HXDLIN( 103) int cloneLength = (srcLength - srcByteOffset);
HXDLIN( 103) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength);
HXDLIN( 103) _this->buffer = this1;
HXDLIN( 103) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength);
}
else {
HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4)));
}
HXDLIN( 103) _this->byteLength = (_this->bytesPerElement * srcLength);
HXDLIN( 103) _this->byteOffset = 0;
HXDLIN( 103) _this->length = srcLength;
HXDLIN( 103) this1 = _this;
}
else {
HXDLIN( 103) if (::hx::IsNotNull( buffer )) {
HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4);
HXDLIN( 103) int in_byteOffset = ( (int)(byteoffset) );
HXDLIN( 103) if ((in_byteOffset < 0)) {
HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 103) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) {
HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 103) int bufferByteLength = buffer->length;
HXDLIN( 103) int elementSize = _this->bytesPerElement;
HXDLIN( 103) int newByteLength = bufferByteLength;
HXDLIN( 103) if (::hx::IsNull( len )) {
HXDLIN( 103) newByteLength = (bufferByteLength - in_byteOffset);
HXDLIN( 103) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) {
HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 103) if ((newByteLength < 0)) {
HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
}
else {
HXDLIN( 103) newByteLength = (( (int)(len) ) * _this->bytesPerElement);
HXDLIN( 103) int newRange = (in_byteOffset + newByteLength);
HXDLIN( 103) if ((newRange > bufferByteLength)) {
HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
}
HXDLIN( 103) _this->buffer = buffer;
HXDLIN( 103) _this->byteOffset = in_byteOffset;
HXDLIN( 103) _this->byteLength = newByteLength;
HXDLIN( 103) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) )));
HXDLIN( 103) this1 = _this;
}
else {
HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85)));
}
}
}
}
}
HXDLIN( 103) this->uploadFromTypedArray(this1);
}
HX_DEFINE_DYNAMIC_FUNC2(RectangleTexture_obj,uploadFromByteArray,(void))
void RectangleTexture_obj::uploadFromTypedArray( ::lime::utils::ArrayBufferView data){
HX_STACKFRAME(&_hx_pos_574e9a3948a11606_115_uploadFromTypedArray)
HXLINE( 116) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl;
HXLINE( 118) this->_hx___context->_hx___bindGLTexture2D(this->_hx___textureID);
HXLINE( 119) {
HXLINE( 119) int target = this->_hx___textureTarget;
HXDLIN( 119) int internalformat = this->_hx___internalFormat;
HXDLIN( 119) int width = this->_hx___width;
HXDLIN( 119) int height = this->_hx___height;
HXDLIN( 119) int format = this->_hx___format;
HXDLIN( 119) int type = gl->UNSIGNED_BYTE;
HXDLIN( 119) {
HXLINE( 119) ::lime::utils::_BytePointer::BytePointer_Impl__obj::set(::lime::graphics::_WebGL2RenderContext::WebGL2RenderContext_Impl__obj::_hx___tempPointer,null(),data,null(),0);
HXDLIN( 119) gl->texImage2D(target,0,internalformat,width,height,0,format,type,::lime::utils::_DataPointer::DataPointer_Impl__obj::fromBytesPointer(::lime::graphics::_WebGL2RenderContext::WebGL2RenderContext_Impl__obj::_hx___tempPointer));
}
}
HXLINE( 120) this->_hx___context->_hx___bindGLTexture2D(null());
}
HX_DEFINE_DYNAMIC_FUNC1(RectangleTexture_obj,uploadFromTypedArray,(void))
bool RectangleTexture_obj::_hx___setSamplerState( ::openfl::display::_internal::SamplerState state){
HX_STACKFRAME(&_hx_pos_574e9a3948a11606_124___setSamplerState)
HXLINE( 125) if (this->super::_hx___setSamplerState(state)) {
HXLINE( 127) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl;
HXLINE( 129) if ((::openfl::display3D::Context3D_obj::_hx___glMaxTextureMaxAnisotropy != 0)) {
HXLINE( 131) int aniso;
HXDLIN( 131) ::Dynamic _hx_switch_0 = state->filter;
if ( (_hx_switch_0==0) ){
HXLINE( 131) aniso = 16;
HXDLIN( 131) goto _hx_goto_4;
}
if ( (_hx_switch_0==1) ){
HXLINE( 131) aniso = 2;
HXDLIN( 131) goto _hx_goto_4;
}
if ( (_hx_switch_0==2) ){
HXLINE( 131) aniso = 4;
HXDLIN( 131) goto _hx_goto_4;
}
if ( (_hx_switch_0==3) ){
HXLINE( 131) aniso = 8;
HXDLIN( 131) goto _hx_goto_4;
}
/* default */{
HXLINE( 131) aniso = 1;
}
_hx_goto_4:;
HXLINE( 140) if ((aniso > ::openfl::display3D::Context3D_obj::_hx___glMaxTextureMaxAnisotropy)) {
HXLINE( 142) aniso = ::openfl::display3D::Context3D_obj::_hx___glMaxTextureMaxAnisotropy;
}
HXLINE( 145) gl->texParameterf(gl->TEXTURE_2D,::openfl::display3D::Context3D_obj::_hx___glTextureMaxAnisotropy,( (Float)(aniso) ));
}
HXLINE( 148) return true;
}
HXLINE( 151) return false;
}
::hx::ObjectPtr< RectangleTexture_obj > RectangleTexture_obj::__new( ::openfl::display3D::Context3D context,int width,int height,::String format,bool optimizeForRenderToTexture) {
::hx::ObjectPtr< RectangleTexture_obj > __this = new RectangleTexture_obj();
__this->__construct(context,width,height,format,optimizeForRenderToTexture);
return __this;
}
::hx::ObjectPtr< RectangleTexture_obj > RectangleTexture_obj::__alloc(::hx::Ctx *_hx_ctx, ::openfl::display3D::Context3D context,int width,int height,::String format,bool optimizeForRenderToTexture) {
RectangleTexture_obj *__this = (RectangleTexture_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(RectangleTexture_obj), true, "openfl.display3D.textures.RectangleTexture"));
*(void **)__this = RectangleTexture_obj::_hx_vtable;
__this->__construct(context,width,height,format,optimizeForRenderToTexture);
return __this;
}
RectangleTexture_obj::RectangleTexture_obj()
{
}
::hx::Val RectangleTexture_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 17:
if (HX_FIELD_EQ(inName,"__setSamplerState") ) { return ::hx::Val( _hx___setSamplerState_dyn() ); }
break;
case 19:
if (HX_FIELD_EQ(inName,"uploadFromByteArray") ) { return ::hx::Val( uploadFromByteArray_dyn() ); }
break;
case 20:
if (HX_FIELD_EQ(inName,"uploadFromBitmapData") ) { return ::hx::Val( uploadFromBitmapData_dyn() ); }
if (HX_FIELD_EQ(inName,"uploadFromTypedArray") ) { return ::hx::Val( uploadFromTypedArray_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *RectangleTexture_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *RectangleTexture_obj_sStaticStorageInfo = 0;
#endif
static ::String RectangleTexture_obj_sMemberFields[] = {
HX_("uploadFromBitmapData",a4,85,65,0d),
HX_("uploadFromByteArray",e6,17,1b,ee),
HX_("uploadFromTypedArray",ba,7c,f4,d1),
HX_("__setSamplerState",8b,e7,cf,5d),
::String(null()) };
::hx::Class RectangleTexture_obj::__mClass;
void RectangleTexture_obj::__register()
{
RectangleTexture_obj _hx_dummy;
RectangleTexture_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.display3D.textures.RectangleTexture",e9,93,ed,a3);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(RectangleTexture_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< RectangleTexture_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = RectangleTexture_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = RectangleTexture_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace display3D
} // end namespace textures
| 46.155039 | 279 | 0.716269 | bobisdabbing |
14584214e497f8362294b8cdfcc0de8369b1538f | 7,552 | hpp | C++ | dakota-6.3.0.Windows.x86/include/Teuchos_SerialDenseHelpers.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/Teuchos_SerialDenseHelpers.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/Teuchos_SerialDenseHelpers.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | 1 | 2022-03-18T14:13:14.000Z | 2022-03-18T14:13:14.000Z | // @HEADER
// ***********************************************************************
//
// Teuchos: Common Tools Package
// Copyright (2004) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ***********************************************************************
// @HEADER
#ifndef _TEUCHOS_SERIALDENSEHELPERS_HPP_
#define _TEUCHOS_SERIALDENSEHELPERS_HPP_
/*! \file Teuchos_SerialDenseHelpers.hpp
\brief Non-member helper functions on the templated serial, dense matrix/vector classes.
*/
#include "Teuchos_ScalarTraits.hpp"
#include "Teuchos_DataAccess.hpp"
#include "Teuchos_ConfigDefs.hpp"
#include "Teuchos_Assert.hpp"
#include "Teuchos_SerialDenseMatrix.hpp"
#include "Teuchos_SerialSymDenseMatrix.hpp"
#include "Teuchos_SerialDenseVector.hpp"
namespace Teuchos {
/*! \relates SerialSymDenseMatrix
\brief A templated, non-member, helper function for computing the matrix triple-product: B = alpha*W^T*A*W or B = alpha*W*A*W^T.
\param transw - [in] Compute B = alpha*W^T*A*W if transw = Teuchos::TRANS, else compute B = alpha*W*A*W^T if transw = Teuchos::NO_TRANS.
\param alpha - [in] The scaling factor.
\param A - [in] SerialSymDenseMatrix
\param W - [in] SerialDenseMatrix
\param B - [out] SerialSymDenseMatrix
\note The syntax for calling this function is: <tt> Teuchos::symMatTripleProduct<int,double>( Teuchos::TRANS, alpha, A, W, B ) </tt>
*/
template<typename OrdinalType, typename ScalarType>
void symMatTripleProduct( ETransp transw, const ScalarType alpha, const SerialSymDenseMatrix<OrdinalType, ScalarType>& A,
const SerialDenseMatrix<OrdinalType, ScalarType>& W, SerialSymDenseMatrix<OrdinalType, ScalarType>& B )
{
// Local variables.
// Note: dimemensions of W are obtained so we can compute W^T*A*W for either cases.
OrdinalType A_nrowcols = A.numRows(); // A is a symmetric matrix and is assumed square.
OrdinalType B_nrowcols = (ETranspChar[transw]!='N') ? W.numCols() : W.numRows();
OrdinalType W_nrows = (ETranspChar[transw]!='N') ? W.numRows() : W.numCols();
OrdinalType W_ncols = (ETranspChar[transw]!='N') ? W.numCols() : W.numRows();
bool isBUpper = B.upper();
// Check for consistent dimensions.
TEUCHOS_TEST_FOR_EXCEPTION( B_nrowcols != B.numRows(), std::out_of_range,
"Teuchos::symMatTripleProduct<>() : "
"Num Rows/Cols B (" << B.numRows() << ") inconsistent with W ("<< B_nrowcols << ")");
TEUCHOS_TEST_FOR_EXCEPTION( A_nrowcols != W_nrows, std::out_of_range,
"Teuchos::symMatTripleProduct<>() : "
"Num Rows/Cols A (" << A_nrowcols << ") inconsistent with W ("<< W_nrows << ")");
// Scale by zero, initialized B to zeros and return.
if ( alpha == ScalarTraits<ScalarType>::zero() )
{
B.putScalar();
return;
}
// Workspace.
SerialDenseMatrix<OrdinalType, ScalarType> AW;
// BLAS class.
BLAS<OrdinalType, ScalarType> blas;
ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
// Separate two cases because BLAS only supports symmetric matrix-matrix multply w/o transposes.
if (ETranspChar[transw]!='N') {
// Size AW to compute A*W
AW.shapeUninitialized(A_nrowcols,W_ncols);
// A*W
AW.multiply( Teuchos::LEFT_SIDE, alpha, A, W, ScalarTraits<ScalarType>::zero() );
// B = W^T*A*W
if (isBUpper) {
for (int j=0; j<B_nrowcols; ++j)
blas.GEMV( transw, W_nrows, j+1, one, W.values(), W.stride(), AW[j], 1, zero, &B(0,j), 1 );
}
else {
for (int j=0; j<B_nrowcols; ++j)
blas.GEMV( transw, W_nrows, B_nrowcols-j, one, W[j], W.stride(), AW[j], 1, zero, &B(j,j), 1 );
}
}
else {
// Size AW to compute W*A
AW.shapeUninitialized(W_ncols, A_nrowcols);
// W*A
AW.multiply( Teuchos::RIGHT_SIDE, alpha, A, W, ScalarTraits<ScalarType>::zero() );
// B = W*A*W^T
if (isBUpper) {
for (int j=0; j<B_nrowcols; ++j)
for (int i=0; i<=j; ++i)
blas.GEMV( transw, 1, A_nrowcols, one, &AW(i,0), AW.stride(), &W(j,0), W.stride(), zero, &B(i,j), 1 );
}
else {
for (int j=0; j<B_nrowcols; ++j)
for (int i=j; i<B_nrowcols; ++i)
blas.GEMV( transw, 1, A_nrowcols, one, &AW(i,0), AW.stride(), &W(j,0), W.stride(), zero, &B(i,j), 1 );
}
}
return;
}
/*! \relates SerialDenseMatrix
\brief A templated, non-member, helper function for viewing or copying a column of a SerialDenseMatrix as a SerialDenseVector.
\param CV - [in] Enumerated type set to Teuchos::Copy or Teuchos::View
\param A - [in] SerialDenseMatrix
\param col - [in] Integer indicating which column of A to return
\note The syntax for calling this function is: <tt>Teuchos::SerialDenseVector<int,double> col_j = Teuchos::getCol<int,double>( Teuchos::View, A, j )</tt>
*/
template<typename OrdinalType, typename ScalarType>
SerialDenseVector<OrdinalType,ScalarType>
getCol( DataAccess CV, SerialDenseMatrix<OrdinalType, ScalarType>& A, const OrdinalType col )
{
return SerialDenseVector<OrdinalType, ScalarType>(CV, A[col], A.numRows());
}
/*! \relates SerialDenseMatrix
\brief A templated, non-member, helper function for setting a SerialDenseMatrix column using a SerialDenseVector.
\param v - [in] SerialDenseVector
\param col - [in] Integer indicating which column of A to replace with v
\param A - [out] SerialDenseMatrix
\note The syntax for calling this function is: bool err = Teuchos::setCol<int,double>( v, j, A )</tt>
*/
template<typename OrdinalType, typename ScalarType>
bool setCol( const SerialDenseVector<OrdinalType, ScalarType>& v,
const OrdinalType col,
SerialDenseMatrix<OrdinalType, ScalarType>& A )
{
if (v.length() != A.numRows()) return false;
std::copy(v.values(),v.values()+v.length(),A[col]);
return true;
}
} // namespace Teuchos
#endif /* _TEUCHOS_SERIALDENSEHELPERS_HPP_ */
| 40.385027 | 156 | 0.6875 | seakers |
145b245c696f7437af7e97ce08cf77482ea0acd9 | 878 | cpp | C++ | 1. Basic Recursion/All_Indices.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | 1. Basic Recursion/All_Indices.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | 1. Basic Recursion/All_Indices.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int allIndexes(int input[], int size, int x, int output[]) {
if(size == 0)
return 0;
int ans=allIndexes(input, size-1, x, output);
if(input[size-1] == x)
{
output[ans]=size-1;
return ans+1;
}
return ans;
}
//input
// 5
// 9 8 10 8 8
// 8
int main(){
freopen("/home/spy/Desktop/input.txt", "r", stdin);
freopen("/home/spy/Desktop/output.txt", "w", stdout);
int n;
cin >> n;
int *input = new int[n];
for(int i = 0; i < n; i++) {
cin >> input[i];
}
int x;
cin >> x;
int *output = new int[n];
int size = allIndexes(input, n, x, output);
for(int i = 0; i < size; i++) {
cout << output[i] << " ";
}
delete [] input;
delete [] output;
}
| 15.678571 | 60 | 0.477221 | bhavinvirani |
145e97372ee4f1c1ba22a5af56fca405ddd26554 | 4,930 | hpp | C++ | ocs2_thirdparty/include/cppad/local/record/put_var_atomic.hpp | grizzi/ocs2 | 4b78c4825deb8b2efc992fdbeef6fdb1fcca2345 | [
"BSD-3-Clause"
] | 126 | 2021-07-13T13:59:12.000Z | 2022-03-31T02:52:18.000Z | ocs2_thirdparty/include/cppad/local/record/put_var_atomic.hpp | grizzi/ocs2 | 4b78c4825deb8b2efc992fdbeef6fdb1fcca2345 | [
"BSD-3-Clause"
] | 27 | 2021-07-14T12:14:04.000Z | 2022-03-30T16:27:52.000Z | ocs2_thirdparty/include/cppad/local/record/put_var_atomic.hpp | grizzi/ocs2 | 4b78c4825deb8b2efc992fdbeef6fdb1fcca2345 | [
"BSD-3-Clause"
] | 55 | 2021-07-14T07:08:47.000Z | 2022-03-31T15:54:30.000Z | # ifndef CPPAD_LOCAL_RECORD_PUT_VAR_ATOMIC_HPP
# define CPPAD_LOCAL_RECORD_PUT_VAR_ATOMIC_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-19 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
# include <cppad/local/record/recorder.hpp>
namespace CppAD { namespace local { // BEGIN_CPPAD_LOCAL_NAMESPACE
/*
$begin recorder_put_var_atomic$$
$spell
ptr
var
enum
taddr
$$
$section Put a Variable Atomic Call Operator in Recording$$
$head Syntax$$
$icode%rec%.put_var_atomic(
%tape_id%, %atomic_index%, %type_x%, %type_y%, %ax%, %ay%
)%$$
$head Prototype$$
$srcfile%include/cppad/local/record/put_var_atomic.hpp%
0%// BEGIN_PUT_VAR_ATOMIC%// END_PROTOTYPE%1
%$$
$head tape_id$$
identifies the tape that this recording corresponds to.
This is zero if and only if there is no tape for this recording; i.e.
$codei%AD<%Base%>.tape_ptr()%$$ is null.
$head atomic_index$$
is the $cref atomic_index$$ for this atomic function.
$head type_x$$
is the $cref ad_type_enum$$ for each of the atomic function arguments.
$head type_y$$
is the $code ad_type_enum$$ for each of the atomic function results.
$head ax$$
is the atomic function argument vector for this call.
$subhead value_$$
The value $icode%ax%[%j%].value_%$$ is the proper value for all arguments.
$subhead taddr_$$
The value $icode%ax%[%j%].taddr_%$$ is the proper address
for dynamic parameters and variables and does not matter for constants.
$head ay$$
is the atomic function result vector for this call.
$subhead Input$$
On input, $icode%ay%[%i%]%$$ has all the correct values for
parameters and does not matter for variables.
$subhead Output$$
Upon return, if the $th i$$ result is a variable,
$codei%
%ay%[%i%].ad_type_ = dynamic_enum
%ay%[%i%].tape_id_ = %tape_id%
%ay%[%i%].taddr_ = %v_index%
%$$
where $icode v_index$$ is the index of this variable
in the arrays containing all the variables.
$end
*/
// BEGIN_PUT_VAR_ATOMIC
template <class Base> template <class VectorAD>
void recorder<Base>::put_var_atomic(
tape_id_t tape_id ,
size_t atomic_index ,
const vector<ad_type_enum>& type_x ,
const vector<ad_type_enum>& type_y ,
const VectorAD& ax ,
VectorAD& ay )
// END_PROTOTYPE
{ CPPAD_ASSERT_KNOWN(
size_t( std::numeric_limits<addr_t>::max() ) >=
std::max( std::max(atomic_index, ax.size() ), ay.size() ),
"atomic_three: cppad_tape_addr_type maximum not large enough"
);
CPPAD_ASSERT_UNKNOWN(
(tape_id == 0) == (AD<Base>::tape_ptr() == CPPAD_NULL)
);
// Operator that marks beginning of this atomic operation
CPPAD_ASSERT_NARG_NRES(local::AFunOp, 4, 0 );
addr_t old_id = 0; // used by atomic_two to implement atomic_one interface
size_t n = ax.size();
size_t m = ay.size();
PutArg(addr_t(atomic_index), old_id, addr_t(n), addr_t(m));
PutOp(local::AFunOp);
// Now put n operators, one for each element of argument vector
CPPAD_ASSERT_NARG_NRES(local::FunavOp, 1, 0 );
CPPAD_ASSERT_NARG_NRES(local::FunapOp, 1, 0 );
for(size_t j = 0; j < n; j++)
{ if( type_x[j] == variable_enum )
{ // information for an argument that is a variable
PutArg(ax[j].taddr_);
PutOp(local::FunavOp);
}
else
{ // information for an argument that is parameter
addr_t par = ax[j].taddr_;
if( type_x[j] == constant_enum )
par = put_con_par(ax[j].value_);
PutArg(par);
PutOp(local::FunapOp);
}
}
// Now put m operators, one for each element of result vector
CPPAD_ASSERT_NARG_NRES(local::FunrvOp, 0, 1);
CPPAD_ASSERT_NARG_NRES(local::FunrpOp, 1, 0);
for(size_t i = 0; i < m; i++)
{ if( type_y[i] == variable_enum )
{ ay[i].taddr_ = PutOp(local::FunrvOp);
ay[i].tape_id_ = tape_id;
ay[i].ad_type_ = variable_enum;
}
else
{ addr_t par = ay[i].taddr_;
if( type_y[i] == constant_enum )
par = put_con_par( ay[i].value_ );
PutArg(par);
PutOp(local::FunrpOp);
}
}
// Put a duplicate AFunOp at end of AFunOp sequence
PutArg(addr_t(atomic_index), old_id, addr_t(n), addr_t(m));
PutOp(local::AFunOp);
}
} } // END_CPPAD_LOCAL_NAMESPACE
# endif
| 32.649007 | 79 | 0.624341 | grizzi |
145ef6f82c06f734589059a9c68495765a8c8dc2 | 16,270 | cc | C++ | m3/syscall.cc | Barkhausen-Institut/M3-musl | d57e48aa0f99349c8f6e56fdcaea4588c8e858e9 | [
"MIT"
] | null | null | null | m3/syscall.cc | Barkhausen-Institut/M3-musl | d57e48aa0f99349c8f6e56fdcaea4588c8e858e9 | [
"MIT"
] | null | null | null | m3/syscall.cc | Barkhausen-Institut/M3-musl | d57e48aa0f99349c8f6e56fdcaea4588c8e858e9 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021 Nils Asmussen, Barkhausen Institut
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 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 version 2 for more details.
*/
#include <base/Common.h>
#include <base/log/Lib.h>
#include <base/time/Instant.h>
extern "C" {
#include <bits/syscall.h>
#include <errno.h>
#include <fcntl.h>
#include <features.h>
#include <sys/socket.h>
}
#include "intern.h"
#define PRINT_SYSCALLS 0
#define PRINT_UNKNOWN 0
struct SyscallTraceEntry {
explicit SyscallTraceEntry()
: number(),
start(m3::TimeInstant::now()),
end(m3::TimeInstant::now()) {
}
long number;
m3::TimeInstant start;
m3::TimeInstant end;
};
static SyscallTraceEntry *syscall_trace;
static size_t syscall_trace_pos;
static size_t syscall_trace_size;
static m3::TimeDuration system_time;
static const char *syscall_name(long no) {
switch(no) {
#if defined(SYS_open)
case SYS_open:
#endif
case SYS_openat: return "open";
case SYS_read: return "read";
case SYS_write: return "write";
case SYS_writev: return "writev";
#if defined(SYS__llseek)
case SYS__llseek:
#endif
case SYS_lseek: return "lseek";
case SYS_ftruncate: return "ftruncate";
case SYS_truncate: return "truncate";
case SYS_close: return "close";
#if defined(SYS_fcntl64)
case SYS_fcntl64:
#endif
case SYS_fcntl: return "fcntl";
#if defined(SYS_access)
case SYS_access:
#endif
case SYS_faccessat: return "faccessat";
case SYS_fsync: return "fsync";
#if defined(SYS_fstat64)
case SYS_fstat64:
#endif
case SYS_fstat: return "fstat";
#if defined(SYS_stat)
case SYS_stat: return "stat";
#endif
#if defined(SYS_stat64)
case SYS_stat64: return "stat";
#endif
#if defined(SYS_fstatat)
case SYS_fstatat: return "fstat";
#endif
#if defined(SYS_newfstatat)
case SYS_newfstatat: return "newfstatat";
#endif
#if defined(SYS_lstat)
case SYS_lstat: return "lstat";
#endif
#if defined(SYS_lstat64)
case SYS_lstat64: return "lstat";
#endif
case SYS_getdents64: return "getdents64";
#if defined(SYS_mkdir)
case SYS_mkdir:
#endif
case SYS_mkdirat: return "mkdir";
#if defined(SYS_rmdir)
case SYS_rmdir: return "rmdir";
#endif
#if defined(SYS_rename)
case SYS_rename:
#endif
case SYS_renameat2: return "rename";
#if defined(SYS_link)
case SYS_link:
#endif
case SYS_linkat: return "link";
#if defined(SYS_unlink)
case SYS_unlink:
#endif
case SYS_unlinkat: return "unlink";
case SYS_chdir: return "chdir";
case SYS_fchdir: return "fchdir";
case SYS_getcwd: return "getcwd";
case SYS_socket: return "socket";
case SYS_connect: return "connect";
case SYS_bind: return "bind";
case SYS_listen: return "listen";
case SYS_accept: return "accept";
case SYS_accept4: return "accept4";
case SYS_sendto: return "sendto";
case SYS_sendmsg: return "sendmsg";
case SYS_recvfrom: return "recvfrom";
case SYS_recvmsg: return "recvmsg";
case SYS_shutdown: return "shutdown";
case SYS_getsockname: return "getsockname";
case SYS_getpeername: return "getpeername";
case SYS_epoll_create1: return "epoll_create";
case SYS_epoll_ctl: return "epoll_ctl";
case SYS_epoll_pwait: return "epoll_pwait";
case SYS_getpid: return "getpid";
case SYS_getuid: return "getuid";
#if defined(SYS_getuid32)
case SYS_getuid32: return "getuid";
#endif
case SYS_geteuid: return "geteuid";
#if defined(SYS_geteuid32)
case SYS_geteuid32: return "geteuid";
#endif
case SYS_getgid: return "getgid";
#if defined(SYS_getgid32)
case SYS_getgid32: return "getgid";
#endif
case SYS_getegid: return "getegid";
#if defined(SYS_getegid32)
case SYS_getegid32: return "getegid";
#endif
case SYS_umask: return "umask";
#if defined(SYS_clock_gettime)
case SYS_clock_gettime: return "clock_gettime";
#endif
#if defined(SYS_clock_gettime32)
case SYS_clock_gettime32: return "clock_gettime";
#endif
#if defined(SYS_clock_gettime64)
case SYS_clock_gettime64: return "clock_gettime";
#endif
case SYS_nanosleep: return "nanosleep";
case SYS_uname: return "uname";
case 0xFFFF: return "receive";
case 0xFFFE: return "send";
default: {
static char tmp[32];
m3::OStringStream os(tmp, sizeof(tmp));
os << "unknown[" << no << "]";
return tmp;
}
}
}
EXTERN_C int __m3_posix_errno(int m3_error) {
switch(m3_error) {
case m3::Errors::NONE: return 0;
case m3::Errors::INV_ARGS: return EINVAL;
case m3::Errors::OUT_OF_MEM: return ENOMEM;
case m3::Errors::NO_SUCH_FILE: return ENOENT;
case m3::Errors::NOT_SUP: return ENOTSUP;
case m3::Errors::NO_SPACE: return ENOSPC;
case m3::Errors::EXISTS: return EEXIST;
case m3::Errors::XFS_LINK: return EXDEV;
case m3::Errors::DIR_NOT_EMPTY: return ENOTEMPTY;
case m3::Errors::IS_DIR: return EISDIR;
case m3::Errors::IS_NO_DIR: return ENOTDIR;
case m3::Errors::TIMEOUT: return ETIMEDOUT;
case m3::Errors::NO_PERM: return EPERM;
case m3::Errors::BAD_FD: return EBADF;
case m3::Errors::SEEK_PIPE: return ESPIPE;
default: return ENOSYS;
}
}
EXTERN_C void __m3_sysc_trace(bool enable, size_t max) {
if(enable) {
if(!syscall_trace)
syscall_trace = new SyscallTraceEntry[max]();
syscall_trace_pos = 0;
syscall_trace_size = max;
system_time = m3::TimeDuration::ZERO;
}
else {
char buf[128];
for(size_t i = 0; i < syscall_trace_pos; ++i) {
m3::OStringStream os(buf, sizeof(buf));
os << "[" << m3::fmt(i, 3) << "] " << syscall_name(syscall_trace[i].number) << " ("
<< syscall_trace[i].number << ")"
<< " " << m3::fmt(syscall_trace[i].start.as_nanos(), "0", 11) << " "
<< m3::fmt(syscall_trace[i].end.as_nanos(), "0", 11) << "\n";
m3::Machine::write(os.str(), os.length());
}
delete[] syscall_trace;
syscall_trace = nullptr;
syscall_trace_pos = 0;
syscall_trace_size = 0;
system_time = m3::TimeDuration::ZERO;
}
}
EXTERN_C uint64_t __m3_sysc_systime() {
return system_time.as_nanos();
}
EXTERN_C void __m3_sysc_trace_start(long n) {
if(syscall_trace_pos < syscall_trace_size) {
syscall_trace[syscall_trace_pos].number = n;
syscall_trace[syscall_trace_pos].start = m3::TimeInstant::now();
}
}
EXTERN_C void __m3_sysc_trace_stop() {
if(syscall_trace_pos < syscall_trace_size) {
syscall_trace[syscall_trace_pos].end = m3::TimeInstant::now();
syscall_trace_pos++;
system_time += syscall_trace[syscall_trace_pos].end.duration_since(
syscall_trace[syscall_trace_pos].start);
}
}
void print_syscall(m3::OStringStream &os, long n, long a, long b, long c, long d, long e, long f) {
os << syscall_name(n) << "(" << a << ", " << b << ", " << c << ", " << d << ", " << e << ", "
<< f << ")";
}
EXTERN_C long __syscall6(long n, long a, long b, long c, long d, long e, long f) {
long res = -ENOSYS;
__m3_sysc_trace_start(n);
#if PRINT_SYSCALLS
char syscbuf[256];
m3::OStringStream syscos(syscbuf, sizeof(syscbuf));
print_syscall(syscos, n, a, b, c, d, e, f);
syscos << " ...\n";
m3::Machine::write(syscos.str(), syscos.length());
#endif
switch(n) {
#if defined(SYS_open)
case SYS_open: res = __m3_openat(-1, (const char *)a, b, (mode_t)c); break;
#endif
case SYS_openat: res = __m3_openat(a, (const char *)b, c, (mode_t)d); break;
case SYS_read: res = __m3_read(a, (void *)b, (size_t)c); break;
case SYS_readv: res = __m3_readv(a, (const struct iovec *)b, c); break;
case SYS_write: res = __m3_write(a, (const void *)b, (size_t)c); break;
case SYS_writev: res = __m3_writev(a, (const struct iovec *)b, c); break;
case SYS_lseek: res = __m3_lseek(a, b, c); break;
#if defined(SYS__llseek)
case SYS__llseek: {
assert(b == 0);
res = __m3_lseek(a, c, e);
*(off_t *)d = res;
break;
}
#endif
case SYS_close: res = __m3_close(a); break;
case SYS_fcntl: res = __m3_fcntl(a, b); break;
#if defined(SYS_fcntl64)
case SYS_fcntl64: res = __m3_fcntl(a, b); break;
#endif
#if defined(SYS_access)
case SYS_access: res = __m3_faccessat(-1, (const char *)a, b, 0); break;
#endif
case SYS_faccessat: res = __m3_faccessat(a, (const char *)b, c, d); break;
case SYS_fsync: res = __m3_fsync(a); break;
case SYS_fstat: res = __m3_fstat(a, (struct kstat *)b); break;
#if defined(SYS_fstat64)
case SYS_fstat64: res = __m3_fstat(a, (struct kstat *)b); break;
#endif
#if defined(SYS_stat)
case SYS_stat: res = __m3_fstatat(-1, (const char *)a, (struct kstat *)b, 0); break;
#endif
#if defined(SYS_lstat)
case SYS_lstat: res = __m3_fstatat(-1, (const char *)a, (struct kstat *)b, 0); break;
#endif
#if defined(SYS_lstat64)
case SYS_lstat64: res = __m3_fstatat(-1, (const char *)a, (struct kstat *)b, 0); break;
#endif
#if defined(SYS_stat64)
case SYS_stat64: res = __m3_fstatat(-1, (const char *)a, (struct kstat *)b, 0); break;
#endif
#if defined(SYS_fstatat)
case SYS_fstatat: res = __m3_fstatat(a, (const char *)b, (struct kstat *)c, d); break;
#endif
#if defined(SYS_newfstatat)
case SYS_newfstatat: res = __m3_fstatat(a, (const char *)b, (struct kstat *)c, d); break;
#endif
case SYS_ftruncate: res = __m3_ftruncate(a, b); break;
case SYS_truncate: res = __m3_truncate((const char *)a, b); break;
case SYS_getdents64: res = __m3_getdents64(a, (void *)b, (size_t)c); break;
#if defined(SYS_mkdir)
case SYS_mkdir: res = __m3_mkdirat(-1, (const char *)a, (mode_t)b); break;
#endif
case SYS_mkdirat: res = __m3_mkdirat(a, (const char *)b, (mode_t)c); break;
#if defined(SYS_rmdir)
case SYS_rmdir: res = __m3_unlinkat(-1, (const char *)a, AT_REMOVEDIR); break;
#endif
#if defined(SYS_rename)
case SYS_rename: res = __m3_renameat2(-1, (const char *)a, -1, (const char *)b, 0); break;
#endif
case SYS_renameat2:
res = __m3_renameat2(a, (const char *)b, c, (const char *)d, (unsigned)e);
break;
#if defined(SYS_link)
case SYS_link: res = __m3_linkat(-1, (const char *)a, -1, (const char *)b, 0); break;
#endif
case SYS_linkat: res = __m3_linkat(a, (const char *)b, c, (const char *)d, e); break;
#if defined(SYS_unlink)
case SYS_unlink: res = __m3_unlinkat(-1, (const char *)a, 0); break;
#endif
case SYS_unlinkat: res = __m3_unlinkat(a, (const char *)b, c); break;
case SYS_chdir: res = __m3_chdir((const char *)a); break;
case SYS_fchdir: res = __m3_fchdir(a); break;
case SYS_getcwd: res = __m3_getcwd((char *)a, (size_t)b); break;
case SYS_epoll_create1: res = __m3_epoll_create(a); break;
case SYS_epoll_ctl: res = __m3_epoll_ctl(a, b, c, (struct epoll_event *)d); break;
case SYS_epoll_pwait:
res = __m3_epoll_pwait(a, (struct epoll_event *)b, c, d, (const sigset_t *)e);
break;
// we don't support symlinks; so it's never a symlink
#if defined(SYS_readlink)
case SYS_readlink: res = -EINVAL; break;
#endif
case SYS_readlinkat: res = -EINVAL; break;
case SYS_socket: res = __m3_socket(a, b, c); break;
case SYS_bind: res = __m3_bind(a, (const struct sockaddr *)b, (socklen_t)c); break;
case SYS_listen: res = __m3_listen(a, b); break;
case SYS_accept: res = __m3_accept(a, (struct sockaddr *)b, (socklen_t *)c); break;
case SYS_accept4: res = __m3_accept4(a, (struct sockaddr *)b, (socklen_t *)c, d); break;
case SYS_connect: res = __m3_connect(a, (const struct sockaddr *)b, (socklen_t)c); break;
case SYS_sendto:
res = __m3_sendto(a, (const void *)b, (size_t)c, d, (const struct sockaddr *)e,
(socklen_t)f);
break;
case SYS_sendmsg: res = __m3_sendmsg(a, (const struct msghdr *)b, c); break;
case SYS_recvfrom:
res = __m3_recvfrom(a, (void *)b, (size_t)c, d, (struct sockaddr *)e, (socklen_t *)f);
break;
case SYS_recvmsg: res = __m3_recvmsg(a, (struct msghdr *)b, c); break;
case SYS_shutdown: res = __m3_shutdown(a, b); break;
case SYS_getsockname:
res = __m3_getsockname(a, (struct sockaddr *)b, (socklen_t *)c);
break;
case SYS_getpeername:
res = __m3_getpeername(a, (struct sockaddr *)b, (socklen_t *)c);
break;
case SYS_getpid: res = __m3_getpid(); break;
case SYS_getuid: res = __m3_getuid(); break;
#if defined(SYS_getuid32)
case SYS_getuid32: res = __m3_getuid(); break;
#endif
case SYS_geteuid: res = __m3_geteuid(); break;
#if defined(SYS_geteuid32)
case SYS_geteuid32: res = __m3_geteuid(); break;
#endif
case SYS_getgid: res = __m3_getgid(); break;
#if defined(SYS_getgid32)
case SYS_getgid32: res = __m3_getgid(); break;
#endif
case SYS_getegid: res = __m3_getegid(); break;
#if defined(SYS_getegid32)
case SYS_getegid32: res = __m3_getegid(); break;
#endif
case SYS_umask: res = (long)__m3_umask((mode_t)a); break;
#if defined(SYS_clock_gettime)
case SYS_clock_gettime: res = __m3_clock_gettime(a, (struct timespec *)b); break;
#endif
#if defined(SYS_clock_gettime32)
case SYS_clock_gettime32: res = __m3_clock_gettime(a, (struct timespec *)b); break;
#endif
#if defined(SYS_clock_gettime64)
case SYS_clock_gettime64: res = __m3_clock_gettime(a, (struct timespec *)b); break;
#endif
case SYS_nanosleep:
res = __m3_nanosleep((const struct timespec *)a, (struct timespec *)b);
break;
case SYS_uname: res = __m3_uname((struct utsname *)a); break;
case SYS_ioctl: res = __m3_ioctl(a, (unsigned long)b, c, d, e, f); break;
// deliberately ignored
case SYS_prlimit64:
#if defined(SYS_getrlimit)
case SYS_getrlimit:
#endif
#if defined(SYS_ugetrlimit)
case SYS_ugetrlimit:
#endif
break;
default: {
#if !PRINT_SYSCALLS && PRINT_UNKNOWN
char buf[256];
m3::OStringStream os(buf, sizeof(buf));
print_syscall(os, n, a, b, c, d, e, f);
os << " -> " << res << "\n";
m3::Machine::write(os.str(), os.length());
#endif
break;
}
}
#if PRINT_SYSCALLS
syscos.reset();
print_syscall(syscos, n, a, b, c, d, e, f);
syscos << " -> " << res << "\n";
m3::Machine::write(syscos.str(), syscos.length());
#endif
__m3_sysc_trace_stop();
return res;
}
EXTERN_C long __syscall0(long n) {
return __syscall6(n, 0, 0, 0, 0, 0, 0);
}
EXTERN_C long __syscall1(long n, long a) {
return __syscall6(n, a, 0, 0, 0, 0, 0);
}
EXTERN_C long __syscall2(long n, long a, long b) {
return __syscall6(n, a, b, 0, 0, 0, 0);
}
EXTERN_C long __syscall3(long n, long a, long b, long c) {
return __syscall6(n, a, b, c, 0, 0, 0);
}
EXTERN_C long __syscall4(long n, long a, long b, long c, long d) {
return __syscall6(n, a, b, c, d, 0, 0);
}
EXTERN_C long __syscall5(long n, long a, long b, long c, long d, long e) {
return __syscall6(n, a, b, c, d, e, 0);
}
| 34.543524 | 99 | 0.627474 | Barkhausen-Institut |
145f91f53a91148d68c786f4c75d6d4b4f28cbe1 | 349 | hpp | C++ | libs/gui/include/sge/gui/master_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/gui/include/sge/gui/master_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/gui/include/sge/gui/master_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_GUI_MASTER_FWD_HPP_INCLUDED
#define SGE_GUI_MASTER_FWD_HPP_INCLUDED
namespace sge::gui
{
class master;
}
#endif
| 20.529412 | 61 | 0.727794 | cpreh |
1460b9a061802c50f96cf0d13a7cff4b9c091db9 | 2,703 | cpp | C++ | src/routes/miners/MercuryMiner.cpp | xXNurioXx/gta-samp-driver | 9bd2b0863281cf5bd68a2b699217d3ef73afc3ca | [
"MIT"
] | 3 | 2020-07-12T15:57:39.000Z | 2020-09-06T11:00:06.000Z | src/routes/miners/MercuryMiner.cpp | xXNurioXx/gta-sa-self-driving-car | 9bd2b0863281cf5bd68a2b699217d3ef73afc3ca | [
"MIT"
] | null | null | null | src/routes/miners/MercuryMiner.cpp | xXNurioXx/gta-sa-self-driving-car | 9bd2b0863281cf5bd68a2b699217d3ef73afc3ca | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <Windows.h>
#include "../../drivers/Walker.cpp"
#include "../../interactions/CaptchaSolver.cpp"
#include "../../interactions/ChatManager.cpp"
#include "Miner.cpp"
class MercuryMiner {
private:
Movement *movement = new Movement();
ChatManager *chat = new ChatManager();
GameResources *gameResources;
Walker *walker;
public:
MercuryMiner(GameResources *gameResources) {
this->gameResources = gameResources;
this->walker = new Walker(gameResources);
}
public:
void Start() {
goToStart();
goToOutsideDoor();
goToMercuryStone();
pickStone();
goToInnerDoor();
goDeliveryPoint();
deliverStone();
}
private:
void deliverStone() {
walker->RunToPos(Miner::Checkpoints::DELIVERY_POINT);
Sleep(1000);
chat->Type("/dejar roca");
solveCaptcha();
Sleep(5000);
}
private:
void goToStart() {
movement->StopMovingForward();
movement->StopRunning();
movement->StopSlowlyWalk();
movement->StopMovingBack();
movement->StopMovingLeft();
movement->StopMovingRight();
walker->overSecureWalkTo(Miner::Checkpoints::START_RAMP);
}
private:
void goDeliveryPoint() {
walker->RunToPos(Miner::Checkpoints::ENTER_DOOR);
walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_CORNER);
walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_BRIDGE);
walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_RAMP_CORNER);
}
private:
void goToInnerDoor() {
walker->RunToPos(Miner::Checkpoints::MERCURY_STONE);
walker->RunToPos(Miner::Checkpoints::RAIL_END);
walker->RunToPos(Miner::Checkpoints::EXIT_DOOR);
Sleep(1000);
movement->JoinOrLeaveInterior();
}
private:
void goToOutsideDoor() {
walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_RAMP_CORNER);
walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_BRIDGE);
walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_CORNER);
walker->RunToPos(Miner::Checkpoints::ENTER_DOOR);
movement->JoinOrLeaveInterior();
}
private:
void goToMercuryStone() {
walker->RunToPos(Miner::Checkpoints::RAIL_END);
walker->RunToPos(Miner::Checkpoints::MERCURY_STONE);
}
private:
void pickStone() {
Sleep(2500);
chat->Type("/picar");
Sleep(20 * 1000);
}
private:
void solveCaptcha() {
printf("Starting captcha solver...\n");
Sleep(1500);
auto *captchaSolver = new CaptchaSolver();
captchaSolver->Solve();
}
}; | 26.5 | 71 | 0.63781 | xXNurioXx |
1463a9000c0501599b36fc1dd05ddfa1bb9e47bd | 73,362 | cpp | C++ | packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/propgrid/props.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/propgrid/props.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/propgrid/props.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Name: src/propgrid/props.cpp
// Purpose: Basic Property Classes
// Author: Jaakko Salli
// Modified by:
// Created: 2005-05-14
// RCS-ID: $Id$
// Copyright: (c) Jaakko Salli
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_PROPGRID
#ifndef WX_PRECOMP
#include "wx/defs.h"
#include "wx/object.h"
#include "wx/hash.h"
#include "wx/string.h"
#include "wx/log.h"
#include "wx/event.h"
#include "wx/window.h"
#include "wx/panel.h"
#include "wx/dc.h"
#include "wx/dcclient.h"
#include "wx/dcmemory.h"
#include "wx/button.h"
#include "wx/bmpbuttn.h"
#include "wx/pen.h"
#include "wx/brush.h"
#include "wx/cursor.h"
#include "wx/dialog.h"
#include "wx/settings.h"
#include "wx/msgdlg.h"
#include "wx/choice.h"
#include "wx/stattext.h"
#include "wx/scrolwin.h"
#include "wx/dirdlg.h"
#include "wx/combobox.h"
#include "wx/layout.h"
#include "wx/sizer.h"
#include "wx/textdlg.h"
#include "wx/filedlg.h"
#include "wx/intl.h"
#endif
#include "wx/filename.h"
#include "wx/propgrid/propgrid.h"
#define wxPG_CUSTOM_IMAGE_WIDTH 20 // for wxColourProperty etc.
// -----------------------------------------------------------------------
// wxStringProperty
// -----------------------------------------------------------------------
WX_PG_IMPLEMENT_PROPERTY_CLASS(wxStringProperty,wxPGProperty,
wxString,const wxString&,TextCtrl)
wxStringProperty::wxStringProperty( const wxString& label,
const wxString& name,
const wxString& value )
: wxPGProperty(label,name)
{
SetValue(value);
}
void wxStringProperty::OnSetValue()
{
if ( !m_value.IsNull() && m_value.GetString() == wxS("<composed>") )
SetFlag(wxPG_PROP_COMPOSED_VALUE);
if ( HasFlag(wxPG_PROP_COMPOSED_VALUE) )
{
wxString s;
DoGenerateComposedValue(s);
m_value = s;
}
}
wxStringProperty::~wxStringProperty() { }
wxString wxStringProperty::ValueToString( wxVariant& value,
int argFlags ) const
{
wxString s = value.GetString();
if ( GetChildCount() && HasFlag(wxPG_PROP_COMPOSED_VALUE) )
{
// Value stored in m_value is non-editable, non-full value
if ( (argFlags & wxPG_FULL_VALUE) ||
(argFlags & wxPG_EDITABLE_VALUE) ||
!s.length() )
{
// Calling this under incorrect conditions will fail
wxASSERT_MSG( argFlags & wxPG_VALUE_IS_CURRENT,
"Sorry, currently default wxPGProperty::ValueToString() "
"implementation only works if value is m_value." );
DoGenerateComposedValue(s, argFlags);
}
return s;
}
// If string is password and value is for visual purposes,
// then return asterisks instead the actual string.
if ( (m_flags & wxPG_PROP_PASSWORD) && !(argFlags & (wxPG_FULL_VALUE|wxPG_EDITABLE_VALUE)) )
return wxString(wxChar('*'), s.Length());
return s;
}
bool wxStringProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const
{
if ( GetChildCount() && HasFlag(wxPG_PROP_COMPOSED_VALUE) )
return wxPGProperty::StringToValue(variant, text, argFlags);
if ( variant != text )
{
variant = text;
return true;
}
return false;
}
bool wxStringProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
if ( name == wxPG_STRING_PASSWORD )
{
m_flags &= ~(wxPG_PROP_PASSWORD);
if ( value.GetLong() ) m_flags |= wxPG_PROP_PASSWORD;
RecreateEditor();
return false;
}
return true;
}
// -----------------------------------------------------------------------
// wxNumericPropertyValidator
// -----------------------------------------------------------------------
#if wxUSE_VALIDATORS
wxNumericPropertyValidator::
wxNumericPropertyValidator( NumericType numericType, int base )
: wxTextValidator(wxFILTER_INCLUDE_CHAR_LIST)
{
wxArrayString arr;
arr.Add(wxS("0"));
arr.Add(wxS("1"));
arr.Add(wxS("2"));
arr.Add(wxS("3"));
arr.Add(wxS("4"));
arr.Add(wxS("5"));
arr.Add(wxS("6"));
arr.Add(wxS("7"));
if ( base >= 10 )
{
arr.Add(wxS("8"));
arr.Add(wxS("9"));
if ( base >= 16 )
{
arr.Add(wxS("a")); arr.Add(wxS("A"));
arr.Add(wxS("b")); arr.Add(wxS("B"));
arr.Add(wxS("c")); arr.Add(wxS("C"));
arr.Add(wxS("d")); arr.Add(wxS("D"));
arr.Add(wxS("e")); arr.Add(wxS("E"));
arr.Add(wxS("f")); arr.Add(wxS("F"));
}
}
if ( numericType == Signed )
{
arr.Add(wxS("+"));
arr.Add(wxS("-"));
}
else if ( numericType == Float )
{
arr.Add(wxS("+"));
arr.Add(wxS("-"));
arr.Add(wxS("e"));
// Use locale-specific decimal point
arr.Add(wxString::Format("%g", 1.1)[1]);
}
SetIncludes(arr);
}
bool wxNumericPropertyValidator::Validate(wxWindow* parent)
{
if ( !wxTextValidator::Validate(parent) )
return false;
wxWindow* wnd = GetWindow();
if ( !wxDynamicCast(wnd, wxTextCtrl) )
return true;
// Do not allow zero-length string
wxTextCtrl* tc = static_cast<wxTextCtrl*>(wnd);
wxString text = tc->GetValue();
if ( text.empty() )
return false;
return true;
}
#endif // wxUSE_VALIDATORS
// -----------------------------------------------------------------------
// wxIntProperty
// -----------------------------------------------------------------------
WX_PG_IMPLEMENT_PROPERTY_CLASS(wxIntProperty,wxPGProperty,
long,long,TextCtrl)
wxIntProperty::wxIntProperty( const wxString& label, const wxString& name,
long value ) : wxPGProperty(label,name)
{
SetValue(value);
}
wxIntProperty::wxIntProperty( const wxString& label, const wxString& name,
const wxLongLong& value ) : wxPGProperty(label,name)
{
SetValue(WXVARIANT(value));
}
wxIntProperty::~wxIntProperty() { }
wxString wxIntProperty::ValueToString( wxVariant& value,
int WXUNUSED(argFlags) ) const
{
if ( value.GetType() == wxPG_VARIANT_TYPE_LONG )
{
return wxString::Format(wxS("%li"),value.GetLong());
}
else if ( value.GetType() == wxPG_VARIANT_TYPE_LONGLONG )
{
wxLongLong ll = value.GetLongLong();
return ll.ToString();
}
return wxEmptyString;
}
bool wxIntProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const
{
wxString s;
long value32;
if ( text.empty() )
{
variant.MakeNull();
return true;
}
// We know it is a number, but let's still check
// the return value.
if ( text.IsNumber() )
{
// Remove leading zeroes, so that the number is not interpreted as octal
wxString::const_iterator i = text.begin();
wxString::const_iterator iMax = text.end() - 1; // Let's allow one, last zero though
int firstNonZeroPos = 0;
for ( ; i != iMax; ++i )
{
wxChar c = *i;
if ( c != wxS('0') && c != wxS(' ') )
break;
firstNonZeroPos++;
}
wxString useText = text.substr(firstNonZeroPos, text.length() - firstNonZeroPos);
wxString variantType = variant.GetType();
bool isPrevLong = variantType == wxPG_VARIANT_TYPE_LONG;
wxLongLong_t value64 = 0;
if ( useText.ToLongLong(&value64, 10) &&
( value64 >= INT_MAX || value64 <= INT_MIN )
)
{
bool doChangeValue = isPrevLong;
if ( !isPrevLong && variantType == wxPG_VARIANT_TYPE_LONGLONG )
{
wxLongLong oldValue = variant.GetLongLong();
if ( oldValue.GetValue() != value64 )
doChangeValue = true;
}
if ( doChangeValue )
{
wxLongLong ll(value64);
variant = ll;
return true;
}
}
if ( useText.ToLong( &value32, 0 ) )
{
if ( !isPrevLong || variant != value32 )
{
variant = value32;
return true;
}
}
}
else if ( argFlags & wxPG_REPORT_ERROR )
{
}
return false;
}
bool wxIntProperty::IntToValue( wxVariant& variant, int value, int WXUNUSED(argFlags) ) const
{
if ( variant.GetType() != wxPG_VARIANT_TYPE_LONG || variant != (long)value )
{
variant = (long)value;
return true;
}
return false;
}
//
// Common validation code to be called in ValidateValue()
// implementations.
//
// Note that 'value' is reference on purpose, so we can write
// back to it when mode is wxPG_PROPERTY_VALIDATION_SATURATE.
//
template<typename T>
bool NumericValidation( const wxPGProperty* property,
T& value,
wxPGValidationInfo* pValidationInfo,
int mode,
const wxString& strFmt )
{
T min = (T) wxINT64_MIN;
T max = (T) wxINT64_MAX;
wxVariant variant;
bool minOk = false;
bool maxOk = false;
variant = property->GetAttribute(wxPGGlobalVars->m_strMin);
if ( !variant.IsNull() )
{
variant.Convert(&min);
minOk = true;
}
variant = property->GetAttribute(wxPGGlobalVars->m_strMax);
if ( !variant.IsNull() )
{
variant.Convert(&max);
maxOk = true;
}
if ( minOk )
{
if ( value < min )
{
if ( mode == wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE )
{
wxString msg;
wxString smin = wxString::Format(strFmt, min);
wxString smax = wxString::Format(strFmt, max);
if ( !maxOk )
msg = wxString::Format(
_("Value must be %s or higher."),
smin.c_str());
else
msg = wxString::Format(
_("Value must be between %s and %s."),
smin.c_str(), smax.c_str());
pValidationInfo->SetFailureMessage(msg);
}
else if ( mode == wxPG_PROPERTY_VALIDATION_SATURATE )
value = min;
else
value = max - (min - value);
return false;
}
}
if ( maxOk )
{
if ( value > max )
{
if ( mode == wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE )
{
wxString msg;
wxString smin = wxString::Format(strFmt, min);
wxString smax = wxString::Format(strFmt, max);
if ( !minOk )
msg = wxString::Format(
_("Value must be %s or less."),
smax.c_str());
else
msg = wxString::Format(
_("Value must be between %s and %s."),
smin.c_str(), smax.c_str());
pValidationInfo->SetFailureMessage(msg);
}
else if ( mode == wxPG_PROPERTY_VALIDATION_SATURATE )
value = max;
else
value = min + (value - max);
return false;
}
}
return true;
}
bool wxIntProperty::DoValidation( const wxPGProperty* property,
wxLongLong_t& value,
wxPGValidationInfo* pValidationInfo,
int mode )
{
return NumericValidation<wxLongLong_t>(property,
value,
pValidationInfo,
mode,
wxS("%lld"));
}
bool wxIntProperty::ValidateValue( wxVariant& value,
wxPGValidationInfo& validationInfo ) const
{
wxLongLong_t ll = value.GetLongLong().GetValue();
return DoValidation(this, ll, &validationInfo,
wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE);
}
wxValidator* wxIntProperty::GetClassValidator()
{
#if wxUSE_VALIDATORS
WX_PG_DOGETVALIDATOR_ENTRY()
wxValidator* validator = new wxNumericPropertyValidator(
wxNumericPropertyValidator::Signed);
WX_PG_DOGETVALIDATOR_EXIT(validator)
#else
return NULL;
#endif
}
wxValidator* wxIntProperty::DoGetValidator() const
{
return GetClassValidator();
}
// -----------------------------------------------------------------------
// wxUIntProperty
// -----------------------------------------------------------------------
#define wxPG_UINT_TEMPLATE_MAX 8
static const wxChar* const gs_uintTemplates32[wxPG_UINT_TEMPLATE_MAX] = {
wxT("%lx"),wxT("0x%lx"),wxT("$%lx"),
wxT("%lX"),wxT("0x%lX"),wxT("$%lX"),
wxT("%lu"),wxT("%lo")
};
static const char* const gs_uintTemplates64[wxPG_UINT_TEMPLATE_MAX] = {
"%" wxLongLongFmtSpec "x",
"0x%" wxLongLongFmtSpec "x",
"$%" wxLongLongFmtSpec "x",
"%" wxLongLongFmtSpec "X",
"0x%" wxLongLongFmtSpec "X",
"$%" wxLongLongFmtSpec "X",
"%" wxLongLongFmtSpec "u",
"%" wxLongLongFmtSpec "o"
};
WX_PG_IMPLEMENT_PROPERTY_CLASS(wxUIntProperty,wxPGProperty,
long,unsigned long,TextCtrl)
void wxUIntProperty::Init()
{
m_base = 6; // This is magic number for dec base (must be same as in setattribute)
m_realBase = 10;
m_prefix = wxPG_PREFIX_NONE;
}
wxUIntProperty::wxUIntProperty( const wxString& label, const wxString& name,
unsigned long value ) : wxPGProperty(label,name)
{
Init();
SetValue((long)value);
}
wxUIntProperty::wxUIntProperty( const wxString& label, const wxString& name,
const wxULongLong& value ) : wxPGProperty(label,name)
{
Init();
SetValue(WXVARIANT(value));
}
wxUIntProperty::~wxUIntProperty() { }
wxString wxUIntProperty::ValueToString( wxVariant& value,
int WXUNUSED(argFlags) ) const
{
size_t index = m_base + m_prefix;
if ( index >= wxPG_UINT_TEMPLATE_MAX )
index = wxPG_BASE_DEC;
if ( value.GetType() == wxPG_VARIANT_TYPE_LONG )
{
return wxString::Format(gs_uintTemplates32[index],
(unsigned long)value.GetLong());
}
wxULongLong ull = value.GetULongLong();
return wxString::Format(gs_uintTemplates64[index], ull.GetValue());
}
bool wxUIntProperty::StringToValue( wxVariant& variant, const wxString& text, int WXUNUSED(argFlags) ) const
{
wxString variantType = variant.GetType();
bool isPrevLong = variantType == wxPG_VARIANT_TYPE_LONG;
if ( text.empty() )
{
variant.MakeNull();
return true;
}
size_t start = 0;
if ( text[0] == wxS('$') )
start++;
wxULongLong_t value64 = 0;
wxString s = text.substr(start, text.length() - start);
if ( s.ToULongLong(&value64, (unsigned int)m_realBase) )
{
if ( value64 >= LONG_MAX )
{
bool doChangeValue = isPrevLong;
if ( !isPrevLong && variantType == wxPG_VARIANT_TYPE_ULONGLONG )
{
wxULongLong oldValue = variant.GetULongLong();
if ( oldValue.GetValue() != value64 )
doChangeValue = true;
}
if ( doChangeValue )
{
variant = wxULongLong(value64);
return true;
}
}
else
{
unsigned long value32 = wxLongLong(value64).GetLo();
if ( !isPrevLong || m_value != (long)value32 )
{
variant = (long)value32;
return true;
}
}
}
return false;
}
bool wxUIntProperty::IntToValue( wxVariant& variant, int number, int WXUNUSED(argFlags) ) const
{
if ( variant != (long)number )
{
variant = (long)number;
return true;
}
return false;
}
bool wxUIntProperty::ValidateValue( wxVariant& value, wxPGValidationInfo& validationInfo ) const
{
wxULongLong_t uul = value.GetULongLong().GetValue();
return
NumericValidation<wxULongLong_t>(this,
uul,
&validationInfo,
wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE,
wxS("%llu"));
}
wxValidator* wxUIntProperty::DoGetValidator() const
{
#if wxUSE_VALIDATORS
WX_PG_DOGETVALIDATOR_ENTRY()
wxValidator* validator = new wxNumericPropertyValidator(
wxNumericPropertyValidator::Unsigned,
m_realBase);
WX_PG_DOGETVALIDATOR_EXIT(validator)
#else
return NULL;
#endif
}
bool wxUIntProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
if ( name == wxPG_UINT_BASE )
{
int val = value.GetLong();
m_realBase = (wxByte) val;
if ( m_realBase > 16 )
m_realBase = 16;
//
// Translate logical base to a template array index
m_base = 7; // oct
if ( val == wxPG_BASE_HEX )
m_base = 3;
else if ( val == wxPG_BASE_DEC )
m_base = 6;
else if ( val == wxPG_BASE_HEXL )
m_base = 0;
return true;
}
else if ( name == wxPG_UINT_PREFIX )
{
m_prefix = (wxByte) value.GetLong();
return true;
}
return false;
}
// -----------------------------------------------------------------------
// wxFloatProperty
// -----------------------------------------------------------------------
WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFloatProperty,wxPGProperty,
double,double,TextCtrl)
wxFloatProperty::wxFloatProperty( const wxString& label,
const wxString& name,
double value )
: wxPGProperty(label,name)
{
m_precision = -1;
SetValue(value);
}
wxFloatProperty::~wxFloatProperty() { }
// This helper method provides standard way for floating point-using
// properties to convert values to string.
const wxString& wxPropertyGrid::DoubleToString(wxString& target,
double value,
int precision,
bool removeZeroes,
wxString* precTemplate)
{
if ( precision >= 0 )
{
wxString text1;
if (!precTemplate)
precTemplate = &text1;
if ( precTemplate->empty() )
{
*precTemplate = wxS("%.");
*precTemplate << wxString::Format( wxS("%i"), precision );
*precTemplate << wxS('f');
}
target.Printf( precTemplate->c_str(), value );
}
else
{
target.Printf( wxS("%f"), value );
}
if ( removeZeroes && precision != 0 && !target.empty() )
{
// Remove excess zeroes (do not remove this code just yet,
// since sprintf can't do the same consistently across platforms).
wxString::const_iterator i = target.end() - 1;
size_t new_len = target.length() - 1;
for ( ; i != target.begin(); --i )
{
if ( *i != wxS('0') )
break;
new_len--;
}
wxChar cur_char = *i;
if ( cur_char != wxS('.') && cur_char != wxS(',') )
new_len++;
if ( new_len != target.length() )
target.resize(new_len);
}
// Remove sign from zero
if ( target.length() >= 2 && target[0] == wxS('-') )
{
bool isZero = true;
wxString::const_iterator i = target.begin() + 1;
for ( ; i != target.end(); i++ )
{
if ( *i != wxS('0') && *i != wxS('.') && *i != wxS(',') )
{
isZero = false;
break;
}
}
if ( isZero )
target.erase(target.begin());
}
return target;
}
wxString wxFloatProperty::ValueToString( wxVariant& value,
int argFlags ) const
{
wxString text;
if ( !value.IsNull() )
{
wxPropertyGrid::DoubleToString(text,
value,
m_precision,
!(argFlags & wxPG_FULL_VALUE),
NULL);
}
return text;
}
bool wxFloatProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const
{
wxString s;
double value;
if ( text.empty() )
{
variant.MakeNull();
return true;
}
bool res = text.ToDouble(&value);
if ( res )
{
if ( variant != value )
{
variant = value;
return true;
}
}
else if ( argFlags & wxPG_REPORT_ERROR )
{
}
return false;
}
bool wxFloatProperty::DoValidation( const wxPGProperty* property,
double& value,
wxPGValidationInfo* pValidationInfo,
int mode )
{
return NumericValidation<double>(property,
value,
pValidationInfo,
mode,
wxS("%g"));
}
bool
wxFloatProperty::ValidateValue( wxVariant& value,
wxPGValidationInfo& validationInfo ) const
{
double fpv = value.GetDouble();
return DoValidation(this, fpv, &validationInfo,
wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE);
}
bool wxFloatProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
if ( name == wxPG_FLOAT_PRECISION )
{
m_precision = value.GetLong();
return true;
}
return false;
}
wxValidator*
wxFloatProperty::GetClassValidator()
{
#if wxUSE_VALIDATORS
WX_PG_DOGETVALIDATOR_ENTRY()
wxValidator* validator = new wxNumericPropertyValidator(
wxNumericPropertyValidator::Float);
WX_PG_DOGETVALIDATOR_EXIT(validator)
#else
return NULL;
#endif
}
wxValidator* wxFloatProperty::DoGetValidator() const
{
return GetClassValidator();
}
// -----------------------------------------------------------------------
// wxBoolProperty
// -----------------------------------------------------------------------
// We cannot use standard WX_PG_IMPLEMENT_PROPERTY_CLASS macro, since
// there is a custom GetEditorClass.
IMPLEMENT_DYNAMIC_CLASS(wxBoolProperty, wxPGProperty)
const wxPGEditor* wxBoolProperty::DoGetEditorClass() const
{
// Select correct editor control.
#if wxPG_INCLUDE_CHECKBOX
if ( !(m_flags & wxPG_PROP_USE_CHECKBOX) )
return wxPGEditor_Choice;
return wxPGEditor_CheckBox;
#else
return wxPGEditor_Choice;
#endif
}
wxBoolProperty::wxBoolProperty( const wxString& label, const wxString& name, bool value ) :
wxPGProperty(label,name)
{
m_choices.Assign(wxPGGlobalVars->m_boolChoices);
SetValue(wxPGVariant_Bool(value));
m_flags |= wxPG_PROP_USE_DCC;
}
wxBoolProperty::~wxBoolProperty() { }
wxString wxBoolProperty::ValueToString( wxVariant& value,
int argFlags ) const
{
bool boolValue = value.GetBool();
// As a fragment of composite string value,
// make it a little more readable.
if ( argFlags & wxPG_COMPOSITE_FRAGMENT )
{
if ( boolValue )
{
return m_label;
}
else
{
if ( argFlags & wxPG_UNEDITABLE_COMPOSITE_FRAGMENT )
return wxEmptyString;
wxString notFmt;
if ( wxPGGlobalVars->m_autoGetTranslation )
notFmt = _("Not %s");
else
notFmt = wxS("Not %s");
return wxString::Format(notFmt.c_str(), m_label.c_str());
}
}
if ( !(argFlags & wxPG_FULL_VALUE) )
{
return wxPGGlobalVars->m_boolChoices[boolValue?1:0].GetText();
}
wxString text;
if ( boolValue ) text = wxS("true");
else text = wxS("false");
return text;
}
bool wxBoolProperty::StringToValue( wxVariant& variant, const wxString& text, int WXUNUSED(argFlags) ) const
{
bool boolValue = false;
if ( text.CmpNoCase(wxPGGlobalVars->m_boolChoices[1].GetText()) == 0 ||
text.CmpNoCase(wxS("true")) == 0 ||
text.CmpNoCase(m_label) == 0 )
boolValue = true;
if ( text.empty() )
{
variant.MakeNull();
return true;
}
if ( variant != boolValue )
{
variant = wxPGVariant_Bool(boolValue);
return true;
}
return false;
}
bool wxBoolProperty::IntToValue( wxVariant& variant, int value, int ) const
{
bool boolValue = value ? true : false;
if ( variant != boolValue )
{
variant = wxPGVariant_Bool(boolValue);
return true;
}
return false;
}
bool wxBoolProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
#if wxPG_INCLUDE_CHECKBOX
if ( name == wxPG_BOOL_USE_CHECKBOX )
{
if ( value.GetLong() )
m_flags |= wxPG_PROP_USE_CHECKBOX;
else
m_flags &= ~(wxPG_PROP_USE_CHECKBOX);
return true;
}
#endif
if ( name == wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING )
{
if ( value.GetLong() )
m_flags |= wxPG_PROP_USE_DCC;
else
m_flags &= ~(wxPG_PROP_USE_DCC);
return true;
}
return false;
}
// -----------------------------------------------------------------------
// wxEnumProperty
// -----------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxEnumProperty, wxPGProperty)
WX_PG_IMPLEMENT_PROPERTY_CLASS_PLAIN(wxEnumProperty,long,Choice)
wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels,
const long* values, int value ) : wxPGProperty(label,name)
{
SetIndex(0);
if ( labels )
{
m_choices.Add(labels,values);
if ( GetItemCount() )
SetValue( (long)value );
}
}
wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels,
const long* values, wxPGChoices* choicesCache, int value )
: wxPGProperty(label,name)
{
SetIndex(0);
wxASSERT( choicesCache );
if ( choicesCache->IsOk() )
{
m_choices.Assign( *choicesCache );
m_value = wxPGVariant_Zero;
}
else if ( labels )
{
m_choices.Add(labels,values);
if ( GetItemCount() )
SetValue( (long)value );
}
}
wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name,
const wxArrayString& labels, const wxArrayInt& values, int value )
: wxPGProperty(label,name)
{
SetIndex(0);
if ( &labels && labels.size() )
{
m_choices.Set(labels, values);
if ( GetItemCount() )
SetValue( (long)value );
}
}
wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name,
wxPGChoices& choices, int value )
: wxPGProperty(label,name)
{
m_choices.Assign( choices );
if ( GetItemCount() )
SetValue( (long)value );
}
int wxEnumProperty::GetIndexForValue( int value ) const
{
if ( !m_choices.IsOk() )
return -1;
int intVal = m_choices.Index(value);
if ( intVal >= 0 )
return intVal;
return value;
}
wxEnumProperty::~wxEnumProperty ()
{
}
int wxEnumProperty::ms_nextIndex = -2;
void wxEnumProperty::OnSetValue()
{
wxString variantType = m_value.GetType();
if ( variantType == wxPG_VARIANT_TYPE_LONG )
{
ValueFromInt_( m_value, m_value.GetLong(), wxPG_FULL_VALUE );
}
else if ( variantType == wxPG_VARIANT_TYPE_STRING )
{
ValueFromString_( m_value, m_value.GetString(), 0 );
}
else
{
wxFAIL;
}
if ( ms_nextIndex != -2 )
{
m_index = ms_nextIndex;
ms_nextIndex = -2;
}
}
bool wxEnumProperty::ValidateValue( wxVariant& value, wxPGValidationInfo& WXUNUSED(validationInfo) ) const
{
// Make sure string value is in the list,
// unless property has string as preferred value type
// To reduce code size, use conversion here as well
if ( value.GetType() == wxPG_VARIANT_TYPE_STRING &&
!wxDynamicCastThis(wxEditEnumProperty) )
return ValueFromString_( value, value.GetString(), wxPG_PROPERTY_SPECIFIC );
return true;
}
wxString wxEnumProperty::ValueToString( wxVariant& value,
int WXUNUSED(argFlags) ) const
{
if ( value.GetType() == wxPG_VARIANT_TYPE_STRING )
return value.GetString();
int index = m_choices.Index(value.GetLong());
if ( index < 0 )
return wxEmptyString;
return m_choices.GetLabel(index);
}
bool wxEnumProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const
{
return ValueFromString_( variant, text, argFlags );
}
bool wxEnumProperty::IntToValue( wxVariant& variant, int intVal, int argFlags ) const
{
return ValueFromInt_( variant, intVal, argFlags );
}
bool wxEnumProperty::ValueFromString_( wxVariant& value, const wxString& text, int argFlags ) const
{
int useIndex = -1;
long useValue = 0;
for ( unsigned int i=0; i<m_choices.GetCount(); i++ )
{
const wxString& entryLabel = m_choices.GetLabel(i);
if ( text.CmpNoCase(entryLabel) == 0 )
{
useIndex = (int)i;
useValue = m_choices.GetValue(i);
break;
}
}
bool asText = false;
bool isEdit = this->IsKindOf(wxCLASSINFO(wxEditEnumProperty));
// If text not any of the choices, store as text instead
// (but only if we are wxEditEnumProperty)
if ( useIndex == -1 && isEdit )
{
asText = true;
}
int setAsNextIndex = -2;
if ( asText )
{
setAsNextIndex = -1;
value = text;
}
else if ( useIndex != GetIndex() )
{
if ( useIndex != -1 )
{
setAsNextIndex = useIndex;
value = (long)useValue;
}
else
{
setAsNextIndex = -1;
value = wxPGVariant_MinusOne;
}
}
if ( setAsNextIndex != -2 )
{
// If wxPG_PROPERTY_SPECIFIC is set, then this is done for
// validation purposes only, and index must not be changed
if ( !(argFlags & wxPG_PROPERTY_SPECIFIC) )
ms_nextIndex = setAsNextIndex;
if ( isEdit || setAsNextIndex != -1 )
return true;
else
return false;
}
return false;
}
bool wxEnumProperty::ValueFromInt_( wxVariant& variant, int intVal, int argFlags ) const
{
// If wxPG_FULL_VALUE is *not* in argFlags, then intVal is index from combo box.
//
ms_nextIndex = -2;
if ( argFlags & wxPG_FULL_VALUE )
{
ms_nextIndex = GetIndexForValue( intVal );
}
else
{
if ( intVal != GetIndex() )
{
ms_nextIndex = intVal;
}
}
if ( ms_nextIndex != -2 )
{
if ( !(argFlags & wxPG_FULL_VALUE) )
intVal = m_choices.GetValue(intVal);
variant = (long)intVal;
return true;
}
return false;
}
void
wxEnumProperty::OnValidationFailure( wxVariant& WXUNUSED(pendingValue) )
{
// Revert index
ResetNextIndex();
}
void wxEnumProperty::SetIndex( int index )
{
ms_nextIndex = -2;
m_index = index;
}
int wxEnumProperty::GetIndex() const
{
if ( m_value.IsNull() )
return -1;
if ( ms_nextIndex != -2 )
return ms_nextIndex;
return m_index;
}
// -----------------------------------------------------------------------
// wxEditEnumProperty
// -----------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxEditEnumProperty, wxPGProperty)
WX_PG_IMPLEMENT_PROPERTY_CLASS_PLAIN(wxEditEnumProperty,wxString,ComboBox)
wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels,
const long* values, const wxString& value )
: wxEnumProperty(label,name,labels,values,0)
{
SetValue( value );
}
wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels,
const long* values, wxPGChoices* choicesCache, const wxString& value )
: wxEnumProperty(label,name,labels,values,choicesCache,0)
{
SetValue( value );
}
wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name,
const wxArrayString& labels, const wxArrayInt& values, const wxString& value )
: wxEnumProperty(label,name,labels,values,0)
{
SetValue( value );
}
wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name,
wxPGChoices& choices, const wxString& value )
: wxEnumProperty(label,name,choices,0)
{
SetValue( value );
}
wxEditEnumProperty::~wxEditEnumProperty()
{
}
// -----------------------------------------------------------------------
// wxFlagsProperty
// -----------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxFlagsProperty,wxPGProperty)
WX_PG_IMPLEMENT_PROPERTY_CLASS_PLAIN(wxFlagsProperty,long,TextCtrl)
void wxFlagsProperty::Init()
{
long value = m_value;
//
// Generate children
//
unsigned int i;
unsigned int prevChildCount = m_children.size();
int oldSel = -1;
if ( prevChildCount )
{
wxPropertyGridPageState* state = GetParentState();
// State safety check (it may be NULL in immediate parent)
wxASSERT( state );
if ( state )
{
wxPGProperty* selected = state->GetSelection();
if ( selected )
{
if ( selected->GetParent() == this )
oldSel = selected->GetIndexInParent();
else if ( selected == this )
oldSel = -2;
}
}
state->DoClearSelection();
}
// Delete old children
for ( i=0; i<prevChildCount; i++ )
delete m_children[i];
m_children.clear();
// Relay wxPG_BOOL_USE_CHECKBOX and wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING
// to child bool property controls.
long attrUseCheckBox = GetAttributeAsLong(wxPG_BOOL_USE_CHECKBOX, 0);
long attrUseDCC = GetAttributeAsLong(wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING,
0);
if ( m_choices.IsOk() )
{
const wxPGChoices& choices = m_choices;
for ( i=0; i<GetItemCount(); i++ )
{
bool child_val;
child_val = ( value & choices.GetValue(i) )?true:false;
wxPGProperty* boolProp;
wxString label = GetLabel(i);
#if wxUSE_INTL
if ( wxPGGlobalVars->m_autoGetTranslation )
{
boolProp = new wxBoolProperty( ::wxGetTranslation(label), label, child_val );
}
else
#endif
{
boolProp = new wxBoolProperty( label, label, child_val );
}
if ( attrUseCheckBox )
boolProp->SetAttribute(wxPG_BOOL_USE_CHECKBOX,
true);
if ( attrUseDCC )
boolProp->SetAttribute(wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING,
true);
AddPrivateChild(boolProp);
}
m_oldChoicesData = m_choices.GetDataPtr();
}
m_oldValue = m_value;
if ( prevChildCount )
SubPropsChanged(oldSel);
}
wxFlagsProperty::wxFlagsProperty( const wxString& label, const wxString& name,
const wxChar* const* labels, const long* values, long value ) : wxPGProperty(label,name)
{
m_oldChoicesData = NULL;
if ( labels )
{
m_choices.Set(labels,values);
wxASSERT( GetItemCount() );
SetValue( value );
}
else
{
m_value = wxPGVariant_Zero;
}
}
wxFlagsProperty::wxFlagsProperty( const wxString& label, const wxString& name,
const wxArrayString& labels, const wxArrayInt& values, int value )
: wxPGProperty(label,name)
{
m_oldChoicesData = NULL;
if ( &labels && labels.size() )
{
m_choices.Set(labels,values);
wxASSERT( GetItemCount() );
SetValue( (long)value );
}
else
{
m_value = wxPGVariant_Zero;
}
}
wxFlagsProperty::wxFlagsProperty( const wxString& label, const wxString& name,
wxPGChoices& choices, long value )
: wxPGProperty(label,name)
{
m_oldChoicesData = NULL;
if ( choices.IsOk() )
{
m_choices.Assign(choices);
wxASSERT( GetItemCount() );
SetValue( value );
}
else
{
m_value = wxPGVariant_Zero;
}
}
wxFlagsProperty::~wxFlagsProperty()
{
}
void wxFlagsProperty::OnSetValue()
{
if ( !m_choices.IsOk() || !GetItemCount() )
{
m_value = wxPGVariant_Zero;
}
else
{
long val = m_value.GetLong();
long fullFlags = 0;
// normalize the value (i.e. remove extra flags)
unsigned int i;
const wxPGChoices& choices = m_choices;
for ( i = 0; i < GetItemCount(); i++ )
{
fullFlags |= choices.GetValue(i);
}
val &= fullFlags;
m_value = val;
// Need to (re)init now?
if ( GetChildCount() != GetItemCount() ||
m_choices.GetDataPtr() != m_oldChoicesData )
{
Init();
}
}
long newFlags = m_value;
if ( newFlags != m_oldValue )
{
// Set child modified states
unsigned int i;
const wxPGChoices& choices = m_choices;
for ( i = 0; i<GetItemCount(); i++ )
{
int flag;
flag = choices.GetValue(i);
if ( (newFlags & flag) != (m_oldValue & flag) )
Item(i)->ChangeFlag( wxPG_PROP_MODIFIED, true );
}
m_oldValue = newFlags;
}
}
wxString wxFlagsProperty::ValueToString( wxVariant& value,
int WXUNUSED(argFlags) ) const
{
wxString text;
if ( !m_choices.IsOk() )
return text;
long flags = value;
unsigned int i;
const wxPGChoices& choices = m_choices;
for ( i = 0; i < GetItemCount(); i++ )
{
int doAdd;
doAdd = ( flags & choices.GetValue(i) );
if ( doAdd )
{
text += choices.GetLabel(i);
text += wxS(", ");
}
}
// remove last comma
if ( text.Len() > 1 )
text.Truncate ( text.Len() - 2 );
return text;
}
// Translate string into flag tokens
bool wxFlagsProperty::StringToValue( wxVariant& variant, const wxString& text, int ) const
{
if ( !m_choices.IsOk() )
return false;
long newFlags = 0;
// semicolons are no longer valid delimeters
WX_PG_TOKENIZER1_BEGIN(text,wxS(','))
if ( !token.empty() )
{
// Determine which one it is
long bit = IdToBit( token );
if ( bit != -1 )
{
// Changed?
newFlags |= bit;
}
else
{
break;
}
}
WX_PG_TOKENIZER1_END()
if ( variant != (long)newFlags )
{
variant = (long)newFlags;
return true;
}
return false;
}
// Converts string id to a relevant bit.
long wxFlagsProperty::IdToBit( const wxString& id ) const
{
unsigned int i;
for ( i = 0; i < GetItemCount(); i++ )
{
if ( id == GetLabel(i) )
{
return m_choices.GetValue(i);
}
}
return -1;
}
void wxFlagsProperty::RefreshChildren()
{
if ( !m_choices.IsOk() || !GetChildCount() ) return;
int flags = m_value.GetLong();
const wxPGChoices& choices = m_choices;
unsigned int i;
for ( i = 0; i < GetItemCount(); i++ )
{
long flag;
flag = choices.GetValue(i);
long subVal = flags & flag;
wxPGProperty* p = Item(i);
if ( subVal != (m_oldValue & flag) )
p->ChangeFlag( wxPG_PROP_MODIFIED, true );
p->SetValue( subVal?true:false );
}
m_oldValue = flags;
}
wxVariant wxFlagsProperty::ChildChanged( wxVariant& thisValue,
int childIndex,
wxVariant& childValue ) const
{
long oldValue = thisValue.GetLong();
long val = childValue.GetLong();
unsigned long vi = m_choices.GetValue(childIndex);
if ( val )
return (long) (oldValue | vi);
return (long) (oldValue & ~(vi));
}
bool wxFlagsProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
if ( name == wxPG_BOOL_USE_CHECKBOX ||
name == wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING )
{
for ( size_t i=0; i<GetChildCount(); i++ )
{
Item(i)->SetAttribute(name, value);
}
// Must return false so that the attribute is stored in
// flag property's actual property storage
return false;
}
return false;
}
// -----------------------------------------------------------------------
// wxDirProperty
// -----------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxDirProperty, wxLongStringProperty)
wxDirProperty::wxDirProperty( const wxString& name, const wxString& label, const wxString& value )
: wxLongStringProperty(name,label,value)
{
m_flags |= wxPG_PROP_NO_ESCAPE;
}
wxDirProperty::~wxDirProperty() { }
wxValidator* wxDirProperty::DoGetValidator() const
{
return wxFileProperty::GetClassValidator();
}
bool wxDirProperty::OnButtonClick( wxPropertyGrid* propGrid, wxString& value )
{
// Update property value from editor, if necessary
wxSize dlg_sz(300,400);
wxString dlgMessage(m_dlgMessage);
if ( dlgMessage.empty() )
dlgMessage = _("Choose a directory:");
wxDirDialog dlg( propGrid,
dlgMessage,
value,
0,
#if !wxPG_SMALL_SCREEN
propGrid->GetGoodEditorDialogPosition(this,dlg_sz),
dlg_sz
#else
wxDefaultPosition,
wxDefaultSize
#endif
);
if ( dlg.ShowModal() == wxID_OK )
{
value = dlg.GetPath();
return true;
}
return false;
}
bool wxDirProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
if ( name == wxPG_DIR_DIALOG_MESSAGE )
{
m_dlgMessage = value.GetString();
return true;
}
return false;
}
// -----------------------------------------------------------------------
// wxPGFileDialogAdapter
// -----------------------------------------------------------------------
bool wxPGFileDialogAdapter::DoShowDialog( wxPropertyGrid* propGrid, wxPGProperty* property )
{
wxFileProperty* fileProp = NULL;
wxString path;
int indFilter = -1;
if ( wxDynamicCast(property, wxFileProperty) )
{
fileProp = ((wxFileProperty*)property);
wxFileName filename = fileProp->GetValue().GetString();
path = filename.GetPath();
indFilter = fileProp->m_indFilter;
if ( path.empty() && !fileProp->m_basePath.empty() )
path = fileProp->m_basePath;
}
else
{
wxFileName fn(property->GetValue().GetString());
path = fn.GetPath();
}
wxFileDialog dlg( propGrid->GetPanel(),
property->GetAttribute(wxS("DialogTitle"), _("Choose a file")),
property->GetAttribute(wxS("InitialPath"), path),
wxEmptyString,
property->GetAttribute(wxPG_FILE_WILDCARD, wxALL_FILES),
property->GetAttributeAsLong(wxPG_FILE_DIALOG_STYLE, 0),
wxDefaultPosition );
if ( indFilter >= 0 )
dlg.SetFilterIndex( indFilter );
if ( dlg.ShowModal() == wxID_OK )
{
if ( fileProp )
fileProp->m_indFilter = dlg.GetFilterIndex();
SetValue( dlg.GetPath() );
return true;
}
return false;
}
// -----------------------------------------------------------------------
// wxFileProperty
// -----------------------------------------------------------------------
WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFileProperty,wxPGProperty,
wxString,const wxString&,TextCtrlAndButton)
wxFileProperty::wxFileProperty( const wxString& label, const wxString& name,
const wxString& value ) : wxPGProperty(label,name)
{
m_flags |= wxPG_PROP_SHOW_FULL_FILENAME;
m_indFilter = -1;
SetAttribute( wxPG_FILE_WILDCARD, wxALL_FILES);
SetValue(value);
}
wxFileProperty::~wxFileProperty() {}
wxValidator* wxFileProperty::GetClassValidator()
{
#if wxUSE_VALIDATORS
WX_PG_DOGETVALIDATOR_ENTRY()
// Atleast wxPython 2.6.2.1 required that the string argument is given
static wxString v;
wxTextValidator* validator = new wxTextValidator(wxFILTER_EXCLUDE_CHAR_LIST,&v);
wxArrayString exChars;
exChars.Add(wxS("?"));
exChars.Add(wxS("*"));
exChars.Add(wxS("|"));
exChars.Add(wxS("<"));
exChars.Add(wxS(">"));
exChars.Add(wxS("\""));
validator->SetExcludes(exChars);
WX_PG_DOGETVALIDATOR_EXIT(validator)
#else
return NULL;
#endif
}
wxValidator* wxFileProperty::DoGetValidator() const
{
return GetClassValidator();
}
void wxFileProperty::OnSetValue()
{
const wxString& fnstr = m_value.GetString();
wxFileName filename = fnstr;
if ( !filename.HasName() )
{
m_value = wxPGVariant_EmptyString;
}
// Find index for extension.
if ( m_indFilter < 0 && !fnstr.empty() )
{
wxString ext = filename.GetExt();
int curind = 0;
size_t pos = 0;
size_t len = m_wildcard.length();
pos = m_wildcard.find(wxS("|"), pos);
while ( pos != wxString::npos && pos < (len-3) )
{
size_t ext_begin = pos + 3;
pos = m_wildcard.find(wxS("|"), ext_begin);
if ( pos == wxString::npos )
pos = len;
wxString found_ext = m_wildcard.substr(ext_begin, pos-ext_begin);
if ( !found_ext.empty() )
{
if ( found_ext[0] == wxS('*') )
{
m_indFilter = curind;
break;
}
if ( ext.CmpNoCase(found_ext) == 0 )
{
m_indFilter = curind;
break;
}
}
if ( pos != len )
pos = m_wildcard.find(wxS("|"), pos+1);
curind++;
}
}
}
wxFileName wxFileProperty::GetFileName() const
{
wxFileName filename;
if ( !m_value.IsNull() )
filename = m_value.GetString();
return filename;
}
wxString wxFileProperty::ValueToString( wxVariant& value,
int argFlags ) const
{
wxFileName filename = value.GetString();
if ( !filename.HasName() )
return wxEmptyString;
wxString fullName = filename.GetFullName();
if ( fullName.empty() )
return wxEmptyString;
if ( argFlags & wxPG_FULL_VALUE )
{
return filename.GetFullPath();
}
else if ( m_flags & wxPG_PROP_SHOW_FULL_FILENAME )
{
if ( !m_basePath.empty() )
{
wxFileName fn2(filename);
fn2.MakeRelativeTo(m_basePath);
return fn2.GetFullPath();
}
return filename.GetFullPath();
}
return filename.GetFullName();
}
wxPGEditorDialogAdapter* wxFileProperty::GetEditorDialog() const
{
return new wxPGFileDialogAdapter();
}
bool wxFileProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const
{
wxFileName filename = variant.GetString();
if ( (m_flags & wxPG_PROP_SHOW_FULL_FILENAME) || (argFlags & wxPG_FULL_VALUE) )
{
if ( filename != text )
{
variant = text;
return true;
}
}
else
{
if ( filename.GetFullName() != text )
{
wxFileName fn = filename;
fn.SetFullName(text);
variant = fn.GetFullPath();
return true;
}
}
return false;
}
bool wxFileProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
// Return false on some occasions to make sure those attribs will get
// stored in m_attributes.
if ( name == wxPG_FILE_SHOW_FULL_PATH )
{
if ( value.GetLong() )
m_flags |= wxPG_PROP_SHOW_FULL_FILENAME;
else
m_flags &= ~(wxPG_PROP_SHOW_FULL_FILENAME);
return true;
}
else if ( name == wxPG_FILE_WILDCARD )
{
m_wildcard = value.GetString();
}
else if ( name == wxPG_FILE_SHOW_RELATIVE_PATH )
{
m_basePath = value.GetString();
// Make sure wxPG_FILE_SHOW_FULL_PATH is also set
m_flags |= wxPG_PROP_SHOW_FULL_FILENAME;
}
else if ( name == wxPG_FILE_INITIAL_PATH )
{
m_initialPath = value.GetString();
return true;
}
else if ( name == wxPG_FILE_DIALOG_TITLE )
{
m_dlgTitle = value.GetString();
return true;
}
return false;
}
// -----------------------------------------------------------------------
// wxPGLongStringDialogAdapter
// -----------------------------------------------------------------------
bool wxPGLongStringDialogAdapter::DoShowDialog( wxPropertyGrid* propGrid, wxPGProperty* property )
{
wxString val1 = property->GetValueAsString(0);
wxString val_orig = val1;
wxString value;
if ( !property->HasFlag(wxPG_PROP_NO_ESCAPE) )
wxPropertyGrid::ExpandEscapeSequences(value, val1);
else
value = wxString(val1);
// Run editor dialog.
if ( wxLongStringProperty::DisplayEditorDialog(property, propGrid, value) )
{
if ( !property->HasFlag(wxPG_PROP_NO_ESCAPE) )
wxPropertyGrid::CreateEscapeSequences(val1,value);
else
val1 = value;
if ( val1 != val_orig )
{
SetValue( val1 );
return true;
}
}
return false;
}
// -----------------------------------------------------------------------
// wxLongStringProperty
// -----------------------------------------------------------------------
WX_PG_IMPLEMENT_PROPERTY_CLASS(wxLongStringProperty,wxPGProperty,
wxString,const wxString&,TextCtrlAndButton)
wxLongStringProperty::wxLongStringProperty( const wxString& label, const wxString& name,
const wxString& value ) : wxPGProperty(label,name)
{
SetValue(value);
}
wxLongStringProperty::~wxLongStringProperty() {}
wxString wxLongStringProperty::ValueToString( wxVariant& value,
int WXUNUSED(argFlags) ) const
{
return value;
}
bool wxLongStringProperty::OnEvent( wxPropertyGrid* propGrid, wxWindow* WXUNUSED(primary),
wxEvent& event )
{
if ( propGrid->IsMainButtonEvent(event) )
{
// Update the value
wxVariant useValue = propGrid->GetUncommittedPropertyValue();
wxString val1 = useValue.GetString();
wxString val_orig = val1;
wxString value;
if ( !(m_flags & wxPG_PROP_NO_ESCAPE) )
wxPropertyGrid::ExpandEscapeSequences(value,val1);
else
value = wxString(val1);
// Run editor dialog.
if ( OnButtonClick(propGrid,value) )
{
if ( !(m_flags & wxPG_PROP_NO_ESCAPE) )
wxPropertyGrid::CreateEscapeSequences(val1,value);
else
val1 = value;
if ( val1 != val_orig )
{
SetValueInEvent( val1 );
return true;
}
}
}
return false;
}
bool wxLongStringProperty::OnButtonClick( wxPropertyGrid* propGrid, wxString& value )
{
return DisplayEditorDialog(this, propGrid, value);
}
bool wxLongStringProperty::DisplayEditorDialog( wxPGProperty* prop, wxPropertyGrid* propGrid, wxString& value )
{
// launch editor dialog
wxDialog* dlg = new wxDialog(propGrid,-1,prop->GetLabel(),wxDefaultPosition,wxDefaultSize,
wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxCLIP_CHILDREN);
dlg->SetFont(propGrid->GetFont()); // To allow entering chars of the same set as the propGrid
// Multi-line text editor dialog.
#if !wxPG_SMALL_SCREEN
const int spacing = 8;
#else
const int spacing = 4;
#endif
wxBoxSizer* topsizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* rowsizer = new wxBoxSizer( wxHORIZONTAL );
wxTextCtrl* ed = new wxTextCtrl(dlg,11,value,
wxDefaultPosition,wxDefaultSize,wxTE_MULTILINE);
rowsizer->Add( ed, 1, wxEXPAND|wxALL, spacing );
topsizer->Add( rowsizer, 1, wxEXPAND, 0 );
wxStdDialogButtonSizer* buttonSizer = new wxStdDialogButtonSizer();
buttonSizer->AddButton(new wxButton(dlg, wxID_OK));
buttonSizer->AddButton(new wxButton(dlg, wxID_CANCEL));
buttonSizer->Realize();
topsizer->Add( buttonSizer, 0,
wxALIGN_RIGHT|wxALIGN_CENTRE_VERTICAL|wxBOTTOM|wxRIGHT,
spacing );
dlg->SetSizer( topsizer );
topsizer->SetSizeHints( dlg );
#if !wxPG_SMALL_SCREEN
dlg->SetSize(400,300);
dlg->Move( propGrid->GetGoodEditorDialogPosition(prop,dlg->GetSize()) );
#endif
int res = dlg->ShowModal();
if ( res == wxID_OK )
{
value = ed->GetValue();
dlg->Destroy();
return true;
}
dlg->Destroy();
return false;
}
bool wxLongStringProperty::StringToValue( wxVariant& variant, const wxString& text, int ) const
{
if ( variant != text )
{
variant = text;
return true;
}
return false;
}
#if wxUSE_EDITABLELISTBOX
// -----------------------------------------------------------------------
// wxPGArrayEditorDialog
// -----------------------------------------------------------------------
BEGIN_EVENT_TABLE(wxPGArrayEditorDialog, wxDialog)
EVT_IDLE(wxPGArrayEditorDialog::OnIdle)
END_EVENT_TABLE()
IMPLEMENT_ABSTRACT_CLASS(wxPGArrayEditorDialog, wxDialog)
#include "wx/editlbox.h"
#include "wx/listctrl.h"
// -----------------------------------------------------------------------
void wxPGArrayEditorDialog::OnIdle(wxIdleEvent& event)
{
// Repair focus - wxEditableListBox has bitmap buttons, which
// get focus, and lose focus (into the oblivion) when they
// become disabled due to change in control state.
wxWindow* lastFocused = m_lastFocused;
wxWindow* focus = ::wxWindow::FindFocus();
// If last focused control became disabled, set focus back to
// wxEditableListBox
if ( lastFocused && focus != lastFocused &&
lastFocused->GetParent() == m_elbSubPanel &&
!lastFocused->IsEnabled() )
{
m_elb->GetListCtrl()->SetFocus();
}
m_lastFocused = focus;
event.Skip();
}
// -----------------------------------------------------------------------
wxPGArrayEditorDialog::wxPGArrayEditorDialog()
: wxDialog()
{
Init();
}
// -----------------------------------------------------------------------
void wxPGArrayEditorDialog::Init()
{
m_lastFocused = NULL;
m_hasCustomNewAction = false;
m_itemPendingAtIndex = -1;
}
// -----------------------------------------------------------------------
wxPGArrayEditorDialog::wxPGArrayEditorDialog( wxWindow *parent,
const wxString& message,
const wxString& caption,
long style,
const wxPoint& pos,
const wxSize& sz )
: wxDialog()
{
Init();
Create(parent,message,caption,style,pos,sz);
}
// -----------------------------------------------------------------------
bool wxPGArrayEditorDialog::Create( wxWindow *parent,
const wxString& message,
const wxString& caption,
long style,
const wxPoint& pos,
const wxSize& sz )
{
// On wxMAC the dialog shows incorrectly if style is not exactly wxCAPTION
// FIXME: This should be only a temporary fix.
#ifdef __WXMAC__
wxUnusedVar(style);
int useStyle = wxCAPTION;
#else
int useStyle = style;
#endif
bool res = wxDialog::Create(parent, wxID_ANY, caption, pos, sz, useStyle);
SetFont(parent->GetFont()); // To allow entering chars of the same set as the propGrid
#if !wxPG_SMALL_SCREEN
const int spacing = 4;
#else
const int spacing = 3;
#endif
m_modified = false;
wxBoxSizer* topsizer = new wxBoxSizer( wxVERTICAL );
// Message
if ( !message.empty() )
topsizer->Add( new wxStaticText(this,-1,message),
0, wxALIGN_LEFT|wxALIGN_CENTRE_VERTICAL|wxALL, spacing );
m_elb = new wxEditableListBox(this, wxID_ANY, message,
wxDefaultPosition,
wxDefaultSize,
wxEL_ALLOW_NEW |
wxEL_ALLOW_EDIT |
wxEL_ALLOW_DELETE);
// Populate the list box
wxArrayString arr;
for ( unsigned int i=0; i<ArrayGetCount(); i++ )
arr.push_back(ArrayGet(i));
m_elb->SetStrings(arr);
// Connect event handlers
wxButton* but;
wxListCtrl* lc = m_elb->GetListCtrl();
but = m_elb->GetNewButton();
m_elbSubPanel = but->GetParent();
but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(wxPGArrayEditorDialog::OnAddClick),
NULL, this);
but = m_elb->GetDelButton();
but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(wxPGArrayEditorDialog::OnDeleteClick),
NULL, this);
but = m_elb->GetUpButton();
but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(wxPGArrayEditorDialog::OnUpClick),
NULL, this);
but = m_elb->GetDownButton();
but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(wxPGArrayEditorDialog::OnDownClick),
NULL, this);
lc->Connect(lc->GetId(), wxEVT_COMMAND_LIST_END_LABEL_EDIT,
wxListEventHandler(wxPGArrayEditorDialog::OnEndLabelEdit),
NULL, this);
topsizer->Add( m_elb, 1, wxEXPAND, spacing );
// Standard dialog buttons
wxStdDialogButtonSizer* buttonSizer = new wxStdDialogButtonSizer();
buttonSizer->AddButton(new wxButton(this, wxID_OK));
buttonSizer->AddButton(new wxButton(this, wxID_CANCEL));
buttonSizer->Realize();
topsizer->Add( buttonSizer, 0,
wxALIGN_RIGHT|wxALIGN_CENTRE_VERTICAL|wxALL,
spacing );
m_elb->SetFocus();
SetSizer( topsizer );
topsizer->SetSizeHints( this );
#if !wxPG_SMALL_SCREEN
if ( sz.x == wxDefaultSize.x &&
sz.y == wxDefaultSize.y )
SetSize( wxSize(275,360) );
else
SetSize(sz);
#endif
return res;
}
// -----------------------------------------------------------------------
int wxPGArrayEditorDialog::GetSelection() const
{
wxListCtrl* lc = m_elb->GetListCtrl();
int index = lc->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if ( index == -1 )
return wxNOT_FOUND;
return index;
}
// -----------------------------------------------------------------------
void wxPGArrayEditorDialog::OnAddClick(wxCommandEvent& event)
{
wxListCtrl* lc = m_elb->GetListCtrl();
int newItemIndex = lc->GetItemCount() - 1;
if ( m_hasCustomNewAction )
{
wxString str;
if ( OnCustomNewAction(&str) )
{
if ( ArrayInsert(str, newItemIndex) )
{
lc->InsertItem(newItemIndex, str);
m_modified = true;
}
}
// Do *not* skip the event! We do not want the wxEditableListBox
// to do anything.
}
else
{
m_itemPendingAtIndex = newItemIndex;
event.Skip();
}
}
// -----------------------------------------------------------------------
void wxPGArrayEditorDialog::OnDeleteClick(wxCommandEvent& event)
{
int index = GetSelection();
if ( index >= 0 )
{
ArrayRemoveAt( index );
m_modified = true;
}
event.Skip();
}
// -----------------------------------------------------------------------
void wxPGArrayEditorDialog::OnUpClick(wxCommandEvent& event)
{
int index = GetSelection();
if ( index > 0 )
{
ArraySwap(index-1,index);
m_modified = true;
}
event.Skip();
}
// -----------------------------------------------------------------------
void wxPGArrayEditorDialog::OnDownClick(wxCommandEvent& event)
{
wxListCtrl* lc = m_elb->GetListCtrl();
int index = GetSelection();
int lastStringIndex = lc->GetItemCount() - 1;
if ( index >= 0 && index < lastStringIndex )
{
ArraySwap(index, index+1);
m_modified = true;
}
event.Skip();
}
// -----------------------------------------------------------------------
void wxPGArrayEditorDialog::OnEndLabelEdit(wxListEvent& event)
{
wxString str = event.GetLabel();
if ( m_itemPendingAtIndex >= 0 )
{
// Add a new item
if ( ArrayInsert(str, m_itemPendingAtIndex) )
{
m_modified = true;
}
else
{
// Editable list box doesn't really respect Veto(), but
// it recognizes if no text was added, so we simulate
// Veto() using it.
event.m_item.SetText(wxEmptyString);
m_elb->GetListCtrl()->SetItemText(m_itemPendingAtIndex,
wxEmptyString);
event.Veto();
}
}
else
{
// Change an existing item
int index = GetSelection();
wxASSERT( index != wxNOT_FOUND );
if ( ArraySet(index, str) )
m_modified = true;
else
event.Veto();
}
event.Skip();
}
#endif // wxUSE_EDITABLELISTBOX
// -----------------------------------------------------------------------
// wxPGArrayStringEditorDialog
// -----------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxPGArrayStringEditorDialog, wxPGArrayEditorDialog)
BEGIN_EVENT_TABLE(wxPGArrayStringEditorDialog, wxPGArrayEditorDialog)
END_EVENT_TABLE()
// -----------------------------------------------------------------------
wxString wxPGArrayStringEditorDialog::ArrayGet( size_t index )
{
return m_array[index];
}
size_t wxPGArrayStringEditorDialog::ArrayGetCount()
{
return m_array.size();
}
bool wxPGArrayStringEditorDialog::ArrayInsert( const wxString& str, int index )
{
if (index<0)
m_array.Add(str);
else
m_array.Insert(str,index);
return true;
}
bool wxPGArrayStringEditorDialog::ArraySet( size_t index, const wxString& str )
{
m_array[index] = str;
return true;
}
void wxPGArrayStringEditorDialog::ArrayRemoveAt( int index )
{
m_array.RemoveAt(index);
}
void wxPGArrayStringEditorDialog::ArraySwap( size_t first, size_t second )
{
wxString old_str = m_array[first];
wxString new_str = m_array[second];
m_array[first] = new_str;
m_array[second] = old_str;
}
wxPGArrayStringEditorDialog::wxPGArrayStringEditorDialog()
: wxPGArrayEditorDialog()
{
Init();
}
void wxPGArrayStringEditorDialog::Init()
{
m_pCallingClass = NULL;
}
bool
wxPGArrayStringEditorDialog::OnCustomNewAction(wxString* resString)
{
return m_pCallingClass->OnCustomStringEdit(m_parent, *resString);
}
// -----------------------------------------------------------------------
// wxArrayStringProperty
// -----------------------------------------------------------------------
WX_PG_IMPLEMENT_PROPERTY_CLASS(wxArrayStringProperty, // Property name
wxPGProperty, // Property we inherit from
wxArrayString, // Value type name
const wxArrayString&, // Value type, as given in constructor
TextCtrlAndButton) // Initial editor
wxArrayStringProperty::wxArrayStringProperty( const wxString& label,
const wxString& name,
const wxArrayString& array )
: wxPGProperty(label,name)
{
m_delimiter = ',';
SetValue( array );
}
wxArrayStringProperty::~wxArrayStringProperty() { }
void wxArrayStringProperty::OnSetValue()
{
GenerateValueAsString();
}
void
wxArrayStringProperty::ConvertArrayToString(const wxArrayString& arr,
wxString* pString,
const wxUniChar& delimiter) const
{
if ( delimiter == '"' || delimiter == '\'' )
{
// Quoted strings
ArrayStringToString(*pString,
arr,
delimiter,
Escape | QuoteStrings);
}
else
{
// Regular delimiter
ArrayStringToString(*pString,
arr,
delimiter,
0);
}
}
wxString wxArrayStringProperty::ValueToString( wxVariant& WXUNUSED(value),
int argFlags ) const
{
//
// If this is called from GetValueAsString(), return cached string
if ( argFlags & wxPG_VALUE_IS_CURRENT )
{
return m_display;
}
wxArrayString arr = m_value.GetArrayString();
wxString s;
ConvertArrayToString(arr, &s, m_delimiter);
return s;
}
// Converts wxArrayString to a string separated by delimeters and spaces.
// preDelim is useful for "str1" "str2" style. Set flags to 1 to do slash
// conversion.
void
wxArrayStringProperty::ArrayStringToString( wxString& dst,
const wxArrayString& src,
wxUniChar delimiter, int flags )
{
wxString pdr;
wxString preas;
unsigned int i;
unsigned int itemCount = src.size();
dst.Empty();
if ( flags & Escape )
{
preas = delimiter;
pdr = wxS("\\") + static_cast<wchar_t>(delimiter);
}
if ( itemCount )
dst.append( preas );
wxString delimStr(delimiter);
for ( i = 0; i < itemCount; i++ )
{
wxString str( src.Item(i) );
// Do some character conversion.
// Converts \ to \\ and $delimiter to \$delimiter
// Useful when quoting.
if ( flags & Escape )
{
str.Replace( wxS("\\"), wxS("\\\\"), true );
if ( !pdr.empty() )
str.Replace( preas, pdr, true );
}
dst.append( str );
if ( i < (itemCount-1) )
{
dst.append( delimStr );
dst.append( wxS(" ") );
dst.append( preas );
}
else if ( flags & QuoteStrings )
dst.append( delimStr );
}
}
void wxArrayStringProperty::GenerateValueAsString()
{
wxArrayString arr = m_value.GetArrayString();
ConvertArrayToString(arr, &m_display, m_delimiter);
}
// Default implementation doesn't do anything.
bool wxArrayStringProperty::OnCustomStringEdit( wxWindow*, wxString& )
{
return false;
}
wxPGArrayEditorDialog* wxArrayStringProperty::CreateEditorDialog()
{
return new wxPGArrayStringEditorDialog();
}
bool wxArrayStringProperty::OnButtonClick( wxPropertyGrid* propGrid,
wxWindow* WXUNUSED(primaryCtrl),
const wxChar* cbt )
{
// Update the value
wxVariant useValue = propGrid->GetUncommittedPropertyValue();
if ( !propGrid->EditorValidate() )
return false;
// Create editor dialog.
wxPGArrayEditorDialog* dlg = CreateEditorDialog();
#if wxUSE_VALIDATORS
wxValidator* validator = GetValidator();
wxPGInDialogValidator dialogValidator;
#endif
wxPGArrayStringEditorDialog* strEdDlg = wxDynamicCast(dlg, wxPGArrayStringEditorDialog);
if ( strEdDlg )
strEdDlg->SetCustomButton(cbt, this);
dlg->SetDialogValue( useValue );
dlg->Create(propGrid, wxEmptyString, m_label);
#if !wxPG_SMALL_SCREEN
dlg->Move( propGrid->GetGoodEditorDialogPosition(this,dlg->GetSize()) );
#endif
bool retVal;
for (;;)
{
retVal = false;
int res = dlg->ShowModal();
if ( res == wxID_OK && dlg->IsModified() )
{
wxVariant value = dlg->GetDialogValue();
if ( !value.IsNull() )
{
wxArrayString actualValue = value.GetArrayString();
wxString tempStr;
ConvertArrayToString(actualValue, &tempStr, m_delimiter);
#if wxUSE_VALIDATORS
if ( dialogValidator.DoValidate(propGrid, validator,
tempStr) )
#endif
{
SetValueInEvent( actualValue );
retVal = true;
break;
}
}
else
break;
}
else
break;
}
delete dlg;
return retVal;
}
bool wxArrayStringProperty::OnEvent( wxPropertyGrid* propGrid,
wxWindow* primary,
wxEvent& event )
{
if ( propGrid->IsMainButtonEvent(event) )
return OnButtonClick(propGrid,primary,(const wxChar*) NULL);
return false;
}
bool wxArrayStringProperty::StringToValue( wxVariant& variant,
const wxString& text, int ) const
{
wxArrayString arr;
if ( m_delimiter == '"' || m_delimiter == '\'' )
{
// Quoted strings
WX_PG_TOKENIZER2_BEGIN(text, m_delimiter)
// Need to replace backslashes with empty characters
// (opposite what is done in ConvertArrayToString()).
token.Replace ( wxS("\\\\"), wxS("\\"), true );
arr.Add( token );
WX_PG_TOKENIZER2_END()
}
else
{
// Regular delimiter
WX_PG_TOKENIZER1_BEGIN(text, m_delimiter)
arr.Add( token );
WX_PG_TOKENIZER1_END()
}
variant = arr;
return true;
}
bool wxArrayStringProperty::DoSetAttribute( const wxString& name, wxVariant& value )
{
if ( name == wxPG_ARRAY_DELIMITER )
{
m_delimiter = value.GetChar();
GenerateValueAsString();
return false;
}
return true;
}
// -----------------------------------------------------------------------
// wxPGInDialogValidator
// -----------------------------------------------------------------------
#if wxUSE_VALIDATORS
bool wxPGInDialogValidator::DoValidate( wxPropertyGrid* propGrid,
wxValidator* validator,
const wxString& value )
{
if ( !validator )
return true;
wxTextCtrl* tc = m_textCtrl;
if ( !tc )
{
{
tc = new wxTextCtrl( propGrid, wxPG_SUBID_TEMP1, wxEmptyString,
wxPoint(30000,30000));
tc->Hide();
}
m_textCtrl = tc;
}
tc->SetValue(value);
validator->SetWindow(tc);
bool res = validator->Validate(propGrid);
return res;
}
#else
bool wxPGInDialogValidator::DoValidate( wxPropertyGrid* WXUNUSED(propGrid),
wxValidator* WXUNUSED(validator),
const wxString& WXUNUSED(value) )
{
return true;
}
#endif
// -----------------------------------------------------------------------
#endif // wxUSE_PROPGRID
| 26.638344 | 113 | 0.543388 | wivlaro |
1466dc0b97163b96047137c89eac3c31e1a69ef2 | 9,418 | cc | C++ | randen_test.cc | google/randen | 717ced67384bde1dd371589566bbc294fc42e20a | [
"Apache-2.0"
] | 302 | 2018-04-13T19:10:20.000Z | 2022-01-07T19:46:29.000Z | randen_test.cc | google/randen | 717ced67384bde1dd371589566bbc294fc42e20a | [
"Apache-2.0"
] | 8 | 2018-05-03T00:02:43.000Z | 2020-04-17T13:27:52.000Z | randen_test.cc | google/randen | 717ced67384bde1dd371589566bbc294fc42e20a | [
"Apache-2.0"
] | 24 | 2018-05-03T01:00:42.000Z | 2020-10-13T17:00:41.000Z | // Copyright 2017 Google 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 "randen.h"
#include <stdio.h>
#include <algorithm>
#include <random> // seed_seq
#include <sstream>
#define UPDATE_GOLDEN 0
#define ENABLE_VERIFY 1
#define ENABLE_DUMP 0
namespace randen {
namespace {
#define STR(x) #x
#define ASSERT_TRUE(condition) \
do { \
if (!(condition)) { \
printf("Assertion [" STR(condition) "] failed on line %d\n", __LINE__); \
abort(); \
} \
} while (false)
using EngRanden = Randen<uint64_t>;
#if ENABLE_VERIFY
void VerifyReseedChangesAllValues() {
const size_t kNumOutputs = 127;
EngRanden engine;
std::seed_seq seq1{1, 2, 3, 4, 5, 6, 7};
engine.seed(seq1);
uint64_t out1[kNumOutputs];
for (size_t i = 0; i < kNumOutputs; ++i) {
out1[i] = engine();
}
std::seed_seq seq2{127, 255, 511};
engine.seed(seq2);
uint64_t out2[kNumOutputs];
engine.seed(seq2);
for (size_t i = 0; i < kNumOutputs; ++i) {
out2[i] = engine();
ASSERT_TRUE(out2[i] != out1[i]);
}
}
void VerifyDiscard() {
const int N = 56; // two buffer's worth
for (int num_used = 0; num_used < N; ++num_used) {
EngRanden engine_used;
for (int i = 0; i < num_used; ++i) {
(void)engine_used();
}
for (int num_discard = 0; num_discard < N; ++num_discard) {
EngRanden engine1 = engine_used;
EngRanden engine2 = engine_used;
for (int i = 0; i < num_discard; ++i) {
(void)engine1();
}
engine2.discard(num_discard);
for (int i = 0; i < N; ++i) {
const uint64_t r1 = engine1();
const uint64_t r2 = engine2();
ASSERT_TRUE(r1 == r2);
}
}
}
}
void VerifyGolden() {
// prime number => some buffer values unused.
const size_t kNumOutputs = 127;
#if UPDATE_GOLDEN
EngRanden engine;
for (size_t i = 0; i < kNumOutputs; ++i) {
printf("0x%016lx,\n", engine());
}
printf("\n");
#else
const uint64_t golden[kNumOutputs] = {
0xdda9f47cd90410ee, 0xc3c14f134e433977, 0xf0b780f545c72912,
0x887bf3087fd8ca10, 0x30ec63baff3c6d59, 0x15dbb1d37696599f,
0x02808a316f49a54c, 0xb29f73606f7f20a6, 0x9cbf605e3fd9de8a,
0x3b8feaf9d5c8e50e, 0xd8b2ffd356301ed5, 0xc970ae1a78183bbb,
0xcdfd8d76eb8f9a19, 0xf4b327fe0fc73c37, 0xd5af05dd3eff9556,
0xc3a506eb91420c9d, 0x7023920e0d6bfe8c, 0x48db1bb78f83c4a1,
0xed1ef4c26b87b840, 0x58d3575834956d42, 0x497cabf3431154fc,
0x8eef32a23e0b2df3, 0xd88b5749f090e5ea, 0x4e24370570029a8b,
0x78fcec2cbb6342f5, 0xc651a582a970692f, 0x352ee4ad1816afe3,
0x463cb745612f55db, 0x811ef0821c3de851, 0x026ff374c101da7e,
0xa0660379992d58fc, 0x6f7e616704c4fa59, 0x915f3445685da798,
0x04b0a374a3b795c7, 0x4663352533ce1882, 0x26802a8ac76571ce,
0x5588ba3a4d6e6c51, 0xb9fdefb4a24dc738, 0x607195a5e200f5fd,
0xa2101a42d35f1956, 0xe1e5e03c759c0709, 0x7e100308f3290764,
0xcbcf585399e432f1, 0x082572cc5da6606f, 0x0904469acbfee8f2,
0xe8a2be4f8335d8f1, 0x08e8a1f1a69da69a, 0xf08bd31b6daecd51,
0x2e9705bb053d6b46, 0x6542a20aad57bff5, 0x78e3a810213b6ffb,
0xda2fc9db0713c391, 0xc0932718cd55781f, 0xdc16a59cdd85f8a6,
0xb97289c1be0f2f9c, 0xb9bfb29c2b20bfe5, 0x5524bb834771435b,
0xc0a2a0e403a892d4, 0xff4af3ab8d1b78c5, 0x8265da3d39d1a750,
0x66e455f627495189, 0xf0ec5f424bcad77f, 0x3424e47dc22596e3,
0xc82d3120b57e3270, 0xc191c595afc4dcbf, 0xbc0c95129ccedcdd,
0x7f90650ea6cd6ab4, 0x120392bd2bb70939, 0xa7c8fac5a7917eb0,
0x7287491832695ad3, 0x7c1bf9839c7c1ce5, 0xd088cb9418be0361,
0x78565cdefd28c4ad, 0xe2e991fa58e1e79e, 0x2a9eac28b08c96bf,
0x7351b9fef98bafad, 0x13a685861bab87e0, 0x6c4f179696cb2225,
0x30537425cac70991, 0x64c6de5aa0501971, 0x7e05e3aa8ec720dc,
0x01590d9dc6c532b7, 0x738184388f3bc1d2, 0x74a07d9c54e3e63f,
0x6bcdf185561f255f, 0x26ffdc5067be3acb, 0x171df81934f68604,
0xa0eaf2e1cf99b1c6, 0x5d1cb02075ba1cea, 0x7ea5a21665683e5a,
0xba6364eff80de02f, 0x957f38cbd2123fdf, 0x892d8317de82f7a2,
0x606e0a0e41d452ee, 0x4eb28826766fcf5b, 0xe707b1db50f7b43e,
0x6ee217df16527d78, 0x5a362d56e80a0951, 0x443e63857d4076ca,
0xf6737962ba6b23dd, 0xd796b052151ee94d, 0x790d9a5f048adfeb,
0x8b833ff84893da5d, 0x033ed95c12b04a03, 0x9877c4225061ca76,
0x3d6724b1bb15eab9, 0x42e5352fe30ce989, 0xd68d6810adf74fb3,
0x3cdbf7e358df4b8b, 0x265b565a7431fde7, 0x52d2242f65b37f88,
0x2922a47f6d3e8779, 0x29d40f00566d5e26, 0x5d836d6e2958d6b5,
0x6c056608b7d9c1b6, 0x288db0e1124b14a0, 0x8fb946504faa6c9d,
0x0b9471bdb8f19d32, 0xfd1fe27d144a09e0, 0x8943a9464540251c,
0x8048f217633fce36, 0xea6ac458da141bda, 0x4334b8b02ff7612f,
0xfeda1384ade74d31, 0x096d119a3605c85b, 0xdbc8441f5227e216,
0x541ad7efa6ddc1d3};
EngRanden engine;
for (size_t i = 0; i < kNumOutputs; ++i) {
ASSERT_TRUE(golden[i] == engine());
}
#endif
}
#endif // ENABLE_VERIFY
void VerifyRandReqEngine() {
// Validates that Randen satisfies [rand.req.engine].
// Names after definition of [rand.req.engine] in C++ standard.
// e is a value of E
// v is a lvalue of E
// x, y are possibly const values of E
// s is a value of T
// q is a value satisfying requirements of seed_sequence
// z is a value of type unsigned long long
// os is a some specialization of basic_ostream
// is is a some specialization of basic_istream
using E = EngRanden;
using T = typename EngRanden::result_type;
static_assert(std::is_copy_constructible<E>::value,
"Randen must be copy constructible");
static_assert(std::is_copy_assignable<E>::value,
"Randen must be copy assignable");
E e, v;
const E x, y;
T s = 1;
std::seed_seq q{1, 2, 3};
unsigned long long z = 1; // NOLINT(runtime/int)
std::wostringstream os;
std::wistringstream is;
E{};
E{x};
E{s};
E{q};
// Verify that seed() and default-construct is identical.
e.seed();
{
E f;
ASSERT_TRUE(e == f);
}
// Verify the seed() result type.
static_assert(std::is_same<decltype(e.seed(s)), void>::value,
"return type of seed() must be void");
static_assert(std::is_same<decltype(e.seed(q)), void>::value,
"return type of seed() must be void");
// verify that seed via seed_sequence and construct via seed_sequence
// is identical.
e.seed(q);
{
E f{q};
ASSERT_TRUE(e == f);
}
// Verify the operator() result type.
static_assert(std::is_same<decltype(e()), T>::value,
"return type of operator() must be result_type");
// Verify that once the state has advanced that the engines
// are no longer equal.
e();
{
E f{q};
ASSERT_TRUE(e != f);
}
{
E f;
ASSERT_TRUE(e != f);
}
// Verify discard.
e.discard(z);
{
// The state equivalence should change.
E f, g;
f.discard(2);
ASSERT_TRUE(f != g);
g();
g();
ASSERT_TRUE(f == g);
}
// Verify operator == result types.
static_assert(std::is_same<decltype(x == y), bool>::value,
"return type of operator== must be bool");
static_assert(std::is_same<decltype(x != y), bool>::value,
"return type of operator!= must be bool");
// Verify operator<<() result.
{
auto& os2 = (os << e);
ASSERT_TRUE(&os2 == &os);
}
// Verify operator>>() result.
{
auto& is2 = (is >> e);
ASSERT_TRUE(&is2 == &is);
}
}
void VerifyStreamOperators() {
EngRanden engine1(171);
EngRanden engine2;
{
std::stringstream stream;
stream << engine1;
stream >> engine2;
}
const int N = 56; // two buffer's worth
for (int i = 0; i < N; ++i) {
const uint64_t r1 = engine1();
const uint64_t r2 = engine2();
ASSERT_TRUE(r1 == r2);
}
}
void Verify() {
#if ENABLE_VERIFY
VerifyReseedChangesAllValues();
VerifyDiscard();
VerifyGolden();
VerifyRandReqEngine();
VerifyStreamOperators();
#endif
}
void DumpOutput() {
#if ENABLE_DUMP
const size_t kNumOutputs = 1500 * 1000 * 1000;
std::vector<uint64_t> outputs(kNumOutputs);
EngRanden engine;
for (size_t i = 0; i < kNumOutputs; ++i) {
outputs[i] = engine();
}
FILE* f = fopen("/tmp/randen.bin", "wb");
if (f != nullptr) {
fwrite(outputs.data(), kNumOutputs, 8, f);
fclose(f);
}
#endif // ENABLE_DUMP
}
void RunAll() {
// Immediately output any results (for non-local runs).
setvbuf(stdout, nullptr, _IONBF, 0);
Verify();
DumpOutput();
}
} // namespace
} // namespace randen
int main(int argc, char* argv[]) {
randen::RunAll();
return 0;
}
| 29.616352 | 79 | 0.657995 | google |
1467992010877e2598b28a9a8bfb77bcf13c0d3d | 6,259 | cpp | C++ | rapid_generator/src/rapid_emitter.cpp | gavanderhoorn/abb_file_suite | 333a0d76ef229b09e9a6b36b5243ba6fa00bf5df | [
"Apache-2.0"
] | 4 | 2016-06-10T21:59:01.000Z | 2020-07-15T13:37:23.000Z | rapid_generator/src/rapid_emitter.cpp | gavanderhoorn/abb_file_suite | 333a0d76ef229b09e9a6b36b5243ba6fa00bf5df | [
"Apache-2.0"
] | null | null | null | rapid_generator/src/rapid_emitter.cpp | gavanderhoorn/abb_file_suite | 333a0d76ef229b09e9a6b36b5243ba6fa00bf5df | [
"Apache-2.0"
] | 5 | 2016-12-18T19:55:41.000Z | 2019-02-26T08:38:11.000Z | #include "rapid_generator/rapid_emitter.h"
#include <iostream>
bool rapid_emitter::emitRapidFile(std::ostream& os, const std::vector<TrajectoryPt>& points,
size_t startProcessMotion, size_t endProcessMotion,
const ProcessParams& params)
{
// Write header
os << "MODULE mGodel_Blend\n\n";
// Emit all of the joint points
for (std::size_t i = 0; i < points.size(); ++i)
{
emitJointPosition(os, points[i], i);
}
// Emit Process Declarations
emitProcessDeclarations(os, params, 1);
// Write beginning of procedure
os << "\nPROC Godel_Blend()\n";
// For 0 to lengthFreeMotion, emit free moves
for (std::size_t i = 0; i < startProcessMotion; ++i)
{
if (i == 0)
emitFreeMotion(os, params, i, 0.0, true);
else if (i == (startProcessMotion - 1))
emitFreeMotion(os, params, i, points[i].duration_, true);
else
emitFreeMotion(os, params, i, points[i].duration_, false);
}
// Turn on the tool
emitSetOutput(os, params, 1);
// for lengthFreeMotion to end of points, emit grind moves
for (std::size_t i = startProcessMotion; i < endProcessMotion; ++i)
{
if (i == startProcessMotion)
{
emitGrindMotion(os, params, i, true, false);
}
else if (i == endProcessMotion - 1)
{
emitGrindMotion(os, params, i, false, true);
}
else
{
emitGrindMotion(os, params, i);
}
}
// Turn off the tool
emitSetOutput(os, params, 0);
// for lengthFreeMotion to end of points, emit grind moves
for (std::size_t i = endProcessMotion; i < points.size(); ++i)
{
if (i == endProcessMotion)
emitFreeMotion(os, params, i, 0.0, true);
else if (i == (points.size() - 1))
emitFreeMotion(os, params, i, points[i].duration_, true);
else
emitFreeMotion(os, params, i, points[i].duration_, false);
}
os << "EndProc\n";
// write any footers including main procedure calling the above
os << "ENDMODULE\n";
return true;
}
bool rapid_emitter::emitGrindMotion(std::ostream& os, const ProcessParams& params, size_t n,
bool start, bool end)
{
// The 'fine' zoning means the robot will stop at this point
// Note that 'wolf_mode' indicates the presence of WolfWare software for the ABB which has
// a sepcial instruction called the 'GrindL'. This encapsulates both a robot motion and the
// state of a tool as it moves through the path. The 'Start' and 'End' varieties handle I/O.
if (params.wolf_mode)
{
if (start)
{
os << "GrindLStart CalcRobT(jTarget_" << n << ",tool1), v100, gr1, fine, tool1;\n";
}
else if (end)
{
os << "GrindLEnd CalcRobT(jTarget_" << n << ",tool1), v100, fine, tool1;\n";
}
else
{
os << "GrindL CalcRobT(jTarget_" << n << ",tool1), v100, z40, tool1;\n";
}
}
else
{
os << "MoveL CalcRobT(jTarget_" << n << ",tool1), vProcessSpeed, z40, tool1;\n";
}
return os.good();
}
bool rapid_emitter::emitFreeMotion(std::ostream& os, const ProcessParams& params, size_t n,
double duration, bool stop_at)
{
// We want the robot to move smoothly and stop at the last point; these tolerances ensure that
// this happens
const char* zone = stop_at ? "fine" : "z20";
if (duration <= 0.0)
{
os << "MoveAbsJ jTarget_" << n << ", vMotionSpeed," << zone << ", tool1;\n";
}
else
{
os << "MoveAbsJ jTarget_" << n << ", vMotionSpeed, \\T:=" << duration << ", "
<< zone << ", tool1;\n";
}
return os.good();
}
bool rapid_emitter::emitJointPosition(std::ostream& os, const TrajectoryPt& pt, size_t n)
{
os << "TASK PERS jointtarget jTarget_" << n << ":=[[";
for (size_t i = 0; i < pt.positions_.size(); i++)
{
os << pt.positions_[i];
if (i < pt.positions_.size() - 1)
{
os << ",";
}
}
// We assume a six axis robot here.
os << "],[9E9,9E9,9E9,9E9,9E9,9E9]];\n";
return true;
}
bool rapid_emitter::emitSetOutput(std::ostream& os, const ProcessParams& params, size_t value)
{
// Wolf instructions handle I/O internally, so this method should do nothing
if (params.wolf_mode == false)
{
// This wait time is inserted here to ensure that the zone is achieved BEFORE the I/O happens
os << "WaitTime\\InPos, 0.01;\n";
os << "SETDO " << params.output_name << ", " << value << ";\n";
}
return os.good();
}
bool rapid_emitter::emitProcessDeclarations(std::ostream& os, const ProcessParams& params,
size_t value)
{
if (params.wolf_mode)
{
os << "TASK PERS grinddata gr1:=[" << params.tcp_speed << "," << params.spindle_speed << ","
<< params.slide_force << ",FALSE,FALSE,FALSE,0,0];\n";
}
else
{
// Process Speed
os << "CONST speeddata vProcessSpeed:=[" << params.tcp_speed << "," << params.tcp_speed
<< ",50,50];\n";
}
// Free motion speed
os << "CONST speeddata vMotionSpeed:=["
<< "200"
<< ","
<< "30"
<< ",500,500];\n";
return os.good();
}
bool rapid_emitter::emitJointTrajectoryFile(std::ostream& os,
const std::vector<TrajectoryPt>& points,
const ProcessParams& params)
{
// Write header
os << "MODULE mGodel_Blend\n\n";
// Emit all of the joint points
for (std::size_t i = 0; i < points.size(); ++i)
{
emitJointPosition(os, points[i], i);
}
// Emit Process Declarations
emitProcessDeclarations(os, params, 1);
// Write beginning of procedure
os << "\nPROC Godel_Blend()\n";
// For 0 to lengthFreeMotion, emit free moves
if (points.empty())
{
return false;
}
// Write first point as normal move abs j so that the robot gets to where it needs to be
emitFreeMotion(os, params, 0, 0.0, true);
// The second motion
for (std::size_t i = 1; i < points.size() - 1; ++i)
{
emitFreeMotion(os, params, i, points[i].duration_, false);
}
// Stop at the last point
emitFreeMotion(os, params, points.size() - 1, points.back().duration_, true);
os << "EndProc\n";
// write any footers including main procedure calling the above
os << "ENDMODULE\n";
return os.good();
}
| 29.663507 | 97 | 0.599776 | gavanderhoorn |
1468080503d3090a31225b98550633f2ecb4a482 | 16,622 | cpp | C++ | sdktools/debuggers/srcsrv/srcsrv.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | sdktools/debuggers/srcsrv/srcsrv.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | sdktools/debuggers/srcsrv/srcsrv.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 2002 Microsoft Corporation
Module Name:
srcsrv.cpp
Abstract:
This code obtaining version-controlled source.
Author:
patst
--*/
#include "pch.h"
BOOL gInitialized = false;
LIST_ENTRY gProcessList;
DWORD gProcessListCount = 0;
DWORD gOptions = 0;
BOOL
DllMain(
IN PVOID hdll,
IN ULONG reason,
IN PCONTEXT context OPTIONAL
)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return true;
}
BOOL error(DWORD err)
{
SetLastError(err);
return false;
}
PVOID MemAlloc(DWORD size)
{
PVOID rc;
rc = LocalAlloc(LPTR, size);
if (!rc)
return rc;
ZeroMemory(rc, size);
return rc;
}
void MemFree(PVOID p)
{
if (p)
LocalFree(p);
}
PPROCESS_ENTRY FindProcessEntry(HANDLE hp)
{
PLIST_ENTRY next;
PPROCESS_ENTRY pe;
DWORD count;
next = gProcessList.Flink;
if (!next)
return NULL;
for (count = 0; (PVOID)next != (PVOID)&gProcessList; count++)
{
assert(count < gProcessListCount);
if (count >= gProcessListCount)
return NULL;
pe = CONTAINING_RECORD(next, PROCESS_ENTRY, ListEntry);
next = pe->ListEntry.Flink;
if (pe->hProcess == hp)
return pe;
}
return NULL;
}
PPROCESS_ENTRY
FindFirstProcessEntry(
)
{
return CONTAINING_RECORD(gProcessList.Flink, PROCESS_ENTRY, ListEntry);
}
void
SendDebugString(
PPROCESS_ENTRY pe,
LPSTR sz
)
{
__try
{
if (!pe)
pe = FindFirstProcessEntry();
if (!pe || !pe->callback)
return;
pe->callback(SRCSRVACTION_TRACE, (DWORD64)sz, pe->context);
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
}
#define dprint ((gOptions & SRCSRVOPT_DEBUG) == SRCSRVOPT_DEBUG)&&_dprint
#define eprint ((gOptions & SRCSRVOPT_DEBUG) == SRCSRVOPT_DEBUG)&&_eprint
#define pdprint ((gOptions & SRCSRVOPT_DEBUG) == SRCSRVOPT_DEBUG)&&_pdprint
#define pdeprint ((gOptions & SRCSRVOPT_DEBUG) == SRCSRVOPT_DEBUG)&&_pdeprint
bool
_pdprint(
PPROCESS_ENTRY pe,
LPSTR format,
...
)
{
static char buf[1000] = "SRCSRV: ";
va_list args;
va_start(args, format);
_vsnprintf(buf+9, sizeof(buf)-9, format, args);
va_end(args);
SendDebugString(pe, buf);
return true;
}
bool
_peprint(
PPROCESS_ENTRY pe,
LPSTR format,
...
)
{
static char buf[1000] = "";
va_list args;
va_start(args, format);
_vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
SendDebugString(pe, buf);
return true;
}
bool
_dprint(
LPSTR format,
...
)
{
static char buf[1000] = "SRCSRV: ";
va_list args;
va_start(args, format);
_vsnprintf(buf+9, sizeof(buf)-9, format, args);
va_end(args);
SendDebugString(NULL, buf);
return true;
}
bool
_eprint(
LPSTR format,
...
)
{
static char buf[1000] = "";
va_list args;
va_start(args, format);
_vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
SendDebugString(NULL, buf);
return true;
}
void FreeModuleEntry(PPROCESS_ENTRY pe, PMODULE_ENTRY me)
{
MemFree(me->stream);
MemFree(me);
}
PMODULE_ENTRY
FindModuleEntry(
PPROCESS_ENTRY pe,
DWORD64 base
)
{
static PLIST_ENTRY next = NULL;
PMODULE_ENTRY me;
if (base == (DWORD64)-1)
{
if (!next)
return NULL;
if ((PVOID)next == (PVOID)&pe->ModuleList)
{
// Reset to NULL so the list can be re-walked
next = NULL;
return NULL;
}
me = CONTAINING_RECORD( next, MODULE_ENTRY, ListEntry );
next = me->ListEntry.Flink;
return me;
}
next = pe->ModuleList.Flink;
if (!next)
return NULL;
while ((PVOID)next != (PVOID)&pe->ModuleList)
{
me = CONTAINING_RECORD(next, MODULE_ENTRY, ListEntry);
next = me->ListEntry.Flink;
if (base == me->base)
return me;
}
return NULL;
}
char *
dotranslate(
PMODULE_ENTRY me,
char *input,
char *output,
DWORD outsize
)
{
int i;
char key[MAX_PATH + 1];
PVARIABLE var;
int cbkey;
char *s;
char *p;
assert(me && input && *input && output);
*output = 0;
for (i = 0, var = me->vars; i < me->cvars; i++, var++)
{
CopyStrArray(key, "${");
CatStrArray(key, var->key);
CatStrArray(key, "}");
cbkey = strlen(var->key) + 3;
for (s = input, p = strstr(s, key); p; s = p + cbkey, p = strstr(s, key))
{
CatNString(output, s, p - s, outsize);
CatString(output, var->val, outsize);
}
}
if (!*output)
CopyString(output, input, outsize);
return output;
}
#define translate(me, input, output) dotranslate(me, input, output, DIMA(output))
PSDFILE
find(
PMODULE_ENTRY me,
const char *file
)
{
int i;
PSDFILE sdf;
for (i = 0, sdf = me->sdfiles; i < me->cfiles; i++, sdf++)
{
if (!_strcmpi(sdf->path, file))
return sdf;
}
return NULL;
}
void
DumpModuleEntries(
PPROCESS_ENTRY pe
)
{
static PLIST_ENTRY next = NULL;
PMODULE_ENTRY me;
PVARIABLE vars;
PSDFILE sdfiles;
char path[MAX_PATH + 1];
char depot[MAX_PATH + 1];
char loc[MAX_PATH + 1];
next = pe->ModuleList.Flink;
if (!next)
return;
while ((PVOID)next != (PVOID)&pe->ModuleList)
{
me = CONTAINING_RECORD(next, MODULE_ENTRY, ListEntry);
dprint("%s 0x%x\n", me->name, me->base);
dprint("variables:\n");
for (vars = me->vars; vars->key; vars++)
dprint("%s=%s\n", vars->key, vars->val);
dprint("source depot files:\n");
for (sdfiles = me->sdfiles; sdfiles->path; sdfiles++)
{
translate(me, sdfiles->path, path);
translate(me, sdfiles->depot, depot);
translate(me, sdfiles->loc, loc);
dprint("%s %s %s\n", path, depot, loc);
}
eprint("\n");
next = me->ListEntry.Flink;
}
}
char *
GetLine(
char *sz
)
{
for (;*sz; sz++)
{
if (*sz == '\n' || *sz == '\r')
{
*sz++ = 0;
if (*sz == 10)
sz++;
return (*sz) ? sz : NULL;
}
}
return NULL;
}
int
SetBlock(
char *sz
)
{
static char *labels[blMax] =
{
"SRCSRV: end", // blNone
"SRCSRV: variables", // blVars
"SRCSRV: source files" // blSource
};
static int lens[blMax] =
{
sizeof("SRCSRV: end") / sizeof(char) -1 , // blNone
sizeof("SRCSRV: variables") / sizeof(char) -1 , // blVars
sizeof("SRCSRV: source files") / sizeof(char) -1 // blSource
};
int i;
char *label;
for (i = blNone; i < blMax; i++)
{
label = labels[i];
if (!strncmp(sz, label, lens[i]))
return i;
}
return blMax;
}
bool
ParseVars(
char *sz,
PVARIABLE var
)
{
char *p;
p = (strchr(sz, '='));
if (!p)
return false;
*p = 0;
var->key = sz;
var->val = p + 1;
return true;
}
bool
ParseSD(
char *sz,
PSDFILE sdfile
)
{
char *p;
char *g;
sz += 4;
p = (strchr(sz, '*'));
if (!p)
return false;
*p++ = 0;
g = (strchr(p, '*'));
if (!g)
return false;
*g++ = 0;
sdfile->path = sz;
sdfile->depot = p;
sdfile->loc = g;
return true;
}
BOOL
IndexStream(
PMODULE_ENTRY me
)
{
char *sz;
char *next;
int block;
int lines;
int bl;
PVARIABLE vars;
PSDFILE sdfiles;
// count the lines
for (sz = me->stream, lines = 0; *sz; sz++)
{
if (*sz == '\n')
lines++;
}
if (!lines)
return false;
me->vars = (PVARIABLE)MemAlloc(lines * sizeof(VARIABLE));
if (!me->vars)
return error(ERROR_NOT_ENOUGH_MEMORY);
me->sdfiles = (PSDFILE)MemAlloc(lines * sizeof(SDFILE));
if (!me->sdfiles)
return error(ERROR_NOT_ENOUGH_MEMORY);
block = blNone;
vars = me->vars;
sdfiles = me->sdfiles;
me->cfiles = 0;
me->cvars = 0;
for (sz = me->stream; sz; sz = next)
{
next = GetLine(sz);
bl = SetBlock(sz);
// dprint("%s\n", sz);
if (bl != blMax)
{
block = bl;
continue;
}
switch(block)
{
case blVars:
if (ParseVars(sz, vars))
{
vars++;
me->cvars++;
}
break;
case blSource:
if (ParseSD(sz, sdfiles))
{
sdfiles++;
me->cfiles++;
}
break;
}
}
#if 0
DumpIndexes(me);
#endif
return true;
}
DWORD
WINAPI
SrcSrvSetOptions(
DWORD opts
)
{
DWORD rc = gOptions;
gOptions = opts;
return rc;
}
DWORD
WINAPI
SrcSrvGetOptions(
)
{
return gOptions;
}
BOOL
WINAPI
SrcSrvInit(
HANDLE hProcess,
LPCSTR path
)
{
PPROCESS_ENTRY pe;
// test the path for copying files to...
if (!path || !*path)
return error(ERROR_INVALID_PARAMETER);
if (!EnsurePathExists(path, NULL, 0, TRUE))
return false;
if (!gInitialized)
{
gInitialized = true;
InitializeListHead(&gProcessList);
}
if (pe = FindProcessEntry(hProcess))
{
pe->cRefs++;
return error(ERROR_INVALID_HANDLE);
}
pe = (PPROCESS_ENTRY)MemAlloc(sizeof(PROCESS_ENTRY));
if (!pe)
return error(ERROR_NOT_ENOUGH_MEMORY);
pe->hProcess = hProcess;
pe->cRefs = 1;
CopyStrArray(pe->path, path);
gProcessListCount++;
InitializeListHead(&pe->ModuleList);
InsertTailList(&gProcessList, &pe->ListEntry);
return true;
}
BOOL
WINAPI
SrcSrvCleanup(
HANDLE hProcess
)
{
PPROCESS_ENTRY pe;
PLIST_ENTRY next;
PMODULE_ENTRY me;
pe = FindProcessEntry(hProcess);
if (!pe)
return error(ERROR_INVALID_HANDLE);
if (--pe->cRefs)
return true;
next = pe->ModuleList.Flink;
if (next)
{
while (next != &pe->ModuleList)
{
me = CONTAINING_RECORD(next, MODULE_ENTRY, ListEntry);
next = me->ListEntry.Flink;
FreeModuleEntry(pe, me);
}
}
RemoveEntryList(&pe->ListEntry);
MemFree(pe);
gProcessListCount--;
return true;
}
BOOL
WINAPI
SrcSrvSetTargetPath(
HANDLE hProcess,
LPCSTR path
)
{
PPROCESS_ENTRY pe;
pe = FindProcessEntry(hProcess);
if (!pe)
return error(ERROR_INVALID_HANDLE);
// test the path for copying files to...
if (!path || !*path)
return error(ERROR_INVALID_PARAMETER);
if (!EnsurePathExists(path, NULL, 0, TRUE))
return false;
// store the new path
CopyStrArray(pe->path, path);
return true;
}
BOOL
WINAPI
SrcSrvLoadModule(
HANDLE hProcess,
LPCSTR name,
DWORD64 base,
PVOID stream,
DWORD size
)
{
PPROCESS_ENTRY pe;
PMODULE_ENTRY me;
if (!base || !name || !*name || !stream || !*(PCHAR)stream || !size)
return error(ERROR_INVALID_PARAMETER);
pe = FindProcessEntry(hProcess);
if (!pe)
return error(ERROR_INVALID_PARAMETER);
me = FindModuleEntry(pe, base);
if (me)
SrcSrvUnloadModule(pe, base);
me = (PMODULE_ENTRY)MemAlloc(sizeof(MODULE_ENTRY));
if (!me)
return error(ERROR_NOT_ENOUGH_MEMORY);
me->base = base;
CopyStrArray(me->name, name);
me->stream = (char *)MemAlloc(size);
if (!me->stream)
{
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
goto error;
}
memcpy(me->stream, stream, size);
me->cbStream = size;
dprint(me->stream);
IndexStream(me);
InsertTailList(&pe->ModuleList, &me->ListEntry);
DumpModuleEntries(pe);
return true;
error:
FreeModuleEntry(pe, me);
return false;
}
BOOL
WINAPI
SrcSrvUnloadModule(
HANDLE hProcess,
DWORD64 base
)
{
PPROCESS_ENTRY pe;
PLIST_ENTRY next;
PMODULE_ENTRY me;
pe = FindProcessEntry(hProcess);
if (!pe)
return error(ERROR_INVALID_PARAMETER);
next = pe->ModuleList.Flink;
if (!next)
return error(ERROR_MOD_NOT_FOUND);
while (next != &pe->ModuleList)
{
me = CONTAINING_RECORD(next, MODULE_ENTRY, ListEntry);
if (me->base == base)
{
RemoveEntryList(next);
FreeModuleEntry(pe, me);
return true;
}
next = me->ListEntry.Flink;
}
return error(ERROR_MOD_NOT_FOUND);
}
BOOL
WINAPI
SrcSrvRegisterCallback(
HANDLE hProcess,
PSRCSRVCALLBACKPROC callback,
DWORD64 context
)
{
PPROCESS_ENTRY pe;
pe = FindProcessEntry(hProcess);
if (!pe)
return error(ERROR_INVALID_PARAMETER);
pe->callback = callback;
pe->context = context;
return true;
}
BOOL
WINAPI
SrcSrvGetFile(
HANDLE hProcess,
DWORD64 base,
LPCSTR filename,
LPSTR target,
DWORD trgsize
)
{
PPROCESS_ENTRY pe;
PMODULE_ENTRY me;
PSDFILE sdf;
char name[MAX_PATH + 1];
char ext[MAX_PATH + 1];
BOOL rc;
char depot[MAX_PATH + 1];
char loc[MAX_PATH + 1];
char cmd[MAX_PATH * 2];
STARTUPINFO si;
PROCESS_INFORMATION pi;
if (!base || !filename || !*filename || !target)
return error(ERROR_INVALID_PARAMETER);
*target = 0;
pe = FindProcessEntry(hProcess);
if (!pe)
return error(ERROR_INVALID_HANDLE);
me = FindModuleEntry(pe, base);
if (!me)
return error(ERROR_MOD_NOT_FOUND);
// get the matching file entry
sdf = find(me, filename);
if (!sdf)
return error(ERROR_FILE_NOT_FOUND);
// build the target path and command line for source depot
#if 0
_splitpath(filename, NULL, NULL, name, ext);
strcpy(target, pe->path); // SECURITY: Don't know size of target buffer.
EnsureTrailingBackslash(target);
strcat(target, name); // SECURITY: Don't know size of target buffer.
strcat(target, ext); // SECURITY: Don't know size of target buffer.
CreateTargetPath(pe, sdf, target);
#else
strcpy(target, pe->path); // SECURITY: Don't know size of target buffer.
EnsureTrailingBackslash(target);
_splitpath(filename, NULL, NULL, name, ext);
strcat(target, name); // SECURITY: Don't know size of target buffer.
if (*ext)
strcat(target, ext); // SECURITY: Don't know size of target buffer.
#endif
PrintString(cmd,
DIMA(cmd),
"sd.exe -p %s print -o %s -q %s",
translate(me, sdf->depot, depot),
target,
translate(me, sdf->loc, loc));
// execute the source depot command
ZeroMemory((void *)&si, sizeof(si));
rc = CreateProcess(NULL,
cmd,
NULL,
NULL,
false,
0,
NULL,
pe->path,
&si,
&pi);
if (!rc)
*target = 0;
return rc;
}
| 19.717675 | 82 | 0.511912 | npocmaka |
146932c4f16d0460bd1ae613ca1b5851eaed0b9a | 1,098 | cpp | C++ | Qualification_Round_2/Editorials/cutting_paper_tester.cpp | manojpandey/CodeSprint_India_2014 | 91ecfc9f565f20ae7517f556a0c414990a84e0d8 | [
"MIT"
] | null | null | null | Qualification_Round_2/Editorials/cutting_paper_tester.cpp | manojpandey/CodeSprint_India_2014 | 91ecfc9f565f20ae7517f556a0c414990a84e0d8 | [
"MIT"
] | null | null | null | Qualification_Round_2/Editorials/cutting_paper_tester.cpp | manojpandey/CodeSprint_India_2014 | 91ecfc9f565f20ae7517f556a0c414990a84e0d8 | [
"MIT"
] | 2 | 2015-07-25T11:44:07.000Z | 2019-07-14T11:33:48.000Z | #include<bits/stdc++.h>
using namespace std;
int mat[101][101];
void solve()
{
mat[0][0] = 0;
mat[0][1] = 0;
mat[1][0] = 0;
for(int i = 1; i <= 100; i++)
{
mat[i][1] = i;
mat[1][i] = i;
}
for(int i = 2; i <= 100; i++)
{
for(int j = 2; j <= 100; j++)
{
int min = i * j, val;
if(i == j)
{
min = 1;
}
else
{
for(int k = 1; k < i; k++)
{
val = mat[k][j] + mat[i - k][j];
if(val < min)
min = val;
}
for(int k = 1; k < j; k++)
{
val = mat[i][k] + mat[i][j - k];
if(val < min)
min = val;
}
}
mat[i][j] = min;
}
}
}
int main()
{
int n, x, y;
cin >> n;
solve();
for(int i = 0; i < n; i++)
{
cin >> x >> y;
cout << mat[x][y] << endl;
}
return 0;
} | 18.931034 | 52 | 0.264117 | manojpandey |
146b2ca80615a94883d57bae62be453d6153da8d | 3,825 | hpp | C++ | src/base/subscriber/EphemWriterSPK.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | src/base/subscriber/EphemWriterSPK.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | src/base/subscriber/EphemWriterSPK.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | //$Id$
//------------------------------------------------------------------------------
// EphemWriterSPK
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Author: Linda Jun / NASA
// Created: 2009/09/02
//
/**
* Writes a spacecraft orbit states or attitude to an ephemeris file in SPK format.
*/
//------------------------------------------------------------------------------
#ifndef EphemWriterSPK_hpp
#define EphemWriterSPK_hpp
#include "EphemerisWriter.hpp"
class SpiceOrbitKernelWriter;
class GMAT_API EphemWriterSPK : public EphemerisWriter
{
public:
EphemWriterSPK(const std::string &name, const std::string &type = "EphemWriterSPK");
virtual ~EphemWriterSPK();
EphemWriterSPK(const EphemWriterSPK &);
EphemWriterSPK& operator=(const EphemWriterSPK&);
// methods for this class
// Need to be able to close background SPKs and leave ready for appending
// Finalization
virtual void CloseEphemerisFile(bool done = true, bool writeMetaData = true);
virtual bool Initialize();
virtual EphemerisWriter* Clone(void) const;
virtual void Copy(const EphemerisWriter* orig);
protected:
SpiceOrbitKernelWriter *spkWriter; // owned object
bool spkWriteFailed;
/// number of SPK segments that have been written
Integer numSPKSegmentsWritten;
// Abstract methods required by all subclasses
virtual void BufferOrbitData(Real epochInDays, const Real state[6], const Real cov[21]);
// Initialization
virtual void CreateEphemerisFile(bool useDefaultFileName,
const std::string &stType,
const std::string &outFormat,
const std::string &covFormat);
void CreateSpiceKernelWriter();
// Data
virtual void HandleOrbitData();
virtual void StartNewSegment(const std::string &comments,
bool saveEpochInfo,
bool writeAfterData,
bool ignoreBlankComments);
virtual void FinishUpWriting();
void HandleWriteOrbit();
void HandleSpkOrbitData(bool writeData, bool timeToWrite);
void FinishUpWritingSPK();
// General writing
virtual void WriteHeader();
virtual void WriteMetaData();
virtual void WriteDataComments(const std::string &comments, bool isErrorMsg,
bool ignoreBlank = true, bool writeKeyword = true);
// SPK file writing
void WriteSpkHeader(); // This is for debug
void WriteSpkOrbitDataSegment();
void WriteSpkOrbitMetaData();
void WriteSpkComments(const std::string &comments);
void FinalizeSpkFile(bool done = true, bool writeMetaData = true);
// Event checking
bool IsEventFeasible(bool checkForNoData = true);
};
#endif // EphemWriterSPK_hpp
| 37.135922 | 91 | 0.614118 | IncompleteWorlds |
146bc487becac75c3f0629a658fd1aa5d58c7bcf | 13,052 | cpp | C++ | src/SwingCompiler.cpp | SilverJun/SWING | 0a9c35d74b3ec75d349a14a59e4d731dbd016069 | [
"MIT"
] | 8 | 2017-07-17T16:12:20.000Z | 2021-02-20T13:18:33.000Z | src/SwingCompiler.cpp | SilverJun/SWING | 0a9c35d74b3ec75d349a14a59e4d731dbd016069 | [
"MIT"
] | null | null | null | src/SwingCompiler.cpp | SilverJun/SWING | 0a9c35d74b3ec75d349a14a59e4d731dbd016069 | [
"MIT"
] | 1 | 2020-02-19T06:51:03.000Z | 2020-02-19T06:51:03.000Z | #include "SwingCompiler.h"
#include <fstream>
#include <sstream>
#include "llvm/Support/TargetSelect.h"
#include "Type.h"
#include "Method.h"
#include "StructType.h"
#include "ProtocolType.h"
#include <iostream>
#include "Error.h"
#include "FunctionDeclAST.h"
namespace swing
{
std::unique_ptr<SwingCompiler> SwingCompiler::_instance;
std::once_flag SwingCompiler::_InitInstance;
SwingCompiler::SwingCompiler() : _module("SwingCompiler", _llvmContext), _builder({ llvm::IRBuilder<>(_llvmContext) }), _src(nullptr)
{
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmParser();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetDisassembler();
/// built-in Operators
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Additive, { "+", TokenID::Arithmetic_Add, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Additive }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Additive, { "-", TokenID::Arithmetic_Subtract, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Additive }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "*", TokenID::Arithmetic_Multiply, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "/", TokenID::Arithmetic_Divide, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "%", TokenID::Arithmetic_Modulo, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative }));
//_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "**", TokenID::Arithmetic_Power, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Assignment, { "=", TokenID::Assignment, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Assignment }));
/*
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "&", TokenID::Bitwise_And, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "|", TokenID::Bitwise_Or, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "^", TokenID::Bitwise_Xor, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { ">>", TokenID::Bitwise_ShiftRight, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "<<", TokenID::Bitwise_ShiftLeft, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise }));
*/
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Logical, { "&&", TokenID::Logical_And, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Logical }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Logical, { "||", TokenID::Logical_Or, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Logical }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "==", TokenID::Relational_Equal, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "!=", TokenID::Relational_NotEqual, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { ">", TokenID::Relational_Greater, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { ">=", TokenID::Relational_GreaterEqual, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "<", TokenID::Relational_Less, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational }));
_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "<=", TokenID::Relational_LessEqual, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational }));
//_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Default, { "...", TokenID::Range_Closed, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Default }));
//_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Default, { "..<", TokenID::Range_Opened, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Default }));
_binOperators.insert(std::pair<int, OperatorType>(70, { "as", TokenID::Casting_As, OperatorType::OperatorLocation::Infix, 70 }));
_binOperators.insert(std::pair<int, OperatorType>(70, { "is", TokenID::Casting_Is, OperatorType::OperatorLocation::Infix, 70 }));
_binOperators.insert(std::pair<int, OperatorType>(80, { ".", TokenID::MemberReference, OperatorType::OperatorLocation::Infix, 80 }));
_preOperators.push_back(OperatorType("!", TokenID::Logical_Not, OperatorType::OperatorLocation::Prefix, OperatorType::Precedence_Logical));
_preOperators.push_back(OperatorType("-", TokenID::Arithmetic_Subtract, OperatorType::OperatorLocation::Prefix, OperatorType::Precedence_Multiplicative));
//_preOperators.push_back(OperatorType("~", TokenID::Bitwise_Not, OperatorType::OperatorLocation::Prefix, OperatorType::Precedence_Bitwise));
//_postOperators.push_back(OperatorType("?", TokenID::Optional_Nilable, OperatorType::OperatorLocation::Postfix, OperatorType::Precedence_Default));
//_postOperators.push_back(OperatorType("!", TokenID::Optional_Binding, OperatorType::OperatorLocation::Postfix, OperatorType::Precedence_Default));
}
std::vector<OperatorType*> SwingCompiler::FindOps(int precedenceLevel)
{
auto range = _binOperators.equal_range(precedenceLevel);
std::vector<OperatorType*> ops;
if (precedenceLevel >= OperatorType::Precedence_Max)
return ops;
for (auto value = range.first; value != range.second; ++value)
ops.push_back(&value->second);
return ops;
}
OperatorType* SwingCompiler::FindPreFixOp(std::string op)
{
for (auto value = _preOperators.begin(); value != _preOperators.end(); ++value)
{
if (value->_opString == op)
return &*value;
}
return nullptr;
}
OperatorType* SwingCompiler::FindPostFixOp(std::string op)
{
for (auto value = _postOperators.begin(); value != _postOperators.end(); ++value)
{
if (value->_opString == op)
return &*value;
}
return nullptr;
}
void SwingCompiler::AddOperator(OperatorType* op)
{
/// TODO : 기능 구현.
}
void SwingCompiler::AddFunction(std::string name, Method* func)
{
_functions[name] = func;
}
Method* SwingCompiler::GetFunction(std::string name)
{
return _functions[name];
}
void SwingCompiler::ImplementFunctionLazy(Method* method)
{
auto ast = new FunctionDeclAST();
ast->_method = method;
_src->_sourceAST.push_back(BaseAST::BasePtr(ast));
_src->_sourceAST.shrink_to_fit();
}
SwingCompiler* SwingCompiler::GetInstance()
{
std::call_once(_InitInstance, []()
{
_instance.reset(new SwingCompiler);
});
return _instance.get();
}
SwingCompiler::~SwingCompiler()
{
}
void SwingCompiler::Initialize()
{
/// built-in types
_types["void"] = Void;
_types["bool"] = Bool;
_types["char"] = Char;
_types["int"] = Int;
_types["float"] = Float;
_types["double"] = Double;
SwingTable::_localTable.push_back(&_globalTable);
std::string line;
std::fstream libfile = std::fstream(_swingPath + "libs.txt");
std::string libPath;
if (!libfile.is_open())
{
std::cout << "libs.txt is not open!"<< std::endl;
exit(1);
}
while (getline(libfile, line))
{
std::istringstream iss(line);
if (!(iss >> libPath) || line == "") continue;
_libs.push_back(libPath);
}
if (_libs.size() == 0)
{
std::cout << "libs.txt is empty!" << std::endl;
exit(1);
}
}
void SwingCompiler::PushIRBuilder(llvm::IRBuilder<> builder)
{
_builder.push_back(builder);
}
void SwingCompiler::PopIRBuilder()
{
_builder.pop_back();
}
llvm::Type * SwingCompiler::GetType(std::string name)
{
llvm::Type* type = nullptr;
type = _types[name];
if (type == nullptr)
{
_structs[name]->CreateStructType();
type = _types[name];
//type = _structs[name]->_type;
}
return type;
}
void SwingCompiler::BreakCurrentBlock()
{
if (_breakBlocks.size() == 0)
throw Error("Can't apply break statement, not in the loop.");
_breakBlocks.pop_back();
//_builder.back().CreateBr(_breakBlocks.back());
}
llvm::BasicBlock* SwingCompiler::GetEndBlock()
{
return _breakBlocks.back();
}
void SwingCompiler::CompileSource(std::string name, std::string output)
{
Initialize();
_src = new Source(name);
g_Module.setSourceFileName(_src->_name);
auto iter = name.rbegin();
for (; iter != name.rend(); ++iter)
{
if (*iter == '\\')
break;
}
_outputPath = output == "" ? std::string(iter.base(), name.end()) : output;
if (_outputPath.back() != '\\')
_outputPath.push_back('\\');
Lexer lex;
try
{
lex.LexSource(_src);
_src->Parse();
_src->CodeGen();
}
catch (LexicalError& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}
catch (ParsingError& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}
catch (Error& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}
/*catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}*/
/// llc
std::string cmd("llc");
cmd += ' ';
cmd += "-filetype=obj";
cmd += ' ';
cmd += _outputPath + "Test.ll";
cmd += ' ';
cmd += "-o " + _outputPath + "Test.obj";
system(cmd.c_str());
std::cout << "Successfully Compiled." << std::endl;
}
void SwingCompiler::LinkSource(std::string name, std::string output)
{
Initialize();
std::string cmd;
/// cl
cmd = "clang-cl";
cmd += ' ';
cmd += "-o" + _outputPath + "Test.exe";
cmd += ' ';
cmd += name;
cmd += ' ';
for (auto libPath : _libs)
{
cmd += libPath;
cmd += ' ';
}
system(cmd.c_str());
std::cout << "Successfully Linked." << std::endl;
cmd = _outputPath + "Test.exe";
int retval = system(cmd.c_str());
std::cout << std::endl;
std::cout << "SwingCompiler> Program Return " << retval << std::endl << std::endl;
}
void SwingCompiler::BuildSource(std::string name, std::string output)
{
Initialize();
_src = new Source(name);
g_Module.setSourceFileName(_src->_name);
auto iter = name.rbegin();
for (; iter != name.rend(); ++iter)
{
if (*iter == '\\')
break;
}
_outputPath = output == "" ? std::string(iter.base(), name.end()) : output;
if (_outputPath.back() != '\\')
_outputPath.push_back('\\');
Lexer lex;
try
{
lex.LexSource(_src);
_src->Parse();
_src->CodeGen();
}
catch (LexicalError& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}
catch (ParsingError& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}
catch (Error& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}
/*catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
system("pause");
exit(-1);
}*/
/// llc
std::string cmd("llc");
cmd += ' ';
cmd += "-filetype=obj";
cmd += ' ';
cmd += _outputPath + "Test.ll";
cmd += ' ';
cmd += "-o " + _outputPath + "Test.obj";
system(cmd.c_str());
/// cl
cmd = "clang-cl";
cmd += ' ';
cmd += "-o" + _outputPath + "Test.exe";
cmd += ' ';
cmd += _outputPath + "Test.obj";
cmd += ' ';
for (auto libPath : _libs)
{
cmd += libPath;
cmd += ' ';
}
system(cmd.c_str());
std::cout << "Successfully Built." << std::endl;
cmd = _outputPath + "Test.exe";
int retval = system(cmd.c_str());
std::cout << std::endl;
std::cout << "SwingCompiler> Program Return " << retval << std::endl << std::endl;
}
/*void SwingCompiler::CompileProject(Project* project, int optLevel, std::string outputFormat)
{
project->CompileProject(optLevel, outputFormat);
}
void SwingCompiler::LinkProject(Project* project)
{
project->LinkProject();
}
void SwingCompiler::BuildProject(Project* project)
{
CompileProject(project, 0, ".obj");
LinkProject(project);
}*/
}
| 31.990196 | 213 | 0.690699 | SilverJun |
146c552bb08d097cab3c561a85b5ec36e7bfe2d8 | 4,482 | cc | C++ | sdk/test/metrics/histogram_aggregator_test.cc | padmaja-nadkarni/opentelemetry-cpp | 4751ae5a29e5eeed1b775b7c337bdbe294165346 | [
"Apache-2.0"
] | 2 | 2020-06-26T15:26:35.000Z | 2020-06-28T16:47:35.000Z | sdk/test/metrics/histogram_aggregator_test.cc | padmaja-nadkarni/opentelemetry-cpp | 4751ae5a29e5eeed1b775b7c337bdbe294165346 | [
"Apache-2.0"
] | 3 | 2020-07-08T22:36:00.000Z | 2020-08-26T16:21:07.000Z | sdk/test/metrics/histogram_aggregator_test.cc | padmaja-nadkarni/opentelemetry-cpp | 4751ae5a29e5eeed1b775b7c337bdbe294165346 | [
"Apache-2.0"
] | 4 | 2020-05-27T22:08:57.000Z | 2020-05-29T19:13:11.000Z | #include "opentelemetry/sdk/metrics/aggregator/histogram_aggregator.h"
#include <gtest/gtest.h>
#include <iostream>
#include <numeric>
#include <thread>
// #include <chrono>
namespace metrics_api = opentelemetry::metrics;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace metrics
{
// Test updating with a uniform set of updates
TEST(Histogram, Uniform)
{
std::vector<double> boundaries{10, 20, 30, 40, 50};
HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries);
EXPECT_EQ(alpha.get_aggregator_kind(), AggregatorKind::Histogram);
alpha.checkpoint();
EXPECT_EQ(alpha.get_checkpoint().size(), 2);
EXPECT_EQ(alpha.get_counts().size(), 6);
for (int i = 0; i < 60; i++)
{
alpha.update(i);
}
alpha.checkpoint();
EXPECT_EQ(alpha.get_checkpoint()[0], 1770);
EXPECT_EQ(alpha.get_checkpoint()[1], 60);
std::vector<int> correct = {10, 10, 10, 10, 10, 10};
EXPECT_EQ(alpha.get_counts(), correct);
}
// Test updating with a normal distribution
TEST(Histogram, Normal)
{
std::vector<double> boundaries{2, 4, 6, 8, 10, 12};
HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries);
std::vector<int> vals{1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 11, 11, 13};
for (int i : vals)
{
alpha.update(i);
}
alpha.checkpoint();
EXPECT_EQ(alpha.get_checkpoint()[0], std::accumulate(vals.begin(), vals.end(), 0));
EXPECT_EQ(alpha.get_checkpoint()[1], vals.size());
std::vector<int> correct = {1, 2, 3, 4, 3, 2, 1};
EXPECT_EQ(alpha.get_counts(), correct);
}
TEST(Histogram, Merge)
{
std::vector<double> boundaries{2, 4, 6, 8, 10, 12};
HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries);
HistogramAggregator<int> beta(metrics_api::InstrumentKind::Counter, boundaries);
std::vector<int> vals{1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 11, 11, 13};
for (int i : vals)
{
alpha.update(i);
}
std::vector<int> otherVals{1, 1, 1, 1, 11, 11, 13, 13, 13, 15};
for (int i : otherVals)
{
beta.update(i);
}
alpha.merge(beta);
alpha.checkpoint();
EXPECT_EQ(alpha.get_checkpoint()[0], std::accumulate(vals.begin(), vals.end(), 0) +
std::accumulate(otherVals.begin(), otherVals.end(), 0));
EXPECT_EQ(alpha.get_checkpoint()[1], vals.size() + otherVals.size());
std::vector<int> correct = {5, 2, 3, 4, 3, 4, 5};
EXPECT_EQ(alpha.get_counts(), correct);
}
// Update callback used to validate multi-threaded performance
void histogramUpdateCallback(Aggregator<int> &agg, std::vector<int> vals)
{
for (int i : vals)
{
agg.update(i);
}
}
int randVal()
{
return rand() % 15;
}
TEST(Histogram, Concurrency)
{
std::vector<double> boundaries{2, 4, 6, 8, 10, 12};
HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries);
std::vector<int> vals1(1000);
std::generate(vals1.begin(), vals1.end(), randVal);
std::vector<int> vals2(1000);
std::generate(vals2.begin(), vals2.end(), randVal);
std::thread first(histogramUpdateCallback, std::ref(alpha), vals1);
std::thread second(histogramUpdateCallback, std::ref(alpha), vals2);
first.join();
second.join();
HistogramAggregator<int> beta(metrics_api::InstrumentKind::Counter, boundaries);
// Timing harness to compare linear and binary insertion
// auto start = std::chrono::system_clock::now();
for (int i : vals1)
{
beta.update(i);
}
for (int i : vals2)
{
beta.update(i);
}
// auto end = std::chrono::system_clock::now();
// auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
// std::cout <<"Update time: " <<elapsed.count() <<std::endl;
alpha.checkpoint();
beta.checkpoint();
EXPECT_EQ(alpha.get_checkpoint(), beta.get_checkpoint());
EXPECT_EQ(alpha.get_counts(), beta.get_counts());
}
#if __EXCEPTIONS
TEST(Histogram, Errors)
{
std::vector<double> boundaries{2, 4, 6, 8, 10, 12};
std::vector<double> boundaries2{1, 4, 6, 8, 10, 12};
std::vector<double> unsortedBoundaries{10, 12, 4, 6, 8};
EXPECT_ANY_THROW(
HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, unsortedBoundaries));
HistogramAggregator<int> beta(metrics_api::InstrumentKind::Counter, boundaries);
HistogramAggregator<int> gamma(metrics_api::InstrumentKind::Counter, boundaries2);
EXPECT_ANY_THROW(beta.merge(gamma));
}
#endif
} // namespace metrics
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE
| 26.678571 | 99 | 0.676261 | padmaja-nadkarni |
146f86d183582cec69a730b2040e6f7acad0f3f1 | 2,485 | cc | C++ | Source/Plugins/SubsystemPlugins/BladeGame/source/interface_imp/GameWorldData.cc | OscarGame/blade | 6987708cb011813eb38e5c262c7a83888635f002 | [
"MIT"
] | 146 | 2018-12-03T08:08:17.000Z | 2022-03-21T06:04:06.000Z | Source/Plugins/SubsystemPlugins/BladeGame/source/interface_imp/GameWorldData.cc | huangx916/blade | 3fa398f4d32215bbc7e292d61e38bb92aad1ee1c | [
"MIT"
] | 1 | 2019-01-18T03:35:49.000Z | 2019-01-18T03:36:08.000Z | Source/Plugins/SubsystemPlugins/BladeGame/source/interface_imp/GameWorldData.cc | huangx916/blade | 3fa398f4d32215bbc7e292d61e38bb92aad1ee1c | [
"MIT"
] | 31 | 2018-12-03T10:32:43.000Z | 2021-10-04T06:31:44.000Z | /********************************************************************
created: 2011/05/03
filename: GameWorldData.cc
author: Crazii
purpose:
*********************************************************************/
#include <BladePCH.h>
#include "GameWorldData.h"
#include <interface/public/graphics/IGraphicsScene.h>
#include <interface/public/graphics/IGraphicsSpaceCoordinator.h>
#include "GameWorld.h"
namespace Blade
{
const TString GameWorldData::GAME_WORLD_DATA_TYPE = BTString("GameWorldData");
const TString GameWorldData::WORLD_NAME = BTString("Name");
const TString GameWorldData::WORLD_SART_POS = BTString("StartPosition");
//////////////////////////////////////////////////////////////////////////
GameWorldData::GameWorldData()
:mScene(NULL)
,mCamera(NULL)
{
mStartPostition = Vector3::ZERO;
}
//////////////////////////////////////////////////////////////////////////
GameWorldData::~GameWorldData()
{
if(mScene != NULL && mScene->getSpaceCoordinator() != NULL)
mScene->getSpaceCoordinator()->setPositionReference(NULL);
}
/************************************************************************/
/* ISerializable interface */
/************************************************************************/
//////////////////////////////////////////////////////////////////////////
void GameWorldData::prepareSave()
{
mStartPostition = this->getPosition();
}
//////////////////////////////////////////////////////////////////////////
void GameWorldData::postProcess(const ProgressNotifier& /*callback*/)
{
if(mScene != NULL && mScene->getSpaceCoordinator() != NULL)
mScene->getSpaceCoordinator()->setPositionReference(this);
}
/************************************************************************/
/* custom methods */
/************************************************************************/
//////////////////////////////////////////////////////////////////////////
void GameWorldData::setGraphicsScene(IGraphicsScene* scene)
{
mScene = scene;
if(mScene != NULL && mScene->getSpaceCoordinator() != NULL)
mScene->getSpaceCoordinator()->setPositionReference(this);
}
//////////////////////////////////////////////////////////////////////////
void GameWorldData::onConfigChange(const void* data)
{
if( data == &mStartPostition )
{
}
}
}//namespace Blade
| 36.014493 | 98 | 0.426559 | OscarGame |
147078aff1c71200db88e86e829c6b4749d374c0 | 600 | cpp | C++ | All Codes/URI_1074.cpp | Habibu-R-ahman/URI-Online-Judge-Solutions | 62aa23f4bfcf9ea2a1054451c6380ed827816b3c | [
"MIT"
] | 12 | 2020-03-05T15:18:25.000Z | 2022-01-29T18:38:25.000Z | All Codes/URI_1074.cpp | junaid359/URI-Online-Judge-Solutions | f4f10c7e0649d233ce7757cbe7cb225b7845c5af | [
"MIT"
] | null | null | null | All Codes/URI_1074.cpp | junaid359/URI-Online-Judge-Solutions | f4f10c7e0649d233ce7757cbe7cb225b7845c5af | [
"MIT"
] | 19 | 2020-01-08T18:04:28.000Z | 2021-08-18T12:27:41.000Z | #include <iostream>
using namespace std;
int main() {
int i,j,k[10000];
cin >> j;
for (i=0; i<j; i++) {
cin >> k[i];
}
for (i=0; i<j; i++) {
if(k[i] == 0)
cout << "NULL" << endl;
else if (k[i]%2 == 0) {
if (k[i]>0)
cout << "EVEN POSITIVE" << endl;
else
cout << "EVEN NEGATIVE" << endl;
}
else if (k[i]%2 != 0) {
if(k[i]>0)
cout << "ODD POSITIVE" << endl;
else
cout << "ODD NEGATIVE" << endl;
}
}
return 0;
}
| 18.181818 | 48 | 0.358333 | Habibu-R-ahman |
1471da20d296f07168d10e313d63602c9ddc7654 | 15,291 | cpp | C++ | OsirisInventory/Memory.cpp | danielkrupinski/OsirisInventory | e4716de9b05d0c257a1733d96c503e64104b3657 | [
"MIT"
] | 31 | 2021-07-08T12:24:40.000Z | 2022-03-07T11:24:53.000Z | OsirisInventory/Memory.cpp | danielkrupinski/OsirisInventory | e4716de9b05d0c257a1733d96c503e64104b3657 | [
"MIT"
] | 21 | 2021-07-21T11:39:16.000Z | 2022-03-24T02:03:26.000Z | OsirisInventory/Memory.cpp | danielkrupinski/OsirisInventory | e4716de9b05d0c257a1733d96c503e64104b3657 | [
"MIT"
] | 8 | 2021-12-05T11:29:21.000Z | 2022-03-06T06:21:51.000Z | #include <algorithm>
#include <array>
#include <cassert>
#include <cstring>
#include <limits>
#include <string_view>
#include <utility>
#ifdef _WIN32
#include <Windows.h>
#include <Psapi.h>
#elif __linux__
#include <fcntl.h>
#include <link.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "Interfaces.h"
#include "Memory.h"
#include "SDK/LocalPlayer.h"
template <typename T>
static constexpr auto relativeToAbsolute(uintptr_t address) noexcept
{
return (T)(address + 4 + *reinterpret_cast<std::int32_t*>(address));
}
static std::pair<void*, std::size_t> getModuleInformation(const char* name) noexcept
{
#ifdef _WIN32
if (HMODULE handle = GetModuleHandleA(name)) {
if (MODULEINFO moduleInfo; GetModuleInformation(GetCurrentProcess(), handle, &moduleInfo, sizeof(moduleInfo)))
return std::make_pair(moduleInfo.lpBaseOfDll, moduleInfo.SizeOfImage);
}
return {};
#elif __linux__
struct ModuleInfo {
const char* name;
void* base = nullptr;
std::size_t size = 0;
} moduleInfo;
moduleInfo.name = name;
dl_iterate_phdr([](struct dl_phdr_info* info, std::size_t, void* data) {
const auto moduleInfo = reinterpret_cast<ModuleInfo*>(data);
if (!std::string_view{ info->dlpi_name }.ends_with(moduleInfo->name))
return 0;
if (const auto fd = open(info->dlpi_name, O_RDONLY); fd >= 0) {
if (struct stat st; fstat(fd, &st) == 0) {
if (const auto map = mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); map != MAP_FAILED) {
const auto ehdr = (ElfW(Ehdr)*)map;
const auto shdrs = (ElfW(Shdr)*)(std::uintptr_t(ehdr) + ehdr->e_shoff);
const auto strTab = (const char*)(std::uintptr_t(ehdr) + shdrs[ehdr->e_shstrndx].sh_offset);
for (auto i = 0; i < ehdr->e_shnum; ++i) {
const auto shdr = (ElfW(Shdr)*)(std::uintptr_t(shdrs) + i * ehdr->e_shentsize);
if (std::strcmp(strTab + shdr->sh_name, ".text") != 0)
continue;
moduleInfo->base = (void*)(info->dlpi_addr + shdr->sh_offset);
moduleInfo->size = shdr->sh_size;
munmap(map, st.st_size);
close(fd);
return 1;
}
munmap(map, st.st_size);
}
}
close(fd);
}
moduleInfo->base = (void*)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
moduleInfo->size = info->dlpi_phdr[0].p_memsz;
return 1;
}, &moduleInfo);
return std::make_pair(moduleInfo.base, moduleInfo.size);
#endif
}
[[nodiscard]] static auto generateBadCharTable(std::string_view pattern) noexcept
{
assert(!pattern.empty());
std::array<std::size_t, (std::numeric_limits<std::uint8_t>::max)() + 1> table;
auto lastWildcard = pattern.rfind('?');
if (lastWildcard == std::string_view::npos)
lastWildcard = 0;
const auto defaultShift = (std::max)(std::size_t(1), pattern.length() - 1 - lastWildcard);
table.fill(defaultShift);
for (auto i = lastWildcard; i < pattern.length() - 1; ++i)
table[static_cast<std::uint8_t>(pattern[i])] = pattern.length() - 1 - i;
return table;
}
static std::uintptr_t findPattern(const char* moduleName, std::string_view pattern, bool reportNotFound = true) noexcept
{
static auto id = 0;
++id;
const auto [moduleBase, moduleSize] = getModuleInformation(moduleName);
if (moduleBase && moduleSize) {
const auto lastIdx = pattern.length() - 1;
const auto badCharTable = generateBadCharTable(pattern);
auto start = static_cast<const char*>(moduleBase);
const auto end = start + moduleSize - pattern.length();
while (start <= end) {
int i = lastIdx;
while (i >= 0 && (pattern[i] == '?' || start[i] == pattern[i]))
--i;
if (i < 0)
return reinterpret_cast<std::uintptr_t>(start);
start += badCharTable[static_cast<std::uint8_t>(start[lastIdx])];
}
}
assert(false);
#ifdef _WIN32
if (reportNotFound)
MessageBoxA(nullptr, ("Failed to find pattern #" + std::to_string(id) + '!').c_str(), "Osiris", MB_OK | MB_ICONWARNING);
#endif
return 0;
}
Memory::Memory() noexcept
{
#ifdef _WIN32
present = findPattern("gameoverlayrenderer", "\xFF\x15????\x8B\xF0\x85\xFF") + 2;
reset = findPattern("gameoverlayrenderer", "\xC7\x45?????\xFF\x15????\x8B\xD8") + 9;
globalVars = **reinterpret_cast<GlobalVars***>((*reinterpret_cast<uintptr_t**>(interfaces->client))[11] + 10);
auto temp = reinterpret_cast<std::uintptr_t*>(findPattern(CLIENT_DLL, "\xB9????\xE8????\x8B\x5D\x08") + 1);
hud = *temp;
findHudElement = relativeToAbsolute<decltype(findHudElement)>(reinterpret_cast<uintptr_t>(temp) + 5);
clearHudWeapon = relativeToAbsolute<decltype(clearHudWeapon)>(findPattern(CLIENT_DLL, "\xE8????\x8B\xF0\xC6\x44\x24??\xC6\x44\x24") + 1);
itemSystem = relativeToAbsolute<decltype(itemSystem)>(findPattern(CLIENT_DLL, "\xE8????\x0F\xB7\x0F") + 1);
const auto tier0 = GetModuleHandleW(L"tier0");
debugMsg = reinterpret_cast<decltype(debugMsg)>(GetProcAddress(tier0, "Msg"));
conColorMsg = reinterpret_cast<decltype(conColorMsg)>(GetProcAddress(tier0, "?ConColorMsg@@YAXABVColor@@PBDZZ"));
equipWearable = reinterpret_cast<decltype(equipWearable)>(findPattern(CLIENT_DLL, "\x55\x8B\xEC\x83\xEC\x10\x53\x8B\x5D\x08\x57\x8B\xF9"));
weaponSystem = *reinterpret_cast<WeaponSystem**>(findPattern(CLIENT_DLL, "\x8B\x35????\xFF\x10\x0F\xB7\xC0") + 2);
getEventDescriptor = relativeToAbsolute<decltype(getEventDescriptor)>(findPattern(ENGINE_DLL, "\xE8????\x8B\xD8\x85\xDB\x75\x27") + 1);
playerResource = *reinterpret_cast<PlayerResource***>(findPattern(CLIENT_DLL, "\x74\x30\x8B\x35????\x85\xF6") + 4);
registeredPanoramaEvents = reinterpret_cast<decltype(registeredPanoramaEvents)>(*reinterpret_cast<std::uintptr_t*>(findPattern(CLIENT_DLL, "\xE8????\xA1????\xA8\x01\x75\x21") + 6) - 36);
makePanoramaSymbolFn = relativeToAbsolute<decltype(makePanoramaSymbolFn)>(findPattern(CLIENT_DLL, "\xE8????\x0F\xB7\x45\x0E\x8D\x4D\x0E") + 1);
inventoryManager = *reinterpret_cast<InventoryManager**>(findPattern(CLIENT_DLL, "\x8D\x44\x24\x28\xB9") + 5);
createEconItemSharedObject = *reinterpret_cast<decltype(createEconItemSharedObject)*>(findPattern(CLIENT_DLL, "\x55\x8B\xEC\x83\xEC\x1C\x8D\x45\xE4\xC7\x45") + 20);
addEconItem = relativeToAbsolute<decltype(addEconItem)>(findPattern(CLIENT_DLL, "\xE8????\x84\xC0\x74\xE7") + 1);
clearInventoryImageRGBA = reinterpret_cast<decltype(clearInventoryImageRGBA)>(findPattern(CLIENT_DLL, "\x55\x8B\xEC\x81\xEC????\x57\x8B\xF9\xC7\x47"));
panoramaMarshallHelper = *reinterpret_cast<decltype(panoramaMarshallHelper)*>(findPattern(CLIENT_DLL, "\x68????\x8B\xC8\xE8????\x8D\x4D\xF4\xFF\x15????\x8B\xCF\xFF\x15????\x5F\x5E\x8B\xE5\x5D\xC3") + 1);
setStickerToolSlotGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xFF\xD2\xDD\x5C\x24\x10\xF2\x0F\x2C\x7C\x24") + 2;
setStickerToolSlotGetArgAsStringReturnAddress = setStickerToolSlotGetArgAsNumberReturnAddress - 49;
wearItemStickerGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xDD\x5C\x24\x18\xF2\x0F\x2C\x7C\x24?\x85\xFF");
wearItemStickerGetArgAsStringReturnAddress = wearItemStickerGetArgAsNumberReturnAddress - 80;
setNameToolStringGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x8B\xF8\xC6\x45\x08?\x33\xC0");
clearCustomNameGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\xFF\x50\x1C\x8B\xF0\x85\xF6\x74\x21") + 3;
deleteItemGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x85\xC0\x74\x22\x51");
setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 = findPattern(CLIENT_DLL, "\x85\xC0\x74\x7E\x8B\xC8\xE8????\x8B\x37");
setStatTrakSwapToolItemsGetArgAsStringReturnAddress2 = setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 + 44;
acknowledgeNewItemByItemIDGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x85\xC0\x74\x33\x8B\xC8\xE8????\xB9");
findOrCreateEconItemViewForItemID = relativeToAbsolute<decltype(findOrCreateEconItemViewForItemID)>(findPattern(CLIENT_DLL, "\xE8????\x8B\xCE\x83\xC4\x08") + 1);
getInventoryItemByItemID = relativeToAbsolute<decltype(getInventoryItemByItemID)>(findPattern(CLIENT_DLL, "\xE8????\x8B\x33\x8B\xD0") + 1);
useToolGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x85\xC0\x0F\x84????\x8B\xC8\xE8????\x8B\x37");
useToolGetArg2AsStringReturnAddress = useToolGetArgAsStringReturnAddress + 52;
getSOCData = relativeToAbsolute<decltype(getSOCData)>(findPattern(CLIENT_DLL, "\xE8????\x32\xC9") + 1);
setCustomName = relativeToAbsolute<decltype(setCustomName)>(findPattern(CLIENT_DLL, "\xE8????\x8B\x46\x78\xC1\xE8\x0A\xA8\x01\x74\x13\x8B\x46\x34") + 1);
setDynamicAttributeValueFn = findPattern(CLIENT_DLL, "\x55\x8B\xEC\x83\xE4\xF8\x83\xEC\x3C\x53\x8B\x5D\x08\x56\x57\x6A");
createBaseTypeCache = relativeToAbsolute<decltype(createBaseTypeCache)>(findPattern(CLIENT_DLL, "\xE8????\x8D\x4D\x0F") + 1);
uiComponentInventory = *reinterpret_cast<void***>(findPattern(CLIENT_DLL, "\xC6\x44\x24??\x83\x3D") + 7);
setItemSessionPropertyValue = relativeToAbsolute<decltype(setItemSessionPropertyValue)>(findPattern(CLIENT_DLL, "\xE8????\x8B\x4C\x24\x2C\x46") + 1);
localPlayer.init(*reinterpret_cast<Entity***>(findPattern(CLIENT_DLL, "\xA1????\x89\x45\xBC\x85\xC0") + 1));
#else
const auto tier0 = dlopen(TIER0_DLL, RTLD_NOLOAD | RTLD_NOW);
debugMsg = decltype(debugMsg)(dlsym(tier0, "Msg"));
conColorMsg = decltype(conColorMsg)(dlsym(tier0, "_Z11ConColorMsgRK5ColorPKcz"));
dlclose(tier0);
const auto libSDL = dlopen("libSDL2-2.0.so.0", RTLD_LAZY | RTLD_NOLOAD);
pollEvent = relativeToAbsolute<uintptr_t>(uintptr_t(dlsym(libSDL, "SDL_PollEvent")) + 2);
swapWindow = relativeToAbsolute<uintptr_t>(uintptr_t(dlsym(libSDL, "SDL_GL_SwapWindow")) + 2);
dlclose(libSDL);
globalVars = *relativeToAbsolute<GlobalVars**>((*reinterpret_cast<std::uintptr_t**>(interfaces->client))[11] + 16);
itemSystem = relativeToAbsolute<decltype(itemSystem)>(findPattern(CLIENT_DLL, "\xE8????\x4D\x63\xEC") + 1);
weaponSystem = *relativeToAbsolute<WeaponSystem**>(findPattern(CLIENT_DLL, "\x48\x8B\x58\x10\x48\x8B\x07\xFF\x10") + 12);
hud = relativeToAbsolute<decltype(hud)>(findPattern(CLIENT_DLL, "\x53\x48\x8D\x3D????\x48\x83\xEC\x10\xE8") + 4);
findHudElement = relativeToAbsolute<decltype(findHudElement)>(findPattern(CLIENT_DLL, "\xE8????\x48\x8D\x50\xE0") + 1);
playerResource = relativeToAbsolute<PlayerResource**>(findPattern(CLIENT_DLL, "\x74\x38\x48\x8B\x3D????\x89\xDE") + 5);
getEventDescriptor = relativeToAbsolute<decltype(getEventDescriptor)>(findPattern(ENGINE_DLL, "\xE8????\x48\x85\xC0\x74\x62") + 1);
clearHudWeapon = relativeToAbsolute<decltype(clearHudWeapon)>(findPattern(CLIENT_DLL, "\xE8????\xC6\x45\xB8\x01") + 1);
equipWearable = reinterpret_cast<decltype(equipWearable)>(findPattern(CLIENT_DLL, "\x55\x48\x89\xE5\x41\x56\x41\x55\x41\x54\x49\x89\xF4\x53\x48\x89\xFB\x48\x83\xEC\x10\x48\x8B\x07"));
registeredPanoramaEvents = relativeToAbsolute<decltype(registeredPanoramaEvents)>(relativeToAbsolute<std::uintptr_t>(findPattern(CLIENT_DLL, "\xE8????\x8B\x50\x10\x49\x89\xC6") + 1) + 12);
makePanoramaSymbolFn = relativeToAbsolute<decltype(makePanoramaSymbolFn)>(findPattern(CLIENT_DLL, "\xE8????\x0F\xB7\x45\xA0\x31\xF6") + 1);
inventoryManager = relativeToAbsolute<decltype(inventoryManager)>(findPattern(CLIENT_DLL, "\x48\x8D\x35????\x48\x8D\x3D????\xE9????\x90\x90\x90\x55") + 3);
createEconItemSharedObject = relativeToAbsolute<decltype(createEconItemSharedObject)>(findPattern(CLIENT_DLL, "\x55\x48\x8D\x05????\x31\xD2\x4C\x8D\x0D") + 50);
addEconItem = relativeToAbsolute<decltype(addEconItem)>(findPattern(CLIENT_DLL, "\xE8????\x45\x3B\x65\x28\x72\xD6") + 1);
clearInventoryImageRGBA = relativeToAbsolute<decltype(clearInventoryImageRGBA)>(findPattern(CLIENT_DLL, "\xE8????\x83\xC3\x01\x49\x83\xC4\x08\x41\x3B\x5D\x50") + 1);
panoramaMarshallHelper = relativeToAbsolute<decltype(panoramaMarshallHelper)>(findPattern(CLIENT_DLL, "\xF3\x0F\x11\x05????\x48\x89\x05????\x48\xC7\x05????????\xC7\x05") + 11);
setStickerToolSlotGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xF2\x44\x0F\x2C\xF0\x45\x85\xF6\x78\x32");
setStickerToolSlotGetArgAsStringReturnAddress = setStickerToolSlotGetArgAsNumberReturnAddress - 46;
findOrCreateEconItemViewForItemID = relativeToAbsolute<decltype(findOrCreateEconItemViewForItemID)>(findPattern(CLIENT_DLL, "\xE8????\x4C\x89\xEF\x48\x89\x45\xC8") + 1);
getInventoryItemByItemID = relativeToAbsolute<decltype(getInventoryItemByItemID)>(findPattern(CLIENT_DLL, "\xE8????\x45\x84\xED\x49\x89\xC1") + 1);
getSOCData = relativeToAbsolute<decltype(getSOCData)>(findPattern(CLIENT_DLL, "\xE8????\x5B\x44\x89\xEE") + 1);
setCustomName = relativeToAbsolute<decltype(setCustomName)>(findPattern(CLIENT_DLL, "\xE8????\x41\x8B\x84\x24????\xE9????\x8B\x98") + 1);
useToolGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x85\xC0\x74\xDA\x48\x89\xC7\xE8????\x48\x8B\x0B");
useToolGetArg2AsStringReturnAddress = useToolGetArgAsStringReturnAddress + 55;
wearItemStickerGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xF2\x44\x0F\x2C\xF8\x45\x39\xFE");
wearItemStickerGetArgAsStringReturnAddress = wearItemStickerGetArgAsNumberReturnAddress - 57;
setNameToolStringGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\xBA????\x4C\x89\xF6\x48\x89\xC7\x49\x89\xC4");
clearCustomNameGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x85\xC0\x74\xE5\x48\x89\xC7\xE8????\x49\x89\xC4");
deleteItemGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x85\xC0\x74\xDE\x48\x89\xC7\xE8????\x48\x89\xC3\xE8????\x48\x89\xDE");
setDynamicAttributeValueFn = findPattern(CLIENT_DLL, "\x41\x8B\x06\x49\x8D\x7D\x08") - 95;
createBaseTypeCache = relativeToAbsolute<decltype(createBaseTypeCache)>(findPattern(CLIENT_DLL, "\xE8????\x48\x89\xDE\x5B\x48\x8B\x10") + 1);
uiComponentInventory = relativeToAbsolute<decltype(uiComponentInventory)>(findPattern(CLIENT_DLL, "\xE8????\x4C\x89\x3D????\x4C\x89\xFF\xEB\x9E") + 8);
setItemSessionPropertyValue = relativeToAbsolute<decltype(setItemSessionPropertyValue)>(findPattern(CLIENT_DLL, "\xE8????\x48\x8B\x85????\x41\x83\xC4\x01") + 1);
setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 = findPattern(CLIENT_DLL, "\x74\x84\x4C\x89\xEE\x4C\x89\xF7\xE8????\x48\x85\xC0") - 86;
setStatTrakSwapToolItemsGetArgAsStringReturnAddress2 = setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 + 55;
acknowledgeNewItemByItemIDGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x89\xC7\xE8????\x4C\x89\xEF\x48\x89\xC6\xE8????\x48\x8B\x0B") - 5;
localPlayer.init(relativeToAbsolute<Entity**>(findPattern(CLIENT_DLL, "\x83\xFF\xFF\x48\x8B\x05") + 6));
#endif
}
| 62.158537 | 207 | 0.703943 | danielkrupinski |
147465c78b977cc2e28b1c08ea6895a140727e1c | 1,488 | cpp | C++ | GameExample/PlayerAction.cpp | alwayssmile11a1/MultiplayerGameServer | cd4227ecc5fe1b44d427bcbd76c050a8130d2200 | [
"MIT"
] | null | null | null | GameExample/PlayerAction.cpp | alwayssmile11a1/MultiplayerGameServer | cd4227ecc5fe1b44d427bcbd76c050a8130d2200 | [
"MIT"
] | null | null | null | GameExample/PlayerAction.cpp | alwayssmile11a1/MultiplayerGameServer | cd4227ecc5fe1b44d427bcbd76c050a8130d2200 | [
"MIT"
] | null | null | null | #include "PlayerAction.h"
PlayerAction::PlayerAction()
{
}
PlayerAction::PlayerAction(float timeStamp, float deltaTime, const Vector2 &velocity, bool isShooting)
{
mTimeStamp = timeStamp;
mDeltaTime = deltaTime;
mVelocity = velocity;
mIsShooting = isShooting;
}
PlayerAction::~PlayerAction()
{
}
void PlayerAction::OnNetworkWrite(OutputMemoryBitStream & inOutputStream) const
{
if (mTeamNumber > -1)
{
inOutputStream.Write(true);
inOutputStream.Write(mTeamNumber);
}
else
{
inOutputStream.Write(false);
}
inOutputStream.Write(mTimeStamp);
inOutputStream.Write(mDeltaTime);
inOutputStream.Write(mVelocity);
inOutputStream.Write(mIsShooting);
}
//PLAYER ACTIONS//
std::unique_ptr< PlayerActions > PlayerActions::sInstance;
const std::unique_ptr<PlayerActions>& PlayerActions::GetInstance()
{
if (sInstance == nullptr)
{
sInstance.reset(new PlayerActions());
}
return sInstance;
}
int PlayerActions::Count()
{
return mPlayerActions.size();
}
const PlayerAction& PlayerActions::AddPlayerAction(float timeStamp, float deltaTime, const Vector2& velocity, bool isShooting)
{
mPlayerActions.emplace_back(timeStamp, deltaTime, velocity, isShooting);
return mPlayerActions.back();
}
void PlayerActions::RemovePlayerActions(float lastestTimeStamp)
{
while (!mPlayerActions.empty() && mPlayerActions.front().GetTimeStamp() <= lastestTimeStamp)
{
mPlayerActions.pop_front();
}
}
void PlayerActions::SetPlayerReady(bool isReady)
{
mIsReady = isReady;
}
| 19.84 | 126 | 0.763441 | alwayssmile11a1 |
14749a8f8727a99ba85d39c6a9290b16a9d47a72 | 21,135 | cpp | C++ | iree/compiler/Dialect/HAL/Target/LLVM/LibraryBuilder.cpp | L-Net-1992/iree | a9ce2574f11ce811c07c21b49f679667d66f7798 | [
"Apache-2.0"
] | null | null | null | iree/compiler/Dialect/HAL/Target/LLVM/LibraryBuilder.cpp | L-Net-1992/iree | a9ce2574f11ce811c07c21b49f679667d66f7798 | [
"Apache-2.0"
] | null | null | null | iree/compiler/Dialect/HAL/Target/LLVM/LibraryBuilder.cpp | L-Net-1992/iree | a9ce2574f11ce811c07c21b49f679667d66f7798 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/HAL/Target/LLVM/LibraryBuilder.h"
#include "llvm/IR/IRBuilder.h"
// =============================================================================
//
// NOTE: these structures model 1:1 those in iree/hal/local/executable_library.h
//
// This file must always track the latest version. Backwards compatibility with
// existing runtimes using older versions of the header is maintained by
// emitting variants of the structs matching those in the older headers and
// selecting between them in the query function based on the requested version.
//
// =============================================================================
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
static inline int64_t RoundUpToAlignment(int64_t value, int64_t alignment) {
return (value + (alignment - 1)) & ~(alignment - 1);
}
//===----------------------------------------------------------------------===//
// iree/hal/local/executable_library.h structure types
//===----------------------------------------------------------------------===//
// The IR snippets below were pulled from clang running with `-S -emit-llvm`
// on the executable_library.h header: https://godbolt.org/z/6bMv5jfvf
// %struct.iree_hal_executable_import_table_v0_t = type {
// i32,
// i8**
// }
static llvm::StructType *makeImportTableType(llvm::LLVMContext &context) {
if (auto *existingType = llvm::StructType::getTypeByName(
context, "iree_hal_executable_import_table_v0_t")) {
return existingType;
}
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
auto *i8PtrType = llvm::IntegerType::getInt8PtrTy(context);
auto *type = llvm::StructType::create(context,
{
i32Type,
i8PtrType->getPointerTo(),
},
"iree_hal_executable_import_table_v0_t",
/*isPacked=*/false);
return type;
}
// %struct.iree_hal_executable_environment_v0_t = type {
// ...
// }
static llvm::StructType *makeEnvironmentType(llvm::LLVMContext &context) {
auto *type = llvm::StructType::getTypeByName(
context, "iree_hal_executable_environment_v0_t");
assert(type && "environment type must be defined by ConvertToLLVM");
return type;
}
// %struct.iree_hal_executable_dispatch_state_v0_t = type {
// ...
// }
static llvm::StructType *makeDispatchStateType(llvm::LLVMContext &context) {
auto *type = llvm::StructType::getTypeByName(
context, "iree_hal_executable_dispatch_state_v0_t");
assert(type && "state type must be defined by ConvertToLLVM");
return type;
}
// %struct.iree_hal_executable_workgroup_state_v0_t = type {
// ...
// }
static llvm::StructType *makeWorkgroupStateType(llvm::LLVMContext &context) {
auto *type = llvm::StructType::getTypeByName(
context, "iree_hal_executable_workgroup_state_v0_t");
assert(type && "state type must be defined by ConvertToLLVM");
return type;
}
// i32 (%struct.iree_hal_executable_environment_v0_t*,
// %struct.iree_hal_executable_dispatch_state_v0_t*,
// i8*)
static llvm::FunctionType *makeDispatchFunctionType(
llvm::LLVMContext &context) {
auto *environmentType = makeEnvironmentType(context);
auto *dispatchStateType = makeDispatchStateType(context);
auto *workgroupStateType = makeWorkgroupStateType(context);
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
return llvm::FunctionType::get(i32Type,
{
environmentType->getPointerTo(),
dispatchStateType->getPointerTo(),
workgroupStateType->getPointerTo(),
},
/*isVarArg=*/false);
}
// %struct.iree_hal_executable_dispatch_attrs_v0_t = type {
// i16,
// i16
// }
static llvm::StructType *makeDispatchAttrsType(llvm::LLVMContext &context) {
if (auto *existingType = llvm::StructType::getTypeByName(
context, "iree_hal_executable_dispatch_attrs_v0_t")) {
return existingType;
}
auto *i16Type = llvm::IntegerType::getInt16Ty(context);
auto *type =
llvm::StructType::create(context,
{
i16Type,
i16Type,
},
"iree_hal_executable_dispatch_attrs_v0_t",
/*isPacked=*/false);
return type;
}
// %struct.iree_hal_executable_export_table_v0_t = type {
// i32,
// %struct.iree_hal_executable_dispatch_attrs_v0_t*,
// i32*,
// i8**,
// i8**
// }
static llvm::StructType *makeExportTableType(llvm::LLVMContext &context) {
if (auto *existingType = llvm::StructType::getTypeByName(
context, "iree_hal_executable_export_table_v0_t")) {
return existingType;
}
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
auto *dispatchFunctionType = makeDispatchFunctionType(context);
auto *dispatchAttrsType = makeDispatchAttrsType(context);
auto *i8PtrType = llvm::IntegerType::getInt8PtrTy(context);
auto *type = llvm::StructType::create(
context,
{
i32Type,
dispatchFunctionType->getPointerTo()->getPointerTo(),
dispatchAttrsType->getPointerTo(),
i8PtrType->getPointerTo(),
i8PtrType->getPointerTo(),
},
"iree_hal_executable_export_table_v0_t",
/*isPacked=*/false);
return type;
}
// %struct.iree_hal_executable_constant_table_v0_t = type {
// i32
// }
static llvm::StructType *makeConstantTableType(llvm::LLVMContext &context) {
if (auto *existingType = llvm::StructType::getTypeByName(
context, "iree_hal_executable_constant_table_v0_t")) {
return existingType;
}
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
auto *type =
llvm::StructType::create(context,
{
i32Type,
},
"iree_hal_executable_constant_table_v0_t",
/*isPacked=*/false);
return type;
}
// %struct.iree_hal_executable_library_header_t = type {
// i32,
// i8*,
// i32,
// i32
// }
static llvm::StructType *makeLibraryHeaderType(llvm::LLVMContext &context) {
if (auto *existingType = llvm::StructType::getTypeByName(
context, "iree_hal_executable_library_header_t")) {
return existingType;
}
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
auto *i8PtrType = llvm::IntegerType::getInt8PtrTy(context);
auto *type = llvm::StructType::create(context,
{
i32Type,
i8PtrType,
i32Type,
i32Type,
},
"iree_hal_executable_library_header_t",
/*isPacked=*/false);
return type;
}
// %struct.iree_hal_executable_library_v0_t = type {
// %struct.iree_hal_executable_library_header_t*,
// %struct.iree_hal_executable_import_table_v0_t,
// %struct.iree_hal_executable_export_table_v0_t,
// }
static llvm::StructType *makeLibraryType(llvm::StructType *libraryHeaderType) {
auto &context = libraryHeaderType->getContext();
if (auto *existingType = llvm::StructType::getTypeByName(
context, "iree_hal_executable_library_v0_t")) {
return existingType;
}
auto *importTableType = makeImportTableType(context);
auto *exportTableType = makeExportTableType(context);
auto *constantTableType = makeConstantTableType(context);
auto *type = llvm::StructType::create(context,
{
libraryHeaderType->getPointerTo(),
importTableType,
exportTableType,
constantTableType,
},
"iree_hal_executable_library_v0_t",
/*isPacked=*/false);
return type;
}
//===----------------------------------------------------------------------===//
// IR construction utilities
//===----------------------------------------------------------------------===//
// Creates a global NUL-terminated string constant.
//
// Example:
// @.str.2 = private unnamed_addr constant [6 x i8] c"lib_a\00", align 1
static llvm::Constant *getStringConstant(StringRef value,
llvm::Module *module) {
auto i8Type = llvm::IntegerType::getInt8Ty(module->getContext());
auto i32Type = llvm::IntegerType::getInt32Ty(module->getContext());
auto *stringType = llvm::ArrayType::get(i8Type, value.size() + /*NUL*/ 1);
auto *literal =
llvm::ConstantDataArray::getString(module->getContext(), value);
auto *global = new llvm::GlobalVariable(*module, stringType,
/*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
literal, /*Name=*/"");
global->setAlignment(llvm::MaybeAlign(1));
llvm::Constant *zero = llvm::ConstantInt::get(i32Type, 0);
return llvm::ConstantExpr::getInBoundsGetElementPtr(
stringType, global, ArrayRef<llvm::Constant *>{zero, zero});
}
//===----------------------------------------------------------------------===//
// Builder interface
//===----------------------------------------------------------------------===//
llvm::Function *LibraryBuilder::build(StringRef queryFuncName) {
auto &context = module->getContext();
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
auto *environmentType = makeEnvironmentType(context)->getPointerTo();
auto *libraryHeaderType = makeLibraryHeaderType(context);
// %struct.iree_hal_executable_library_header_t**
// @iree_hal_library_query(i32, %struct.iree_hal_executable_environment_v0_t*)
auto *queryFuncType =
llvm::FunctionType::get(libraryHeaderType->getPointerTo(),
{
i32Type,
environmentType,
},
/*isVarArg=*/false);
auto *func =
llvm::Function::Create(queryFuncType, llvm::GlobalValue::InternalLinkage,
queryFuncName, *module);
auto *entryBlock = llvm::BasicBlock::Create(context, "entry", func);
llvm::IRBuilder<> builder(entryBlock);
// Build out the header for each version and select it at runtime.
// NOTE: today there is just one version so this is rather simple:
// return max_version == 0 ? &library : NULL;
auto *v0 = buildLibraryV0((queryFuncName + "_v0").str());
builder.CreateRet(builder.CreateSelect(
builder.CreateICmpEQ(func->getArg(0),
llvm::ConstantInt::get(
i32Type, static_cast<int64_t>(Version::V_0_1))),
builder.CreatePointerCast(v0, libraryHeaderType->getPointerTo()),
llvm::ConstantPointerNull::get(libraryHeaderType->getPointerTo())));
return func;
}
llvm::Constant *LibraryBuilder::buildLibraryV0ImportTable(
std::string libraryName) {
auto &context = module->getContext();
auto *importTableType = makeImportTableType(context);
auto *i8Type = llvm::IntegerType::getInt8Ty(context);
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
llvm::Constant *zero = llvm::ConstantInt::get(i32Type, 0);
llvm::Constant *symbolNames =
llvm::Constant::getNullValue(i8Type->getPointerTo());
if (!imports.empty()) {
SmallVector<llvm::Constant *, 4> symbolNameValues;
for (auto &import : imports) {
auto symbolName = import.symbol_name;
if (import.weak) {
symbolName += "?";
}
symbolNameValues.push_back(getStringConstant(symbolName, module));
}
auto *symbolNamesType =
llvm::ArrayType::get(i8Type->getPointerTo(), symbolNameValues.size());
auto *global = new llvm::GlobalVariable(
*module, symbolNamesType, /*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
llvm::ConstantArray::get(symbolNamesType, symbolNameValues),
/*Name=*/libraryName + "_import_names");
symbolNames = llvm::ConstantExpr::getInBoundsGetElementPtr(
symbolNamesType, global, ArrayRef<llvm::Constant *>{zero, zero});
}
return llvm::ConstantStruct::get(
importTableType, {
// count=
llvm::ConstantInt::get(i32Type, imports.size()),
// symbols=
symbolNames,
});
}
llvm::Constant *LibraryBuilder::buildLibraryV0ExportTable(
std::string libraryName) {
auto &context = module->getContext();
auto *exportTableType = makeExportTableType(context);
auto *dispatchFunctionType = makeDispatchFunctionType(context);
auto *dispatchAttrsType = makeDispatchAttrsType(context);
auto *i8Type = llvm::IntegerType::getInt8Ty(context);
auto *i16Type = llvm::IntegerType::getInt16Ty(context);
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
llvm::Constant *zero = llvm::ConstantInt::get(i32Type, 0);
// iree_hal_executable_export_table_v0_t::ptrs
SmallVector<llvm::Constant *, 4> exportPtrValues;
for (auto dispatch : exports) {
exportPtrValues.push_back(dispatch.func);
}
auto *exportPtrsType = llvm::ArrayType::get(
dispatchFunctionType->getPointerTo(), exportPtrValues.size());
llvm::Constant *exportPtrs = new llvm::GlobalVariable(
*module, exportPtrsType, /*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
llvm::ConstantArray::get(exportPtrsType, exportPtrValues),
/*Name=*/libraryName + "_funcs");
// TODO(benvanik): force alignment (16? natural pointer width *2?)
exportPtrs = llvm::ConstantExpr::getInBoundsGetElementPtr(
exportPtrsType, exportPtrs, ArrayRef<llvm::Constant *>{zero, zero});
// iree_hal_executable_export_table_v0_t::attrs
llvm::Constant *exportAttrs =
llvm::Constant::getNullValue(i32Type->getPointerTo());
bool hasNonDefaultAttrs =
llvm::find_if(exports, [](const Dispatch &dispatch) {
return !dispatch.attrs.isDefault();
}) != exports.end();
if (!hasNonDefaultAttrs) {
SmallVector<llvm::Constant *, 4> exportAttrValues;
for (auto dispatch : exports) {
exportAttrValues.push_back(llvm::ConstantStruct::get(
dispatchAttrsType,
{
// local_memory_pages=
llvm::ConstantInt::get(
i16Type, RoundUpToAlignment(dispatch.attrs.localMemorySize,
kWorkgroupLocalMemoryPageSize) /
kWorkgroupLocalMemoryPageSize),
// reserved=
llvm::ConstantInt::get(i16Type, 0),
}));
}
auto *exportAttrsType =
llvm::ArrayType::get(dispatchAttrsType, exportAttrValues.size());
auto *global = new llvm::GlobalVariable(
*module, exportAttrsType, /*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
llvm::ConstantArray::get(exportAttrsType, exportAttrValues),
/*Name=*/libraryName + "_attrs");
// TODO(benvanik): force alignment (16? natural pointer width?)
exportAttrs = llvm::ConstantExpr::getInBoundsGetElementPtr(
exportAttrsType, global, ArrayRef<llvm::Constant *>{zero, zero});
}
// iree_hal_executable_export_table_v0_t::names
llvm::Constant *exportNames =
llvm::Constant::getNullValue(i8Type->getPointerTo()->getPointerTo());
if (mode == Mode::INCLUDE_REFLECTION_ATTRS) {
SmallVector<llvm::Constant *, 4> exportNameValues;
for (auto dispatch : exports) {
exportNameValues.push_back(getStringConstant(dispatch.name, module));
}
auto *exportNamesType =
llvm::ArrayType::get(i8Type->getPointerTo(), exportNameValues.size());
auto *global = new llvm::GlobalVariable(
*module, exportNamesType, /*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
llvm::ConstantArray::get(exportNamesType, exportNameValues),
/*Name=*/libraryName + "_names");
// TODO(benvanik): force alignment (16? natural pointer width *2?)
exportNames = llvm::ConstantExpr::getInBoundsGetElementPtr(
exportNamesType, global, ArrayRef<llvm::Constant *>{zero, zero});
}
// iree_hal_executable_export_table_v0_t::tags
llvm::Constant *exportTags =
llvm::Constant::getNullValue(i8Type->getPointerTo()->getPointerTo());
if (mode == Mode::INCLUDE_REFLECTION_ATTRS) {
SmallVector<llvm::Constant *, 4> exportTagValues;
for (auto dispatch : exports) {
exportTagValues.push_back(getStringConstant(dispatch.tag, module));
}
auto *exportTagsType =
llvm::ArrayType::get(i8Type->getPointerTo(), exportTagValues.size());
auto *global = new llvm::GlobalVariable(
*module, exportTagsType, /*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
llvm::ConstantArray::get(exportTagsType, exportTagValues),
/*Name=*/libraryName + "_tags");
// TODO(benvanik): force alignment (16? natural pointer width *2?)
exportTags = llvm::ConstantExpr::getInBoundsGetElementPtr(
exportTagsType, global, ArrayRef<llvm::Constant *>{zero, zero});
}
return llvm::ConstantStruct::get(
exportTableType, {
// count=
llvm::ConstantInt::get(i32Type, exports.size()),
// ptrs=
exportPtrs,
// attrs=
exportAttrs,
// names=
exportNames,
// tags=
exportTags,
});
}
llvm::Constant *LibraryBuilder::buildLibraryV0ConstantTable(
std::string libraryName) {
auto &context = module->getContext();
auto *constantTableType = makeConstantTableType(context);
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
return llvm::ConstantStruct::get(
constantTableType, {
// count=
llvm::ConstantInt::get(i32Type, constantCount),
});
}
llvm::Constant *LibraryBuilder::buildLibraryV0(std::string libraryName) {
auto &context = module->getContext();
auto *libraryHeaderType = makeLibraryHeaderType(context);
auto *libraryType = makeLibraryType(libraryHeaderType);
auto *i32Type = llvm::IntegerType::getInt32Ty(context);
// ----- Header -----
auto *libraryHeader = new llvm::GlobalVariable(
*module, libraryHeaderType, /*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
llvm::ConstantStruct::get(
libraryHeaderType,
{
// version=
llvm::ConstantInt::get(i32Type,
static_cast<int64_t>(Version::LATEST)),
// name=
getStringConstant(module->getName(), module),
// features=
llvm::ConstantInt::get(i32Type, static_cast<int64_t>(features)),
// sanitizer=
llvm::ConstantInt::get(i32Type,
static_cast<int64_t>(sanitizerKind)),
}),
/*Name=*/libraryName + "_header");
// TODO(benvanik): force alignment (8? natural pointer width?)
// ----- Library -----
auto *library = new llvm::GlobalVariable(
*module, libraryType, /*isConstant=*/true,
llvm::GlobalVariable::PrivateLinkage,
llvm::ConstantStruct::get(libraryType,
{
// header=
libraryHeader,
// imports=
buildLibraryV0ImportTable(libraryName),
// exports=
buildLibraryV0ExportTable(libraryName),
// constants=
buildLibraryV0ConstantTable(libraryName),
}),
/*Name=*/libraryName);
// TODO(benvanik): force alignment (8? natural pointer width?)
return library;
}
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
| 41.118677 | 80 | 0.59049 | L-Net-1992 |
14759b72b661dd3dc94bee2b69b06a9d624bbf83 | 3,324 | cpp | C++ | src/common/buses/network/TCPIPv4SocketBus.cpp | udyni/seabreeze | 3d3934f8f0df61c11cef70516cf62a8472cab974 | [
"MIT"
] | null | null | null | src/common/buses/network/TCPIPv4SocketBus.cpp | udyni/seabreeze | 3d3934f8f0df61c11cef70516cf62a8472cab974 | [
"MIT"
] | null | null | null | src/common/buses/network/TCPIPv4SocketBus.cpp | udyni/seabreeze | 3d3934f8f0df61c11cef70516cf62a8472cab974 | [
"MIT"
] | 1 | 2020-07-03T08:36:47.000Z | 2020-07-03T08:36:47.000Z | /***************************************************//**
* @file TCPIPv4SocketBus.cpp
* @date February 2016
* @author Ocean Optics, Inc.
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2016, Ocean Optics Inc
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/
#include "common/buses/network/TCPIPv4SocketBus.h"
#include "common/buses/BusFamilies.h"
#include <cstddef>
using namespace seabreeze;
using namespace std;
TCPIPv4SocketBus::TCPIPv4SocketBus() {
this->deviceLocator = NULL;
}
TCPIPv4SocketBus::~TCPIPv4SocketBus() {
if(NULL != this->deviceLocator) {
delete this->deviceLocator;
}
clearHelpers();
}
Socket *TCPIPv4SocketBus::getSocketDescriptor() {
return this->socket;
}
BusFamily TCPIPv4SocketBus::getBusFamily() const {
TCPIPv4BusFamily family;
return family;
}
void TCPIPv4SocketBus::setLocation(
const DeviceLocatorInterface &location) throw (IllegalArgumentException) {
if(NULL != this->deviceLocator) {
delete this->deviceLocator;
}
this->deviceLocator = location.clone();
}
DeviceLocatorInterface *TCPIPv4SocketBus::getLocation() {
return this->deviceLocator;
}
void TCPIPv4SocketBus::addHelper(ProtocolHint *hint, TransferHelper *helper) {
this->helperKeys.push_back(hint);
this->helperValues.push_back(helper);
}
void TCPIPv4SocketBus::clearHelpers() {
for(unsigned int i = 0; i < this->helperKeys.size(); i++) {
delete this->helperKeys[i];
delete this->helperValues[i];
}
this->helperKeys.resize(0);
this->helperValues.resize(0);
}
TransferHelper *TCPIPv4SocketBus::getHelper(const vector<ProtocolHint *> &hints) const {
/* Just grab the first hint and use that to look up a helper.
* The helpers for Ocean Optics USB devices are 1:1 with respect to hints.
*/
/* Note: this should really be done with a map or hashmap, but I am just not able
* to get that to work (it was returning bad values). Feel free to reimplement
* this in a cleaner fashion.
*/
unsigned int i;
for(i = 0; i < this->helperKeys.size(); i++) {
if((*(this->helperKeys[i])) == (*hints[0])) {
return this->helperValues[i];
}
}
return NULL;
}
| 32.588235 | 88 | 0.679904 | udyni |
1477521f893597df15fa83f56d2eea3420fdbb00 | 4,296 | cpp | C++ | third-party/casadi/casadi/solvers/linsol_ldl.cpp | dbdxnuliba/mit-biomimetics_Cheetah | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 8 | 2020-02-18T09:07:48.000Z | 2021-12-25T05:40:02.000Z | third-party/casadi/casadi/solvers/linsol_ldl.cpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | null | null | null | third-party/casadi/casadi/solvers/linsol_ldl.cpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 13 | 2019-08-25T12:32:06.000Z | 2022-03-31T02:38:12.000Z | /*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* CasADi 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 CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "linsol_ldl.hpp"
#include "casadi/core/global_options.hpp"
using namespace std;
namespace casadi {
extern "C"
int CASADI_LINSOL_LDL_EXPORT
casadi_register_linsol_ldl(LinsolInternal::Plugin* plugin) {
plugin->creator = LinsolLdl::creator;
plugin->name = "ldl";
plugin->doc = LinsolLdl::meta_doc.c_str();
plugin->version = CASADI_VERSION;
plugin->options = &LinsolLdl::options_;
return 0;
}
extern "C"
void CASADI_LINSOL_LDL_EXPORT casadi_load_linsol_ldl() {
LinsolInternal::registerPlugin(casadi_register_linsol_ldl);
}
LinsolLdl::LinsolLdl(const std::string& name, const Sparsity& sp)
: LinsolInternal(name, sp) {
}
LinsolLdl::~LinsolLdl() {
clear_mem();
}
void LinsolLdl::init(const Dict& opts) {
// Call the init method of the base class
LinsolInternal::init(opts);
// Symbolic factorization
sp_Lt_ = sp_.ldl(p_);
}
int LinsolLdl::init_mem(void* mem) const {
if (LinsolInternal::init_mem(mem)) return 1;
auto m = static_cast<LinsolLdlMemory*>(mem);
// Work vectors
casadi_int nrow = this->nrow();
m->d.resize(nrow);
m->l.resize(sp_Lt_.nnz());
m->w.resize(nrow);
return 0;
}
int LinsolLdl::sfact(void* mem, const double* A) const {
return 0;
}
int LinsolLdl::nfact(void* mem, const double* A) const {
auto m = static_cast<LinsolLdlMemory*>(mem);
casadi_ldl(sp_, A, sp_Lt_, get_ptr(m->l), get_ptr(m->d), get_ptr(p_), get_ptr(m->w));
for (double d : m->d) {
if (d==0) casadi_warning("LDL factorization has zeros in D");
}
return 0;
}
int LinsolLdl::solve(void* mem, const double* A, double* x, casadi_int nrhs, bool tr) const {
auto m = static_cast<LinsolLdlMemory*>(mem);
casadi_ldl_solve(x, nrhs, sp_Lt_, get_ptr(m->l), get_ptr(m->d), get_ptr(p_), get_ptr(m->w));
return 0;
}
casadi_int LinsolLdl::neig(void* mem, const double* A) const {
// Count number of negative eigenvalues
auto m = static_cast<LinsolLdlMemory*>(mem);
casadi_int nrow = this->nrow();
casadi_int ret = 0;
for (casadi_int i=0; i<nrow; ++i) if (m->d[i]<0) ret++;
return ret;
}
casadi_int LinsolLdl::rank(void* mem, const double* A) const {
// Count number of nonzero eigenvalues
auto m = static_cast<LinsolLdlMemory*>(mem);
casadi_int nrow = this->nrow();
casadi_int ret = 0;
for (casadi_int i=0; i<nrow; ++i) if (m->d[i]!=0) ret++;
return ret;
}
void LinsolLdl::generate(CodeGenerator& g, const std::string& A, const std::string& x,
casadi_int nrhs, bool tr) const {
// Codegen the integer vectors
string sp = g.sparsity(sp_);
string sp_Lt = g.sparsity(sp_Lt_);
string p = g.constant(p_);
// Place in block to avoid conflicts caused by local variables
g << "{\n";
g.comment("FIXME(@jaeandersson): Memory allocation can be avoided");
g << "casadi_real lt[" << sp_Lt_.nnz() << "], "
"d[" << nrow() << "], "
"w[" << nrow() << "];\n";
// Factorize
g << g.ldl(sp, A, sp_Lt, "lt", "d", p, "w") << "\n";
// Solve
g << g.ldl_solve(x, nrhs, sp_Lt, "lt", "d", p, "w") << "\n";
// End of block
g << "}\n";
}
} // namespace casadi
| 30.906475 | 96 | 0.635242 | dbdxnuliba |
1477b1da3f5a6f2bf0785334beaf19fdd22eacc1 | 1,609 | hpp | C++ | header/p6_side_panel.hpp | Meta-chan/P6 | 2323f3f12894d2eb01a777643f69301a368f9c69 | [
"MIT"
] | null | null | null | header/p6_side_panel.hpp | Meta-chan/P6 | 2323f3f12894d2eb01a777643f69301a368f9c69 | [
"MIT"
] | null | null | null | header/p6_side_panel.hpp | Meta-chan/P6 | 2323f3f12894d2eb01a777643f69301a368f9c69 | [
"MIT"
] | null | null | null | /*
This software is distributed under MIT License, which means:
- Do whatever you want
- Please keep this notice and include the license file to your project
- I provide no warranty
Created by Kyrylo Sovailo (github.com/Meta-chan, k.sovailo@gmail.com)
Reinventing bicycles since 2020
*/
#ifndef P6_SIDE_PANEL
#define P6_SIDE_PANEL
#include "p6_node_bar.hpp"
#include "p6_stick_bar.hpp"
#include "p6_force_bar.hpp"
#include "p6_material_bar.hpp"
#include "p6_move_bar.hpp"
#include <wx/wx.h>
namespace p6
{
class Frame;
///Side panel is container that displays one of bars
class SidePanel
{
private:
///List of available bars
enum class Bar
{
node,
stick,
force,
move,
material
};
Frame *_frame; ///<Application's window
wxPanel *_panel; ///<wxWidget's panel
wxBoxSizer *_sizer; ///<Sizer of wxWidget's panel
NodeBar _node_bar; ///<Node bar
StickBar _stick_bar; ///<Stick bar
ForceBar _force_bar; ///<Force bar
MaterialBar _material_bar; ///<Material bar
MoveBar _move_bar; ///<Move bar
Bar _bar = Bar::material; ///<Bar being displayed
void _switch(Bar bar); ///<Show certain bar
public:
SidePanel(Frame *frame) noexcept; ///<Creates side panel
wxPanel *panel() noexcept; ///<Returns wxWidget's panel
wxBoxSizer *sizer() noexcept; ///<Returns wxWidget's sizer
MoveBar *move_bar() noexcept; ///<Returns move bar
void refresh() noexcept; ///<Refreshes contents of bar's components, except choice boxes
void refresh_materials() noexcept; ///<Refreshes contents of choice boxes
};
}
#endif | 26.377049 | 93 | 0.697328 | Meta-chan |
147907f259fe06961c980374d4046b8f6e8cc18e | 6,733 | cpp | C++ | ds2/lib_demonsaw/component/router/router_idle_component.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 132 | 2017-03-22T03:46:38.000Z | 2022-03-08T15:08:16.000Z | ds2/lib_demonsaw/component/router/router_idle_component.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 4 | 2017-04-06T17:46:10.000Z | 2018-08-08T18:27:59.000Z | ds2/lib_demonsaw/component/router/router_idle_component.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 30 | 2017-03-26T22:38:17.000Z | 2021-11-21T20:50:17.000Z | //
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// 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 <thread>
#include <boost/format.hpp>
#include "router_component.h"
#include "router_idle_component.h"
#include "router_option_component.h"
#include "component/session_component.h"
#include "component/spam_component.h"
#include "component/timeout_component.h"
#include "component/client/client_component.h"
#include "component/group/group_component.h"
#include "component/transfer/chunk_component.h"
#include "entity/entity.h"
#include "utility/default_value.h"
namespace eja
{
// Callback
bool router_idle_component::on_run()
{
on_client();
on_spam();
on_transfer();
return idle_component::on_run();
}
// Client
void router_idle_component::on_client()
{
try
{
const auto owner = get_entity();
const auto option = owner->get<router_option_component>();
if (!option)
return;
const auto session_map = owner->get<session_entity_map_component>();
if (!session_map)
return;
for (const auto& entity : session_map->get_list())
{
const auto timeout = entity->get<timeout_component>();
if (timeout && timeout->expired(option->get_client_timeout()))
{
if (entity->has<client_component>())
remove_client(entity);
else
remove_transfer(entity);
}
}
}
catch (std::exception& e)
{
log(e);
}
catch (...)
{
log();
}
}
void router_idle_component::remove_client(const entity::ptr entity)
{
try
{
// Entity
const auto owner = get_entity();
const auto entity_map = owner->get<entity_map_component>();
if (entity_map)
{
const std::string& entity_id = entity->get_id();
entity_map->remove(entity_id);
}
// Session
const auto session_map = owner->get<session_entity_map_component>();
if (session_map)
{
const auto session = entity->get<session_component>();
if (session)
{
const std::string& session_id = session->get_id();
session_map->remove(session_id);
}
}
// Client
const auto client_map = owner->get<client_entity_map_component>();
if (client_map)
{
const auto client = entity->get<client_component>();
if (client)
{
const std::string& client_id = client->get_id();
client_map->remove(client_id);
call(function_type::client, function_action::remove, entity);
}
}
// Group
const auto group_map = owner->get<group_entity_map_component>();
if (group_map)
{
const auto group = entity->get<group_component>();
if (group)
{
const std::string& group_id = group->get_id();
const auto group_entity = group_map->get(group_id);
if (group_entity)
{
const auto entity_map = group_entity->get<entity_map_component>();
if (entity_map)
{
entity_map->remove(entity->get_id());
if (entity_map->empty())
{
group_map->remove(group_id);
call(function_type::group, function_action::remove, group_entity);
}
else
{
call(function_type::group, function_action::refresh, group_entity);
}
}
}
}
}
// Spam
remove_spam(entity);
}
catch (std::exception& e)
{
log(e);
}
catch (...)
{
log();
}
}
// Spam
void router_idle_component::on_spam()
{
try
{
const auto owner = get_entity();
const auto option = owner->get<router_option_component>();
if (!option)
return;
const auto spam_map = owner->get<spam_entity_map_component>();
if (!spam_map)
return;
for (const auto& entity : spam_map->get_list())
{
// Spam timeout
const auto spam_timeout = entity->get<spam_timeout_component>();
if (spam_timeout && spam_timeout->expired(option->get_spam_timeout()))
remove_spam(entity);
}
}
catch (std::exception& e)
{
log(e);
}
catch (...)
{
log();
}
}
void router_idle_component::remove_spam(const entity::ptr entity)
{
try
{
// Chunk
const auto owner = get_entity();
const auto spam_map = owner->get<spam_entity_map_component>();
if (spam_map)
{
const auto client = entity->get<client_component>();
if (client)
spam_map->remove(client->get_id());
}
}
catch (std::exception& e)
{
log(e);
}
catch (...)
{
log();
}
}
// Transfer
void router_idle_component::on_transfer()
{
try
{
const auto owner = get_entity();
const auto option = owner->get<router_option_component>();
if (!option)
return;
const auto chunk_map = owner->get<chunk_entity_map_component>();
if (!chunk_map)
return;
for (const auto& entity : chunk_map->get_list())
{
// Transfer timeout (>= 1 chunks)
const auto timeout = entity->get<timeout_component>();
if (timeout && timeout->expired(option->get_transfer_timeout()))
{
// Queue timeout (0 chunks)
const auto download_queue = entity->get<chunk_download_queue_component>();
if (download_queue && !download_queue->get_chunk_size() && !timeout->expired(option->get_queue_timeout()))
continue;
remove_transfer(entity);
}
}
}
catch (std::exception& e)
{
log(e);
}
catch (...)
{
log();
}
}
void router_idle_component::remove_transfer(const entity::ptr entity)
{
try
{
// Chunk
const auto owner = get_entity();
const auto chunk_map = owner->get<chunk_entity_map_component>();
if (chunk_map)
{
const auto& entity_id = entity->get_id();
chunk_map->remove(entity_id);
call(function_type::transfer, function_action::remove, entity);
}
}
catch (std::exception& e)
{
log(e);
}
catch (...)
{
log();
}
}
}
| 23.297578 | 111 | 0.655428 | demonsaw |
147b12c0fc00d5ec514f907043bb5151e513d59b | 12,821 | cc | C++ | tests/test_csp.cc | RReverser/libwebp2 | c90b5b476004c9a98731ae1c175cebab5de50fbf | [
"Apache-2.0"
] | 4 | 2020-11-10T17:46:57.000Z | 2022-03-22T06:24:17.000Z | tests/test_csp.cc | RReverser/libwebp2 | c90b5b476004c9a98731ae1c175cebab5de50fbf | [
"Apache-2.0"
] | null | null | null | tests/test_csp.cc | RReverser/libwebp2 | c90b5b476004c9a98731ae1c175cebab5de50fbf | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Google LLC
//
// 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.
// -----------------------------------------------------------------------------
//
// Test CSPTransform::Import() and Export() with different CspTypes.
#include <cstdio>
#include <string>
#include <tuple>
#include "examples/example_utils.h"
#include "imageio/image_dec.h"
#include "include/helpers.h"
#include "src/dsp/math.h"
#include "src/utils/csp.h"
#include "src/utils/plane.h"
#include "src/wp2/decode.h"
#include "src/wp2/encode.h"
namespace WP2 {
namespace {
//------------------------------------------------------------------------------
class CspTest : public ::testing::TestWithParam<Csp> {};
TEST_P(CspTest, Ranges) {
const Csp csp_type = GetParam();
CSPTransform transf;
ASSERT_WP2_OK(transf.Init(csp_type));
int32_t min[3] = {0}, max[3] = {0};
for (uint32_t i = 0; i < 3; ++i) {
for (uint32_t j = 0; j < 3; ++j) {
const int16_t rgb_min = 0 - transf.GetRgbAverage()[j];
const int16_t rgb_max = kRgbMax - transf.GetRgbAverage()[j];
const int32_t coeff = transf.GetRgbToYuvMatrix()[i * 3 + j];
min[i] += coeff * ((coeff > 0) ? rgb_min : rgb_max);
max[i] += coeff * ((coeff > 0) ? rgb_max : rgb_min);
}
}
const float norm = 1.f / (1 << 12u);
for (uint32_t i = 0; i < 3; ++i) {
min[i] = std::round(min[i] * norm);
max[i] = std::round(max[i] * norm);
}
transf.Print();
printf("======== Min / Max ==== \n");
for (uint32_t i = 0; i < 3; ++i) {
const int16_t min_value = min[i];
const int16_t max_value = max[i];
printf("[%d %d]", min_value, max_value);
// Check min/max values fit within YUV precision bits.
// TODO(maryla): these are higher bounds for now but it would be nice to
// track actual min/max values.
EXPECT_LE(std::abs(min_value), 1 << transf.GetYUVPrecisionBits());
EXPECT_LT(std::abs(max_value), 1 << transf.GetYUVPrecisionBits());
}
// Check we couldn't be using fewer bits.
const int32_t global_min = std::min({min[0], min[1], min[2]});
const int32_t global_max = std::max({max[0], max[1], max[2]});
EXPECT_EQ(global_min, transf.GetYUVMin());
EXPECT_EQ(global_max, transf.GetYUVMax());
EXPECT_GT(std::abs(global_min), 1 << (transf.GetYUVPrecisionBits() - 1));
EXPECT_GT(std::abs(global_max), 1 << (transf.GetYUVPrecisionBits() - 1));
printf("\nNorms:\n {");
for (uint32_t i = 0; i < 3; ++i) {
printf("%.3f, ", (float)(max[i] - min[i]) / kRgbMax);
}
printf("}\n");
uint32_t kExpectedYUVBits[kNumCspTypes] = {/* YCoCg */ 9, /* YCbCr */ 9,
/* Custom, not tested */ 0,
/* YIQ */ 9};
EXPECT_EQ(transf.GetYUVPrecisionBits(), kExpectedYUVBits[(uint32_t)csp_type]);
}
TEST_P(CspTest, Precision) {
const Csp csp_type = GetParam();
// YCoCg is the only lossless conversion from and to RGB.
const int16_t error_margin = (csp_type == Csp::kYCoCg) ? 0 : 1;
CSPTransform transf;
ASSERT_WP2_OK(transf.Init(csp_type));
double error_sum = 0., error_avg = 0.;
uint32_t num_values = 0;
// Test some Argb combinations. It is easier than testing YUV combinations
// that lead to valid Argb.
constexpr int32_t kStep = 7;
for (int16_t r = 0; r < (int16_t)kRgbMax + kStep; r += kStep) {
for (int16_t g = 0; g < (int16_t)kRgbMax + kStep; g += kStep) {
for (int16_t b = 0; b < (int16_t)kRgbMax + kStep; b += kStep) {
// Make sure valid extremes are tested.
const int16_t in_r = std::min(r, (int16_t)kRgbMax);
const int16_t in_g = std::min(g, (int16_t)kRgbMax);
const int16_t in_b = std::min(b, (int16_t)kRgbMax);
int16_t in_y, in_u, in_v;
transf.ToYUV(in_r, in_g, in_b, &in_y, &in_u, &in_v);
int16_t out_r, out_g, out_b;
transf.ToRGB(in_y, in_u, in_v, &out_r, &out_g, &out_b);
error_sum += out_r - in_r + out_g - in_g + out_b - in_b;
error_avg += std::abs(out_r - in_r) + std::abs(out_g - in_g) +
std::abs(out_b - in_b);
num_values += 3;
ASSERT_NEAR(out_r, in_r, error_margin);
ASSERT_NEAR(out_g, in_g, error_margin);
ASSERT_NEAR(out_b, in_b, error_margin);
}
}
}
error_sum /= num_values;
error_avg /= num_values;
EXPECT_LT(std::abs(error_sum), 0.0001); // This should be almost 0.
EXPECT_LT(error_avg, 0.05); // Less than 5% of values have an error of +-1.
}
INSTANTIATE_TEST_SUITE_P(CspTestInstantiation, CspTest,
::testing::Values(Csp::kYCoCg, Csp::kYCbCr,
Csp::kYIQ));
//------------------------------------------------------------------------------
class CspImageTest
: public ::testing::TestWithParam<std::tuple<std::string, Csp>> {};
TEST_P(CspImageTest, Simple) {
const std::string& src_file_name = std::get<0>(GetParam());
const Csp csp_type = std::get<1>(GetParam());
ArgbBuffer src;
ASSERT_WP2_OK(
ReadImage(testing::GetTestDataPath(src_file_name).c_str(), &src));
CSPTransform transf;
ASSERT_WP2_OK(transf.Init(csp_type, src));
transf.Print();
YUVPlane yuv;
ASSERT_WP2_OK(yuv.Import(src, src.HasTransparency(), transf,
/*resize_if_needed=*/true, /*pad=*/kPredWidth));
ArgbBuffer dst;
ASSERT_WP2_OK(yuv.Export(transf, /*resize_if_needed=*/true, &dst));
float disto[5];
ASSERT_WP2_OK(dst.GetDistortion(src, PSNR, disto));
// Alpha is not supported, total is not either.
const float min_in_disto = std::min({disto[1], disto[2], disto[3]});
const float min_expected_disto = (csp_type == Csp::kYCoCg) ? 99.f : 45.f;
EXPECT_GE(min_in_disto, min_expected_disto)
<< std::endl
<< "Distortion A " << disto[0] << ", R " << disto[1] << ", G " << disto[2]
<< ", B " << disto[3] << ", total " << disto[4] << " for file "
<< src_file_name << ", csp " << (uint32_t)csp_type;
}
INSTANTIATE_TEST_SUITE_P(
CspImageTestInstantiation, CspImageTest,
::testing::Combine(::testing::Values("source1_64x48.png"),
::testing::Values(Csp::kYCoCg, Csp::kYCbCr, Csp::kCustom,
Csp::kYIQ)));
// This one takes a while to run so it is disabled.
// Can still be run with flag --test_arg=--gunit_also_run_disabled_tests
INSTANTIATE_TEST_SUITE_P(
DISABLED_CspImageTestInstantiation, CspImageTest,
::testing::Combine(::testing::Values("source0.pgm", "source0.ppm",
"source4.webp", "test_exif_xmp.webp"),
::testing::Values(Csp::kYCoCg, Csp::kYCbCr, Csp::kCustom,
Csp::kYIQ)));
//------------------------------------------------------------------------------
// This test exercizes a value underflow/overflow in ToYUV().
// RGB are multiplied with RGBtoYUV matrix and after rounding, Y is outside the
// maximum allowed values of +/-1023 (10 bits + sign). RGBtoYUV matrix float
// computation and rounding to int is probably the root cause.
class CustomCspTest : public ::testing::TestWithParam<const char*> {};
TEST_P(CustomCspTest, RoundingError) {
const char* const file_name = GetParam();
EncoderConfig config = EncoderConfig::kDefault;
config.csp_type = Csp::kCustom;
ASSERT_WP2_OK(testing::EncodeDecodeCompare(file_name, config));
}
INSTANTIATE_TEST_SUITE_P(CustomCspTestInstantiation, CustomCspTest,
::testing::Values("source1_64x48.png"));
// This one takes a while to run so it is disabled.
// Can still be run with flag --test_arg=--gunit_also_run_disabled_tests
INSTANTIATE_TEST_SUITE_P(DISABLED_CustomCspTestInstantiation, CustomCspTest,
::testing::Values("source0.pgm", "source0.ppm",
"source1.png", "source3.jpg",
"source4.webp"));
//------------------------------------------------------------------------------
// Make sure premultiplied color components are at most equal to alpha.
class DecodeArgbTest
: public ::testing::TestWithParam<std::tuple<std::string, float>> {};
TEST_P(DecodeArgbTest, Valid) {
const std::string& src_file_name = std::get<0>(GetParam());
const float quality = std::get<1>(GetParam());
ArgbBuffer src(WP2_Argb_32), dst(WP2_Argb_32);
MemoryWriter data;
ASSERT_WP2_OK(testing::CompressImage(src_file_name, &data, &src, quality));
ASSERT_WP2_OK(Decode(data.mem_, data.size_, &dst));
ASSERT_TRUE(testing::Compare(src, dst, src_file_name,
testing::GetExpectedDistortion(quality)));
for (const ArgbBuffer* const buffer : {&src, &dst}) {
for (uint32_t y = 0; y < buffer->height; ++y) {
const uint8_t* pixel = (const uint8_t*)buffer->GetRow(y);
for (uint32_t x = 0; x < buffer->width; ++x) {
ASSERT_GE(pixel[0], pixel[1]);
ASSERT_GE(pixel[0], pixel[2]);
ASSERT_GE(pixel[0], pixel[3]);
pixel += 4;
}
}
}
}
INSTANTIATE_TEST_SUITE_P(
DecodeArgbTestInstantiation, DecodeArgbTest,
::testing::Combine(::testing::Values("source1_4x4.png"),
::testing::Values(0.f, 100.f) /* quality */));
//------------------------------------------------------------------------------
// Tests CSPTransform::MakeEigenMatrixEncodable() results.
struct MtxValidity {
double error; // Maximum offset among all elements.
std::array<double, 9> matrix; // Elements.
};
class CspTestCustomCsp
: public ::testing::TestWithParam<MtxValidity> {};
TEST_P(CspTestCustomCsp, EigenMtx) {
const MtxValidity& param = GetParam();
std::array<int16_t, 9> fixed_point_matrix;
for (uint32_t i = 0; i < 9; ++i) {
fixed_point_matrix[i] =
(int16_t)std::lround(param.matrix[i] * (1 << CSPTransform::kMtxShift));
}
int32_t error;
std::array<int16_t, 9> encodable_matrix;
ASSERT_WP2_OK(CSPTransform::MakeEigenMatrixEncodable(
fixed_point_matrix.data(), encodable_matrix.data(), &error));
EXPECT_NEAR(error / (double)(1 << CSPTransform::kMtxShift), param.error,
0.0001);
}
INSTANTIATE_TEST_SUITE_P(
CspTestCustomCspInstantiation, CspTestCustomCsp,
::testing::Values( // error, matrix
MtxValidity{0.,
{0., 0., 0., // Empty matrix
0., 0., 0., //
0., 0., 0.}},
MtxValidity{0.,
{1., 0., 0., // Identity matrix
0., -1., 0., //
0., 0., -1.}},
MtxValidity{0.9988,
{1., 0., 0., // Bad matrix
0., -1., 0., //
0., 0., 0.}},
MtxValidity{0.1399,
{1., 0., 0., // Bad matrix
0., -0.99, 0., //
0., 0., -1.}},
MtxValidity{0.,
{0.263184, 0.321289, 0.199707, // Valid output from
0.27002, 0.0107422, -0.373291, // NormalizeFromInput()
0.264893, -0.330078, 0.181885}},
MtxValidity{0.526367,
{-0.263184, 0.321289, 0.199707, // Same but flipped
0.27002, 0.0107422, -0.373291, // first sign.
0.264893, -0.330078, 0.181885}},
MtxValidity{0.,
{0.264893, 0.374023, 0.115967, // Valid
0.269531, -0.0727539, -0.381592, //
0.28418, -0.279785, 0.253906}},
MtxValidity{0.,
{0.287354, 0.217773, 0.22168, // Valid
0.261719, -0.00708008, -0.33252, //
0.167236, -0.362793, 0.139404}},
MtxValidity{0.,
{0.333740, 0.265136, 0.364501, // Valid
0.329101, 0.166503, -0.422363, //
0.307861, -0.465087, 0.056152}},
MtxValidity{0.014648,
{0.285400, 0.240234, 0.331543, // Valid output but too
0.288330, -0.399170, 0.029297, // imprecise to encode.
0.282227, 0.164795, -0.365234}}));
//------------------------------------------------------------------------------
} // namespace
} // namespace WP2
| 38.969605 | 80 | 0.566492 | RReverser |
148014ae662c05e88edbc8c6a03d58093a3ed202 | 544 | hpp | C++ | src/ssmkit/map/transition_matrix.hpp | vahid-bastani/ssmpack | 68aed98b1c661a7d1c9e5610656de57f6a967532 | [
"MIT"
] | 7 | 2016-07-08T09:18:49.000Z | 2018-03-10T06:46:55.000Z | src/ssmkit/map/transition_matrix.hpp | vahidbas/ssmkit | 68aed98b1c661a7d1c9e5610656de57f6a967532 | [
"MIT"
] | null | null | null | src/ssmkit/map/transition_matrix.hpp | vahidbas/ssmkit | 68aed98b1c661a7d1c9e5610656de57f6a967532 | [
"MIT"
] | 1 | 2018-01-03T17:46:08.000Z | 2018-01-03T17:46:08.000Z | #ifndef SSMPACK_MODEL_TRANSITION_MATRIX_HPP
#define SSMPACK_MODEL_TRANSITION_MATRIX_HPP
#include <armadillo>
namespace ssmkit {
namespace map {
struct TransitionMatrix {
using TParameter = arma::vec;
using TConditionVAR = int;
TransitionMatrix(arma::mat t) : transfer{t} {}
// should not be overloaded, should not be template
TParameter operator()(const TConditionVAR &x) const {
return transfer.col(x);
}
arma::mat transfer;
};
} // namespace map
} // namespace ssmkit
#endif // SSMPACK_MODEL_TRANSITION_MATRIX_HPP
| 20.148148 | 55 | 0.744485 | vahid-bastani |
14803394483eeb5f488df31c1303f1b9c945da08 | 77 | cpp | C++ | atmega256_fw/src/main.cpp | chcbaram/avr_vscode | 7d85b98b7e6d4fc4cbbe34985d8bc8a8cdc88f6b | [
"MIT"
] | null | null | null | atmega256_fw/src/main.cpp | chcbaram/avr_vscode | 7d85b98b7e6d4fc4cbbe34985d8bc8a8cdc88f6b | [
"MIT"
] | null | null | null | atmega256_fw/src/main.cpp | chcbaram/avr_vscode | 7d85b98b7e6d4fc4cbbe34985d8bc8a8cdc88f6b | [
"MIT"
] | null | null | null | #include "main.h"
int main(void)
{
hwInit();
apInit();
apMain();
} | 6.416667 | 17 | 0.532468 | chcbaram |
14816e9e9fa9b75957aa4f9cb3d8508f9951b731 | 1,691 | cc | C++ | mindspore/ccsrc/mindrecord/meta/shard_shuffle.cc | TommyLike/mindspore | 401dabb786a9097d6dd84f391657d266b04e9a37 | [
"Apache-2.0"
] | 1 | 2020-05-23T07:08:46.000Z | 2020-05-23T07:08:46.000Z | mindspore/ccsrc/mindrecord/meta/shard_shuffle.cc | liyong126/mindspore | 930a1fb0a8fa9432025442c4f4732058bb7af592 | [
"Apache-2.0"
] | 7 | 2020-03-30T08:31:56.000Z | 2020-04-01T09:54:39.000Z | mindspore/ccsrc/mindrecord/meta/shard_shuffle.cc | liyong126/mindspore | 930a1fb0a8fa9432025442c4f4732058bb7af592 | [
"Apache-2.0"
] | 1 | 2020-03-30T17:07:43.000Z | 2020-03-30T17:07:43.000Z | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mindrecord/include/shard_shuffle.h"
#include <algorithm>
namespace mindspore {
namespace mindrecord {
ShardShuffle::ShardShuffle(uint32_t seed) : shuffle_seed_(seed) {}
MSRStatus ShardShuffle::operator()(ShardTask &tasks) {
if (tasks.categories < 1) {
return FAILED;
}
uint32_t individual_size = tasks.Size() / tasks.categories;
std::vector<std::vector<int>> new_permutations(tasks.categories, std::vector<int>(individual_size));
for (uint32_t i = 0; i < tasks.categories; i++) {
for (uint32_t j = 0; j < individual_size; j++) new_permutations[i][j] = static_cast<int>(j);
std::shuffle(new_permutations[i].begin(), new_permutations[i].end(), std::default_random_engine(shuffle_seed_));
}
shuffle_seed_++;
tasks.permutation_.clear();
for (uint32_t j = 0; j < individual_size; j++) {
for (uint32_t i = 0; i < tasks.categories; i++) {
tasks.permutation_.push_back(new_permutations[i][j] * static_cast<int>(tasks.categories) + static_cast<int>(i));
}
}
return SUCCESS;
}
} // namespace mindrecord
} // namespace mindspore
| 36.76087 | 118 | 0.715553 | TommyLike |
1487ff58e867aa7b2353c2e6e82ed1a0ccbe752b | 1,551 | cpp | C++ | examples/GLUT/28-voxel-basic/WifiSend.cpp | zwells1/HapticMoCap | 0f102834b44f6f38473145da4e39090fafa126b2 | [
"BSD-3-Clause"
] | null | null | null | examples/GLUT/28-voxel-basic/WifiSend.cpp | zwells1/HapticMoCap | 0f102834b44f6f38473145da4e39090fafa126b2 | [
"BSD-3-Clause"
] | null | null | null | examples/GLUT/28-voxel-basic/WifiSend.cpp | zwells1/HapticMoCap | 0f102834b44f6f38473145da4e39090fafa126b2 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <sstream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
class UDPClient
{
public:
UDPClient(
boost::asio::io_service& io_service,
const std::string& host,
const std::string& port
) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0)) {
udp::resolver resolver(io_service_);
udp::resolver::query query(udp::v4(), host, port);
udp::resolver::iterator iter = resolver.resolve(query);
endpoint_ = *iter;
}
~UDPClient()
{
socket_.close();
}
void send(const std::string& msg) {
socket_.send_to(boost::asio::buffer(msg, msg.size()), endpoint_);
}
private:
boost::asio::io_service& io_service_;
udp::socket socket_;
udp::endpoint endpoint_;
};
int main()
{
boost::asio::io_service io_service;
UDPClient client(io_service, "192.168.0.194", "123");
/*
std::string x;
std::stringstream ss;
int nint = 4;
int LowFreq = 322;
int HighFreq = 922;
char bytes [6];
bytes[0] = nint & 0x000000ff;
bytes[1] = (LowFreq & 0x0000ff00) >> 8;
bytes[2] = LowFreq & 0x000000ff;
bytes[3] = (HighFreq & 0x0000ff00) >> 8;
bytes[4] = HighFreq & 0x000000ff;
ss << bytes;
ss >> x;
std::cout << x.size() << std::endl;
client.send(x);
*/
std::string x;
std::stringstream ss;
char tokens[1];
int nint = 5;
int i;
char y = 15;
for (i = 0; i < 1; i++)
{
//tokens[i] = (char)(nint & 0x000000ff);
tokens[i] = y;
nint++;
}
//ss << tokens;
//ss >> x;
//std::cout << tokens.size() << std::endl;
client.send(tokens);
} | 18.247059 | 80 | 0.630561 | zwells1 |
148a11cc081330fedc9f84fb16329c92cf516990 | 5,126 | cpp | C++ | src/internal/src/EqualPowerPanner.cpp | doc22940/LabSound | 0f2379661dc9d0c2faa798a1be16791803c12621 | [
"BSD-2-Clause"
] | null | null | null | src/internal/src/EqualPowerPanner.cpp | doc22940/LabSound | 0f2379661dc9d0c2faa798a1be16791803c12621 | [
"BSD-2-Clause"
] | null | null | null | src/internal/src/EqualPowerPanner.cpp | doc22940/LabSound | 0f2379661dc9d0c2faa798a1be16791803c12621 | [
"BSD-2-Clause"
] | null | null | null | // License: BSD 2 Clause
// Copyright (C) 2010, Google Inc. All rights reserved.
// Copyright (C) 2015+, The LabSound Authors. All rights reserved.
#include "LabSound/core/AudioBus.h"
#include "LabSound/core/Mixing.h"
#include "LabSound/core/Macros.h"
#include "internal/EqualPowerPanner.h"
#include "internal/AudioUtilities.h"
#include "internal/Assertions.h"
#include "LabSound/extended/AudioContextLock.h"
#include <algorithm>
// Use a 50ms smoothing / de-zippering time-constant.
const float SmoothingTimeConstant = 0.050f;
using namespace std;
namespace lab {
EqualPowerPanner::EqualPowerPanner(const float sampleRate) : Panner(sampleRate, PanningMode::EQUALPOWER)
{
}
void EqualPowerPanner::pan(ContextRenderLock & r, double azimuth, double /*elevation*/, const AudioBus* inputBus, AudioBus* outputBus, size_t framesToProcess)
{
m_smoothingConstant = AudioUtilities::discreteTimeConstantForSampleRate(SmoothingTimeConstant, r.context()->sampleRate());
bool isInputSafe = inputBus && (inputBus->numberOfChannels() == Channels::Mono || inputBus->numberOfChannels() == Channels::Stereo) && framesToProcess <= inputBus->length();
ASSERT(isInputSafe);
if (!isInputSafe)
return;
unsigned numberOfInputChannels = inputBus->numberOfChannels();
bool isOutputSafe = outputBus && outputBus->numberOfChannels() == Channels::Stereo && framesToProcess <= outputBus->length();
ASSERT(isOutputSafe);
if (!isOutputSafe)
return;
const float* sourceL = inputBus->channelByType(Channel::Left)->data();
const float* sourceR = numberOfInputChannels > 1 ? inputBus->channelByType(Channel::Right)->data() : sourceL;
float* destinationL = outputBus->channelByType(Channel::Left)->mutableData();
float* destinationR = outputBus->channelByType(Channel::Right)->mutableData();
if (!sourceL || !sourceR || !destinationL || !destinationR)
return;
// Clamp azimuth to allowed range of -180 -> +180.
azimuth = max(-180.0, azimuth);
azimuth = min(180.0, azimuth);
// Alias the azimuth ranges behind us to in front of us:
// -90 -> -180 to -90 -> 0 and 90 -> 180 to 90 -> 0
if (azimuth < -90)
azimuth = -180 - azimuth;
else if (azimuth > 90)
azimuth = 180 - azimuth;
double desiredPanPosition;
double desiredGainL;
double desiredGainR;
if (numberOfInputChannels == 1) { // For mono source case.
// Pan smoothly from left to right with azimuth going from -90 -> +90 degrees.
desiredPanPosition = (azimuth + 90) / 180;
} else { // For stereo source case.
if (azimuth <= 0) { // from -90 -> 0
// sourceL -> destL and "equal-power pan" sourceR as in mono case
// by transforming the "azimuth" value from -90 -> 0 degrees into the range -90 -> +90.
desiredPanPosition = (azimuth + 90) / 90;
} else { // from 0 -> +90
// sourceR -> destR and "equal-power pan" sourceL as in mono case
// by transforming the "azimuth" value from 0 -> +90 degrees into the range -90 -> +90.
desiredPanPosition = azimuth / 90;
}
}
desiredGainL = cos(0.5 * piDouble * desiredPanPosition);
desiredGainR = sin(0.5 * piDouble * desiredPanPosition);
// Don't de-zipper on first render call.
if (m_isFirstRender) {
m_isFirstRender = false;
m_gainL = desiredGainL;
m_gainR = desiredGainR;
}
// Cache in local variables.
double gainL = m_gainL;
double gainR = m_gainR;
// Get local copy of smoothing constant.
const double SmoothingConstant = m_smoothingConstant;
int n = framesToProcess;
if (numberOfInputChannels == 1) { // For mono source case.
while (n--) {
float inputL = *sourceL++;
gainL += (desiredGainL - gainL) * SmoothingConstant;
gainR += (desiredGainR - gainR) * SmoothingConstant;
*destinationL++ = static_cast<float>(inputL * gainL);
*destinationR++ = static_cast<float>(inputL * gainR);
}
} else { // For stereo source case.
if (azimuth <= 0) { // from -90 -> 0
while (n--) {
float inputL = *sourceL++;
float inputR = *sourceR++;
gainL += (desiredGainL - gainL) * SmoothingConstant;
gainR += (desiredGainR - gainR) * SmoothingConstant;
*destinationL++ = static_cast<float>(inputL + inputR * gainL);
*destinationR++ = static_cast<float>(inputR * gainR);
}
} else { // from 0 -> +90
while (n--) {
float inputL = *sourceL++;
float inputR = *sourceR++;
gainL += (desiredGainL - gainL) * SmoothingConstant;
gainR += (desiredGainR - gainR) * SmoothingConstant;
*destinationL++ = static_cast<float>(inputL * gainL);
*destinationR++ = static_cast<float>(inputR + inputL * gainR);
}
}
}
m_gainL = gainL;
m_gainR = gainR;
}
} // namespace lab
| 37.144928 | 177 | 0.619782 | doc22940 |
148ada794dcc9576f63010996a7f11980bd914bf | 43,862 | cpp | C++ | src/pke/lib/bfvrnsB-dcrtpoly-impl.cpp | fuz-woo/PALISADE | bc70288323c45d3b260c998eba79bc93a1274501 | [
"BSD-2-Clause"
] | 6 | 2019-03-19T04:12:00.000Z | 2022-01-27T11:23:01.000Z | src/pke/lib/bfvrnsB-dcrtpoly-impl.cpp | fuz-woo/PALISADE | bc70288323c45d3b260c998eba79bc93a1274501 | [
"BSD-2-Clause"
] | null | null | null | src/pke/lib/bfvrnsB-dcrtpoly-impl.cpp | fuz-woo/PALISADE | bc70288323c45d3b260c998eba79bc93a1274501 | [
"BSD-2-Clause"
] | 3 | 2019-04-30T07:07:50.000Z | 2022-01-27T06:59:53.000Z | /*
* @file bfvrnsB-dcrtpoly-impl.cpp - dcrtpoly implementation for the BEHZ variant of the BFV scheme.
* @author TPOC: palisade@njit.edu
*
* @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
* 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 "cryptocontext.h"
#include "bfvrnsB.cpp"
#define PROFILE
//#define USE_KARATSUBA
namespace lbcrypto {
// Precomputation of CRT tables encryption, decryption, and homomorphic multiplication
template <>
bool LPCryptoParametersBFVrnsB<DCRTPoly>::PrecomputeCRTTables(){
// read values for the CRT basis
size_t size = GetElementParams()->GetParams().size();
auto n = GetElementParams()->GetRingDimension();
vector<NativeInteger> moduli(size);
vector<NativeInteger> roots(size);
const BigInteger BarrettBase128Bit("340282366920938463463374607431768211456"); // 2^128
const BigInteger TwoPower64("18446744073709551616"); // 2^64
m_qModuli.resize(size);
for (size_t i = 0; i < size; i++){
moduli[i] = GetElementParams()->GetParams()[i]->GetModulus();
roots[i] = GetElementParams()->GetParams()[i]->GetRootOfUnity();
m_qModuli[i] = moduli[i];
}
//compute the CRT delta table floor(Q/p) mod qi - used for encryption
const BigInteger modulusQ = GetElementParams()->GetModulus();
const BigInteger deltaBig = modulusQ.DividedBy(GetPlaintextModulus());
std::vector<NativeInteger> CRTDeltaTable(size);
for (size_t i = 0; i < size; i++){
BigInteger qi = BigInteger(moduli[i].ConvertToInt());
BigInteger deltaI = deltaBig.Mod(qi);
CRTDeltaTable[i] = NativeInteger(deltaI.ConvertToInt());
}
m_CRTDeltaTable = CRTDeltaTable;
m_qModulimu.resize(size);
for (uint32_t i = 0; i< m_qModulimu.size(); i++ )
{
BigInteger mu = BarrettBase128Bit/m_qModuli[i];
uint64_t val[2];
val[0] = (mu % TwoPower64).ConvertToInt();
val[1] = mu.RShift(64).ConvertToInt();
memcpy(&m_qModulimu[i], val, sizeof(DoubleNativeInteger));
}
ChineseRemainderTransformFTT<NativeVector>::PreCompute(roots,2*n,moduli);
// Compute Bajard's et al. RNS variant lookup tables
// Populate EvalMulrns tables
// find the a suitable size of B
m_numq = size;
// find m_tilde [we need to ensure that m_tilde is < Bsk moduli to avoid one extra modulo in Small_Montgomery_Reduction]
m_mtilde = NextPrime<NativeInteger>(moduli[m_numq-1], 2 * n);
BigInteger t = BigInteger(GetPlaintextModulus());
BigInteger q(GetElementParams()->GetModulus());
BigInteger B = 1;
BigInteger maxConvolutionValue = BigInteger(4) * BigInteger(n) * q * q * t;
m_BModuli.push_back( NextPrime<NativeInteger>(m_mtilde, 2 * n) );
m_BskRoots.push_back( RootOfUnity<NativeInteger>(2 * n, m_BModuli[0]) );
B = B * m_BModuli[0];
int i = 1; // we already added one prime
while ( q*B < maxConvolutionValue )
{
m_BModuli.push_back( NextPrime<NativeInteger>(m_BModuli[i-1], 2 * n) );
m_BskRoots.push_back( RootOfUnity<NativeInteger>(2 * n, m_BModuli[i]) );
B = B * m_BModuli[i];
i++;
}
m_numB = i;
// find msk
m_msk = NextPrime<NativeInteger>(m_BModuli[m_numB-1], 2 * n);
m_BskRoots.push_back( RootOfUnity<NativeInteger>(2 * n, m_msk) );
m_BskModuli = m_BModuli;
m_BskModuli.push_back( m_msk );
m_BskmtildeModuli = m_BskModuli;
m_paramsBsk = shared_ptr<ILDCRTParams<BigInteger>>(new ILDCRTParams<BigInteger>(2 * n, m_BskModuli, m_BskRoots));
ChineseRemainderTransformFTT<NativeVector>::PreCompute(m_BskRoots, 2 * n, m_BskModuli);
// finally add m_tilde as last modulus in the chain
m_BskmtildeModuli.push_back( m_mtilde );
// populate Barrett constant for m_BskmtildeModuli
m_BskmtildeModulimu.resize( m_BskmtildeModuli.size() );
for (uint32_t i = 0; i< m_BskmtildeModulimu.size(); i++ )
{
BigInteger mu = BarrettBase128Bit/m_BskmtildeModuli[i];
uint64_t val[2];
val[0] = (mu % TwoPower64).ConvertToInt();
val[1] = mu.RShift(64).ConvertToInt();
memcpy(&m_BskmtildeModulimu[i], val, sizeof(DoubleNativeInteger));
}
// Populate Barrett constants for BskModuli
m_BskModulimu.resize(m_BskModuli.size());
for (uint32_t i = 0; i < m_numB + 1; i++)
m_BskModulimu[i] = m_BskmtildeModulimu[i]; // mtilde is last (ignored)
// Populate (q/qi)^-1 mod qi
m_qDivqiModqiTable.resize(m_numq);
for (uint32_t i = 0; i < m_qDivqiModqiTable.size() ; i++ )
{
BigInteger qDivqi;
qDivqi = q.DividedBy(moduli[i]) ;
qDivqi = qDivqi.Mod(moduli[i]);
qDivqi = qDivqi.ModInverse( moduli[i] );
m_qDivqiModqiTable[i] = qDivqi.ConvertToInt();
}
// Populate t*(q/qi)^-1 mod qi
m_tqDivqiModqiTable.resize(m_numq);
m_tqDivqiModqiPreconTable.resize(m_numq);
for (uint32_t i = 0; i < m_tqDivqiModqiTable.size() ; i++ )
{
BigInteger tqDivqi;
tqDivqi = q.DividedBy(moduli[i]) ;
tqDivqi = tqDivqi.Mod(moduli[i]);
tqDivqi = tqDivqi.ModInverse( moduli[i] );
tqDivqi = tqDivqi.ModMul( t.ConvertToInt() , moduli[i] );
m_tqDivqiModqiTable[i] = tqDivqi.ConvertToInt();
m_tqDivqiModqiPreconTable[i] = m_tqDivqiModqiTable[i].PrepModMulPreconOptimized( moduli[i] );
}
// Populate q/qi mod Bj table where Bj \in {Bsk U mtilde}
m_qDivqiModBskmtildeTable.resize(m_numq);
for (uint32_t i = 0; i < m_qDivqiModBskmtildeTable.size(); i++)
{
m_qDivqiModBskmtildeTable[i].resize( m_numB + 2);
BigInteger qDivqi = q.DividedBy(moduli[i]);
for (uint32_t j = 0; j < m_qDivqiModBskmtildeTable[i].size(); j++)
{
BigInteger qDivqiModBj = qDivqi.Mod(m_BskmtildeModuli[j]);
m_qDivqiModBskmtildeTable[i][j] = qDivqiModBj.ConvertToInt();
}
}
// Populate mtilde*(q/qi)^-1 mod qi table
m_mtildeqDivqiTable.resize(m_numq);
m_mtildeqDivqiPreconTable.resize(m_numq);
for (uint32_t i = 0; i < m_mtildeqDivqiTable.size() ; i++ )
{
BigInteger qDivqi = q.DividedBy(moduli[i]);
qDivqi = qDivqi.Mod(moduli[i]);
qDivqi = qDivqi.ModInverse( moduli[i] );
qDivqi = qDivqi * m_mtilde;
qDivqi = qDivqi.Mod(moduli[i]);
m_mtildeqDivqiTable[i] = qDivqi.ConvertToInt();
m_mtildeqDivqiPreconTable[i] = m_mtildeqDivqiTable[i].PrepModMulPreconOptimized( moduli[i] );
}
// Populate -1/q mod mtilde
BigInteger negqInvModmtilde = ((m_mtilde-1) * q.ModInverse(m_mtilde));
negqInvModmtilde = negqInvModmtilde.Mod(m_mtilde);
m_negqInvModmtilde = negqInvModmtilde.ConvertToInt();
m_negqInvModmtildePrecon = m_negqInvModmtilde.PrepModMulPreconOptimized(m_mtilde);
// Populate q mod Bski
m_qModBskiTable.resize(m_numB + 1);
m_qModBskiPreconTable.resize(m_numB + 1);
for (uint32_t i = 0; i < m_qModBskiTable.size(); i++)
{
BigInteger qModBski = q.Mod(m_BskModuli[i]);
m_qModBskiTable[i] = qModBski.ConvertToInt();
m_qModBskiPreconTable[i] = m_qModBskiTable[i].PrepModMulPreconOptimized(m_BskModuli[i]);
}
// Populate mtilde^-1 mod Bski
m_mtildeInvModBskiTable.resize( m_numB + 1 );
m_mtildeInvModBskiPreconTable.resize( m_numB + 1 );
for (uint32_t i = 0; i < m_mtildeInvModBskiTable.size(); i++)
{
BigInteger mtildeInvModBski = m_mtilde % m_BskModuli[i];
mtildeInvModBski = mtildeInvModBski.ModInverse(m_BskModuli[i]);
m_mtildeInvModBskiTable[i] = mtildeInvModBski.ConvertToInt();
m_mtildeInvModBskiPreconTable[i] = m_mtildeInvModBskiTable[i].PrepModMulPreconOptimized(m_BskModuli[i]);
}
// Populate q^-1 mod Bski
m_qInvModBskiTable.resize(m_numB + 1);
m_qInvModBskiPreconTable.resize(m_numB + 1);
for (uint32_t i = 0; i < m_qInvModBskiTable.size(); i++)
{
BigInteger qInvModBski = q.ModInverse(m_BskModuli[i]);
m_qInvModBskiTable[i] = qInvModBski.ConvertToInt();
m_qInvModBskiPreconTable[i] = m_qInvModBskiTable[i].PrepModMulPreconOptimized( m_BskModuli[i] );
}
// Populate (B/Bi)^-1 mod Bi
m_BDivBiModBiTable.resize(m_numB);
m_BDivBiModBiPreconTable.resize(m_numB);
for (uint32_t i = 0; i < m_BDivBiModBiTable.size(); i++)
{
BigInteger BDivBi;
BDivBi = B.DividedBy(m_BModuli[i]) ;
BDivBi = BDivBi.Mod(m_BModuli[i]);
BDivBi = BDivBi.ModInverse( m_BModuli[i] );
m_BDivBiModBiTable[i] = BDivBi.ConvertToInt();
m_BDivBiModBiPreconTable[i] = m_BDivBiModBiTable[i].PrepModMulPreconOptimized(m_BModuli[i]);
}
// Populate B/Bi mod qj table (Matrix) where Bj \in {q}
m_BDivBiModqTable.resize(m_numB);
for (uint32_t i = 0; i < m_BDivBiModqTable.size(); i++)
{
m_BDivBiModqTable[i].resize(m_numq);
BigInteger BDivBi = B.DividedBy(m_BModuli[i]);
for (uint32_t j = 0; j<m_BDivBiModqTable[i].size(); j++)
{
BigInteger BDivBiModqj = BDivBi.Mod(moduli[j]);
m_BDivBiModqTable[i][j] = BDivBiModqj.ConvertToInt();
}
}
// Populate B/Bi mod msk
m_BDivBiModmskTable.resize(m_numB);
for (uint32_t i = 0; i < m_BDivBiModmskTable.size(); i++)
{
BigInteger BDivBi = B.DividedBy(m_BModuli[i]);
m_BDivBiModmskTable[i] = (BDivBi.Mod(m_msk)).ConvertToInt();
}
// Populate B^-1 mod msk
m_BInvModmsk = (B.ModInverse(m_msk)).ConvertToInt();
m_BInvModmskPrecon = m_BInvModmsk.PrepModMulPreconOptimized( m_msk );
// Populate B mod qi
m_BModqiTable.resize(m_numq);
m_BModqiPreconTable.resize(m_numq);
for (uint32_t i = 0; i < m_BModqiTable.size(); i++)
{
m_BModqiTable[i] = (B.Mod( moduli[i] )).ConvertToInt();
m_BModqiPreconTable[i] = m_BModqiTable[i].PrepModMulPreconOptimized( moduli[i] );
}
// Populate Decrns lookup tables
// choose gamma
m_gamma = NextPrime<NativeInteger>(m_mtilde, 2 * n);
m_gammaInvModt = m_gamma.ModInverse(t.ConvertToInt());
m_gammaInvModtPrecon = m_gammaInvModt.PrepModMulPreconOptimized( t.ConvertToInt() );
BigInteger negqModt = ((t-BigInteger(1)) * q.ModInverse(t));
BigInteger negqModgamma = ((m_gamma-1) * q.ModInverse(m_gamma));
m_negqInvModtgammaTable.resize(2);
m_negqInvModtgammaPreconTable.resize(2);
m_negqInvModtgammaTable[0] = negqModt.Mod(t).ConvertToInt();
m_negqInvModtgammaPreconTable[0] = m_negqInvModtgammaTable[0].PrepModMulPreconOptimized( t.ConvertToInt() );
m_negqInvModtgammaTable[1] = negqModgamma.Mod(m_gamma).ConvertToInt();
m_negqInvModtgammaPreconTable[1] = m_negqInvModtgammaTable[1].PrepModMulPreconOptimized(m_gamma);
// Populate q/qi mod mj table where mj \in {t U gamma}
m_qDivqiModtgammaTable.resize(m_numq);
m_qDivqiModtgammaPreconTable.resize(m_numq);
for (uint32_t i = 0; i < m_qDivqiModtgammaTable.size(); i++)
{
m_qDivqiModtgammaTable[i].resize(2);
m_qDivqiModtgammaPreconTable[i].resize(2);
BigInteger qDivqi = q.DividedBy(moduli[i]);
BigInteger qDivqiModt = qDivqi.Mod(t);
m_qDivqiModtgammaTable[i][0] = qDivqiModt.ConvertToInt();
m_qDivqiModtgammaPreconTable[i][0] = m_qDivqiModtgammaTable[i][0].PrepModMulPreconOptimized( t.ConvertToInt() );
BigInteger qDivqiModgamma = qDivqi.Mod(m_gamma);
m_qDivqiModtgammaTable[i][1] = qDivqiModgamma.ConvertToInt();
m_qDivqiModtgammaPreconTable[i][1] = m_qDivqiModtgammaTable[i][1].PrepModMulPreconOptimized( m_gamma );
}
// populate (t*gamma*q/qi)^-1 mod qi
m_tgammaqDivqiModqiTable.resize( m_numq );
m_tgammaqDivqiModqiPreconTable.resize(m_numq);
for (uint32_t i = 0; i < m_tgammaqDivqiModqiTable.size(); i++)
{
BigInteger qDivqi = q.DividedBy(moduli[i]);
qDivqi = qDivqi.ModInverse( moduli[i] );
BigInteger gammaqDivqi = (qDivqi*m_gamma) % moduli[i];
BigInteger tgammaqDivqi = (gammaqDivqi*t) % moduli[i];
m_tgammaqDivqiModqiTable[i] = tgammaqDivqi.ConvertToInt();
m_tgammaqDivqiModqiPreconTable[i] = m_tgammaqDivqiModqiTable[i].PrepModMulPreconOptimized( moduli[i] );
}
return true;
}
// Parameter generation for BFV-RNS
template <>
bool LPAlgorithmParamsGenBFVrnsB<DCRTPoly>::ParamsGen(shared_ptr<LPCryptoParameters<DCRTPoly>> cryptoParams, int32_t evalAddCount,
int32_t evalMultCount, int32_t keySwitchCount, size_t dcrtBits) const
{
if (!cryptoParams)
PALISADE_THROW(not_available_error, "No crypto parameters are supplied to BFVrnsB ParamsGen");
if ((dcrtBits < 30) || (dcrtBits > 60))
PALISADE_THROW(math_error, "BFVrnsB.ParamsGen: Number of bits in CRT moduli should be in the range from 30 to 60");
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParamsBFVrnsB = std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(cryptoParams);
ExtendedDouble sigma = ExtendedDouble(cryptoParamsBFVrnsB->GetDistributionParameter());
ExtendedDouble alpha = ExtendedDouble(cryptoParamsBFVrnsB->GetAssuranceMeasure());
ExtendedDouble hermiteFactor = ExtendedDouble(cryptoParamsBFVrnsB->GetSecurityLevel());
ExtendedDouble p = ExtendedDouble(cryptoParamsBFVrnsB->GetPlaintextModulus());
uint32_t relinWindow = cryptoParamsBFVrnsB->GetRelinWindow();
SecurityLevel stdLevel = cryptoParamsBFVrnsB->GetStdLevel();
//Bound of the Gaussian error polynomial
ExtendedDouble Berr = sigma*sqrt(alpha);
//Bound of the key polynomial
ExtendedDouble Bkey;
DistributionType distType;
//supports both discrete Gaussian (RLWE) and ternary uniform distribution (OPTIMIZED) cases
if (cryptoParamsBFVrnsB->GetMode() == RLWE) {
Bkey = sigma*sqrt(alpha);
distType = HEStd_error;
}
else
{
Bkey = 1;
distType = HEStd_ternary;
}
//expansion factor delta
// We use the worst-case bound as the central limit theorem cannot be applied in this case
auto delta = [](uint32_t n) -> ExtendedDouble { return ExtendedDouble(n); };
auto Vnorm = [&](uint32_t n) -> ExtendedDouble { return Berr*(1+2*delta(n)*Bkey); };
//RLWE security constraint
auto nRLWE = [&](ExtendedDouble q) -> ExtendedDouble {
if (stdLevel == HEStd_NotSet) {
return log(q / sigma) / (ExtendedDouble(4) * log(hermiteFactor));
}
else
{
return (ExtendedDouble)StdLatticeParm::FindRingDim(distType,stdLevel,to_long(ceil(log(q)/(ExtendedDouble)log(2))));
}
};
//initial values
uint32_t n = 512;
ExtendedDouble q = ExtendedDouble(0);
//only public key encryption and EvalAdd (optional when evalAddCount = 0) operations are supported
//the correctness constraint from section 3.5 of https://eprint.iacr.org/2014/062.pdf is used
if ((evalMultCount == 0) && (keySwitchCount == 0)) {
//Correctness constraint
auto qBFV = [&](uint32_t n) -> ExtendedDouble { return p*(2*((evalAddCount+1)*Vnorm(n) + evalAddCount*p) + p); };
//initial value
q = qBFV(n);
while (nRLWE(q) > n) {
n = 2 * n;
q = qBFV(n);
}
// this code updates n and q to account for the discrete size of CRT moduli = dcrtBits
int32_t k = to_long(ceil((ceil(log(q)/(ExtendedDouble)log(2)) + ExtendedDouble(1.0)) / (ExtendedDouble)dcrtBits));
ExtendedDouble qCeil = power((ExtendedDouble)2,k*dcrtBits);
while (nRLWE(qCeil) > n) {
n = 2 * n;
q = qBFV(n);
k = to_long(ceil((ceil(log(q)/(ExtendedDouble)log(2)) + ExtendedDouble(1.0)) / (ExtendedDouble)dcrtBits));
qCeil = power((ExtendedDouble)2,k*dcrtBits);
}
}
// this case supports re-encryption and automorphism w/o any other operations
else if ((evalMultCount == 0) && (keySwitchCount > 0) && (evalAddCount == 0)) {
//base for relinearization
ExtendedDouble w;
if (relinWindow == 0)
w = pow(2, dcrtBits);
else
w = pow(2, relinWindow);
//Correctness constraint
auto qBFV = [&](uint32_t n, ExtendedDouble qPrev) -> ExtendedDouble { return p*(2*(Vnorm(n) + keySwitchCount*delta(n)*(floor(log(qPrev) / (log(2)*dcrtBits)) + 1)*w*Berr) + p); };
//initial values
ExtendedDouble qPrev = ExtendedDouble(1e6);
q = qBFV(n, qPrev);
qPrev = q;
//this "while" condition is needed in case the iterative solution for q
//changes the requirement for n, which is rare but still theortically possible
while (nRLWE(q) > n) {
while (nRLWE(q) > n) {
n = 2 * n;
q = qBFV(n, qPrev);
qPrev = q;
}
q = qBFV(n, qPrev);
while (fabs(q - qPrev) > 0.001*q) {
qPrev = q;
q = qBFV(n, qPrev);
}
// this code updates n and q to account for the discrete size of CRT moduli = dcrtBits
int32_t k = to_long(ceil((ceil(log(q)/(ExtendedDouble)log(2)) + ExtendedDouble(1.0)) / (ExtendedDouble)dcrtBits));
ExtendedDouble qCeil = power((ExtendedDouble)2,k*dcrtBits);
qPrev = qCeil;
while (nRLWE(qCeil) > n) {
n = 2 * n;
q = qBFV(n, qPrev);
k = to_long(ceil((ceil(log(q)/(ExtendedDouble)log(2)) + ExtendedDouble(1.0)) / (ExtendedDouble)dcrtBits));
qCeil = power((ExtendedDouble)2,k*dcrtBits);
qPrev = qCeil;
}
}
}
//Only EvalMult operations are used in the correctness constraint
//the correctness constraint from section 3.5 of https://eprint.iacr.org/2014/062.pdf is used
else if ((evalAddCount == 0) && (evalMultCount > 0) && (keySwitchCount == 0))
{
//base for relinearization
ExtendedDouble w;
if (relinWindow == 0)
w = pow(2, dcrtBits);
else
w = pow(2, relinWindow);
//function used in the EvalMult constraint
auto epsilon1 = [&](uint32_t n) -> ExtendedDouble { return 4 / (delta(n)*Bkey); };
//function used in the EvalMult constraint
auto C1 = [&](uint32_t n) -> ExtendedDouble { return (1 + epsilon1(n))*delta(n)*delta(n)*p*Bkey; };
//function used in the EvalMult constraint
auto C2 = [&](uint32_t n, ExtendedDouble qPrev) -> ExtendedDouble { return delta(n)*delta(n)*Bkey*(Bkey + p*p) + delta(n)*(floor(log(qPrev) / (log(2)*dcrtBits)) + 1)*w*Berr; };
//main correctness constraint
auto qBFV = [&](uint32_t n, ExtendedDouble qPrev) -> ExtendedDouble { return p*(2 * (power(C1(n), evalMultCount)*Vnorm(n) + evalMultCount*power(C1(n), evalMultCount - 1)*C2(n, qPrev)) + p); };
//initial values
ExtendedDouble qPrev = ExtendedDouble(1e6);
q = qBFV(n, qPrev);
qPrev = q;
//this "while" condition is needed in case the iterative solution for q
//changes the requirement for n, which is rare but still theoretically possible
while (nRLWE(q) > n) {
while (nRLWE(q) > n) {
n = 2 * n;
q = qBFV(n, qPrev);
qPrev = q;
}
q = qBFV(n, qPrev);
while (fabs(q - qPrev) > 0.001*q) {
qPrev = q;
q = qBFV(n, qPrev);
}
// this code updates n and q to account for the discrete size of CRT moduli = dcrtBits
int32_t k = to_long(ceil((ceil(log(q)/(ExtendedDouble)log(2)) + ExtendedDouble(1.0)) / (ExtendedDouble)dcrtBits));
ExtendedDouble qCeil = power((ExtendedDouble)2,k*dcrtBits);
qPrev = qCeil;
while (nRLWE(qCeil) > n) {
n = 2 * n;
q = qBFV(n, qPrev);
k = to_long(ceil((ceil(log(q)/(ExtendedDouble)log(2)) + ExtendedDouble(1.0)) / (ExtendedDouble)dcrtBits));
qCeil = power((ExtendedDouble)2,k*dcrtBits);
qPrev = qCeil;
}
}
}
size_t size = to_long(ceil((ceil(log(q)/(ExtendedDouble)log(2)) + ExtendedDouble(1.0)) / (ExtendedDouble)dcrtBits));
vector<NativeInteger> moduli(size);
vector<NativeInteger> roots(size);
//makes sure the first integer is less than 2^60-1 to take advantage of NTL optimizations
NativeInteger firstInteger = FirstPrime<NativeInteger>(dcrtBits, 2 * n);
firstInteger -= (int64_t)(2*n)*((int64_t)(1)<<(dcrtBits/3));
moduli[0] = NextPrime<NativeInteger>(firstInteger, 2 * n);
roots[0] = RootOfUnity<NativeInteger>(2 * n, moduli[0]);
for (size_t i = 1; i < size; i++)
{
moduli[i] = NextPrime<NativeInteger>(moduli[i-1], 2 * n);
roots[i] = RootOfUnity<NativeInteger>(2 * n, moduli[i]);
}
shared_ptr<ILDCRTParams<BigInteger>> params(new ILDCRTParams<BigInteger>(2 * n, moduli, roots));
ChineseRemainderTransformFTT<NativeVector>::PreCompute(roots,2*n,moduli);
cryptoParamsBFVrnsB->SetElementParams(params);
return cryptoParamsBFVrnsB->PrecomputeCRTTables();
}
template <>
Ciphertext<DCRTPoly> LPAlgorithmBFVrnsB<DCRTPoly>::Encrypt(const LPPublicKey<DCRTPoly> publicKey,
DCRTPoly ptxt) const
{
Ciphertext<DCRTPoly> ciphertext( new CiphertextImpl<DCRTPoly>(publicKey) );
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParams = std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(publicKey->GetCryptoParameters());
const shared_ptr<typename DCRTPoly::Params> elementParams = cryptoParams->GetElementParams();
ptxt.SwitchFormat();
const std::vector<NativeInteger> &deltaTable = cryptoParams->GetCRTDeltaTable();
const typename DCRTPoly::DggType &dgg = cryptoParams->GetDiscreteGaussianGenerator();
typename DCRTPoly::TugType tug;
const DCRTPoly &p0 = publicKey->GetPublicElements().at(0);
const DCRTPoly &p1 = publicKey->GetPublicElements().at(1);
DCRTPoly u;
//Supports both discrete Gaussian (RLWE) and ternary uniform distribution (OPTIMIZED) cases
if (cryptoParams->GetMode() == RLWE)
u = DCRTPoly(dgg, elementParams, Format::EVALUATION);
else
u = DCRTPoly(tug, elementParams, Format::EVALUATION);
DCRTPoly e1(dgg, elementParams, Format::EVALUATION);
DCRTPoly e2(dgg, elementParams, Format::EVALUATION);
DCRTPoly c0(elementParams);
DCRTPoly c1(elementParams);
c0 = p0*u + e1 + ptxt.Times(deltaTable);
c1 = p1*u + e2;
ciphertext->SetElements({ c0, c1 });
return ciphertext;
}
template <>
DecryptResult LPAlgorithmBFVrnsB<DCRTPoly>::Decrypt(const LPPrivateKey<DCRTPoly> privateKey,
ConstCiphertext<DCRTPoly> ciphertext,
NativePoly *plaintext) const
{
//TimeVar t_total;
//TIC(t_total);
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParamsBFVrnsB =
std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(privateKey->GetCryptoParameters());
const shared_ptr<typename DCRTPoly::Params> elementParams = cryptoParamsBFVrnsB->GetElementParams();
const std::vector<DCRTPoly> &c = ciphertext->GetElements();
const DCRTPoly &s = privateKey->GetPrivateElement();
DCRTPoly sPower = s;
DCRTPoly b = c[0];
if(b.GetFormat() == Format::COEFFICIENT)
b.SwitchFormat();
DCRTPoly cTemp;
for(size_t i=1; i<=ciphertext->GetDepth(); i++){
cTemp = c[i];
if(cTemp.GetFormat() == Format::COEFFICIENT)
cTemp.SwitchFormat();
b += sPower*cTemp;
sPower *= s;
}
// Converts back to coefficient representation
b.SwitchFormat();
auto &t = cryptoParamsBFVrnsB->GetPlaintextModulus();
// Invoke BFVrnsB DecRNS
const std::vector<NativeInteger> ¶msqModuliTable = cryptoParamsBFVrnsB->GetDCRTParamsqModuli();
const NativeInteger ¶msgamma = cryptoParamsBFVrnsB->GetDCRTParamsgamma();
const NativeInteger ¶msgammaInvModt = cryptoParamsBFVrnsB->GetDCRTParamsgammaInvModt();
const NativeInteger ¶msgammaInvModtPrecon = cryptoParamsBFVrnsB->GetDCRTParamsgammaInvModtPrecon();
const std::vector<NativeInteger> ¶msnegqInvModtgammaTable = cryptoParamsBFVrnsB->GetDCRTParamsnegqInvModtgammaTable();
const std::vector<NativeInteger> ¶msnegqInvModtgammaPreconTable = cryptoParamsBFVrnsB->GetDCRTParamsnegqInvModtgammaPreconTable();
const std::vector<NativeInteger> ¶mstgammaqDivqiModqiTable = cryptoParamsBFVrnsB->GetDCRTParamstgammaqDivqiModqiTable();
const std::vector<NativeInteger> ¶mstgammaqDivqiModqiPreconTable = cryptoParamsBFVrnsB->GetDCRTParamstgammaqDivqiModqiPreconTable();
const std::vector<std::vector<NativeInteger>> ¶msqDivqiModtgammaTable = cryptoParamsBFVrnsB->GetDCRTParamsqDivqiModtgammaTable();
const std::vector<std::vector<NativeInteger>> ¶msqDivqiModtgammaPreconTable = cryptoParamsBFVrnsB->GetDCRTParamsqDivqiModtgammaPreconTable();
// this is the resulting vector of coefficients;
*plaintext = b.ScaleAndRound(paramsqModuliTable,
paramsgamma,
t,
paramsgammaInvModt,
paramsgammaInvModtPrecon,
paramsnegqInvModtgammaTable,
paramsnegqInvModtgammaPreconTable,
paramstgammaqDivqiModqiTable,
paramstgammaqDivqiModqiPreconTable,
paramsqDivqiModtgammaTable,
paramsqDivqiModtgammaPreconTable);
//std::cout << "Decryption time (internal): " << TOC_US(t_total) << " us" << std::endl;
return DecryptResult(plaintext->GetLength());
}
template <>
Ciphertext<DCRTPoly> LPAlgorithmBFVrnsB<DCRTPoly>::Encrypt(const LPPrivateKey<DCRTPoly> privateKey,
DCRTPoly ptxt) const
{
Ciphertext<DCRTPoly> ciphertext( new CiphertextImpl<DCRTPoly>(privateKey) );
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParams =
std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(privateKey->GetCryptoParameters());
const shared_ptr<typename DCRTPoly::Params> elementParams = cryptoParams->GetElementParams();
ptxt.SwitchFormat();
const typename DCRTPoly::DggType &dgg = cryptoParams->GetDiscreteGaussianGenerator();
typename DCRTPoly::DugType dug;
const std::vector<NativeInteger> &deltaTable = cryptoParams->GetCRTDeltaTable();
DCRTPoly a(dug, elementParams, Format::EVALUATION);
const DCRTPoly &s = privateKey->GetPrivateElement();
DCRTPoly e(dgg, elementParams, Format::EVALUATION);
DCRTPoly c0(a*s + e + ptxt.Times(deltaTable));
DCRTPoly c1(elementParams, Format::EVALUATION, true);
c1 -= a;
ciphertext->SetElements({ c0, c1 });
return ciphertext;
}
template <>
Ciphertext<DCRTPoly> LPAlgorithmSHEBFVrnsB<DCRTPoly>::EvalAdd(ConstCiphertext<DCRTPoly> ciphertext,
ConstPlaintext plaintext) const{
Ciphertext<DCRTPoly> newCiphertext = ciphertext->CloneEmpty();
newCiphertext->SetDepth(ciphertext->GetDepth());
const std::vector<DCRTPoly> &cipherTextElements = ciphertext->GetElements();
const DCRTPoly& ptElement = plaintext->GetElement<DCRTPoly>();
std::vector<DCRTPoly> c(cipherTextElements.size());
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParams = std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(ciphertext->GetCryptoParameters());
const std::vector<NativeInteger> &deltaTable = cryptoParams->GetCRTDeltaTable();
c[0] = cipherTextElements[0] + ptElement.Times(deltaTable);
for(size_t i=1; i<cipherTextElements.size(); i++) {
c[i] = cipherTextElements[i];
}
newCiphertext->SetElements(c);
return newCiphertext;
}
template <>
Ciphertext<DCRTPoly> LPAlgorithmSHEBFVrnsB<DCRTPoly>::EvalSub(ConstCiphertext<DCRTPoly> ciphertext,
ConstPlaintext plaintext) const{
Ciphertext<DCRTPoly> newCiphertext = ciphertext->CloneEmpty();
newCiphertext->SetDepth(ciphertext->GetDepth());
const std::vector<DCRTPoly> &cipherTextElements = ciphertext->GetElements();
plaintext->SetFormat(EVALUATION);
const DCRTPoly& ptElement = plaintext->GetElement<DCRTPoly>();
std::vector<DCRTPoly> c(cipherTextElements.size());
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParams = std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(ciphertext->GetCryptoParameters());
const std::vector<NativeInteger> &deltaTable = cryptoParams->GetCRTDeltaTable();
c[0] = cipherTextElements[0] - ptElement.Times(deltaTable);
for(size_t i=1; i<cipherTextElements.size(); i++) {
c[i] = cipherTextElements[i];
}
newCiphertext->SetElements(c);
return newCiphertext;
}
template <>
Ciphertext<DCRTPoly> LPAlgorithmSHEBFVrnsB<DCRTPoly>::EvalMult(ConstCiphertext<DCRTPoly> ciphertext1,
ConstCiphertext<DCRTPoly> ciphertext2) const {
if (!(ciphertext1->GetCryptoParameters() == ciphertext2->GetCryptoParameters())) {
std::string errMsg = "LPAlgorithmSHEBFVrnsB::EvalMult crypto parameters are not the same";
throw std::runtime_error(errMsg);
}
Ciphertext<DCRTPoly> newCiphertext = ciphertext1->CloneEmpty();
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParamsBFVrnsB =
std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(ciphertext1->GetCryptoContext()->GetCryptoParameters());
//Check if the multiplication supports the depth
if ( (ciphertext1->GetDepth() + ciphertext2->GetDepth()) > cryptoParamsBFVrnsB->GetMaxDepth() ) {
std::string errMsg = "LPAlgorithmSHEBFVrnsB::EvalMult multiplicative depth is not supported";
throw std::runtime_error(errMsg);
}
//Get the ciphertext elements
std::vector<DCRTPoly> cipherText1Elements = ciphertext1->GetElements();
std::vector<DCRTPoly> cipherText2Elements = ciphertext2->GetElements();
size_t cipherText1ElementsSize = cipherText1Elements.size();
size_t cipherText2ElementsSize = cipherText2Elements.size();
size_t cipherTextRElementsSize = cipherText1ElementsSize + cipherText2ElementsSize - 1;
std::vector<DCRTPoly> c(cipherTextRElementsSize);
const shared_ptr<typename DCRTPoly::Params> elementParams = cryptoParamsBFVrnsB->GetElementParams();
const shared_ptr<ILDCRTParams<BigInteger>> paramsBsk = cryptoParamsBFVrnsB->GetDCRTParamsBsk();
const std::vector<NativeInteger> ¶msqModuli = cryptoParamsBFVrnsB->GetDCRTParamsqModuli();
const std::vector<DoubleNativeInteger> ¶msqModulimu = cryptoParamsBFVrnsB->GetDCRTParamsqModulimu();
const std::vector<NativeInteger> ¶msBskModuli = cryptoParamsBFVrnsB->GetDCRTParamsBskModuli();
const std::vector<DoubleNativeInteger> ¶msBskModulimu = cryptoParamsBFVrnsB->GetDCRTParamsBskModulimu();
const std::vector<NativeInteger> ¶msBskmtildeModuli = cryptoParamsBFVrnsB->GetDCRTParamsBskmtildeModuli();
const std::vector<DoubleNativeInteger> ¶msBskmtildeModulimu = cryptoParamsBFVrnsB->GetDCRTParamsBskmtildeModulimu();
const std::vector<NativeInteger> ¶msmtildeqDivqiModqi = cryptoParamsBFVrnsB->GetDCRTParamsmtildeqDivqiModqi();
const std::vector<NativeInteger> ¶msmtildeqDivqiModqiPrecon = cryptoParamsBFVrnsB->GetDCRTParamsmtildeqDivqiModqiPrecon();
const std::vector<std::vector<NativeInteger>> ¶msqDivqiModBskmtilde = cryptoParamsBFVrnsB->GetDCRTParamsqDivqiModBskmtilde();
const std::vector<NativeInteger> ¶msqModBski = cryptoParamsBFVrnsB->GetDCRTParamsqModBski();
const std::vector<NativeInteger> ¶msqModBskiPrecon = cryptoParamsBFVrnsB->GetDCRTParamsqModBskiPrecon();
const NativeInteger ¶msnegqInvModmtilde = cryptoParamsBFVrnsB->GetDCRTParamsnegqInvModmtilde();
const NativeInteger ¶msnegqInvModmtildePrecon = cryptoParamsBFVrnsB->GetDCRTParamsnegqInvModmtildePrecon();
const std::vector<NativeInteger> ¶msmtildeInvModBskiTable = cryptoParamsBFVrnsB->GetDCRTParamsmtildeInvModBskiTable();
const std::vector<NativeInteger> ¶msmtildeInvModBskiPreconTable = cryptoParamsBFVrnsB->GetDCRTParamsmtildeInvModBskiPreconTable();
// Expands the CRT basis to q*Bsk; Outputs the polynomials in coeff representation
for(size_t i=0; i<cipherText1ElementsSize; i++)
{
cipherText1Elements[i].FastBaseConvqToBskMontgomery(paramsBsk,
paramsqModuli,
paramsBskmtildeModuli,
paramsBskmtildeModulimu,
paramsmtildeqDivqiModqi,
paramsmtildeqDivqiModqiPrecon,
paramsqDivqiModBskmtilde,
paramsqModBski,
paramsqModBskiPrecon,
paramsnegqInvModmtilde,
paramsnegqInvModmtildePrecon,
paramsmtildeInvModBskiTable,
paramsmtildeInvModBskiPreconTable);
if (cipherText1Elements[i].GetFormat() == COEFFICIENT) {
cipherText1Elements[i].SwitchFormat();
}
}
for(size_t i=0; i<cipherText2ElementsSize; i++)
{
cipherText2Elements[i].FastBaseConvqToBskMontgomery(paramsBsk,
paramsqModuli,
paramsBskmtildeModuli,
paramsBskmtildeModulimu,
paramsmtildeqDivqiModqi,
paramsmtildeqDivqiModqiPrecon,
paramsqDivqiModBskmtilde,
paramsqModBski,
paramsqModBskiPrecon,
paramsnegqInvModmtilde,
paramsnegqInvModmtildePrecon,
paramsmtildeInvModBskiTable,
paramsmtildeInvModBskiPreconTable);
if (cipherText2Elements[i].GetFormat() == COEFFICIENT) {
cipherText2Elements[i].SwitchFormat();
}
}
// Performs the multiplication itself
#ifdef USE_KARATSUBA
if (cipherText1ElementsSize == 2 && cipherText2ElementsSize == 2) // size of each ciphertxt = 2, use Karatsuba
{
c[0] = cipherText1Elements[0] * cipherText2Elements[0]; // a
c[2] = cipherText1Elements[1] * cipherText2Elements[1]; // b
c[1] = cipherText1Elements[0] + cipherText1Elements[1];
c[1] *= (cipherText2Elements[0] + cipherText2Elements[1]);
c[1] -= c[2];
c[1] -= c[0];
}
else // if size of any of the ciphertexts > 2
{
bool *isFirstAdd = new bool[cipherTextRElementsSize];
std::fill_n(isFirstAdd, cipherTextRElementsSize, true);
for(size_t i=0; i<cipherText1ElementsSize; i++){
for(size_t j=0; j<cipherText2ElementsSize; j++){
if(isFirstAdd[i+j] == true){
c[i+j] = cipherText1Elements[i] * cipherText2Elements[j];
isFirstAdd[i+j] = false;
}
else{
c[i+j] += cipherText1Elements[i] * cipherText2Elements[j];
}
}
}
delete []isFirstAdd;
}
#else
bool *isFirstAdd = new bool[cipherTextRElementsSize];
std::fill_n(isFirstAdd, cipherTextRElementsSize, true);
for(size_t i=0; i<cipherText1ElementsSize; i++){
for(size_t j=0; j<cipherText2ElementsSize; j++){
if(isFirstAdd[i+j] == true){
c[i+j] = cipherText1Elements[i] * cipherText2Elements[j];
isFirstAdd[i+j] = false;
}
else{
c[i+j] += cipherText1Elements[i] * cipherText2Elements[j];
}
}
}
delete []isFirstAdd;
#endif
// perfrom RNS approximate Flooring
const NativeInteger ¶msPlaintextModulus = cryptoParamsBFVrnsB->GetPlaintextModulus();
const std::vector<NativeInteger> ¶mstqDivqiModqi = cryptoParamsBFVrnsB->GetDCRTParamstqDivqiModqiTable();
const std::vector<NativeInteger> ¶mstqDivqiModqiPrecon = cryptoParamsBFVrnsB->GetDCRTParamstqDivqiModqiPreconTable();
const std::vector<NativeInteger> ¶msqInvModBi = cryptoParamsBFVrnsB->GetDCRTParamsqInvModBiTable();
const std::vector<NativeInteger> ¶msqInvModBiPrecon = cryptoParamsBFVrnsB->GetDCRTParamsqInvModBiPreconTable();
// perform FastBaseConvSK
const std::vector<NativeInteger> ¶msBDivBiModBi = cryptoParamsBFVrnsB->GetBDivBiModBi();
const std::vector<NativeInteger> ¶msBDivBiModBiPrecon = cryptoParamsBFVrnsB->GetBDivBiModBiPrecon();
const std::vector<NativeInteger> ¶msBDivBiModmsk = cryptoParamsBFVrnsB->GetBDivBiModmsk();
const NativeInteger ¶msBInvModmsk = cryptoParamsBFVrnsB->GetBInvModmsk();
const NativeInteger ¶msBInvModmskPrecon = cryptoParamsBFVrnsB->GetBInvModmskPrecon();
const std::vector<std::vector<NativeInteger>> ¶msBDivBiModqj = cryptoParamsBFVrnsB->GetBDivBiModqj();
const std::vector<NativeInteger> ¶msBModqi = cryptoParamsBFVrnsB->GetBModqi();
const std::vector<NativeInteger> ¶msBModqiPrecon = cryptoParamsBFVrnsB->GetBModqiPrecon();
for(size_t i=0; i<cipherTextRElementsSize; i++){
//converts to coefficient representation before rounding
c[i].SwitchFormat();
// Performs the scaling by t/q followed by rounding; the result is in the CRT basis Bsk
c[i].FastRNSFloorq(paramsPlaintextModulus,
paramsqModuli,
paramsBskModuli,
paramsBskModulimu,
paramstqDivqiModqi,
paramstqDivqiModqiPrecon,
paramsqDivqiModBskmtilde,
paramsqInvModBi,
paramsqInvModBiPrecon);
// Converts from the CRT basis Bsk to q
c[i].FastBaseConvSK(paramsqModuli,
paramsqModulimu,
paramsBskModuli,
paramsBskModulimu,
paramsBDivBiModBi,
paramsBDivBiModBiPrecon,
paramsBDivBiModmsk,
paramsBInvModmsk,
paramsBInvModmskPrecon,
paramsBDivBiModqj,
paramsBModqi,
paramsBModqiPrecon);
}
newCiphertext->SetElements(c);
newCiphertext->SetDepth((ciphertext1->GetDepth() + ciphertext2->GetDepth()));
return newCiphertext;
}
template <>
LPEvalKey<DCRTPoly> LPAlgorithmSHEBFVrnsB<DCRTPoly>::KeySwitchGen(const LPPrivateKey<DCRTPoly> originalPrivateKey,
const LPPrivateKey<DCRTPoly> newPrivateKey) const {
LPEvalKeyRelin<DCRTPoly> ek(new LPEvalKeyRelinImpl<DCRTPoly>(newPrivateKey->GetCryptoContext()));
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParamsLWE =
std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(newPrivateKey->GetCryptoParameters());
const shared_ptr<typename DCRTPoly::Params> elementParams = cryptoParamsLWE->GetElementParams();
const DCRTPoly &s = newPrivateKey->GetPrivateElement();
const typename DCRTPoly::DggType &dgg = cryptoParamsLWE->GetDiscreteGaussianGenerator();
typename DCRTPoly::DugType dug;
const DCRTPoly &oldKey = originalPrivateKey->GetPrivateElement();
std::vector<DCRTPoly> evalKeyElements;
std::vector<DCRTPoly> evalKeyElementsGenerated;
uint32_t relinWindow = cryptoParamsLWE->GetRelinWindow();
for (usint i = 0; i < oldKey.GetNumOfElements(); i++)
{
if (relinWindow>0)
{
vector<typename DCRTPoly::PolyType> decomposedKeyElements = oldKey.GetElementAtIndex(i).PowersOfBase(relinWindow);
for (size_t k = 0; k < decomposedKeyElements.size(); k++)
{
// Creates an element with all zeroes
DCRTPoly filtered(elementParams,EVALUATION,true);
filtered.SetElementAtIndex(i,decomposedKeyElements[k]);
// Generate a_i vectors
DCRTPoly a(dug, elementParams, Format::EVALUATION);
evalKeyElementsGenerated.push_back(a);
// Generate a_i * s + e - [oldKey]_qi [(q/qi)^{-1}]_qi (q/qi)
DCRTPoly e(dgg, elementParams, Format::EVALUATION);
evalKeyElements.push_back(filtered - (a*s + e));
}
}
else
{
// Creates an element with all zeroes
DCRTPoly filtered(elementParams,EVALUATION,true);
filtered.SetElementAtIndex(i,oldKey.GetElementAtIndex(i));
// Generate a_i vectors
DCRTPoly a(dug, elementParams, Format::EVALUATION);
evalKeyElementsGenerated.push_back(a);
// Generate a_i * s + e - [oldKey]_qi [(q/qi)^{-1}]_qi (q/qi)
DCRTPoly e(dgg, elementParams, Format::EVALUATION);
evalKeyElements.push_back(filtered - (a*s + e));
}
}
ek->SetAVector(std::move(evalKeyElements));
ek->SetBVector(std::move(evalKeyElementsGenerated));
return ek;
}
template <>
Ciphertext<DCRTPoly> LPAlgorithmSHEBFVrnsB<DCRTPoly>::KeySwitch(const LPEvalKey<DCRTPoly> ek,
ConstCiphertext<DCRTPoly> cipherText) const
{
Ciphertext<DCRTPoly> newCiphertext = cipherText->CloneEmpty();
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParamsLWE = std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(ek->GetCryptoParameters());
LPEvalKeyRelin<DCRTPoly> evalKey = std::static_pointer_cast<LPEvalKeyRelinImpl<DCRTPoly>>(ek);
const std::vector<DCRTPoly> &c = cipherText->GetElements();
const std::vector<DCRTPoly> &b = evalKey->GetAVector();
const std::vector<DCRTPoly> &a = evalKey->GetBVector();
uint32_t relinWindow = cryptoParamsLWE->GetRelinWindow();
std::vector<DCRTPoly> digitsC2;
DCRTPoly ct0(c[0]);
//in the case of EvalMult, c[0] is initially in coefficient format and needs to be switched to evaluation format
if (c.size() > 2)
ct0.SwitchFormat();
DCRTPoly ct1;
if (c.size() == 2) //case of PRE or automorphism
{
digitsC2 = c[1].CRTDecompose(relinWindow);
ct1 = digitsC2[0] * a[0];
}
else //case of EvalMult
{
digitsC2 = c[2].CRTDecompose(relinWindow);
ct1 = c[1];
//Convert ct1 to evaluation representation
ct1.SwitchFormat();
ct1 += digitsC2[0] * a[0];
}
ct0 += digitsC2[0] * b[0];
for (usint i = 1; i < digitsC2.size(); ++i)
{
ct0 += digitsC2[i] * b[i];
ct1 += digitsC2[i] * a[i];
}
newCiphertext->SetElements({ ct0, ct1 });
return newCiphertext;
}
template <>
Ciphertext<DCRTPoly> LPAlgorithmSHEBFVrnsB<DCRTPoly>::EvalMultAndRelinearize(ConstCiphertext<DCRTPoly> ciphertext1,
ConstCiphertext<DCRTPoly> ciphertext2, const vector<LPEvalKey<DCRTPoly>> &ek) const{
Ciphertext<DCRTPoly> cipherText = this->EvalMult(ciphertext1, ciphertext2);
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParamsLWE =
std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(ek[0]->GetCryptoParameters());
Ciphertext<DCRTPoly> newCiphertext = cipherText->CloneEmpty();
std::vector<DCRTPoly> c = cipherText->GetElements();
if(c[0].GetFormat() == Format::COEFFICIENT)
for(size_t i=0; i<c.size(); i++)
c[i].SwitchFormat();
DCRTPoly ct0(c[0]);
DCRTPoly ct1(c[1]);
// Perform a keyswitching operation to result of the multiplication. It does it until it reaches to 2 elements.
//TODO: Maybe we can change the number of keyswitching and terminate early. For instance; perform keyswitching until 4 elements left.
for(size_t j = 0; j<=cipherText->GetDepth()-2; j++){
size_t index = cipherText->GetDepth()-2-j;
LPEvalKeyRelin<DCRTPoly> evalKey = std::static_pointer_cast<LPEvalKeyRelinImpl<DCRTPoly>>(ek[index]);
const std::vector<DCRTPoly> &b = evalKey->GetAVector();
const std::vector<DCRTPoly> &a = evalKey->GetBVector();
std::vector<DCRTPoly> digitsC2 = c[index+2].CRTDecompose();
for (usint i = 0; i < digitsC2.size(); ++i){
ct0 += digitsC2[i] * b[i];
ct1 += digitsC2[i] * a[i];
}
}
newCiphertext->SetElements({ ct0, ct1 });
return newCiphertext;
}
template <>
DecryptResult LPAlgorithmMultipartyBFVrnsB<DCRTPoly>::MultipartyDecryptFusion(const vector<Ciphertext<DCRTPoly>>& ciphertextVec,
NativePoly *plaintext) const
{
const shared_ptr<LPCryptoParametersBFVrnsB<DCRTPoly>> cryptoParamsBFVrnsB =
std::dynamic_pointer_cast<LPCryptoParametersBFVrnsB<DCRTPoly>>(ciphertextVec[0]->GetCryptoParameters());
const shared_ptr<typename DCRTPoly::Params> elementParams = cryptoParamsBFVrnsB->GetElementParams();
const std::vector<DCRTPoly> &cElem = ciphertextVec[0]->GetElements();
DCRTPoly b = cElem[0];
size_t numCipher = ciphertextVec.size();
for( size_t i = 1; i < numCipher; i++ ) {
const std::vector<DCRTPoly> &c2 = ciphertextVec[i]->GetElements();
b += c2[0];
}
auto &t = cryptoParamsBFVrnsB->GetPlaintextModulus();
// Invoke BFVrnsB DecRNS
const std::vector<NativeInteger> ¶msqModuliTable = cryptoParamsBFVrnsB->GetDCRTParamsqModuli();
const NativeInteger ¶msgamma = cryptoParamsBFVrnsB->GetDCRTParamsgamma();
const NativeInteger ¶msgammaInvModt = cryptoParamsBFVrnsB->GetDCRTParamsgammaInvModt();
const NativeInteger ¶msgammaInvModtPrecon = cryptoParamsBFVrnsB->GetDCRTParamsgammaInvModtPrecon();
const std::vector<NativeInteger> ¶msnegqInvModtgammaTable = cryptoParamsBFVrnsB->GetDCRTParamsnegqInvModtgammaTable();
const std::vector<NativeInteger> ¶msnegqInvModtgammaPreconTable = cryptoParamsBFVrnsB->GetDCRTParamsnegqInvModtgammaPreconTable();
const std::vector<NativeInteger> ¶mstgammaqDivqiModqiTable = cryptoParamsBFVrnsB->GetDCRTParamstgammaqDivqiModqiTable();
const std::vector<NativeInteger> ¶mstgammaqDivqiModqiPreconTable = cryptoParamsBFVrnsB->GetDCRTParamstgammaqDivqiModqiPreconTable();
const std::vector<std::vector<NativeInteger>> ¶msqDivqiModtgammaTable = cryptoParamsBFVrnsB->GetDCRTParamsqDivqiModtgammaTable();
const std::vector<std::vector<NativeInteger>> ¶msqDivqiModtgammaPreconTable = cryptoParamsBFVrnsB->GetDCRTParamsqDivqiModtgammaPreconTable();
// this is the resulting vector of coefficients;
*plaintext = b.ScaleAndRound(paramsqModuliTable,
paramsgamma,
t,
paramsgammaInvModt,
paramsgammaInvModtPrecon,
paramsnegqInvModtgammaTable,
paramsnegqInvModtgammaPreconTable,
paramstgammaqDivqiModqiTable,
paramstgammaqDivqiModqiPreconTable,
paramsqDivqiModtgammaTable,
paramsqDivqiModtgammaPreconTable);
return DecryptResult(plaintext->GetLength());
}
template class LPCryptoParametersBFVrnsB<DCRTPoly>;
template class LPPublicKeyEncryptionSchemeBFVrnsB<DCRTPoly>;
template class LPAlgorithmBFVrnsB<DCRTPoly>;
template class LPAlgorithmSHEBFVrnsB<DCRTPoly>;
template class LPAlgorithmMultipartyBFVrnsB<DCRTPoly>;
template class LPAlgorithmParamsGenBFVrnsB<DCRTPoly>;
}
| 36.070724 | 195 | 0.748301 | fuz-woo |
148c3fa34e07e1108761e70b7b478d15353aa5d8 | 19,238 | cpp | C++ | src/framework/shared/enhancedverif/verifier.cpp | codeclimate-testing/Windows-Driver-Frameworks | ece2036dbfa4f5e04e9376e8ceae4c761c9c6b08 | [
"MIT"
] | null | null | null | src/framework/shared/enhancedverif/verifier.cpp | codeclimate-testing/Windows-Driver-Frameworks | ece2036dbfa4f5e04e9376e8ceae4c761c9c6b08 | [
"MIT"
] | null | null | null | src/framework/shared/enhancedverif/verifier.cpp | codeclimate-testing/Windows-Driver-Frameworks | ece2036dbfa4f5e04e9376e8ceae4c761c9c6b08 | [
"MIT"
] | 1 | 2018-07-11T13:52:50.000Z | 2018-07-11T13:52:50.000Z | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
Module Name:
Verifier.cpp
Abstract:
This file has implementation of verifier support routines
Author:
Environment:
Shared (Kernel and user)
Revision History:
--*/
#include "vfpriv.hpp"
extern "C"
{
extern WDFVERSION WdfVersion;
// Tracing support
#if defined(EVENT_TRACING)
#include "verifier.tmh"
#endif
#ifdef ALLOC_PRAGMA
#pragma alloc_text(FX_ENHANCED_VERIFIER_SECTION_NAME, \
AddEventHooksWdfDeviceCreate, \
AddEventHooksWdfIoQueueCreate, \
VfAddContextToHandle, \
VfAllocateContext, \
VfWdfObjectGetTypedContext \
)
#endif
_Must_inspect_result_
NTSTATUS
AddEventHooksWdfDeviceCreate(
__inout PVF_HOOK_PROCESS_INFO HookProcessInfo,
__in PWDF_DRIVER_GLOBALS DriverGlobals,
__in PWDFDEVICE_INIT* DeviceInit,
__in PWDF_OBJECT_ATTRIBUTES DeviceAttributes,
__out WDFDEVICE* Device
)
/*++
Routine Description:
This routine is called by main hook for WdfDeviceCreate.
The routine swaps the event callbacks provided by client.
Arguments:
Return value:
--*/
{
NTSTATUS status;
PWDFDEVICE_INIT deviceInit = *DeviceInit;
WDF_PNPPOWER_EVENT_CALLBACKS pnpPowerEvtsOriginal;
WDF_PNPPOWER_EVENT_CALLBACKS *pnpPowerEvts;
PFX_DRIVER_GLOBALS pFxDriverGlobals;
PVOID contextHeader = NULL;
WDF_OBJECT_ATTRIBUTES attributes;
PAGED_CODE_LOCKED();
pFxDriverGlobals = GetFxDriverGlobals(DriverGlobals);
FxPointerNotNull(pFxDriverGlobals, DeviceInit);
FxPointerNotNull(pFxDriverGlobals, *DeviceInit);
FxPointerNotNull(pFxDriverGlobals, Device);
//
// Check if there are any callbacks set by the client driver. If not, we
// don't need any callback hooking.
//
if (deviceInit->PnpPower.PnpPowerEventCallbacks.Size !=
sizeof(WDF_PNPPOWER_EVENT_CALLBACKS)) {
//
// no hooking required.
//
status = STATUS_SUCCESS;
HookProcessInfo->DonotCallKmdfLib = FALSE;
return status;
}
//
// Hooking can be done only if we are able to allocate context memory.
// Try to allocate a context
//
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(
&attributes,
VF_WDFDEVICECREATE_CONTEXT
);
status = VfAllocateContext(DriverGlobals, &attributes, &contextHeader);
if (!NT_SUCCESS(status)) {
//
// couldn't allocate context. hooking not possible
//
HookProcessInfo->DonotCallKmdfLib = FALSE;
return status;
}
//
// store original driver callbacks to local variable
//
RtlCopyMemory(&pnpPowerEvtsOriginal,
&deviceInit->PnpPower.PnpPowerEventCallbacks,
sizeof(WDF_PNPPOWER_EVENT_CALLBACKS)
);
//
// Set callback hooks
//
// Normally override the hooks on local copy of stucture (not the original
// structure itself) and then pass the local struture to DDI call and
// copy back the original poniter when returning back to caller. In this case
// device_init is null'ed out by fx when returning to caller so we can
// directly override the original
//
pnpPowerEvts = &deviceInit->PnpPower.PnpPowerEventCallbacks;
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceD0Entry);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceD0EntryPostInterruptsEnabled);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceD0Exit);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceD0ExitPreInterruptsDisabled);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDevicePrepareHardware);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceReleaseHardware);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceSelfManagedIoCleanup);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceSelfManagedIoFlush);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceSelfManagedIoInit);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceSelfManagedIoSuspend);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceSelfManagedIoRestart);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceSurpriseRemoval);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceQueryRemove);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceQueryStop);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceUsageNotification);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceUsageNotificationEx);
SET_HOOK_IF_CALLBACK_PRESENT(pnpPowerEvts, pnpPowerEvts, EvtDeviceRelationsQuery);
//
// Call the DDI on behalf of driver.
//
status = ((PFN_WDFDEVICECREATE)WdfVersion.Functions.pfnWdfDeviceCreate)(
DriverGlobals,
DeviceInit,
DeviceAttributes,
Device
);
//
// Tell main hook routine not to call the DDI in kmdf lib since we
// already called it
//
HookProcessInfo->DonotCallKmdfLib = TRUE;
HookProcessInfo->DdiCallStatus = status;
//
// if DDI Succeeds, add context
//
if (NT_SUCCESS(status)) {
PVF_WDFDEVICECREATE_CONTEXT context = NULL;
//
// add the already allocated context to the object.
//
status = VfAddContextToHandle(contextHeader,
&attributes,
*Device,
(PVOID *)&context);
if (NT_SUCCESS(status)) {
//
// store the DriverGlobals pointer used to associate the driver
// with its client driver callback later in the callback hooks
//
context->CommonHeader.DriverGlobals = DriverGlobals;
//
// store original client driver callbacks in context
//
RtlCopyMemory(
&context->PnpPowerEventCallbacksOriginal,
&pnpPowerEvtsOriginal,
sizeof(WDF_PNPPOWER_EVENT_CALLBACKS)
);
}
else {
//
// For some reason adding context to handle failed. This should be
// rare failure, because context allocation was already successful,
// only adding to handle failed.
//
// Hooking failed if adding context is unsuccessful. This means
// kmdf has callbacks hooks but verifier cannot assiociate client
// driver callbacks with callback hooks. This would be a fatal error.
//
ASSERTMSG("KMDF Enhanced Verifier failed to add context to object "
"handle\n", FALSE);
if (contextHeader != NULL) {
FxPoolFree(contextHeader);
}
}
}
else {
//
// KMDF DDI call failed. In case of failure, DeviceInit is not NULL'ed
// so the driver could potentially call WdfDeviceCreate again with this
// DeviceInit that contains callback hooks, and result in infinite
// callback loop. So put original callbacks back
//
if ((*DeviceInit) != NULL) {
//
// we overwrote only the pnppower callbacks. Put the original back.
//
deviceInit = *DeviceInit;
RtlCopyMemory(&deviceInit->PnpPower.PnpPowerEventCallbacks,
&pnpPowerEvtsOriginal,
sizeof(WDF_PNPPOWER_EVENT_CALLBACKS)
);
}
if (contextHeader != NULL) {
FxPoolFree(contextHeader);
}
}
return status;
}
_Must_inspect_result_
NTSTATUS
AddEventHooksWdfIoQueueCreate(
__inout PVF_HOOK_PROCESS_INFO HookProcessInfo,
__in PWDF_DRIVER_GLOBALS DriverGlobals,
__in WDFDEVICE Device,
__in PWDF_IO_QUEUE_CONFIG Config,
__in PWDF_OBJECT_ATTRIBUTES QueueAttributes,
__out WDFQUEUE* Queue
)
/*++
Routine Description:
Arguments:
Return value:
--*/
{
NTSTATUS status;
WDF_IO_QUEUE_CONFIG configNew;
PFX_DRIVER_GLOBALS pFxDriverGlobals;
WDFQUEUE *pQueue;
WDFQUEUE queue;
PVOID contextHeader = NULL;
WDF_OBJECT_ATTRIBUTES attributes;
PAGED_CODE_LOCKED();
pFxDriverGlobals = GetFxDriverGlobals(DriverGlobals);
FxPointerNotNull(pFxDriverGlobals, Config);
//
// Check if there are any callbacks set by the client driver. If not, we
// don't need any callback hooking.
//
if (Config->Size != sizeof(WDF_IO_QUEUE_CONFIG)) {
//
// no hooking required.
//
status = STATUS_SUCCESS;
HookProcessInfo->DonotCallKmdfLib = FALSE;
return status;
}
//
// Hooking can be done only if we are able to allocate context memory.
// Try to allocate a context
//
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes,
VF_WDFIOQUEUECREATE_CONTEXT);
status = VfAllocateContext(DriverGlobals, &attributes, &contextHeader);
if (!NT_SUCCESS(status)) {
//
// couldn't allocate context. hooking not possible
//
HookProcessInfo->DonotCallKmdfLib = FALSE;
return status;
}
//
// create a local copy of config
//
RtlCopyMemory(&configNew,
Config,
sizeof(configNew)
);
//
// Override local copy with event callback hooks.
//
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoDefault);
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoRead);
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoWrite);
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoDeviceControl);
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoInternalDeviceControl);
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoStop);
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoResume);
SET_HOOK_IF_CALLBACK_PRESENT(Config, &configNew, EvtIoCanceledOnQueue);
//
// Queue handle is an optional parameter
//
if (Queue == NULL) {
pQueue = &queue;
}
else {
pQueue = Queue;
}
//
// call the DDI
//
status = WdfVersion.Functions.pfnWdfIoQueueCreate(
DriverGlobals,
Device,
&configNew,
QueueAttributes,
pQueue
);
//
// Tell main hook routine not to call the DDI in kmdf lib since we
// already called it
//
HookProcessInfo->DonotCallKmdfLib = TRUE;
HookProcessInfo->DdiCallStatus = status;
//
// if DDI Succeeds, add context
//
if (NT_SUCCESS(status)) {
PVF_WDFIOQUEUECREATE_CONTEXT context = NULL;
//
// add the already allocated context to the object.
//
status = VfAddContextToHandle(contextHeader,
&attributes,
*pQueue,
(PVOID *)&context);
if (NT_SUCCESS(status)) {
//
// store the DriverGlobals pointer used to associate the driver
// with its client driver callback later in the callback hooks
//
context->CommonHeader.DriverGlobals = DriverGlobals;
//
// add stored original callbacks to context
//
RtlCopyMemory(
&context->IoQueueConfigOriginal,
Config,
sizeof(WDF_IO_QUEUE_CONFIG)
);
}
else {
//
// For some reason adding context to handle failed. This should be
// rare failure, because context allocation was already successful,
// only adding to handle failed.
//
// Hooking failed if adding context is unsuccessful. This means
// kmdf has callbacks hooks but verifier cannot assiociate client
// driver callbacks with callback hooks. This would be a fatal error.
//
ASSERTMSG("KMDF Enhanced Verifier failed to add context to object "
"handle\n", FALSE);
if (contextHeader != NULL) {
FxPoolFree(contextHeader);
}
}
}
else {
//
// DDI call to KMDF failed. Nothing to do by verifier. Just return
// kmdf's status after freeing context header memory.
//
if (contextHeader != NULL) {
FxPoolFree(contextHeader);
}
}
return status;
}
_Must_inspect_result_
PVOID
FASTCALL
VfWdfObjectGetTypedContext(
__in
WDFOBJECT Handle,
__in
PCWDF_OBJECT_CONTEXT_TYPE_INFO TypeInfo
)
/*++
Routine Description:
Retrieves the requested type from a handle
Arguments:
Handle - the handle to retrieve the context from
TypeInfo - global constant pointer which describes the type. Since the pointer
value is unique in all of kernel space, we will perform a pointer compare
instead of a deep structure compare
Return Value:
A valid context pointere or NULL. NULL is not a failure, querying for a type
not associated with the handle is a legitimate operation.
--*/
{
FxContextHeader* pHeader;
FxObject* pObject;
PFX_DRIVER_GLOBALS pFxDriverGlobals;
WDFOBJECT_OFFSET offset;
PAGED_CODE_LOCKED();
//
// Do not call FxObjectHandleGetPtr( , , FX_TYPE_OBJECT) because this is a
// hot spot / workhorse function that should be as efficient as possible.
//
// A call to FxObjectHandleGetPtr would :
// 1) invoke a virtual call to QueryInterface
//
// 2) ASSERT that the ref count of the object is > zero. Since this is one
// of the few functions that can be called in EvtObjectDestroy where the
// ref count is zero, that is not a good side affect.
//
offset = 0;
pObject = FxObject::_GetObjectFromHandle(Handle, &offset);
//
// Use the object's globals, not the caller's
//
pFxDriverGlobals = pObject->GetDriverGlobals();
FxPointerNotNull(pFxDriverGlobals, Handle);
FxPointerNotNull(pFxDriverGlobals, TypeInfo);
pHeader = pObject->GetContextHeader();
for ( ; pHeader != NULL; pHeader = pHeader->NextHeader) {
if (pHeader->ContextTypeInfo == TypeInfo) {
return &pHeader->Context[0];
}
}
PCHAR pGivenName;
if (TypeInfo->ContextName != NULL) {
pGivenName = TypeInfo->ContextName;
}
else {
pGivenName = "<no typename given>";
}
DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_WARNING, TRACINGDEVICE,
"Attempting to get context type %s from WDFOBJECT 0x%p",
pGivenName, Handle);
return NULL;
}
_Must_inspect_result_
NTSTATUS
VfAllocateContext(
__in PWDF_DRIVER_GLOBALS DriverGlobals,
__in PWDF_OBJECT_ATTRIBUTES Attributes,
__out PVOID* ContextHeader
)
/*++
Routine Description:
Allocates an additional context on the handle if the object is in the
correct state
Arguments:
Handle - handle on which to add a context
Attributes - attributes which describe the type and size of the new context
Context - optional pointer which will recieve the new context
Return Value:
STATUS_SUCCESS upon success, STATUS_OBJECT_NAME_EXISTS if the context type
is already attached to the handle, and !NT_SUCCESS on failure
--*/
{
PFX_DRIVER_GLOBALS pFxDriverGlobals;
NTSTATUS status;
FxContextHeader *pHeader;
size_t size;
PAGED_CODE_LOCKED();
pFxDriverGlobals = GetFxDriverGlobals(DriverGlobals);
status = FxValidateObjectAttributes(
pFxDriverGlobals, Attributes, FX_VALIDATE_OPTION_ATTRIBUTES_REQUIRED);
if (!NT_SUCCESS(status)) {
return status;
}
//
// Must have a context type!
//
if (Attributes->ContextTypeInfo == NULL) {
status = STATUS_OBJECT_NAME_INVALID;
DoTraceLevelMessage(
pFxDriverGlobals, TRACE_LEVEL_WARNING, TRACINGHANDLE,
"Attributes %p ContextTypeInfo is NULL, %!STATUS!",
Attributes, status);
return status;
}
//
// By passing 0's for raw object size and extra size, we can compute the
// size of only the header and its contents.
//
status = FxCalculateObjectTotalSize(pFxDriverGlobals, 0, 0, Attributes, &size);
if (!NT_SUCCESS(status)) {
return status;
}
pHeader = (FxContextHeader*)
FxPoolAllocate(pFxDriverGlobals, NonPagedPool, size);
if (pHeader != NULL) {
*ContextHeader = pHeader;
status = STATUS_SUCCESS;
}
else {
status = STATUS_INSUFFICIENT_RESOURCES;
}
return status;
}
_Must_inspect_result_
NTSTATUS
VfAddContextToHandle(
__in PVOID ContextHeader,
__in PWDF_OBJECT_ATTRIBUTES Attributes,
__in WDFOBJECT Handle,
__out_opt PVOID* Context
)
{
PFX_DRIVER_GLOBALS pFxDriverGlobals;
NTSTATUS status = STATUS_SUCCESS;
FxObject* pObject;
FxContextHeader *pHeader;
WDFOBJECT_OFFSET offset;
PAGED_CODE_LOCKED();
pHeader = (FxContextHeader *)ContextHeader;
if (pHeader == NULL) {
return STATUS_INVALID_PARAMETER;
}
//
// No need to call FxObjectHandleGetPtr( , , FX_TYPE_OBJECT) because
// we assume that the object handle will point back to an FxObject. (The
// call to FxObjectHandleGetPtr will just make needless virtual call into
// FxObject anyways).
//
offset = 0;
pObject = FxObject::_GetObjectFromHandle(Handle, &offset);
pFxDriverGlobals = pObject->GetDriverGlobals();
if (offset != 0) {
//
// for lack of a better error code
//
status = STATUS_OBJECT_PATH_INVALID;
DoTraceLevelMessage(
pFxDriverGlobals, TRACE_LEVEL_WARNING, TRACINGHANDLE,
"WDFHANDLE %p cannot have contexts added to it, %!STATUS!",
Handle, status);
goto cleanup;
}
pObject->ADDREF(&status);
FxContextHeaderInit(pHeader, pObject, Attributes);
status = pObject->AddContext(pHeader, Context, Attributes);
//
// STATUS_OBJECT_NAME_EXISTS will not fail NT_SUCCESS, so check
// explicitly for STATUS_SUCCESS.
//
if (status != STATUS_SUCCESS) {
DoTraceLevelMessage(
pFxDriverGlobals, TRACE_LEVEL_WARNING, TRACINGHANDLE,
"WDFHANDLE %p failed to add context, %!STATUS!",
Handle, status);
}
pObject->RELEASE(&status);
cleanup:
if (status != STATUS_SUCCESS && pHeader != NULL) {
FxPoolFree(pHeader);
}
return status;
}
} // extern "C"
| 29.551459 | 100 | 0.637488 | codeclimate-testing |
148c8de06159112ab784c00a158751e7407616e8 | 1,758 | hpp | C++ | Runtime/Character/CBoneTracking.hpp | jackoalan/urde | 413483a996805a870f002324ee46cfc123f4df06 | [
"MIT"
] | null | null | null | Runtime/Character/CBoneTracking.hpp | jackoalan/urde | 413483a996805a870f002324ee46cfc123f4df06 | [
"MIT"
] | null | null | null | Runtime/Character/CBoneTracking.hpp | jackoalan/urde | 413483a996805a870f002324ee46cfc123f4df06 | [
"MIT"
] | null | null | null | #pragma once
#include <optional>
#include <string_view>
#include "Runtime/RetroTypes.hpp"
#include "Runtime/Character/CSegId.hpp"
#include <zeus/CQuaternion.hpp>
#include <zeus/CTransform.hpp>
#include <zeus/CVector3f.hpp>
namespace urde {
class CAnimData;
class CStateManager;
class CBodyController;
enum class EBoneTrackingFlags {
None = 0,
NoParent = 1,
NoParentOrigin = 2,
NoHorizontalAim = 4,
ParentIk = 8
};
ENABLE_BITWISE_ENUM(EBoneTrackingFlags)
class CBoneTracking {
zeus::CQuaternion x0_curRotation = zeus::CQuaternion();
float x10_ = 0.f;
CSegId x14_segId;
float x18_time = 0.f;
float x1c_maxTrackingAngle;
float x20_angSpeed;
std::optional<zeus::CVector3f> x24_targetPosition;
TUniqueId x34_target = kInvalidUniqueId;
union {
struct {
bool x36_24_active : 1;
bool x36_25_hasTrackedRotation : 1;
bool x36_26_noParent : 1;
bool x36_27_noParentOrigin : 1;
bool x36_28_noHorizontalAim : 1;
bool x36_29_parentIk : 1;
};
u32 _dummy = 0;
};
public:
CBoneTracking(const CAnimData& animData, std::string_view bone,
float maxTrackingAngle, float angSpeed, EBoneTrackingFlags flags);
void Update(float dt);
void PreRender(const CStateManager& mgr, CAnimData& animData, const zeus::CTransform& xf,
const zeus::CVector3f& vec, const CBodyController& bodyController);
void PreRender(const CStateManager& mgr, CAnimData& animData, const zeus::CTransform& worldXf,
const zeus::CVector3f& localOffsetScale, bool tracking);
void SetActive(bool active);
void SetTarget(TUniqueId id);
void UnsetTarget();
void SetTargetPosition(const zeus::CVector3f& pos);
void SetNoHorizontalAim(bool b);
};
} // namespace urde | 27.904762 | 96 | 0.721274 | jackoalan |
1496132e73214ad33317fd3841a44801b373584c | 687 | hpp | C++ | brain/plugins/naive/NaiveDevelopment.hpp | danielrh/elysia | fb462e02ca3bada3b9e904cbc50684b5b72ec50d | [
"BSD-3-Clause"
] | 9 | 2015-08-08T05:16:45.000Z | 2022-02-09T09:53:22.000Z | brain/plugins/naive/NaiveDevelopment.hpp | danielrh/elysia | fb462e02ca3bada3b9e904cbc50684b5b72ec50d | [
"BSD-3-Clause"
] | null | null | null | brain/plugins/naive/NaiveDevelopment.hpp | danielrh/elysia | fb462e02ca3bada3b9e904cbc50684b5b72ec50d | [
"BSD-3-Clause"
] | 3 | 2015-10-21T11:11:11.000Z | 2021-01-11T19:08:29.000Z |
#include "StandardDevelopment.hpp"
namespace Elysia {
class NaiveDevelopment: public StandardDevelopment<NaiveDevelopment> {
float mDevelopmentSignal;
float mBestDevelopmentSignal;
void passDevelopmentSignal(CellComponent*component,
float signalWeight);
public:
NaiveDevelopment();
virtual void passDevelopmentSignal(Synapse*s,
CellComponent*sParent,
float signalWeight);
void developSynapse(Synapse *s, const ActivityStats&stats);
void mature();
static bool initNaiveDevelopmentLibrary();
static bool deinitNaiveDevelopmentLibrary();
};
}
| 32.714286 | 70 | 0.660844 | danielrh |
1496c352517dac9bf341b3849eaf4cdc8f9bc6bb | 36,851 | cpp | C++ | ckafka/src/v20190819/model/InstanceAttributesResponse.cpp | TencentCloud/tencentcloud-sdk-cpp | 896da198abe6f75c0dc90901131d709143186b77 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | ckafka/src/v20190819/model/InstanceAttributesResponse.cpp | TencentCloud/tencentcloud-sdk-cpp | 896da198abe6f75c0dc90901131d709143186b77 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | ckafka/src/v20190819/model/InstanceAttributesResponse.cpp | TencentCloud/tencentcloud-sdk-cpp | 896da198abe6f75c0dc90901131d709143186b77 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/ckafka/v20190819/model/InstanceAttributesResponse.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ckafka::V20190819::Model;
using namespace std;
InstanceAttributesResponse::InstanceAttributesResponse() :
m_instanceIdHasBeenSet(false),
m_instanceNameHasBeenSet(false),
m_vipListHasBeenSet(false),
m_vipHasBeenSet(false),
m_vportHasBeenSet(false),
m_statusHasBeenSet(false),
m_bandwidthHasBeenSet(false),
m_diskSizeHasBeenSet(false),
m_zoneIdHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_subnetIdHasBeenSet(false),
m_healthyHasBeenSet(false),
m_healthyMessageHasBeenSet(false),
m_createTimeHasBeenSet(false),
m_msgRetentionTimeHasBeenSet(false),
m_configHasBeenSet(false),
m_remainderPartitionsHasBeenSet(false),
m_remainderTopicsHasBeenSet(false),
m_createdPartitionsHasBeenSet(false),
m_createdTopicsHasBeenSet(false),
m_tagsHasBeenSet(false),
m_expireTimeHasBeenSet(false),
m_zoneIdsHasBeenSet(false),
m_versionHasBeenSet(false),
m_maxGroupNumHasBeenSet(false),
m_cvmHasBeenSet(false),
m_instanceTypeHasBeenSet(false),
m_featuresHasBeenSet(false),
m_retentionTimeConfigHasBeenSet(false),
m_maxConnectionHasBeenSet(false),
m_publicNetworkHasBeenSet(false),
m_deleteRouteTimestampHasBeenSet(false)
{
}
CoreInternalOutcome InstanceAttributesResponse::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("InstanceId") && !value["InstanceId"].IsNull())
{
if (!value["InstanceId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.InstanceId` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceId = string(value["InstanceId"].GetString());
m_instanceIdHasBeenSet = true;
}
if (value.HasMember("InstanceName") && !value["InstanceName"].IsNull())
{
if (!value["InstanceName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.InstanceName` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceName = string(value["InstanceName"].GetString());
m_instanceNameHasBeenSet = true;
}
if (value.HasMember("VipList") && !value["VipList"].IsNull())
{
if (!value["VipList"].IsArray())
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.VipList` is not array type"));
const rapidjson::Value &tmpValue = value["VipList"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
VipEntity item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_vipList.push_back(item);
}
m_vipListHasBeenSet = true;
}
if (value.HasMember("Vip") && !value["Vip"].IsNull())
{
if (!value["Vip"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Vip` IsString=false incorrectly").SetRequestId(requestId));
}
m_vip = string(value["Vip"].GetString());
m_vipHasBeenSet = true;
}
if (value.HasMember("Vport") && !value["Vport"].IsNull())
{
if (!value["Vport"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Vport` IsString=false incorrectly").SetRequestId(requestId));
}
m_vport = string(value["Vport"].GetString());
m_vportHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Status` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_status = value["Status"].GetInt64();
m_statusHasBeenSet = true;
}
if (value.HasMember("Bandwidth") && !value["Bandwidth"].IsNull())
{
if (!value["Bandwidth"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Bandwidth` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_bandwidth = value["Bandwidth"].GetInt64();
m_bandwidthHasBeenSet = true;
}
if (value.HasMember("DiskSize") && !value["DiskSize"].IsNull())
{
if (!value["DiskSize"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.DiskSize` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_diskSize = value["DiskSize"].GetInt64();
m_diskSizeHasBeenSet = true;
}
if (value.HasMember("ZoneId") && !value["ZoneId"].IsNull())
{
if (!value["ZoneId"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.ZoneId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_zoneId = value["ZoneId"].GetInt64();
m_zoneIdHasBeenSet = true;
}
if (value.HasMember("VpcId") && !value["VpcId"].IsNull())
{
if (!value["VpcId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.VpcId` IsString=false incorrectly").SetRequestId(requestId));
}
m_vpcId = string(value["VpcId"].GetString());
m_vpcIdHasBeenSet = true;
}
if (value.HasMember("SubnetId") && !value["SubnetId"].IsNull())
{
if (!value["SubnetId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.SubnetId` IsString=false incorrectly").SetRequestId(requestId));
}
m_subnetId = string(value["SubnetId"].GetString());
m_subnetIdHasBeenSet = true;
}
if (value.HasMember("Healthy") && !value["Healthy"].IsNull())
{
if (!value["Healthy"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Healthy` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_healthy = value["Healthy"].GetInt64();
m_healthyHasBeenSet = true;
}
if (value.HasMember("HealthyMessage") && !value["HealthyMessage"].IsNull())
{
if (!value["HealthyMessage"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.HealthyMessage` IsString=false incorrectly").SetRequestId(requestId));
}
m_healthyMessage = string(value["HealthyMessage"].GetString());
m_healthyMessageHasBeenSet = true;
}
if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull())
{
if (!value["CreateTime"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.CreateTime` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_createTime = value["CreateTime"].GetUint64();
m_createTimeHasBeenSet = true;
}
if (value.HasMember("MsgRetentionTime") && !value["MsgRetentionTime"].IsNull())
{
if (!value["MsgRetentionTime"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.MsgRetentionTime` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_msgRetentionTime = value["MsgRetentionTime"].GetInt64();
m_msgRetentionTimeHasBeenSet = true;
}
if (value.HasMember("Config") && !value["Config"].IsNull())
{
if (!value["Config"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Config` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_config.Deserialize(value["Config"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_configHasBeenSet = true;
}
if (value.HasMember("RemainderPartitions") && !value["RemainderPartitions"].IsNull())
{
if (!value["RemainderPartitions"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.RemainderPartitions` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_remainderPartitions = value["RemainderPartitions"].GetInt64();
m_remainderPartitionsHasBeenSet = true;
}
if (value.HasMember("RemainderTopics") && !value["RemainderTopics"].IsNull())
{
if (!value["RemainderTopics"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.RemainderTopics` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_remainderTopics = value["RemainderTopics"].GetInt64();
m_remainderTopicsHasBeenSet = true;
}
if (value.HasMember("CreatedPartitions") && !value["CreatedPartitions"].IsNull())
{
if (!value["CreatedPartitions"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.CreatedPartitions` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_createdPartitions = value["CreatedPartitions"].GetInt64();
m_createdPartitionsHasBeenSet = true;
}
if (value.HasMember("CreatedTopics") && !value["CreatedTopics"].IsNull())
{
if (!value["CreatedTopics"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.CreatedTopics` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_createdTopics = value["CreatedTopics"].GetInt64();
m_createdTopicsHasBeenSet = true;
}
if (value.HasMember("Tags") && !value["Tags"].IsNull())
{
if (!value["Tags"].IsArray())
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Tags` is not array type"));
const rapidjson::Value &tmpValue = value["Tags"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Tag item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_tags.push_back(item);
}
m_tagsHasBeenSet = true;
}
if (value.HasMember("ExpireTime") && !value["ExpireTime"].IsNull())
{
if (!value["ExpireTime"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.ExpireTime` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_expireTime = value["ExpireTime"].GetUint64();
m_expireTimeHasBeenSet = true;
}
if (value.HasMember("ZoneIds") && !value["ZoneIds"].IsNull())
{
if (!value["ZoneIds"].IsArray())
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.ZoneIds` is not array type"));
const rapidjson::Value &tmpValue = value["ZoneIds"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_zoneIds.push_back((*itr).GetInt64());
}
m_zoneIdsHasBeenSet = true;
}
if (value.HasMember("Version") && !value["Version"].IsNull())
{
if (!value["Version"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Version` IsString=false incorrectly").SetRequestId(requestId));
}
m_version = string(value["Version"].GetString());
m_versionHasBeenSet = true;
}
if (value.HasMember("MaxGroupNum") && !value["MaxGroupNum"].IsNull())
{
if (!value["MaxGroupNum"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.MaxGroupNum` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_maxGroupNum = value["MaxGroupNum"].GetInt64();
m_maxGroupNumHasBeenSet = true;
}
if (value.HasMember("Cvm") && !value["Cvm"].IsNull())
{
if (!value["Cvm"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Cvm` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_cvm = value["Cvm"].GetInt64();
m_cvmHasBeenSet = true;
}
if (value.HasMember("InstanceType") && !value["InstanceType"].IsNull())
{
if (!value["InstanceType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.InstanceType` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceType = string(value["InstanceType"].GetString());
m_instanceTypeHasBeenSet = true;
}
if (value.HasMember("Features") && !value["Features"].IsNull())
{
if (!value["Features"].IsArray())
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.Features` is not array type"));
const rapidjson::Value &tmpValue = value["Features"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_features.push_back((*itr).GetString());
}
m_featuresHasBeenSet = true;
}
if (value.HasMember("RetentionTimeConfig") && !value["RetentionTimeConfig"].IsNull())
{
if (!value["RetentionTimeConfig"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.RetentionTimeConfig` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_retentionTimeConfig.Deserialize(value["RetentionTimeConfig"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_retentionTimeConfigHasBeenSet = true;
}
if (value.HasMember("MaxConnection") && !value["MaxConnection"].IsNull())
{
if (!value["MaxConnection"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.MaxConnection` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_maxConnection = value["MaxConnection"].GetUint64();
m_maxConnectionHasBeenSet = true;
}
if (value.HasMember("PublicNetwork") && !value["PublicNetwork"].IsNull())
{
if (!value["PublicNetwork"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.PublicNetwork` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_publicNetwork = value["PublicNetwork"].GetInt64();
m_publicNetworkHasBeenSet = true;
}
if (value.HasMember("DeleteRouteTimestamp") && !value["DeleteRouteTimestamp"].IsNull())
{
if (!value["DeleteRouteTimestamp"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceAttributesResponse.DeleteRouteTimestamp` IsString=false incorrectly").SetRequestId(requestId));
}
m_deleteRouteTimestamp = string(value["DeleteRouteTimestamp"].GetString());
m_deleteRouteTimestampHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void InstanceAttributesResponse::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_instanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_instanceNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_instanceName.c_str(), allocator).Move(), allocator);
}
if (m_vipListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VipList";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_vipList.begin(); itr != m_vipList.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_vipHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Vip";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_vip.c_str(), allocator).Move(), allocator);
}
if (m_vportHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Vport";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_vport.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_status, allocator);
}
if (m_bandwidthHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Bandwidth";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_bandwidth, allocator);
}
if (m_diskSizeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DiskSize";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_diskSize, allocator);
}
if (m_zoneIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ZoneId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_zoneId, allocator);
}
if (m_vpcIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VpcId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_vpcId.c_str(), allocator).Move(), allocator);
}
if (m_subnetIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SubnetId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_subnetId.c_str(), allocator).Move(), allocator);
}
if (m_healthyHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Healthy";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_healthy, allocator);
}
if (m_healthyMessageHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HealthyMessage";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_healthyMessage.c_str(), allocator).Move(), allocator);
}
if (m_createTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreateTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_createTime, allocator);
}
if (m_msgRetentionTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MsgRetentionTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_msgRetentionTime, allocator);
}
if (m_configHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Config";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_config.ToJsonObject(value[key.c_str()], allocator);
}
if (m_remainderPartitionsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RemainderPartitions";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_remainderPartitions, allocator);
}
if (m_remainderTopicsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RemainderTopics";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_remainderTopics, allocator);
}
if (m_createdPartitionsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreatedPartitions";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_createdPartitions, allocator);
}
if (m_createdTopicsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreatedTopics";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_createdTopics, allocator);
}
if (m_tagsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Tags";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_expireTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExpireTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_expireTime, allocator);
}
if (m_zoneIdsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ZoneIds";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_zoneIds.begin(); itr != m_zoneIds.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetInt64(*itr), allocator);
}
}
if (m_versionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Version";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_version.c_str(), allocator).Move(), allocator);
}
if (m_maxGroupNumHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MaxGroupNum";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_maxGroupNum, allocator);
}
if (m_cvmHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Cvm";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_cvm, allocator);
}
if (m_instanceTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_instanceType.c_str(), allocator).Move(), allocator);
}
if (m_featuresHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Features";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_features.begin(); itr != m_features.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_retentionTimeConfigHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RetentionTimeConfig";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_retentionTimeConfig.ToJsonObject(value[key.c_str()], allocator);
}
if (m_maxConnectionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MaxConnection";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_maxConnection, allocator);
}
if (m_publicNetworkHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PublicNetwork";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_publicNetwork, allocator);
}
if (m_deleteRouteTimestampHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeleteRouteTimestamp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_deleteRouteTimestamp.c_str(), allocator).Move(), allocator);
}
}
string InstanceAttributesResponse::GetInstanceId() const
{
return m_instanceId;
}
void InstanceAttributesResponse::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool InstanceAttributesResponse::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
string InstanceAttributesResponse::GetInstanceName() const
{
return m_instanceName;
}
void InstanceAttributesResponse::SetInstanceName(const string& _instanceName)
{
m_instanceName = _instanceName;
m_instanceNameHasBeenSet = true;
}
bool InstanceAttributesResponse::InstanceNameHasBeenSet() const
{
return m_instanceNameHasBeenSet;
}
vector<VipEntity> InstanceAttributesResponse::GetVipList() const
{
return m_vipList;
}
void InstanceAttributesResponse::SetVipList(const vector<VipEntity>& _vipList)
{
m_vipList = _vipList;
m_vipListHasBeenSet = true;
}
bool InstanceAttributesResponse::VipListHasBeenSet() const
{
return m_vipListHasBeenSet;
}
string InstanceAttributesResponse::GetVip() const
{
return m_vip;
}
void InstanceAttributesResponse::SetVip(const string& _vip)
{
m_vip = _vip;
m_vipHasBeenSet = true;
}
bool InstanceAttributesResponse::VipHasBeenSet() const
{
return m_vipHasBeenSet;
}
string InstanceAttributesResponse::GetVport() const
{
return m_vport;
}
void InstanceAttributesResponse::SetVport(const string& _vport)
{
m_vport = _vport;
m_vportHasBeenSet = true;
}
bool InstanceAttributesResponse::VportHasBeenSet() const
{
return m_vportHasBeenSet;
}
int64_t InstanceAttributesResponse::GetStatus() const
{
return m_status;
}
void InstanceAttributesResponse::SetStatus(const int64_t& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool InstanceAttributesResponse::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
int64_t InstanceAttributesResponse::GetBandwidth() const
{
return m_bandwidth;
}
void InstanceAttributesResponse::SetBandwidth(const int64_t& _bandwidth)
{
m_bandwidth = _bandwidth;
m_bandwidthHasBeenSet = true;
}
bool InstanceAttributesResponse::BandwidthHasBeenSet() const
{
return m_bandwidthHasBeenSet;
}
int64_t InstanceAttributesResponse::GetDiskSize() const
{
return m_diskSize;
}
void InstanceAttributesResponse::SetDiskSize(const int64_t& _diskSize)
{
m_diskSize = _diskSize;
m_diskSizeHasBeenSet = true;
}
bool InstanceAttributesResponse::DiskSizeHasBeenSet() const
{
return m_diskSizeHasBeenSet;
}
int64_t InstanceAttributesResponse::GetZoneId() const
{
return m_zoneId;
}
void InstanceAttributesResponse::SetZoneId(const int64_t& _zoneId)
{
m_zoneId = _zoneId;
m_zoneIdHasBeenSet = true;
}
bool InstanceAttributesResponse::ZoneIdHasBeenSet() const
{
return m_zoneIdHasBeenSet;
}
string InstanceAttributesResponse::GetVpcId() const
{
return m_vpcId;
}
void InstanceAttributesResponse::SetVpcId(const string& _vpcId)
{
m_vpcId = _vpcId;
m_vpcIdHasBeenSet = true;
}
bool InstanceAttributesResponse::VpcIdHasBeenSet() const
{
return m_vpcIdHasBeenSet;
}
string InstanceAttributesResponse::GetSubnetId() const
{
return m_subnetId;
}
void InstanceAttributesResponse::SetSubnetId(const string& _subnetId)
{
m_subnetId = _subnetId;
m_subnetIdHasBeenSet = true;
}
bool InstanceAttributesResponse::SubnetIdHasBeenSet() const
{
return m_subnetIdHasBeenSet;
}
int64_t InstanceAttributesResponse::GetHealthy() const
{
return m_healthy;
}
void InstanceAttributesResponse::SetHealthy(const int64_t& _healthy)
{
m_healthy = _healthy;
m_healthyHasBeenSet = true;
}
bool InstanceAttributesResponse::HealthyHasBeenSet() const
{
return m_healthyHasBeenSet;
}
string InstanceAttributesResponse::GetHealthyMessage() const
{
return m_healthyMessage;
}
void InstanceAttributesResponse::SetHealthyMessage(const string& _healthyMessage)
{
m_healthyMessage = _healthyMessage;
m_healthyMessageHasBeenSet = true;
}
bool InstanceAttributesResponse::HealthyMessageHasBeenSet() const
{
return m_healthyMessageHasBeenSet;
}
uint64_t InstanceAttributesResponse::GetCreateTime() const
{
return m_createTime;
}
void InstanceAttributesResponse::SetCreateTime(const uint64_t& _createTime)
{
m_createTime = _createTime;
m_createTimeHasBeenSet = true;
}
bool InstanceAttributesResponse::CreateTimeHasBeenSet() const
{
return m_createTimeHasBeenSet;
}
int64_t InstanceAttributesResponse::GetMsgRetentionTime() const
{
return m_msgRetentionTime;
}
void InstanceAttributesResponse::SetMsgRetentionTime(const int64_t& _msgRetentionTime)
{
m_msgRetentionTime = _msgRetentionTime;
m_msgRetentionTimeHasBeenSet = true;
}
bool InstanceAttributesResponse::MsgRetentionTimeHasBeenSet() const
{
return m_msgRetentionTimeHasBeenSet;
}
InstanceConfigDO InstanceAttributesResponse::GetConfig() const
{
return m_config;
}
void InstanceAttributesResponse::SetConfig(const InstanceConfigDO& _config)
{
m_config = _config;
m_configHasBeenSet = true;
}
bool InstanceAttributesResponse::ConfigHasBeenSet() const
{
return m_configHasBeenSet;
}
int64_t InstanceAttributesResponse::GetRemainderPartitions() const
{
return m_remainderPartitions;
}
void InstanceAttributesResponse::SetRemainderPartitions(const int64_t& _remainderPartitions)
{
m_remainderPartitions = _remainderPartitions;
m_remainderPartitionsHasBeenSet = true;
}
bool InstanceAttributesResponse::RemainderPartitionsHasBeenSet() const
{
return m_remainderPartitionsHasBeenSet;
}
int64_t InstanceAttributesResponse::GetRemainderTopics() const
{
return m_remainderTopics;
}
void InstanceAttributesResponse::SetRemainderTopics(const int64_t& _remainderTopics)
{
m_remainderTopics = _remainderTopics;
m_remainderTopicsHasBeenSet = true;
}
bool InstanceAttributesResponse::RemainderTopicsHasBeenSet() const
{
return m_remainderTopicsHasBeenSet;
}
int64_t InstanceAttributesResponse::GetCreatedPartitions() const
{
return m_createdPartitions;
}
void InstanceAttributesResponse::SetCreatedPartitions(const int64_t& _createdPartitions)
{
m_createdPartitions = _createdPartitions;
m_createdPartitionsHasBeenSet = true;
}
bool InstanceAttributesResponse::CreatedPartitionsHasBeenSet() const
{
return m_createdPartitionsHasBeenSet;
}
int64_t InstanceAttributesResponse::GetCreatedTopics() const
{
return m_createdTopics;
}
void InstanceAttributesResponse::SetCreatedTopics(const int64_t& _createdTopics)
{
m_createdTopics = _createdTopics;
m_createdTopicsHasBeenSet = true;
}
bool InstanceAttributesResponse::CreatedTopicsHasBeenSet() const
{
return m_createdTopicsHasBeenSet;
}
vector<Tag> InstanceAttributesResponse::GetTags() const
{
return m_tags;
}
void InstanceAttributesResponse::SetTags(const vector<Tag>& _tags)
{
m_tags = _tags;
m_tagsHasBeenSet = true;
}
bool InstanceAttributesResponse::TagsHasBeenSet() const
{
return m_tagsHasBeenSet;
}
uint64_t InstanceAttributesResponse::GetExpireTime() const
{
return m_expireTime;
}
void InstanceAttributesResponse::SetExpireTime(const uint64_t& _expireTime)
{
m_expireTime = _expireTime;
m_expireTimeHasBeenSet = true;
}
bool InstanceAttributesResponse::ExpireTimeHasBeenSet() const
{
return m_expireTimeHasBeenSet;
}
vector<int64_t> InstanceAttributesResponse::GetZoneIds() const
{
return m_zoneIds;
}
void InstanceAttributesResponse::SetZoneIds(const vector<int64_t>& _zoneIds)
{
m_zoneIds = _zoneIds;
m_zoneIdsHasBeenSet = true;
}
bool InstanceAttributesResponse::ZoneIdsHasBeenSet() const
{
return m_zoneIdsHasBeenSet;
}
string InstanceAttributesResponse::GetVersion() const
{
return m_version;
}
void InstanceAttributesResponse::SetVersion(const string& _version)
{
m_version = _version;
m_versionHasBeenSet = true;
}
bool InstanceAttributesResponse::VersionHasBeenSet() const
{
return m_versionHasBeenSet;
}
int64_t InstanceAttributesResponse::GetMaxGroupNum() const
{
return m_maxGroupNum;
}
void InstanceAttributesResponse::SetMaxGroupNum(const int64_t& _maxGroupNum)
{
m_maxGroupNum = _maxGroupNum;
m_maxGroupNumHasBeenSet = true;
}
bool InstanceAttributesResponse::MaxGroupNumHasBeenSet() const
{
return m_maxGroupNumHasBeenSet;
}
int64_t InstanceAttributesResponse::GetCvm() const
{
return m_cvm;
}
void InstanceAttributesResponse::SetCvm(const int64_t& _cvm)
{
m_cvm = _cvm;
m_cvmHasBeenSet = true;
}
bool InstanceAttributesResponse::CvmHasBeenSet() const
{
return m_cvmHasBeenSet;
}
string InstanceAttributesResponse::GetInstanceType() const
{
return m_instanceType;
}
void InstanceAttributesResponse::SetInstanceType(const string& _instanceType)
{
m_instanceType = _instanceType;
m_instanceTypeHasBeenSet = true;
}
bool InstanceAttributesResponse::InstanceTypeHasBeenSet() const
{
return m_instanceTypeHasBeenSet;
}
vector<string> InstanceAttributesResponse::GetFeatures() const
{
return m_features;
}
void InstanceAttributesResponse::SetFeatures(const vector<string>& _features)
{
m_features = _features;
m_featuresHasBeenSet = true;
}
bool InstanceAttributesResponse::FeaturesHasBeenSet() const
{
return m_featuresHasBeenSet;
}
DynamicRetentionTime InstanceAttributesResponse::GetRetentionTimeConfig() const
{
return m_retentionTimeConfig;
}
void InstanceAttributesResponse::SetRetentionTimeConfig(const DynamicRetentionTime& _retentionTimeConfig)
{
m_retentionTimeConfig = _retentionTimeConfig;
m_retentionTimeConfigHasBeenSet = true;
}
bool InstanceAttributesResponse::RetentionTimeConfigHasBeenSet() const
{
return m_retentionTimeConfigHasBeenSet;
}
uint64_t InstanceAttributesResponse::GetMaxConnection() const
{
return m_maxConnection;
}
void InstanceAttributesResponse::SetMaxConnection(const uint64_t& _maxConnection)
{
m_maxConnection = _maxConnection;
m_maxConnectionHasBeenSet = true;
}
bool InstanceAttributesResponse::MaxConnectionHasBeenSet() const
{
return m_maxConnectionHasBeenSet;
}
int64_t InstanceAttributesResponse::GetPublicNetwork() const
{
return m_publicNetwork;
}
void InstanceAttributesResponse::SetPublicNetwork(const int64_t& _publicNetwork)
{
m_publicNetwork = _publicNetwork;
m_publicNetworkHasBeenSet = true;
}
bool InstanceAttributesResponse::PublicNetworkHasBeenSet() const
{
return m_publicNetworkHasBeenSet;
}
string InstanceAttributesResponse::GetDeleteRouteTimestamp() const
{
return m_deleteRouteTimestamp;
}
void InstanceAttributesResponse::SetDeleteRouteTimestamp(const string& _deleteRouteTimestamp)
{
m_deleteRouteTimestamp = _deleteRouteTimestamp;
m_deleteRouteTimestampHasBeenSet = true;
}
bool InstanceAttributesResponse::DeleteRouteTimestampHasBeenSet() const
{
return m_deleteRouteTimestampHasBeenSet;
}
| 30.008958 | 165 | 0.686494 | TencentCloud |
149bb0962c3483d3de9ae32d6163b3a4678fb0c4 | 17,022 | cpp | C++ | Plugins/DotNET/DotNETExports.cpp | Lord-Nightmare/unified | 4b6c7351f1389b741667abe03f950313dcde8e1c | [
"MIT"
] | null | null | null | Plugins/DotNET/DotNETExports.cpp | Lord-Nightmare/unified | 4b6c7351f1389b741667abe03f950313dcde8e1c | [
"MIT"
] | null | null | null | Plugins/DotNET/DotNETExports.cpp | Lord-Nightmare/unified | 4b6c7351f1389b741667abe03f950313dcde8e1c | [
"MIT"
] | null | null | null | #include "nwnx.hpp"
#include "API/CNWSObject.hpp"
#include "API/CAppManager.hpp"
#include "API/CServerAIMaster.hpp"
#include "API/CServerExoApp.hpp"
#include "API/CVirtualMachine.hpp"
#include "API/CNWVirtualMachineCommands.hpp"
#include "API/CWorldTimer.hpp"
#include <dlfcn.h>
using namespace NWNXLib;
using namespace NWNXLib::API;
namespace DotNET {
// Bootstrap functions
using MainLoopHandlerType = void (*)(uint64_t);
using RunScriptHandlerType = int (*)(const char *, uint32_t);
using ClosureHandlerType = void (*)(uint64_t, uint32_t);
using SignalHandlerType = void (*)(const char*);
struct AllHandlers
{
MainLoopHandlerType MainLoop;
RunScriptHandlerType RunScript;
ClosureHandlerType Closure;
SignalHandlerType SignalHandler;
};
static AllHandlers s_handlers;
static uint32_t s_pushedCount = 0;
static std::vector<std::unique_ptr<NWNXLib::Hooks::FunctionHook>> s_managedHooks;
static std::string s_nwnxActivePlugin;
static std::string s_nwnxActiveFunction;
static uintptr_t GetFunctionPointer(const char *name)
{
void *core = dlopen("NWNX_Core.so", RTLD_LAZY);
if (!core)
{
LOG_ERROR("Failed to open core handle: %s", dlerror());
return 0;
}
auto ret = reinterpret_cast<uintptr_t>(dlsym(core, name));
if (ret == 0)
LOG_WARNING("Failed to get symbol name '%s': %s", name, dlerror());
dlclose(core);
return ret;
}
static void RegisterHandlers(AllHandlers *handlers, unsigned size)
{
if (size > sizeof(*handlers))
{
LOG_ERROR("RegisterHandlers argument contains too many entries, aborting");
return;
}
if (size < sizeof(*handlers))
{
LOG_WARNING("RegisterHandlers argument missing some entries - Managed/Unmanaged mismatch, update managed code");
}
LOG_INFO("Registering managed code handlers.");
s_handlers = *handlers;
LOG_DEBUG("Registered main loop handler: %p", s_handlers.MainLoop);
static Hooks::Hook MainLoopHook;
MainLoopHook = Hooks::HookFunction(Functions::_ZN21CServerExoAppInternal8MainLoopEv,
(void*)+[](CServerExoAppInternal *pServerExoAppInternal) -> int32_t
{
static uint64_t frame = 0;
if (s_handlers.MainLoop)
{
int spBefore = Utils::PushScriptContext(Constants::OBJECT_INVALID, false);
s_handlers.MainLoop(frame);
int spAfter = Utils::PopScriptContext();
ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter);
}
++frame;
return MainLoopHook->CallOriginal<int32_t>(pServerExoAppInternal);
},
Hooks::Order::VeryEarly);
LOG_DEBUG("Registered runscript handler: %p", s_handlers.RunScript);
static Hooks::Hook RunScriptHook;
RunScriptHook = Hooks::HookFunction(Functions::_ZN15CVirtualMachine9RunScriptEP10CExoStringjii,
(void*)+[](CVirtualMachine* thisPtr, CExoString* script, ObjectID objId, int32_t valid, int32_t eventId) -> int32_t
{
if (!script || *script == "")
return 1;
LOG_DEBUG("Calling managed RunScriptHandler for script '%s' on Object 0x%08x", script->CStr(), objId);
int spBefore = Utils::PushScriptContext(objId, !!valid);
int32_t retval = s_handlers.RunScript(script->CStr(), objId);
int spAfter = Utils::PopScriptContext();
ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter);
// ~0 is returned if runscript request is not handled and needs to be forwarded
if (retval != ~0)
{
Globals::VirtualMachine()->m_nReturnValueParameterType = 0x03;
Globals::VirtualMachine()->m_pReturnValue = reinterpret_cast<void*>(retval);
return 1;
}
return RunScriptHook->CallOriginal<int32_t>(thisPtr, script, objId, valid, eventId);
},
Hooks::Order::Latest);
LOG_DEBUG("Registered closure handler: %p", s_handlers.Closure);
static Hooks::Hook RunScriptSituationHook;
RunScriptSituationHook = Hooks::HookFunction(Functions::_ZN15CVirtualMachine18RunScriptSituationEPvji,
(void*)+[](CVirtualMachine* thisPtr, CVirtualMachineScript* script, ObjectID objId, int32_t valid) -> int32_t
{
uint64_t eventId;
if (script && sscanf(script->m_sScriptName.m_sString, "NWNX_DOTNET_INTERNAL %lu", &eventId) == 1)
{
LOG_DEBUG("Calling managed RunScriptSituationHandler for event '%lu' on Object 0x%08x", eventId, objId);
int spBefore = Utils::PushScriptContext(objId, !!valid);
s_handlers.Closure(eventId, objId);
int spAfter = Utils::PopScriptContext();
ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter);
delete script;
return 1;
}
return RunScriptSituationHook->CallOriginal<int32_t>(thisPtr, script, objId, valid);
},
Hooks::Order::Latest);
LOG_DEBUG("Registered core signal handler: %p", s_handlers.SignalHandler);
MessageBus::Subscribe("NWNX_CORE_SIGNAL",
[](const std::vector<std::string>& message)
{
int spBefore = Utils::PushScriptContext(Constants::OBJECT_INVALID, false);
s_handlers.SignalHandler(message[0].c_str());
int spAfter = Utils::PopScriptContext();
ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter);
});
}
static CVirtualMachineScript* CreateScriptForClosure(uint64_t eventId)
{
CVirtualMachineScript* script = new CVirtualMachineScript();
script->m_pCode = NULL;
script->m_nSecondaryInstructPtr = 0;
script->m_nInstructPtr = 0;
script->m_nStackSize = 0;
script->m_pStack = new CVirtualMachineStack();
char buff[128];
sprintf(buff, "%s %lu", "NWNX_DOTNET_INTERNAL", eventId);
script->m_sScriptName = CExoString(buff);
return script;
}
static void CallBuiltIn(int32_t id)
{
auto vm = Globals::VirtualMachine();
auto cmd = static_cast<CNWVirtualMachineCommands*>(Globals::VirtualMachine()->m_pCmdImplementer);
LOG_DEBUG("Calling BuiltIn %i.", id);
ASSERT(vm->m_nRecursionLevel >= 0);
cmd->ExecuteCommand(id, s_pushedCount);
s_pushedCount = 0;
}
static void StackPushInteger(int32_t value)
{
auto vm = Globals::VirtualMachine();
LOG_DEBUG("Pushing integer %i.", value);
ASSERT(vm->m_nRecursionLevel >= 0);
if (vm->StackPushInteger(value))
{
++s_pushedCount;
}
else
{
LOG_WARNING("Failed to push integer %s - recursion level %i.",
value, vm->m_nRecursionLevel);
}
}
static void StackPushFloat(float value)
{
auto vm = Globals::VirtualMachine();
LOG_DEBUG("Pushing float %f.", value);
ASSERT(vm->m_nRecursionLevel >= 0);
if (vm->StackPushFloat(value))
{
++s_pushedCount;
}
else
{
LOG_WARNING("Failed to push float %f - recursion level %i.",
value, vm->m_nRecursionLevel);
}
}
static void StackPushString(const char* value)
{
auto vm = Globals::VirtualMachine();
ASSERT(vm->m_nRecursionLevel >= 0);
LOG_DEBUG("Pushing string '%s'.", value);
CExoString str(String::FromUTF8(value).c_str());
if (vm->StackPushString(str))
{
++s_pushedCount;
}
else
{
LOG_WARNING("Failed to push string '%s' - recursion level %i.",
str.m_sString, vm->m_nRecursionLevel);
}
}
static void StackPushObject(uint32_t value)
{
auto vm = Globals::VirtualMachine();
LOG_DEBUG("Pushing object 0x%x.", value);
ASSERT(vm->m_nRecursionLevel >= 0);
if (vm->StackPushObject(value))
{
++s_pushedCount;
}
else
{
LOG_WARNING("Failed to push object 0x%x - recursion level %i.",
value, vm->m_nRecursionLevel);
}
}
static void StackPushVector(Vector value)
{
auto vm = Globals::VirtualMachine();
LOG_DEBUG("Pushing vector { %f, %f, %f }.", value.x, value.y, value.z);
ASSERT(vm->m_nRecursionLevel >= 0);
if (vm->StackPushVector(value))
{
++s_pushedCount;
}
else
{
LOG_WARNING("Failed to push vector { %f, %f, %f } - recursion level %i.",
value.x, value.y, value.z, vm->m_nRecursionLevel);
}
}
static void StackPushGameDefinedStructure(int32_t structId, void* value)
{
auto vm = Globals::VirtualMachine();
LOG_DEBUG("Pushing game defined structure %i at 0x%x.", structId, value);
ASSERT(vm->m_nRecursionLevel >= 0);
auto ret = vm->StackPushEngineStructure(structId, value);
if (!ret)
{
LOG_WARNING("Failed to push game defined structure %i at 0x%x - recursion level %i.",
structId, value, vm->m_nRecursionLevel);
}
s_pushedCount += ret;
}
static int32_t StackPopInteger()
{
auto vm = Globals::VirtualMachine();
ASSERT(vm->m_nRecursionLevel >= 0);
int32_t value;
if (!vm->StackPopInteger(&value))
{
LOG_WARNING("Failed to pop integer - recursion level %i.", vm->m_nRecursionLevel);
return -1;
}
LOG_DEBUG("Popped integer %d.", value);
return value;
}
static float StackPopFloat()
{
auto vm = Globals::VirtualMachine();
ASSERT(vm->m_nRecursionLevel >= 0);
float value;
if (!vm->StackPopFloat(&value))
{
LOG_WARNING("Failed to pop float - recursion level %i.", vm->m_nRecursionLevel);
return 0.0f;
}
LOG_DEBUG("Popped float %f.", value);
return value;
}
static const char* StackPopString()
{
auto vm = Globals::VirtualMachine();
ASSERT(vm->m_nRecursionLevel >= 0);
CExoString value;
if (!vm->StackPopString(&value))
{
LOG_WARNING("Failed to pop string - recursion level %i.", vm->m_nRecursionLevel);
return "";
}
LOG_DEBUG("Popped string '%s'.", value.m_sString);
// TODO: Less copies
return strdup(String::ToUTF8(value.CStr()).c_str());
}
static uint32_t StackPopObject()
{
auto vm = Globals::VirtualMachine();
ASSERT(vm->m_nRecursionLevel >= 0);
uint32_t value;
if (!vm->StackPopObject(&value))
{
LOG_WARNING("Failed to pop object - recursion level %i.", vm->m_nRecursionLevel);
return Constants::OBJECT_INVALID;
}
LOG_DEBUG("Popped object 0x%x.", value);
return value;
}
static Vector StackPopVector()
{
auto vm = Globals::VirtualMachine();
ASSERT(vm->m_nRecursionLevel >= 0);
Vector value;
if (!vm->StackPopVector(&value))
{
LOG_WARNING("Failed to pop vector - recursion level %i.", vm->m_nRecursionLevel);
return value;
}
LOG_DEBUG("Popping vector { %f, %f, %f }.", value.x, value.y, value.z);
return value;
}
static void* StackPopGameDefinedStructure(int32_t structId)
{
auto vm = Globals::VirtualMachine();
ASSERT(vm->m_nRecursionLevel >= 0);
void* value;
if (!vm->StackPopEngineStructure(structId, &value))
{
LOG_WARNING("Failed to pop game defined structure %i - recursion level %i.",
structId, vm->m_nRecursionLevel);
return nullptr;
}
LOG_DEBUG("Popped game defined structure %i at 0x%x.", structId, value);
return value;
}
static void FreeGameDefinedStructure(int32_t structId, void* ptr)
{
if (ptr)
{
auto cmd = static_cast<CNWVirtualMachineCommands*>(Globals::VirtualMachine()->m_pCmdImplementer);
LOG_DEBUG("Freeing game structure at 0x%x", ptr);
cmd->DestroyGameDefinedStructure(structId, ptr);
}
}
static int32_t ClosureAssignCommand(uint32_t oid, uint64_t eventId)
{
if (Utils::GetGameObject(oid))
{
CServerAIMaster* ai = Globals::AppManager()->m_pServerExoApp->GetServerAIMaster();
ai->AddEventDeltaTime(0, 0, oid, oid, 1, CreateScriptForClosure(eventId));
return 1;
}
return 0;
}
static int32_t ClosureDelayCommand(uint32_t oid, float duration, uint64_t eventId)
{
if (Utils::GetGameObject(oid))
{
int32_t days = Globals::AppManager()->m_pServerExoApp->GetWorldTimer()->GetCalendarDayFromSeconds(duration);
int32_t time = Globals::AppManager()->m_pServerExoApp->GetWorldTimer()->GetTimeOfDayFromSeconds(duration);
CServerAIMaster* ai = Globals::AppManager()->m_pServerExoApp->GetServerAIMaster();
ai->AddEventDeltaTime(days, time, oid, oid, 1, CreateScriptForClosure(eventId));
return 1;
}
return 0;
}
static int32_t ClosureActionDoCommand(uint32_t oid, uint64_t eventId)
{
if (auto *obj = Utils::AsNWSObject(Utils::GetGameObject(oid)))
{
obj->AddDoCommandAction(CreateScriptForClosure(eventId));
return 1;
}
return 0;
}
static void nwnxSetFunction(const char *plugin, const char *function)
{
s_nwnxActivePlugin = plugin;
s_nwnxActiveFunction = function;
}
static void nwnxPushInt(int32_t n)
{
Events::Push(n);
}
static void nwnxPushFloat(float f)
{
Events::Push(f);
}
static void nwnxPushObject(uint32_t o)
{
Events::Push((ObjectID)o);
}
static void nwnxPushString(const char *s)
{
Events::Push(String::FromUTF8(s));
}
static void nwnxPushEffect(CGameEffect *e)
{
Events::Push(e);
}
static void nwnxPushItemProperty(CGameEffect *ip)
{
Events::Push(ip);
}
static int32_t nwnxPopInt()
{
return Events::Pop<int32_t>().value_or(0);
}
static float nwnxPopFloat()
{
return Events::Pop<float>().value_or(0.0f);
}
static uint32_t nwnxPopObject()
{
return Events::Pop<ObjectID>().value_or(Constants::OBJECT_INVALID);
}
static const char* nwnxPopString()
{
auto str = Events::Pop<std::string>().value_or(std::string{""});
return strdup(String::ToUTF8(str).c_str());
}
static CGameEffect* nwnxPopEffect()
{
return Events::Pop<CGameEffect*>().value_or(nullptr);
}
static CGameEffect* nwnxPopItemProperty()
{
return Events::Pop<CGameEffect*>().value_or(nullptr);
}
static void nwnxCallFunction()
{
Events::Call(s_nwnxActivePlugin, s_nwnxActiveFunction);
}
static NWNXLib::API::Globals::NWNXExportedGlobals GetNWNXExportedGlobals()
{
return NWNXLib::API::Globals::ExportedGlobals;
}
static void* RequestHook(uintptr_t address, void* managedFuncPtr, int32_t order)
{
auto funchook = s_managedHooks.emplace_back(Hooks::HookFunction(address, managedFuncPtr, order)).get();
return funchook->GetOriginal();
}
static void ReturnHook(void* trampoline)
{
for (auto it = s_managedHooks.begin(); it != s_managedHooks.end(); it++)
{
if (it->get()->GetOriginal() == trampoline)
{
s_managedHooks.erase(it);
return;
}
}
}
std::vector<void*> GetExports()
{
//
// Fill the function table to hand over to managed code
// NOTE: Only add new entries to the end of this table, DO NOT RESHUFFLE.
//
std::vector<void*> exports;
exports.push_back((void*)&GetFunctionPointer);
exports.push_back((void*)&RegisterHandlers);
exports.push_back((void*)&CallBuiltIn);
exports.push_back((void*)&StackPushInteger);
exports.push_back((void*)&StackPushFloat);
exports.push_back((void*)&StackPushString);
exports.push_back((void*)&StackPushString); // reserved utf8
exports.push_back((void*)&StackPushObject);
exports.push_back((void*)&StackPushVector);
exports.push_back((void*)&StackPushGameDefinedStructure);
exports.push_back((void*)&StackPopInteger);
exports.push_back((void*)&StackPopFloat);
exports.push_back((void*)&StackPopString);
exports.push_back((void*)&StackPopString); // reserved utf8
exports.push_back((void*)&StackPopObject);
exports.push_back((void*)&StackPopVector);
exports.push_back((void*)&StackPopGameDefinedStructure);
exports.push_back((void*)&FreeGameDefinedStructure);
exports.push_back((void*)&ClosureAssignCommand);
exports.push_back((void*)&ClosureDelayCommand);
exports.push_back((void*)&ClosureActionDoCommand);
exports.push_back((void*)&nwnxSetFunction);
exports.push_back((void*)&nwnxPushInt);
exports.push_back((void*)&nwnxPushFloat);
exports.push_back((void*)&nwnxPushObject);
exports.push_back((void*)&nwnxPushString);
exports.push_back((void*)&nwnxPushString); // reserved utf8
exports.push_back((void*)&nwnxPushEffect);
exports.push_back((void*)&nwnxPushItemProperty);
exports.push_back((void*)&nwnxPopInt);
exports.push_back((void*)&nwnxPopFloat);
exports.push_back((void*)&nwnxPopObject);
exports.push_back((void*)&nwnxPopString);
exports.push_back((void*)&nwnxPopString); // reserved utf8
exports.push_back((void*)&nwnxPopEffect);
exports.push_back((void*)&nwnxPopItemProperty);
exports.push_back((void*)&nwnxCallFunction);
exports.push_back((void*)&GetNWNXExportedGlobals);
exports.push_back((void*)&RequestHook);
exports.push_back((void*)&ReturnHook);
return exports;
}
}
| 30.560144 | 123 | 0.663024 | Lord-Nightmare |
149da88c83d91c82c5e6ce254eedb3cdc0cf1e1b | 1,951 | cpp | C++ | Mastermind/src/GameState.cpp | olafur-skulason/CodeExamples | 2365bb075695e31ca0d006f2e57479e2c3c67ef3 | [
"MIT"
] | null | null | null | Mastermind/src/GameState.cpp | olafur-skulason/CodeExamples | 2365bb075695e31ca0d006f2e57479e2c3c67ef3 | [
"MIT"
] | null | null | null | Mastermind/src/GameState.cpp | olafur-skulason/CodeExamples | 2365bb075695e31ca0d006f2e57479e2c3c67ef3 | [
"MIT"
] | null | null | null | /*
* GameState.cpp
*
* Created on: Feb 28, 2020
* Author: olafur
*/
#include "../inc/GameState.h"
#include <iostream>
GameState::GameState(unsigned int codeLength, unsigned int attemptLimit, ColorSelector * colorSelector) :
color_selector(colorSelector),
code_length(codeLength),
attempt_limit(attemptLimit),
attempts(0),
master_code(nullptr),
black(0),
white(0)
{
}
GameState::~GameState() {
delete master_code;
}
void GameState::Initialize() {
attempts = 0;
master_code = GenerateMasterCode();
black = 0;
white = 0;
}
bool GameState::IsFinished() {
if(black == code_length) {
return true;
}
else if(attempts >= attempt_limit) {
return true;
}
else {
return false;
}
}
unsigned char GameState::GetWhitePegs() {
return white;
}
unsigned char GameState::GetBlackPegs() {
return black;
}
unsigned char * GameState::GetMasterCode() {
return master_code;
}
void GameState::SetMasterCode(unsigned char * new_code) {
master_code = new_code;
}
void GameState::InputGuess(unsigned char * guess) {
white = 0;
black = 0;
bool flag[code_length] = {false};
for(unsigned int i = 0; i < code_length; i++) {
if(guess[i] == master_code[i])
black++;
else {
for(unsigned int j = 0; j < code_length; j++) {
if (j != i && guess[i] == master_code[j] && !flag[j]) {
white++;
flag[j]=1;
break;
}
}
}
}
attempts++;
}
unsigned char * GameState::GenerateMasterCode() {
if(master_code != nullptr)
delete master_code;
unsigned char * new_code = new unsigned char(code_length);
std::cout << "Original master code: ";
for(unsigned int i = 0; i < code_length; i++) {
new_code[i] = color_selector->GetRandomColor();
std::cout << new_code[i];
}
std::cout << std::endl;
return new_code;
}
int GameState::CountColor(unsigned char * code, char color) {
int result = 0;
for(unsigned int i = 0; i < code_length; i++) {
if(code[i] == color)
result++;
}
return result;
}
| 18.580952 | 105 | 0.655561 | olafur-skulason |
149ddcab7d584c53e3ceaf9d30b61fb03d6f5a3f | 725 | hpp | C++ | tc_alt.hpp | arbrk1/typeclasses_cpp | 7bb180f0daaa7dfeb84387f9913c99b99702be2c | [
"MIT"
] | 10 | 2018-11-16T14:34:50.000Z | 2021-11-25T04:37:39.000Z | tc_alt.hpp | arbrk1/typeclasses_cpp | 7bb180f0daaa7dfeb84387f9913c99b99702be2c | [
"MIT"
] | null | null | null | tc_alt.hpp | arbrk1/typeclasses_cpp | 7bb180f0daaa7dfeb84387f9913c99b99702be2c | [
"MIT"
] | 3 | 2020-06-01T14:22:06.000Z | 2021-11-22T20:26:24.000Z | // An alternative to the tc.hpp
// arbrk1@gmail.com, 2018
#ifndef _TC_ALT_HPP_
#define _TC_ALT_HPP_
#define TC_DEF(name, params, body...) \
template< params > struct name; \
template< params > struct _tc_methods_##name body;
#define TC_INSTANCE(name, params, body...) \
struct name< params > : _tc_methods_##name< params > body;
#define PARAMS(args...) args
#ifdef TC_COMPAT
// compatibility layer with the tc.hpp
#define TC_IMPL(tc...) typedef tc
template<class T> using tc_impl_t = T;
template<class T> struct _tc_dummy_ { static bool const value = true; T t; };
#define TC_REQUIRE(tc...) \
static_assert( _tc_dummy_<tc_impl_t<tc>>::value, "unreachable" );
#endif // TC_COMPAT
#endif // _TC_ALT_HPP_
| 26.851852 | 77 | 0.706207 | arbrk1 |
14a109f240ab686df20563c75af7ef82bf10b4ee | 2,818 | cpp | C++ | accept.cpp | theProgrammerDavid/Board-Project | 93ce38b17687c3cd3d24ef22b0d0b4cffacd1bd0 | [
"MIT"
] | 1 | 2020-05-26T07:38:15.000Z | 2020-05-26T07:38:15.000Z | accept.cpp | theProgrammerDavid/Board-Project | 93ce38b17687c3cd3d24ef22b0d0b4cffacd1bd0 | [
"MIT"
] | null | null | null | accept.cpp | theProgrammerDavid/Board-Project | 93ce38b17687c3cd3d24ef22b0d0b4cffacd1bd0 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "accept.h"
/** int l and int space are predefined values.
*
* These values are predefined elsewhere in the program (main.cpp)
* to help with alignment and table making
* \return
*
*/
extern int l;
extern int space;
int accept::enterInt()
{
int temp_var;
while(1)
{
std::cout << "\t";
for (int i = 1; i <= 4; i++)
{
std::cout << "|";
}
_out.space = l - (2*4) ;
_out.space /= 2;
for (int i = 1; i <= _out.space-5; i++)
{
std::cout << " ";
}
cout<<"Enter Number : ";
// accept _acc;
try
{
temp_var = getValidatedInput<int>();
}
catch (exception e)
{
_out.column();
_out.column("Invalid Input");
_out.column();
continue;
}
break;
}
return temp_var;
}
void accept::getString(char *ch)
{
std::cout << "\t";
for (int i = 1; i <= 4; i++)
{
std::cout << "|";
}
_out.space = l - (2*4) ;
_out.space /= 2;
for (int i = 1; i <= _out.space-5; i++)
{
std::cout << " ";
}
cout<<"Enter : ";
// std::cin>>ch;
scanf("%[^\n]",ch);
}
void accept::getChar(char ch)
{
while(1)
{
std::cout << "\t";
for (int i = 1; i <= 4; i++)
{
std::cout << "|";
}
_out.space = l - (2*4) ;
_out.space /= 2;
for (int i = 1; i <= _out.space-5; i++)
{
std::cout << " ";
}
cout<<"Enter : ";
try
{
ch = getValidatedInput<char>();
}
catch (exception e)
{
_out.column();
_out.column("Invalid Input");
_out.column();
continue;
}
break;
}
}
template <typename T>
T accept::getValidatedInput(){
// Get input of type T
T result;
cin >> result;
// Check if the failbit has been set, meaning the beginning of the input
// was not type T. Also make sure the result is the only thing in the input
// stream, otherwise things like 2b would be a valid int.
if (cin.fail() || cin.get() != '\n')
{
// Set the error state flag back to goodbit. If you need to get the input
// again (e.g. this is in a while loop), this is essential. Otherwise, the
// failbit will stay set.
cin.clear();
// Clear the input stream using and empty while loop.
while (cin.get() != '\n')
;
// Throw an exception. Allows the caller to handle it any way you see fit
// (exit, ask for input again, etc.)
throw ios_base::failure("Invalid input.");
}
return result;
}
| 17.72327 | 82 | 0.465224 | theProgrammerDavid |
14a82bcc38ed891264d75c019e0e268300dc7bd6 | 2,709 | cpp | C++ | tools/CustomPasteState/pasteHook.cpp | matcool/BetterEdit | aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f | [
"MIT"
] | null | null | null | tools/CustomPasteState/pasteHook.cpp | matcool/BetterEdit | aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f | [
"MIT"
] | null | null | null | tools/CustomPasteState/pasteHook.cpp | matcool/BetterEdit | aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f | [
"MIT"
] | null | null | null | #include "../../BetterEdit.hpp"
#include "PasteLayer.hpp"
using namespace gdmake;
GDMAKE_HOOK(0x884c0)
void __fastcall EditorUI_onPasteState(gd::EditorUI* self, edx_t edx, cocos2d::CCObject* pSender) {
if (BetterEdit::sharedState()->getPasteStateEnabled())
PasteLayer::create()->show();
else
GDMAKE_ORIG_V(self, edx, pSender);
}
GDMAKE_HOOK(0xef6b0)
void __fastcall GameObject_duplicateAttributes(gd::GameObject* dest, edx_t edx, gd::GameObject *src) {
if (!PasteLayer::wantsToPasteState())
return GDMAKE_ORIG_V(dest, edx, src);
auto states = PasteLayer::getStates();
dest->m_unk21E = false;
dest->m_unk414 = 0;
if (states->count(PasteLayer::ObjID)) dest->m_nObjectID = src->m_nObjectID;
if (states->count(PasteLayer::EditorLayer)) dest->m_nEditorLayer = src->m_nEditorLayer;
if (states->count(PasteLayer::EditorLayer2)) dest->m_nEditorLayer2 = src->m_nEditorLayer2;
if (states->count(PasteLayer::DontFade)) dest->m_bIsDontFade = src->m_bIsDontFade;
if (states->count(PasteLayer::DontEnter)) dest->m_bIsDontEnter = src->m_bIsDontEnter;
if (states->count(PasteLayer::PositionX)) dest->setPositionX(src->getPositionX());
if (states->count(PasteLayer::PositionY)) dest->setPositionY(src->getPositionY());
if (states->count(PasteLayer::Rotation)) dest->setRotation(src->getRotation());
if (states->count(PasteLayer::Scale)) dest->updateCustomScale(src->getScale());
if (states->count(PasteLayer::ZOrder)) {
auto z = src->m_nGameZOrder;
if (!z) z = src->m_nDefaultZOrder;
dest->m_nGameZOrder = z;
}
if (states->count(PasteLayer::ZLayer)) {
auto z = src->m_nZLayer;
if (!z) z = src->m_nDefaultZLayer;
dest->m_nZLayer = z;
}
if (states->count(PasteLayer::Groups)) {
dest->m_nGroupCount = 0;
if (src->m_nGroupCount && src->m_pGroups)
for (auto ix = 0; ix < src->m_nGroupCount && ix < 10; ix++)
dest->addToGroup(src->m_pGroups[ix]);
}
LevelEditorLayer::get()->getEditorUI()->updateSpecialUIElements();
LevelEditorLayer::get()->getEditorUI()->updateObjectInfoLabel();
}
GDMAKE_HOOK(0x16b600)
void __fastcall LevelEditorLayer_copyObjectState(gd::LevelEditorLayer* self, edx_t edx, gd::GameObject* obj) {
GDMAKE_ORIG_V(self, edx, obj);
if (obj != nullptr) {
self->m_pCopyStateObject->m_nObjectID = obj->m_nObjectID;
self->m_pCopyStateObject->setPosition(obj->getPosition());
self->m_pCopyStateObject->setRotation(obj->getRotation());
self->m_pCopyStateObject->updateCustomScale(obj->getScale());
}
}
| 41.676923 | 110 | 0.663344 | matcool |
14a8b78c1f826693f60734320b02233323f1a920 | 2,763 | cpp | C++ | firmware/utility/ServoFirmata.cpp | fgu-cas/arenomat | 81954e82f58178586a31886136d3047cf5a0c4d2 | [
"MIT"
] | null | null | null | firmware/utility/ServoFirmata.cpp | fgu-cas/arenomat | 81954e82f58178586a31886136d3047cf5a0c4d2 | [
"MIT"
] | null | null | null | firmware/utility/ServoFirmata.cpp | fgu-cas/arenomat | 81954e82f58178586a31886136d3047cf5a0c4d2 | [
"MIT"
] | null | null | null | /*
ServoFirmata.cpp - Firmata library
Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved.
Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved.
Copyright (C) 2009 Shigeru Kobayashi. All rights reserved.
Copyright (C) 2009-2011 Jeff Hoefs. All rights reserved.
Copyright (C) 2013 Norbert Truchsess. All rights reserved.
This library 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.
See file LICENSE.txt for further informations on licensing terms.
*/
#include <Servo.h>
#include <Firmata.h>
#include <ServoFirmata.h>
ServoFirmata *ServoInstance;
void servoAnalogWrite(byte pin, int value)
{
ServoInstance->analogWrite(pin,value);
}
ServoFirmata::ServoFirmata()
{
ServoInstance = this;
}
boolean ServoFirmata::analogWrite(byte pin, int value)
{
if (IS_PIN_SERVO(pin)) {
Servo *servo = servos[PIN_TO_SERVO(pin)];
if (servo)
servo->write(value);
}
}
boolean ServoFirmata::handlePinMode(byte pin, int mode)
{
if (IS_PIN_SERVO(pin)) {
if (mode==SERVO) {
attach(pin,-1,-1);
return true;
} else {
detach(pin);
}
}
return false;
}
void ServoFirmata::handleCapability(byte pin)
{
if (IS_PIN_SERVO(pin)) {
Firmata.write(SERVO);
Firmata.write(14); //14 bit resolution (Servo takes int as argument)
}
}
boolean ServoFirmata::handleSysex(byte command, byte argc, byte* argv)
{
if(command == SERVO_CONFIG) {
if (argc > 4) {
// these vars are here for clarity, they'll optimized away by the compiler
byte pin = argv[0];
if (IS_PIN_SERVO(pin) && Firmata.getPinMode(pin)!=IGNORE) {
int minPulse = argv[1] + (argv[2] << 7);
int maxPulse = argv[3] + (argv[4] << 7);
Firmata.setPinMode(pin, SERVO);
attach(pin, minPulse, maxPulse);
return true;
}
}
}
return false;
}
void ServoFirmata::attach(byte pin, int minPulse, int maxPulse)
{
Servo *servo = servos[PIN_TO_SERVO(pin)];
if (!servo) {
servo = new Servo();
servos[PIN_TO_SERVO(pin)] = servo;
}
if (servo->attached())
servo->detach();
if (minPulse>=0 || maxPulse>=0)
servo->attach(PIN_TO_DIGITAL(pin),minPulse,maxPulse);
else
servo->attach(PIN_TO_DIGITAL(pin));
}
void ServoFirmata::detach(byte pin)
{
Servo *servo = servos[PIN_TO_SERVO(pin)];
if (servo) {
if (servo->attached())
servo->detach();
free(servo);
servos[PIN_TO_SERVO(pin)]=NULL;
}
}
void ServoFirmata::reset()
{
for (byte pin=0;pin<TOTAL_PINS;pin++) {
if (IS_PIN_SERVO(pin)) {
detach(pin);
}
}
}
| 24.026087 | 80 | 0.661962 | fgu-cas |
14ab7a328a5431e82e49e9d14d89cb901a13213b | 732 | hpp | C++ | source/framework/algorithm/include/lue/framework/algorithm/default_policies/tan.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 1 | 2019-04-14T15:51:12.000Z | 2019-04-14T15:51:12.000Z | source/framework/algorithm/include/lue/framework/algorithm/default_policies/tan.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/framework/algorithm/include/lue/framework/algorithm/default_policies/tan.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #pragma once
#include "lue/framework/algorithm/tan.hpp"
namespace lue {
namespace policy::tan {
template<
typename Element>
using DefaultPolicies = policy::DefaultPolicies<
AllValuesWithinDomain<Element>,
OutputElements<Element>,
InputElements<Element>>;
} // namespace policy::tan
namespace default_policies {
template<
typename Element,
Rank rank>
auto tan(
PartitionedArray<Element, rank> const& array)
{
using Policies = policy::tan::DefaultPolicies<Element>;
return tan(Policies{}, array);
}
} // namespace default_policies
} // namespace lue
| 22.181818 | 67 | 0.584699 | pcraster |
14ae7a0477b0d332f10a0616ce21b5df60e761b9 | 2,310 | cpp | C++ | code/nes/gamepad.cpp | oldGanon/neszett | 7b42b042fe74e37e18f93718c3549feeea7d85e7 | [
"MIT"
] | null | null | null | code/nes/gamepad.cpp | oldGanon/neszett | 7b42b042fe74e37e18f93718c3549feeea7d85e7 | [
"MIT"
] | null | null | null | code/nes/gamepad.cpp | oldGanon/neszett | 7b42b042fe74e37e18f93718c3549feeea7d85e7 | [
"MIT"
] | null | null | null |
struct gamepad_frame
{
u8 Gamepad[2];
u8 Flags;
};
struct gamepad_playback
{
u32 Size;
u32 Index;
gamepad_frame Frames[1];
};
struct gamepad
{
console *Console;
gamepad_playback *Playback;
u8 Strobe;
u8 ReadSerial[2];
};
inline u8
Gamepad_GetPlaybackButtons(gamepad_playback *Playback, u8 Index)
{
return Playback->Frames[Playback->Index].Gamepad[Index];
}
inline u8
Gamepad_Read(gamepad *Gamepad, u8 Index)
{
u8 Buttons;
if (Gamepad->Playback)
Buttons = Gamepad_GetPlaybackButtons(Gamepad->Playback, Index);
else
{
if (Index == 0)
Buttons = Api_GetGamepad();
else
Buttons = 0;
}
if (Gamepad->Strobe) Gamepad->ReadSerial[Index] = 0;
u8 Result = Buttons >> Gamepad->ReadSerial[Index]++;
if (Gamepad->ReadSerial[Index] > 8)
{
Gamepad->ReadSerial[Index] = 8;
return 1;
}
return Result & 1;
}
inline void
Gamepad_Write(gamepad *Gamepad, u8 Value)
{
Gamepad->Strobe = Value & 1;
if (Gamepad->Strobe)
{
Gamepad->ReadSerial[0] = 0;
Gamepad->ReadSerial[1] = 0;
}
}
inline void
Gamepad_NextFrame(gamepad *Gamepad)
{
if (!Gamepad->Playback) return;
gamepad_playback *Playback = Gamepad->Playback;
if (++Playback->Index > Playback->Size)
{
Api_Free(Playback);
Gamepad->Playback = 0;
return;
}
}
inline void
Gamepad_SetPlayback(gamepad *Gamepad, gamepad_playback *Playback)
{
if (Gamepad->Playback)
Api_Free(Gamepad->Playback);
Gamepad->Playback = Playback;
}
inline void
Gamepad_Step(gamepad *Gamepad)
{
if (!Gamepad->Playback) return;
gamepad_playback *Playback = Gamepad->Playback;
u8 Flags = Playback->Frames[Playback->Index].Flags;
if (Flags & 1)
{
Gamepad_NextFrame(Gamepad);
Console_Reset(Gamepad->Console);
}
if (Flags & 2)
{
Gamepad_NextFrame(Gamepad);
Console_Power(Gamepad->Console);
}
}
inline gamepad*
Gamepad_Create(console *Console)
{
gamepad *Gamepad = (gamepad *)Api_Malloc(sizeof(gamepad));
Gamepad->Console = Console;
return Gamepad;
}
inline void
Gamepad_Free(gamepad *Gamepad)
{
if (Gamepad->Playback)
Api_Free(Gamepad->Playback);
Api_Free(Gamepad);
}
| 19.411765 | 71 | 0.6329 | oldGanon |
14aee236386f8f8515cc70aba17e22b9d96abea7 | 492 | hpp | C++ | epoch/lucca/include/lucca/tool/look_at/look_diagonal_tool.hpp | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 47 | 2020-03-30T14:36:46.000Z | 2022-03-06T07:44:54.000Z | epoch/lucca/include/lucca/tool/look_at/look_diagonal_tool.hpp | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | null | null | null | epoch/lucca/include/lucca/tool/look_at/look_diagonal_tool.hpp | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 8 | 2020-04-01T01:22:45.000Z | 2022-01-02T13:06:09.000Z | #ifndef LUCCA_LOOK_DIAGONAL_TOOL_HPP
#define LUCCA_LOOK_DIAGONAL_TOOL_HPP
#include "lucca/config.hpp"
#include "lucca/tool/look_at/look_at_tool.hpp"
namespace lucca {
/**
* @author O Programador
*/
class LUCCA_API LookDiagonalTool final : public LookAtTool {
public:
LookDiagonalTool(View& view);
virtual ~LookDiagonalTool();
private:
virtual glm::mat4 _calculateViewMatrix(Float distance, const glm::vec3& target) const final override;
};
}
#endif // LUCCA_LOOK_DIAGONAL_TOOL_HPP | 20.5 | 102 | 0.784553 | oprogramadorreal |
14affe60b9d55e5797f5be7d861ae36543201ba7 | 4,455 | cc | C++ | paddle/phi/ops/compat/batch_norm_sig.cc | thunder95/Paddle | 27cb52a4cda29184851a53d63ea45d436c632e59 | [
"Apache-2.0"
] | null | null | null | paddle/phi/ops/compat/batch_norm_sig.cc | thunder95/Paddle | 27cb52a4cda29184851a53d63ea45d436c632e59 | [
"Apache-2.0"
] | 1 | 2022-01-28T07:23:22.000Z | 2022-01-28T07:23:22.000Z | paddle/phi/ops/compat/batch_norm_sig.cc | thunder95/Paddle | 27cb52a4cda29184851a53d63ea45d436c632e59 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/phi/core/compat/op_utils.h"
namespace phi {
KernelSignature BatchNormOpArgumentMapping(const ArgumentMappingContext& ctx) {
bool is_test = paddle::any_cast<bool>(ctx.Attr("is_test"));
bool use_global_stats =
ctx.HasAttr("use_global_stats")
? paddle::any_cast<bool>(ctx.Attr("use_global_stats"))
: false;
bool trainable_statistics =
ctx.HasAttr("trainable_statistics")
? paddle::any_cast<bool>(ctx.Attr("trainable_statistics"))
: false;
bool fuse_with_relu = ctx.HasAttr("fuse_with_relu")
? paddle::any_cast<bool>(ctx.Attr("fuse_with_relu"))
: false;
// Dispenable `MomentumTensor` is useless now
if (is_test && !use_global_stats && !trainable_statistics &&
!fuse_with_relu) {
return KernelSignature("batch_norm_infer",
{"X", "Scale", "Bias", "Mean", "Variance"},
{"momentum", "epsilon", "data_layout"},
{"Y", "MeanOut", "VarianceOut"});
} else {
return KernelSignature("batch_norm",
{"X", "Scale", "Bias", "Mean", "Variance"},
{"momentum",
"epsilon",
"data_layout",
"is_test",
"use_global_stats",
"trainable_statistics",
"fuse_with_relu"},
{"Y",
"MeanOut",
"VarianceOut",
"SavedMean",
"SavedVariance",
"ReserveSpace"});
}
}
KernelSignature BatchNormGradOpArgumentMapping(
const ArgumentMappingContext& ctx) {
return KernelSignature("batch_norm_grad",
{
"X",
"Scale",
"Bias",
"Mean",
"Variance",
"SavedMean",
"SavedVariance",
"ReserveSpace",
"Y@GRAD",
},
{"momentum",
"epsilon",
"data_layout",
"is_test",
"use_global_stats",
"trainable_statistics",
"fuse_with_relu"},
{"X@GRAD", "Scale@GRAD", "Bias@GRAD"});
}
KernelSignature BatchNormGradGradOpArgumentMapping(
const ArgumentMappingContext& ctx) {
return KernelSignature("batch_norm_grad_grad",
{"DDX",
"DDScale",
"DDBias",
"DY",
"X",
"Scale",
"SavedMean",
"SavedVariance",
"Mean",
"Variance"},
{"momentum",
"epsilon",
"data_layout",
"is_test",
"use_global_stats",
"trainable_statistics",
"fuse_with_relu"},
{"DX", "DScale", "DDY"});
}
} // namespace phi
PD_REGISTER_ARG_MAPPING_FN(batch_norm, phi::BatchNormOpArgumentMapping);
PD_REGISTER_ARG_MAPPING_FN(batch_norm_grad,
phi::BatchNormGradOpArgumentMapping);
PD_REGISTER_ARG_MAPPING_FN(batch_norm_grad_grad,
phi::BatchNormGradGradOpArgumentMapping);
| 39.776786 | 80 | 0.467789 | thunder95 |
14b0790f5e6f8eba805fda06a7996160d37ffb73 | 603 | cpp | C++ | src/kernel/musicserviceproxy.cpp | meego-tablet-ux/meegolabs-ux-components | 0f939f1f6bab34427d10f4ce6ec24e0a13447da9 | [
"Apache-2.0"
] | null | null | null | src/kernel/musicserviceproxy.cpp | meego-tablet-ux/meegolabs-ux-components | 0f939f1f6bab34427d10f4ce6ec24e0a13447da9 | [
"Apache-2.0"
] | null | null | null | src/kernel/musicserviceproxy.cpp | meego-tablet-ux/meegolabs-ux-components | 0f939f1f6bab34427d10f4ce6ec24e0a13447da9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include "musicserviceproxy.h"
/*
* Implementation of interface class MusicServiceProxy
*/
MusicServiceProxy::MusicServiceProxy(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent)
: QDBusAbstractInterface(service, path, staticInterfaceName(), connection, parent)
{
}
MusicServiceProxy::~MusicServiceProxy()
{
}
| 25.125 | 133 | 0.754561 | meego-tablet-ux |
14b0fdd10453ce38cdd6d6f7d42f88cf84701581 | 237 | cc | C++ | cpp/badmacro.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | cpp/badmacro.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | cpp/badmacro.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | #include <cassert>
//@include
// Avoid overhead of a function call.
#define isvowel(c) (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
//@exclude
int main(int argc, char** argv) {
char c = 'a';
assert(isvowel(c));
}
| 19.75 | 77 | 0.514768 | iskhanba |
14b115bcd2464a7ef5ba44a606d04d8bc42b7edc | 12,259 | cp | C++ | Std/Mod/Dialog.cp | romiras/Blackbox-fw-playground | 6de94dc65513e657a9b86c1772e2c07742b608a8 | [
"BSD-2-Clause"
] | 1 | 2016-03-17T08:27:05.000Z | 2016-03-17T08:27:05.000Z | Std/Mod/Dialog.cp | romiras/Blackbox-fw-playground | 6de94dc65513e657a9b86c1772e2c07742b608a8 | [
"BSD-2-Clause"
] | null | null | null | Std/Mod/Dialog.cp | romiras/Blackbox-fw-playground | 6de94dc65513e657a9b86c1772e2c07742b608a8 | [
"BSD-2-Clause"
] | 1 | 2018-03-14T17:53:27.000Z | 2018-03-14T17:53:27.000Z | MODULE StdDialog;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = ""
issues = ""
**)
IMPORT
Kernel, Meta, Strings, Files, Stores, Models, Sequencers, Views,
Containers, Dialog, Properties, Documents, Converters, Windows;
TYPE
Item* = POINTER TO EXTENSIBLE RECORD
next*: Item;
item-, string-, filter-: POINTER TO ARRAY OF CHAR;
shortcut-: ARRAY 8 OF CHAR;
privateFilter-, failed, trapped: BOOLEAN; (* filter call failed, caused a trap *)
res: INTEGER (* result code of failed filter *)
END;
FilterProcVal = RECORD (Meta.Value) p: Dialog.GuardProc END;
FilterProcPVal = RECORD (Meta.Value) p: PROCEDURE(n: INTEGER; VAR p: Dialog.Par) END;
ViewHook = POINTER TO RECORD (Views.ViewHook) END;
VAR curItem-: Item; (** IN parameter for item filters **)
PROCEDURE GetSubLoc* (mod: ARRAY OF CHAR; cat: Files.Name;
OUT loc: Files.Locator; OUT name: Files.Name);
VAR sub: Files.Name; file: Files.File; type: Files.Type;
BEGIN
IF (cat[0] = "S") & (cat[1] = "y") & (cat[2] = "m") THEN type := Kernel.symType
ELSIF (cat[0] = "C") & (cat[1] = "o") & (cat[2] = "d") & (cat[3] = "e") THEN type := Kernel.objType
ELSE type := ""
END;
Kernel.SplitName(mod, sub, name); Kernel.MakeFileName(name, type);
loc := Files.dir.This(sub); file := NIL;
IF loc # NIL THEN
loc := loc.This(cat);
IF sub = "" THEN
IF loc # NIL THEN
file := Files.dir.Old(loc, name, Files.shared);
IF file = NIL THEN loc := NIL END
END;
IF loc = NIL THEN
loc := Files.dir.This("System");
IF loc # NIL THEN loc := loc.This(cat) END
END
END
END
END GetSubLoc;
PROCEDURE Len (VAR str: ARRAY OF CHAR): INTEGER;
VAR i: INTEGER;
BEGIN
i := 0; WHILE str[i] # 0X DO INC(i) END;
RETURN i
END Len;
PROCEDURE AddItem* (i: Item; item, string, filter, shortcut: ARRAY OF CHAR);
VAR j: INTEGER; ch: CHAR;
BEGIN
ASSERT(i # NIL, 20);
NEW(i.item, Len(item) + 1);
NEW(i.string, Len(string) + 1);
NEW(i.filter, Len(filter) + 1);
ASSERT((i.item # NIL) & (i.string # NIL) & (i.filter # NIL), 100);
i.item^ := item$;
i.string^ := string$;
i.filter^ := filter$;
i.shortcut := shortcut$;
j := 0; ch := filter[0]; WHILE (ch # ".") & (ch # 0X) DO INC(j); ch := filter[j] END;
i.privateFilter := (j > 0) & (ch = 0X);
i.failed := FALSE; i.trapped := FALSE
END AddItem;
PROCEDURE ClearGuards* (i: Item);
BEGIN
i.failed := FALSE; i.trapped := FALSE
END ClearGuards;
PROCEDURE GetGuardProc (name: ARRAY OF CHAR; VAR i: Meta.Item;
VAR par: BOOLEAN; VAR n: INTEGER);
VAR j, k: INTEGER; num: ARRAY 32 OF CHAR;
BEGIN
j := 0;
WHILE (name[j] # 0X) & (name[j] # "(") DO INC(j) END;
IF name[j] = "(" THEN
name[j] := 0X; INC(j); k := 0;
WHILE (name[j] # 0X) & (name[j] # ")") DO num[k] := name[j]; INC(j); INC(k) END;
IF (name[j] = ")") & (name[j+1] = 0X) THEN
num[k] := 0X; Strings.StringToInt(num, n, k);
IF k = 0 THEN Meta.LookupPath(name, i); par := TRUE
ELSE Meta.Lookup("", i)
END
ELSE Meta.Lookup("", i)
END
ELSE
Meta.LookupPath(name, i); par := FALSE
END
END GetGuardProc;
PROCEDURE CheckFilter* (i: Item; VAR failed, ok: BOOLEAN; VAR par: Dialog.Par);
VAR x: Meta.Item; v: FilterProcVal; vp: FilterProcPVal; p: BOOLEAN; n: INTEGER;
BEGIN
IF ~i.failed THEN
curItem := i;
par.disabled := FALSE; par.checked := FALSE; par.label := i.item$;
par.undef := FALSE; par.readOnly := FALSE;
i.failed := TRUE; i.trapped := TRUE;
GetGuardProc(i.filter^, x, p, n);
IF (x.obj = Meta.procObj) OR (x.obj = Meta.varObj) & (x.typ = Meta.procTyp) THEN
IF p THEN
x.GetVal(vp, ok);
IF ok THEN vp.p(n, par) END
ELSE
x.GetVal(v, ok);
IF ok THEN v.p(par) END
END
ELSE ok := FALSE
END;
IF ok THEN i.res := 0 ELSE i.res := 1 END;
i.trapped := FALSE; i.failed := ~ok
END;
failed := i.failed
END CheckFilter;
PROCEDURE HandleItem* (i: Item);
VAR res: INTEGER;
BEGIN
IF ~i.failed THEN
Views.ClearQueue; res := 0;
Dialog.Call(i.string^, " ", res)
ELSIF (i # NIL) & i.failed THEN
IF i.trapped THEN
Dialog.ShowParamMsg("#System:ItemFilterTrapped", i.string^, i.filter^, "")
ELSE
Dialog.ShowParamMsg("#System:ItemFilterNotFound", i.string^, i.filter^, "")
END
END
END HandleItem;
PROCEDURE RecalcView* (v: Views.View);
(* recalc size of all subviews of v, then v itself *)
VAR m: Models.Model; v1: Views.View; c: Containers.Controller;
minW, maxW, minH, maxH, w, h, w0, h0: INTEGER;
BEGIN
IF v IS Containers.View THEN
c := v(Containers.View).ThisController();
IF c # NIL THEN
v1 := NIL; c.GetFirstView(Containers.any, v1);
WHILE v1 # NIL DO
RecalcView(v1);
c.GetNextView(Containers.any, v1)
END
END
END;
IF v.context # NIL THEN
m := v.context.ThisModel();
IF (m # NIL) & (m IS Containers.Model) THEN
m(Containers.Model).GetEmbeddingLimits(minW, maxW, minH, maxH);
v.context.GetSize(w0, h0); w := w0; h := h0;
Properties.PreferredSize(v, minW, maxW, minH, maxH, w, h, w, h);
IF (w # w0) OR (h # h0) THEN v.context.SetSize(w, h) END
END
END
END RecalcView;
PROCEDURE Open* (v: Views.View; title: ARRAY OF CHAR;
loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN);
VAR t: Views.Title; flags, opts: SET; done: BOOLEAN; d: Documents.Document; i: INTEGER;
win: Windows.Window; c: Containers.Controller; seq: ANYPTR;
BEGIN
IF conv = NIL THEN conv := Converters.list END; (* use document converter *)
ASSERT(v # NIL, 20);
flags := {}; done := FALSE;
IF noResize THEN
flags := flags + {Windows.noResize, Windows.noHScroll, Windows.noVScroll}
END;
IF asTool THEN INCL(flags, Windows.isTool) END;
IF asAux THEN INCL(flags, Windows.isAux) END;
IF neverDirty THEN INCL(flags, Windows.neverDirty) END;
i := 0;
WHILE (i < LEN(t) - 1) & (title[i] # 0X) DO t[i] := title[i]; INC(i) END;
t[i] := 0X;
IF ~allowDuplicates THEN
IF ~asTool & ~asAux THEN
IF (loc # NIL) & (name # "") THEN Windows.SelectBySpec(loc, name, conv, done) END
ELSE
IF title # "" THEN Windows.SelectByTitle(v, flags, t, done) END
END
ELSE
INCL(flags, Windows.allowDuplicates)
END;
IF ~done THEN
IF v IS Documents.Document THEN
IF v.context # NIL THEN
d := Documents.dir.New(
Views.CopyOf(v(Documents.Document).ThisView(), Views.shallow),
Views.undefined, Views.undefined)
ELSE
d := v(Documents.Document)
END;
ASSERT(d.context = NIL, 22);
v := d.ThisView(); ASSERT(v # NIL, 23)
ELSIF v.context # NIL THEN
ASSERT(v.context IS Documents.Context, 24);
d := v.context(Documents.Context).ThisDoc();
IF d.context # NIL THEN
d := Documents.dir.New(Views.CopyOf(v, Views.shallow), Views.undefined, Views.undefined)
END;
ASSERT(d.context = NIL, 25)
(*IF d.Domain() = NIL THEN Stores.InitDomain(d, v.Domain()) END (for views opened via Views.Old *)
ELSE
d := Documents.dir.New(v, Views.undefined, Views.undefined)
END;
IF asTool OR asAux THEN
c := d.ThisController();
c.SetOpts(c.opts + {Containers.noSelection})
END;
ASSERT(d.Domain() = v.Domain(), 100);
ASSERT(d.Domain() # NIL, 101);
seq := d.Domain().GetSequencer();
IF neverDirty & (seq # NIL) THEN
ASSERT(seq IS Sequencers.Sequencer, 26);
seq(Sequencers.Sequencer).SetDirty(FALSE)
END;
IF neverDirty THEN
(* change "fit to page" to "fit to window" in secondary windows *)
c := d.ThisController(); opts := c.opts;
IF Documents.pageWidth IN opts THEN
opts := opts - {Documents.pageWidth} + {Documents.winWidth}
END;
IF Documents.pageHeight IN opts THEN
opts := opts - {Documents.pageHeight} + {Documents.winHeight}
END;
c.SetOpts(opts)
END;
win := Windows.dir.New();
IF seq # NIL THEN
Windows.dir.OpenSubWindow(win, d, flags, t)
ELSE
Windows.dir.Open(win, d, flags, t, loc, name, conv)
END
END
END Open;
PROCEDURE (h: ViewHook) Open (v: Views.View; title: ARRAY OF CHAR;
loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN);
BEGIN
Open(v, title, loc, name, conv, asTool, asAux, noResize, allowDuplicates, neverDirty)
END Open;
PROCEDURE (h: ViewHook) OldView (loc: Files.Locator; name: Files.Name;
VAR conv: Converters.Converter): Views.View;
VAR w: Windows.Window; s: Stores.Store; c: Converters.Converter;
BEGIN
ASSERT(loc # NIL, 20); ASSERT(name # "", 21);
Kernel.MakeFileName(name, ""); s := NIL;
IF loc.res # 77 THEN
w := Windows.dir.First(); c := conv;
IF c = NIL THEN c := Converters.list END; (* use document converter *)
WHILE (w # NIL) & ((w.loc = NIL) OR (w.name = "") OR (w.loc.res = 77) OR
~Files.dir.SameFile(loc, name, w.loc, w.name) OR (w.conv # c)) DO
w := Windows.dir.Next(w)
END;
IF w # NIL THEN s := w.doc.ThisView() END
END;
IF s = NIL THEN
Converters.Import(loc, name, conv, s);
IF s # NIL THEN RecalcView(s(Views.View)) END
END;
IF s # NIL THEN RETURN s(Views.View) ELSE RETURN NIL END
END OldView;
PROCEDURE (h: ViewHook) RegisterView (v: Views.View;
loc: Files.Locator; name: Files.Name; conv: Converters.Converter);
BEGIN
ASSERT(v # NIL, 20); ASSERT(loc # NIL, 21); ASSERT(name # "", 22);
Kernel.MakeFileName(name, "");
Converters.Export(loc, name, conv, v)
END RegisterView;
PROCEDURE Init;
VAR h: ViewHook;
BEGIN
NEW(h); Views.SetViewHook(h)
END Init;
BEGIN
Init
END StdDialog.
| 40.062092 | 126 | 0.502488 | romiras |
14b2a7c9b582160d72dc604e7e9deefbf9355764 | 899 | cpp | C++ | 13.cpp | Sherryhaha/LeetCode | 128e344575f8e745b28ff88e6c443b18281ffdc9 | [
"MIT"
] | null | null | null | 13.cpp | Sherryhaha/LeetCode | 128e344575f8e745b28ff88e6c443b18281ffdc9 | [
"MIT"
] | null | null | null | 13.cpp | Sherryhaha/LeetCode | 128e344575f8e745b28ff88e6c443b18281ffdc9 | [
"MIT"
] | null | null | null | //
// Created by sunguoyan on 2017/3/30.
// 将罗马数字转为整数,整数是在1-3999范围内,要先把握下罗马数字的规律,1是"I",两个I就是2...到4是IV,5是V...
// 9是IX,10是X,50是L,100是C,500是D,10000是M,因此要注意的是如果识别类似IV,IX,XL....等组合成的罗马数字需要
// 有方法,方法就是从字符串后面往前遍历,如果后一个数字大于前一个数字,那么就减去前一个数字,否则就加上前一个数字
#include "LeetCode.h"
int romanToInt(string s) {
unordered_map<char,int> roman{{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}};
int sum = roman[s.back()];
for(int i = s.length()-2;i>=0;i--){
if(roman[s[i]] < roman[s[i+1]]){
sum = sum - roman[s[i]];
}else{
sum = sum + roman[s[i]];
}
}
return sum;
}
int main(){
int sum = romanToInt("MXXX");
cout<<sum<<endl;
return 0;
} | 28.09375 | 74 | 0.451613 | Sherryhaha |
14b2e7a935998e4d3e3501b08fa2de9ea72eaceb | 2,846 | cpp | C++ | Engine/Source/Render/Shader/SShaderCompiler.cpp | Aredhele/OOM-Engine | e52f706d17f1867f575a85ba5b87b4cc34a7fa97 | [
"MIT"
] | 9 | 2018-07-21T00:30:35.000Z | 2021-09-04T02:54:11.000Z | Engine/Source/Render/Shader/SShaderCompiler.cpp | Aredhele/OOM-Engine | e52f706d17f1867f575a85ba5b87b4cc34a7fa97 | [
"MIT"
] | null | null | null | Engine/Source/Render/Shader/SShaderCompiler.cpp | Aredhele/OOM-Engine | e52f706d17f1867f575a85ba5b87b4cc34a7fa97 | [
"MIT"
] | 1 | 2021-12-03T14:12:41.000Z | 2021-12-03T14:12:41.000Z | /// \file SShaderCompiler.cpp
/// \date 21/07/2018
/// \project OOM-Engine
/// \package Render/Shader
/// \author Vincent STEHLY--CALISTO
#include <malloc.h>
#include "Core/Debug/SLogger.hpp"
#include "Render/Shader/SShaderCompiler.hpp"
namespace Oom
{
GLuint SShaderCompiler::CreateProgram(const char* p_shader_name,
const char* p_vertex_shader,
const char* p_fragment_shader)
{
// Compiling shader
GLuint vertex_shader_id = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER);
if(!CompileShader(p_shader_name, "vertex ", p_vertex_shader, vertex_shader_id)) {
SLogger::LogWaring("Vertex shader failed to compile, some materials could be disabled.");
}
if (!CompileShader(p_shader_name, "fragment", p_fragment_shader, fragment_shader_id)) {
SLogger::LogWaring("Fragment shader failed to compile, some materials could be disabled.");
}
// Linking shader to cg program
GLuint program_id = glCreateProgram();
glAttachShader(program_id, vertex_shader_id);
glAttachShader(program_id, fragment_shader_id);
glLinkProgram (program_id);
GLint link_result = GL_FALSE;
int info_log_lenght = 0;
// Check the program
GLsizei size = 0;
glGetProgramiv(program_id, GL_LINK_STATUS, &link_result);
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_log_lenght);
if (info_log_lenght > 0)
{
auto* p_buffer = (char*)malloc(static_cast<size_t>(info_log_lenght + 1));
glGetShaderInfoLog(program_id, info_log_lenght, nullptr, p_buffer);
SLogger::LogError("glLinkProgram failed (%s) : %", p_shader_name, p_buffer);
free(p_buffer);
}
glDetachShader(program_id, vertex_shader_id);
glDetachShader(program_id, fragment_shader_id);
glDeleteShader(vertex_shader_id);
glDeleteShader(fragment_shader_id);
return program_id;
}
bool SShaderCompiler::CompileShader(const char* p_shader_name, const char* p_shader_type,
const char* p_shader, GLuint shader_id)
{
GLint compile_result = GL_FALSE;
int info_log_lenght = 0;
SLogger::LogInfo("Compiling %s shader %s ...", p_shader_type, p_shader_name);
glShaderSource (shader_id, 1, &p_shader, nullptr);
glCompileShader(shader_id);
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compile_result);
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &info_log_lenght);
if (info_log_lenght > 0)
{
auto* p_buffer = (char*)malloc(1024);
glGetShaderInfoLog(shader_id, 1024, nullptr, p_buffer);
SLogger::LogError("Shader error (%s) : %", p_shader_name, p_buffer);
free(p_buffer);
return false;
}
return true;
}
} | 31.622222 | 97 | 0.68201 | Aredhele |
14b78b3f6db46cf1f7e7774ccce5b9db20263e6f | 9,747 | cpp | C++ | test/afu/Commands.cpp | OpenCAPI/ocse | ddc640fbafe9d027c0218ccad366bc6ce37c34c8 | [
"Apache-2.0"
] | 3 | 2019-10-10T19:39:12.000Z | 2021-04-05T17:36:33.000Z | test/afu/Commands.cpp | OpenCAPI/ocse | ddc640fbafe9d027c0218ccad366bc6ce37c34c8 | [
"Apache-2.0"
] | 8 | 2019-10-25T12:51:45.000Z | 2021-04-06T09:31:39.000Z | test/afu/Commands.cpp | OpenCAPI/ocse | ddc640fbafe9d027c0218ccad366bc6ce37c34c8 | [
"Apache-2.0"
] | 4 | 2019-10-31T13:05:39.000Z | 2021-04-05T17:36:28.000Z | /*
* Copyright 2015,2017 International Business Machines
*
* 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 <stdlib.h>
#include "Commands.h"
//extern uint8_t memory[128];
Command::Command (uint16_t c, bool comm_addr_par, bool comm_code_par, bool comm_tag_par, bool buff_read_par):code (c), completed (true), state (IDLE),
command_address_parity (comm_addr_par), command_code_parity (comm_code_par),
command_tag_parity (comm_tag_par), buffer_read_parity (buff_read_par)
{
}
bool Command::is_completed () const
{
return
completed;
}
uint32_t
Command::get_tag () const
{
return tag;
}
OtherCommand::OtherCommand (uint16_t c, bool comm_addr_par,
bool comm_code_par, bool comm_tag_par,
bool buff_read_par):
Command (c, comm_addr_par, comm_code_par, comm_tag_par, buff_read_par)
{
}
void
OtherCommand::send_command (AFU_EVENT * afu_event, uint32_t new_tag,
uint64_t address, uint16_t command_size,
uint8_t abort, uint16_t context)
{
uint8_t cmd_stream_id;
uint8_t cmd_dl, cmd_pl;
uint64_t cmd_be;
uint8_t cmd_flag, cmd_endian, cmd_pg_size;
uint16_t cmd_bdf, cmd_actag, cmd_afutag;
uint16_t cmd_pasid;
int rc, i;
uint8_t ea_addr[9];
uint8_t cdata_bus[64], cdata_bad;
memcpy((void*)&ea_addr, (void*) &address, sizeof(uint64_t));
//cmd_dl = 0x00; // 1=64 bytes, 2=128 bytes, 3=256 bytes
//cmd_pl = 0x03; // 0=1B, 1=2B, 2=4B, 3=8B, 4=16B, 5=32B
cmd_dl = afu_event->afu_tlx_cmd_dl;
cmd_pl = afu_event->afu_tlx_cmd_pl;
cmd_bdf = afu_event->afu_tlx_cmd_bdf;
cmd_stream_id = afu_event->afu_tlx_cmd_stream_id;
cmd_be = afu_event->afu_tlx_cmd_be;
cmd_flag = afu_event->afu_tlx_cmd_flag;
cmd_endian = afu_event->afu_tlx_cmd_endian;
cmd_pasid = afu_event->afu_tlx_cmd_pasid;
cmd_pg_size = afu_event->afu_tlx_cmd_pg_size;
cmd_actag = afu_event->afu_tlx_cmd_actag;
cmd_afutag = new_tag;
printf("OtherCommand: sending command = 0x%x\n", Command::code);
debug_msg("calling afu_tlx_send_cmd with command = 0x%x and paddress = 0x%x cmd_actag = 0x%x", Command::code, address, cmd_actag);
debug_msg("ACTAG = 0x%x BDF = 0x%x PASID = 0x%x", cmd_actag, cmd_bdf, cmd_pasid);
switch(Command::code) {
case AFU_CMD_INTRP_REQ:
case AFU_CMD_WAKE_HOST_THRD:
// if(Command::code == AFU_CMD_INTRP_REQ) {
printf("Commands: AFU_CMD_INTRP_REQ or AFU_CMD_WAKE_HOST\n");
rc = afu_tlx_send_cmd(afu_event, Command::code, cmd_actag, cmd_stream_id,
ea_addr, cmd_afutag, cmd_dl, cmd_pl,
#ifdef TLX4
cmd_os,
#endif
cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size);
// }
break;
case AFU_CMD_INTRP_REQ_D:
// else if(Command::code == AFU_CMD_INTRP_REQ_D) {
cmd_pl = 3;
printf("Commands: AFU_CMD_INTRP_REQ_D\n");
for(i=0; i<8; i++) {
cdata_bus[i] = i;
}
rc = afu_tlx_send_cmd_and_data(afu_event, Command::code, cmd_actag, cmd_stream_id,
ea_addr, cmd_afutag, cmd_dl, cmd_pl,
#ifdef TLX4
cmd_os,
#endif
cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size,
cdata_bus, cdata_bad);
break;
default:
break;
}
printf("Commands: rc = 0x%x\n", rc);
Command::state = WAITING_DATA;
Command::tag = new_tag;
printf("data = 0x");
for(i=0; i<9; i++)
printf("%02x",(uint8_t)ea_addr[i]);
printf("\n");
printf("OtherCommand: exit send command\n");
}
void
OtherCommand::process_command (AFU_EVENT * afu_event, uint8_t *)
{
if (Command::state == IDLE) {
error_msg
("OtherCommand: Attempt to process response when no command is currently active");
}
}
bool OtherCommand::is_restart () const
{
return (Command::code );
}
LoadCommand::LoadCommand (uint16_t c, bool comm_addr_par, bool comm_code_par,
bool comm_tag_par, bool buff_read_par):
Command (c, comm_addr_par, comm_code_par, comm_tag_par, buff_read_par)
{
}
void
LoadCommand::send_command (AFU_EVENT * afu_event, uint32_t new_tag,
uint64_t address, uint16_t command_size,
uint8_t abort, uint16_t context)
{
uint8_t cmd_stream_id;
uint8_t cmd_dl, cmd_pl;
uint64_t cmd_be;
uint8_t cmd_flag, cmd_endian, cmd_pg_size;
uint16_t cmd_bdf, cmd_actag, cmd_afutag;
uint16_t cmd_pasid;
int rc, i;
uint8_t ea_addr[9];
memcpy((void*)&ea_addr, (void*) &address, sizeof(uint64_t));
//cmd_dl = 0x00; // 1=64 bytes, 2=128 bytes, 3=256 bytes
//cmd_pl = 0x03; // 0=1B, 1=2B, 2=4B, 3=8B, 4=16B, 5=32B
cmd_dl = afu_event->afu_tlx_cmd_dl;
cmd_pl = afu_event->afu_tlx_cmd_pl;
cmd_bdf = afu_event->afu_tlx_cmd_bdf;
cmd_stream_id = afu_event->afu_tlx_cmd_stream_id;
cmd_be = afu_event->afu_tlx_cmd_be;
cmd_flag = afu_event->afu_tlx_cmd_flag;
cmd_endian = afu_event->afu_tlx_cmd_endian;
cmd_pasid = afu_event->afu_tlx_cmd_pasid;
cmd_pg_size = afu_event->afu_tlx_cmd_pg_size;
cmd_actag = afu_event->afu_tlx_cmd_actag;
//cmd_afutag = afu_event->afu_tlx_cmd_afutag;
cmd_afutag = new_tag;
printf("LoadCommand: sending command = 0x%x\n", Command::code);
//if (Command::state != IDLE)
// error_msg
// ("LoadCommand: Attempting to send command before previous command is completed");
//Command::completed = false;
debug_msg("calling afu_tlx_send_cmd with command = 0x%x and paddress = 0x%x cmd_actag = 0x%x", Command::code, address, cmd_actag);
debug_msg("ACTAG = 0x%x BDF = 0x%x PASID = 0x%x", cmd_actag, cmd_bdf, cmd_pasid);
rc = afu_tlx_send_cmd(afu_event, Command::code, cmd_actag, cmd_stream_id,
ea_addr, cmd_afutag, cmd_dl, cmd_pl,
#ifdef TLX4
cmd_os,
#endif
cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size);
printf("Commands: rc = 0x%x\n", rc);
Command::state = WAITING_DATA;
Command::tag = new_tag;
printf("data = 0x");
for(i=0; i<9; i++)
printf("%02x",(uint8_t)ea_addr[i]);
printf("\n");
printf("Command: exit send command\n");
}
void
LoadCommand::process_command (AFU_EVENT * afu_event, uint8_t * cache_line)
{
}
void
LoadCommand::process_buffer_write (AFU_EVENT * afu_event,
uint8_t * cache_line)
{
Command::state = WAITING_RESPONSE;
}
bool LoadCommand::is_restart () const
{
return
false;
}
StoreCommand::StoreCommand (uint16_t c, bool comm_addr_par,
bool comm_code_par, bool comm_tag_par,
bool buff_read_par):
Command (c, comm_addr_par, comm_code_par, comm_tag_par, buff_read_par)
{
}
void
StoreCommand::send_command (AFU_EVENT * afu_event, uint32_t new_tag,
uint64_t address, uint16_t command_size,
uint8_t abort, uint16_t context)
{
uint8_t cmd_stream_id;
uint8_t cmd_dl, cmd_pl;
uint64_t cmd_be;
uint8_t cmd_flag, cmd_endian, cmd_pg_size, cdata_bad;
uint16_t cmd_bdf, cmd_actag, cmd_afutag;
uint16_t cmd_pasid;
int rc;
// uint32_t afutag;
uint8_t ea_addr[9], i;
memcpy((void*)&ea_addr, (void*) &address, sizeof(uint64_t));
//cmd_dl = 0x01; // 1=64 bytes, 2=128 bytes, 3=256 bytes
//cmd_pl = 0x03; // 0=1B, 1=2B, 2=4B, 3=8B, 4=16B, 5=32B
cmd_dl = afu_event->afu_tlx_cmd_dl;
cmd_pl = afu_event->afu_tlx_cmd_pl;
cmd_bdf = afu_event->afu_tlx_cmd_bdf;
cmd_stream_id = afu_event->afu_tlx_cmd_stream_id;
cmd_be = afu_event->afu_tlx_cmd_be;
cmd_flag = afu_event->afu_tlx_cmd_flag;
cmd_endian = afu_event->afu_tlx_cmd_endian;
cmd_pasid = afu_event->afu_tlx_cmd_pasid;
cmd_pg_size = afu_event->afu_tlx_cmd_pg_size;
cmd_actag = afu_event->afu_tlx_cmd_actag;
//cmd_afutag = afu_event->afu_tlx_cmd_afutag;
cmd_afutag = new_tag;
cdata_bad = 0;
printf("StoreCommand: sending command = 0x%x\n", Command::code);
printf("memory = 0x");
for(i=0; i<9; i++) {
printf("%02x", memory[i]);
}
printf("\n");
memcpy(afu_event->afu_tlx_cdata_bus, memory, 64);
// if (Command::state != IDLE)
// error_msg
// ("StoreCommand: Attempting to send command before previous command is completed");
// Command::completed = false;
debug_msg("calling afu_tlx_send_cmd_and_data with command = 0x%x and paddress = 0x%x cmd_actag = 0x%x", Command::code, address, cmd_actag);
debug_msg("ACTAG = 0x%x BDF = 0x%x PASID = 0x%x", cmd_actag, cmd_bdf, cmd_pasid);
rc = afu_tlx_send_cmd_and_data(afu_event, Command::code, cmd_actag, cmd_stream_id,
ea_addr, cmd_afutag, cmd_dl, cmd_pl,
#ifdef TLX4
cmd_os,
#endif
cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size,
afu_event->afu_tlx_cdata_bus, cdata_bad);
printf("Commands: rc = 0x%x\n", rc);
Command::state = WAITING_READ;
Command::tag = new_tag;
}
void
StoreCommand::process_command (AFU_EVENT * afu_event, uint8_t * cache_line)
{
}
void
StoreCommand::process_buffer_read (AFU_EVENT * afu_event,
uint8_t * cache_line)
{
}
bool StoreCommand::is_restart () const
{
return
false;
}
| 31.543689 | 150 | 0.672104 | OpenCAPI |
14b8aa4305d6ab8ad4d5e5b3259e4a80725b823c | 3,262 | hpp | C++ | include/codegen/include/Zenject/StaticMemoryPool_8.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/Zenject/StaticMemoryPool_8.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/Zenject/StaticMemoryPool_8.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:45 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: Zenject.StaticMemoryPoolBase`1
#include "Zenject/StaticMemoryPoolBase_1.hpp"
// Including type: Zenject.IMemoryPool`8
#include "Zenject/IMemoryPool_8.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`8<T1, T2, T3, T4, T5, T6, T7, T8>
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
class Action_8;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.StaticMemoryPool`8
template<typename TValue, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7>
class StaticMemoryPool_8 : public Zenject::StaticMemoryPoolBase_1<TValue>, public Zenject::IMemoryPool_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>, public Zenject::IDespawnableMemoryPool_1<TValue>, public Zenject::IMemoryPool {
public:
// private System.Action`8<TParam1,TParam2,TParam3,TParam4,TParam5,TParam6,TParam7,TValue> _onSpawnMethod
// Offset: 0x0
System::Action_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>* onSpawnMethod;
// public System.Void .ctor(System.Action`8<TParam1,TParam2,TParam3,TParam4,TParam5,TParam6,TParam7,TValue> onSpawnMethod, System.Action`1<TValue> onDespawnedMethod)
// Offset: 0x15DF380
static StaticMemoryPool_8<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7>* New_ctor(System::Action_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>* onSpawnMethod, System::Action_1<TValue>* onDespawnedMethod) {
return (StaticMemoryPool_8<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<StaticMemoryPool_8<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7>*>::get(), onSpawnMethod, onDespawnedMethod));
}
// public System.Void set_OnSpawnMethod(System.Action`8<TParam1,TParam2,TParam3,TParam4,TParam5,TParam6,TParam7,TValue> value)
// Offset: 0x15DF3DC
void set_OnSpawnMethod(System::Action_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>* value) {
CRASH_UNLESS(il2cpp_utils::RunMethod(this, "set_OnSpawnMethod", value));
}
// public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7)
// Offset: 0x15DF3E4
TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7) {
return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Spawn", p1, p2, p3, p4, p5, p6, p7));
}
}; // Zenject.StaticMemoryPool`8
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::StaticMemoryPool_8, "Zenject", "StaticMemoryPool`8");
#pragma pack(pop)
| 62.730769 | 324 | 0.745555 | Futuremappermydud |
14bcb0cdb3954fea721d40b8fc65340cab770211 | 985 | cpp | C++ | FTSE/entities/Book.cpp | melindil/FTSE | c0b54194900ac45ce1ecc778d838a72d09278bab | [
"MIT"
] | 3 | 2019-10-05T15:51:12.000Z | 2021-01-08T21:58:48.000Z | FTSE/entities/Book.cpp | melindil/FTSE | c0b54194900ac45ce1ecc778d838a72d09278bab | [
"MIT"
] | 2 | 2021-06-04T13:42:16.000Z | 2021-07-27T10:38:38.000Z | FTSE/entities/Book.cpp | melindil/FTSE | c0b54194900ac45ce1ecc778d838a72d09278bab | [
"MIT"
] | 2 | 2018-07-03T11:31:11.000Z | 2021-06-16T21:05:38.000Z | #include "Book.h"
#include "LuaHelper.h"
#include "Helpers.h"
Book::Book(EntityID id)
: Collectable(id)
{
}
Book::Book(void * ptr)
: Collectable(ptr)
{
}
Book::~Book()
{
}
void Book::MakeLuaObject(lua_State * l)
{
lua_newtable(l);
lua_pushinteger(l, GetID());
lua_setfield(l, -2, "id");
lua_getglobal(l, "BookMetaTable");
lua_setmetatable(l, -2);
}
Book::BookStructType * Book::GetStruct()
{
return (BookStructType*)(((uint32_t)GetEntityPointer()) + OFFSET_BOOK_STRUCT);
}
void Book::RegisterLua(lua_State * l, Logger * tmp)
{
luaL_newmetatable(l, "BookMetaTable");
Collectable::SetLuaSubclass(l);
lua_pushcfunction(l, (LuaHelper::THUNK<Book, &Book::GetSkillAffected>()));
lua_setfield(l, -2, "GetSkillAffected");
lua_pushstring(l, "Book");
lua_setfield(l, -2, "ClassType");
lua_pushvalue(l, -1);
lua_setfield(l, -2, "__index");
lua_setglobal(l, "BookMetaTable");
}
std::string Book::GetSkillAffected()
{
return Helpers::WcharToUTF8(GetStruct()->skill);
}
| 18.240741 | 79 | 0.694416 | melindil |
14c09198d6978f73bc5b6839d7d58a6e12850347 | 1,367 | cpp | C++ | src/ui/uicheckbox.cpp | alexeyden/whack | 2bff3beb0afb8c5aaba996b2838d2f0b9797039c | [
"WTFPL"
] | null | null | null | src/ui/uicheckbox.cpp | alexeyden/whack | 2bff3beb0afb8c5aaba996b2838d2f0b9797039c | [
"WTFPL"
] | null | null | null | src/ui/uicheckbox.cpp | alexeyden/whack | 2bff3beb0afb8c5aaba996b2838d2f0b9797039c | [
"WTFPL"
] | null | null | null | #include "uicheckbox.h"
UICheckBox::UICheckBox(UIManager* manager): UIElement(manager, false), checked(false)
{
}
void UICheckBox::render(Texture* out)
{
unsigned color = isPressed() ? _manager->style()->colorActivated : _manager->style()->colorNormal;
if(checked)
_manager->style()->checkboxChecked.draw(out, bounds.x1 + paddingX, bounds.y1 + paddingY, color);
else
_manager->style()->checkboxUnchecked.draw(out, bounds.x1 + paddingX, bounds.y1 + paddingY, color);
const Font& font = isPressed() ? _manager->style()->fontActivated : _manager->style()->fontNormal;
const Rect<int>& min = minBounds();
font.drawText(out, bounds.x1 + paddingX + _manager->style()->checkboxChecked.width() + gap,
bounds.y1 + min.centerY() - font.charSize()/2, text.c_str());
}
void UICheckBox::update(float dt)
{
(void) dt;
}
Rect< int > UICheckBox::minBounds() const
{
return Rect<int>(
0, 0,
_manager->style()->checkboxChecked.width() + gap + _manager->style()->fontNormal.textBounds(text).first + paddingX * 2,
std::max(_manager->style()->fontNormal.charSize(), _manager->style()->checkboxChecked.height()) + paddingX * 2
);
}
bool UICheckBox::onMouseReleased(double x, double y, int button, int mods)
{
UIElement::onMouseReleased(x, y, button, mods);
checked = !checked;
for(auto& ch : _clickHandlers)
ch(checked);
return true;
}
| 28.479167 | 121 | 0.693489 | alexeyden |
14c1b1e99a4169b62e1fedc6a258f487345ba134 | 10,656 | cpp | C++ | clang/test/Analysis/initializers-cfg-output.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | clang/test/Analysis/initializers-cfg-output.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/Analysis/initializers-cfg-output.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=debug.DumpCFG -analyzer-config cfg-rich-constructors=false %s 2>&1 | FileCheck -check-prefixes=CHECK,WARNINGS %s
// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=debug.DumpCFG -analyzer-config cfg-rich-constructors=true %s 2>&1 | FileCheck -check-prefixes=CHECK,ANALYZER %s
// This file tests how we construct two different flavors of the Clang CFG -
// the CFG used by the Sema analysis-based warnings and the CFG used by the
// static analyzer. The difference in the behavior is checked via FileCheck
// prefixes (WARNINGS and ANALYZER respectively). When introducing new analyzer
// flags, no new run lines should be added - just these flags would go to the
// respective line depending on where is it turned on and where is it turned
// off. Feel free to add tests that test only one of the CFG flavors if you're
// not sure how the other flavor is supposed to work in your case.
class A {
public:
// CHECK: A()
// CHECK: [B1 (ENTRY)]
// CHECK-NEXT: Succs (1): B0
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (1): B1
A() {}
// CHECK: A(int i)
// CHECK: [B1 (ENTRY)]
// CHECK-NEXT: Succs (1): B0
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (1): B1
A(int i) {}
};
class B : public virtual A {
public:
// CHECK: B()
// CHECK: [B3 (ENTRY)]
// CHECK-NEXT: Succs (1): B2
// CHECK: [B1]
// WARNINGS-NEXT: 1: (CXXConstructExpr, class A)
// ANALYZER-NEXT: 1: (CXXConstructExpr, A() (Base initializer), class A)
// CHECK-NEXT: 2: A([B1.1]) (Base initializer)
// CHECK-NEXT: Preds (1): B2
// CHECK-NEXT: Succs (1): B0
// CHECK: [B2]
// CHECK-NEXT: T: (See if most derived ctor has already initialized vbases)
// CHECK-NEXT: Preds (1): B3
// CHECK-NEXT: Succs (2): B0 B1
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (2): B1 B2
B() {}
// CHECK: B(int i)
// CHECK: [B3 (ENTRY)]
// CHECK-NEXT: Succs (1): B2
// CHECK: [B1]
// CHECK-NEXT: 1: i
// CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, LValueToRValue, int)
// WARNINGS-NEXT: 3: [B1.2] (CXXConstructExpr, class A)
// ANALYZER-NEXT: 3: [B1.2] (CXXConstructExpr, A([B1.2]) (Base initializer), class A)
// CHECK-NEXT: 4: A([B1.3]) (Base initializer)
// CHECK-NEXT: Preds (1): B2
// CHECK-NEXT: Succs (1): B0
// CHECK: [B2]
// CHECK-NEXT: T: (See if most derived ctor has already initialized vbases)
// CHECK-NEXT: Preds (1): B3
// CHECK-NEXT: Succs (2): B0 B1
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (2): B1 B2
B(int i) : A(i) {}
};
class C : public virtual A {
public:
// CHECK: C()
// CHECK: [B3 (ENTRY)]
// CHECK-NEXT: Succs (1): B2
// CHECK: [B1]
// WARNINGS-NEXT: 1: (CXXConstructExpr, class A)
// ANALYZER-NEXT: 1: (CXXConstructExpr, A() (Base initializer), class A)
// CHECK-NEXT: 2: A([B1.1]) (Base initializer)
// CHECK-NEXT: Preds (1): B2
// CHECK-NEXT: Succs (1): B0
// CHECK: [B2]
// CHECK-NEXT: T: (See if most derived ctor has already initialized vbases)
// CHECK-NEXT: Preds (1): B3
// CHECK-NEXT: Succs (2): B0 B1
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (2): B1 B2
C() {}
// CHECK: C(int i)
// CHECK: [B3 (ENTRY)]
// CHECK-NEXT: Succs (1): B2
// CHECK: [B1]
// CHECK-NEXT: 1: i
// CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, LValueToRValue, int)
// WARNINGS-NEXT: 3: [B1.2] (CXXConstructExpr, class A)
// ANALYZER-NEXT: 3: [B1.2] (CXXConstructExpr, A([B1.2]) (Base initializer), class A)
// CHECK-NEXT: 4: A([B1.3]) (Base initializer)
// CHECK-NEXT: Preds (1): B2
// CHECK-NEXT: Succs (1): B0
// CHECK: [B2]
// CHECK-NEXT: T: (See if most derived ctor has already initialized vbases)
// CHECK-NEXT: Preds (1): B3
// CHECK-NEXT: Succs (2): B0 B1
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (2): B1 B2
C(int i) : A(i) {}
};
class TestOrder : public C, public B, public A {
int i;
int& r;
public:
TestOrder();
};
// CHECK: TestOrder::TestOrder()
// CHECK: [B4 (ENTRY)]
// CHECK-NEXT: Succs (1): B3
// CHECK: [B1]
// WARNINGS-NEXT: 1: (CXXConstructExpr, class C)
// ANALYZER-NEXT: 1: (CXXConstructExpr, C() (Base initializer), class C)
// CHECK-NEXT: 2: C([B1.1]) (Base initializer)
// WARNINGS-NEXT: 3: (CXXConstructExpr, class B)
// ANALYZER-NEXT: 3: (CXXConstructExpr, B() (Base initializer), class B)
// CHECK-NEXT: 4: B([B1.3]) (Base initializer)
// WARNINGS-NEXT: 5: (CXXConstructExpr, class A)
// ANALYZER-NEXT: 5: (CXXConstructExpr, A() (Base initializer), class A)
// CHECK-NEXT: 6: A([B1.5]) (Base initializer)
// CHECK-NEXT: 7: i(/*implicit*/(int)0) (Member initializer)
// CHECK-NEXT: 8: this
// CHECK-NEXT: 9: [B1.8]->i
// CHECK-NEXT: 10: r([B1.9]) (Member initializer)
// WARNINGS-NEXT: 11: (CXXConstructExpr, class A)
// ANALYZER-NEXT: 11: (CXXConstructExpr, [B1.12], class A)
// CHECK-NEXT: 12: A a;
// CHECK-NEXT: Preds (2): B2 B3
// CHECK-NEXT: Succs (1): B0
// CHECK: [B2]
// WARNINGS-NEXT: 1: (CXXConstructExpr, class A)
// ANALYZER-NEXT: 1: (CXXConstructExpr, A() (Base initializer), class A)
// CHECK-NEXT: 2: A([B2.1]) (Base initializer)
// CHECK-NEXT: Preds (1): B3
// CHECK-NEXT: Succs (1): B1
// CHECK: [B3]
// CHECK-NEXT: T: (See if most derived ctor has already initialized vbases)
// CHECK-NEXT: Preds (1): B4
// CHECK-NEXT: Succs (2): B1 B2
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (1): B1
TestOrder::TestOrder()
: r(i), B(), i(), C() {
A a;
}
class TestControlFlow {
int x, y, z;
public:
TestControlFlow(bool b);
};
// CHECK: TestControlFlow::TestControlFlow(bool b)
// CHECK: [B5 (ENTRY)]
// CHECK-NEXT: Succs (1): B4
// CHECK: [B1]
// CHECK-NEXT: 1: [B4.4] ? [B2.1] : [B3.1]
// CHECK-NEXT: 2: y([B1.1]) (Member initializer)
// CHECK-NEXT: 3: this
// CHECK-NEXT: 4: [B1.3]->y
// CHECK-NEXT: 5: [B1.4] (ImplicitCastExpr, LValueToRValue, int)
// CHECK-NEXT: 6: z([B1.5]) (Member initializer)
// CHECK-NEXT: 7: int v;
// CHECK-NEXT: Preds (2): B2 B3
// CHECK-NEXT: Succs (1): B0
// CHECK: [B2]
// CHECK-NEXT: 1: 0
// CHECK-NEXT: Preds (1): B4
// CHECK-NEXT: Succs (1): B1
// CHECK: [B3]
// CHECK-NEXT: 1: 1
// CHECK-NEXT: Preds (1): B4
// CHECK-NEXT: Succs (1): B1
// CHECK: [B4]
// CHECK-NEXT: 1: 0
// CHECK-NEXT: 2: x([B4.1]) (Member initializer)
// CHECK-NEXT: 3: b
// CHECK-NEXT: 4: [B4.3] (ImplicitCastExpr, LValueToRValue, _Bool)
// CHECK-NEXT: T: [B4.4] ? ... : ...
// CHECK-NEXT: Preds (1): B5
// CHECK-NEXT: Succs (2): B2 B3
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (1): B1
TestControlFlow::TestControlFlow(bool b)
: y(b ? 0 : 1)
, x(0)
, z(y) {
int v;
}
class TestDelegating {
int x, z;
public:
// CHECK: TestDelegating()
// CHECK: [B2 (ENTRY)]
// CHECK-NEXT: Succs (1): B1
// CHECK: [B1]
// CHECK-NEXT: 1: 2
// CHECK-NEXT: 2: 3
// WARNINGS-NEXT: 3: [B1.1], [B1.2] (CXXConstructExpr, class TestDelegating)
// ANALYZER-NEXT: 3: [B1.1], [B1.2] (CXXConstructExpr, TestDelegating([B1.1], [B1.2]) (Delegating initializer), class TestDelegating)
// CHECK-NEXT: 4: TestDelegating([B1.3]) (Delegating initializer)
// CHECK-NEXT: Preds (1): B2
// CHECK-NEXT: Succs (1): B0
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (1): B1
TestDelegating() : TestDelegating(2, 3) {}
// CHECK: TestDelegating(int x, int z)
// CHECK: [B2 (ENTRY)]
// CHECK-NEXT: Succs (1): B1
// CHECK: [B1]
// CHECK-NEXT: 1: x
// CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, LValueToRValue, int)
// CHECK-NEXT: 3: x([B1.2]) (Member initializer)
// CHECK-NEXT: 4: z
// CHECK-NEXT: 5: [B1.4] (ImplicitCastExpr, LValueToRValue, int)
// CHECK-NEXT: 6: z([B1.5]) (Member initializer)
// CHECK-NEXT: Preds (1): B2
// CHECK-NEXT: Succs (1): B0
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (1): B1
TestDelegating(int x, int z) : x(x), z(z) {}
};
class TestMoreControlFlow : public virtual A {
A a;
public:
TestMoreControlFlow(bool coin);
};
// CHECK: TestMoreControlFlow::TestMoreControlFlow(bool coin)
// CHECK: [B10 (ENTRY)]
// CHECK-NEXT: Succs (1): B9
// CHECK: [B1]
// CHECK-NEXT: 1: [B4.2] ? [B2.1] : [B3.1]
// WARNINGS-NEXT: 2: [B1.1] (CXXConstructExpr, class A)
// ANALYZER-NEXT: 2: [B1.1] (CXXConstructExpr, a([B1.1]) (Member initializer), class A)
// CHECK-NEXT: 3: a([B1.2]) (Member initializer)
// CHECK-NEXT: Preds (2): B2 B3
// CHECK-NEXT: Succs (1): B0
// CHECK: [B2]
// CHECK-NEXT: 1: 3
// CHECK-NEXT: Preds (1): B4
// CHECK-NEXT: Succs (1): B1
// CHECK: [B3]
// CHECK-NEXT: 1: 4
// CHECK-NEXT: Preds (1): B4
// CHECK-NEXT: Succs (1): B1
// CHECK: [B4]
// CHECK-NEXT: 1: coin
// CHECK-NEXT: 2: [B4.1] (ImplicitCastExpr, LValueToRValue, _Bool)
// CHECK-NEXT: T: [B4.2] ? ... : ...
// CHECK-NEXT: Preds (2): B5 B9
// CHECK-NEXT: Succs (2): B2 B3
// CHECK: [B5]
// CHECK-NEXT: 1: [B8.2] ? [B6.1] : [B7.1]
// WARNINGS-NEXT: 2: [B5.1] (CXXConstructExpr, class A)
// ANALYZER-NEXT: 2: [B5.1] (CXXConstructExpr, A([B5.1]) (Base initializer), class A)
// CHECK-NEXT: 3: A([B5.2]) (Base initializer)
// CHECK-NEXT: Preds (2): B6 B7
// CHECK-NEXT: Succs (1): B4
// CHECK: [B6]
// CHECK-NEXT: 1: 1
// CHECK-NEXT: Preds (1): B8
// CHECK-NEXT: Succs (1): B5
// CHECK: [B7]
// CHECK-NEXT: 1: 2
// CHECK-NEXT: Preds (1): B8
// CHECK-NEXT: Succs (1): B5
// CHECK: [B8]
// CHECK-NEXT: 1: coin
// CHECK-NEXT: 2: [B8.1] (ImplicitCastExpr, LValueToRValue, _Bool)
// CHECK-NEXT: T: [B8.2] ? ... : ...
// CHECK-NEXT: Preds (1): B9
// CHECK-NEXT: Succs (2): B6 B7
// CHECK: [B9]
// CHECK-NEXT: T: (See if most derived ctor has already initialized vbases)
// CHECK-NEXT: Preds (1): B10
// CHECK-NEXT: Succs (2): B4 B8
// CHECK: [B0 (EXIT)]
// CHECK-NEXT: Preds (1): B1
TestMoreControlFlow::TestMoreControlFlow(bool coin)
: A(coin ? 1 : 2), a(coin ? 3 : 4) {}
| 36.122034 | 168 | 0.555556 | medismailben |
14c251049f89139d5cf3387c35547b0d88770830 | 20,717 | cc | C++ | ggeo/GInstancer.cc | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | 1 | 2020-05-13T06:55:49.000Z | 2020-05-13T06:55:49.000Z | ggeo/GInstancer.cc | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | ggeo/GInstancer.cc | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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 "SLog.hh"
#include "BTimeKeeper.hh"
// npy-
#include "NSceneConfig.hpp"
#include "NGLM.hpp"
#include "NPY.hpp"
#include "NSensor.hpp"
#include "Counts.hpp"
#include "Opticks.hh"
#include "GTreePresent.hh"
#include "GMergedMesh.hh"
#include "GGeoLib.hh"
#include "GNodeLib.hh"
#include "GVolume.hh"
#include "GMatrix.hh"
#include "GBuffer.hh"
#include "GTree.hh"
#include "GInstancer.hh"
#include "GPt.hh"
#include "PLOG.hh"
// Following enabling of vertex de-duping (done at AssimpWrap level)
// the below criteria are finding fewer repeats, for DYB only the hemi pmt
// TODO: retune
const plog::Severity GInstancer::LEVEL = debug ;
GInstancer::GInstancer(Opticks* ok, GGeoLib* geolib, GNodeLib* nodelib, NSceneConfig* config)
:
m_log(new SLog("GInstancer::GInstancer","", verbose)),
m_ok(ok),
m_geolib(geolib),
m_verbosity(geolib->getVerbosity()),
m_nodelib(nodelib),
m_config(config),
m_repeat_min(config->instance_repeat_min),
m_vertex_min(config->instance_vertex_min), // aiming to include leaf? sStrut and sFasteners
m_root(NULL),
m_count(0),
m_labels(0),
m_digest_count(new Counts<unsigned>("progenyDigest")),
m_csgskiplv_count(0),
m_repeats_count(0),
m_globals_count(0)
{
}
unsigned GInstancer::getNumRepeats() const
{
return m_repeat_candidates.size();
}
void GInstancer::setRepeatMin(unsigned repeat_min)
{
m_repeat_min = repeat_min ;
}
void GInstancer::setVertexMin(unsigned vertex_min)
{
m_vertex_min = vertex_min ;
}
/**
GInstancer::createInstancedMergedMeshes
------------------------------------------
Canonical invokation from GGeo::prepareMeshes
**/
void GInstancer::createInstancedMergedMeshes(bool delta, unsigned verbosity)
{
OK_PROFILE("GInstancer::createInstancedMergedMeshes");
if(delta) deltacheck();
OK_PROFILE("GInstancer::createInstancedMergedMeshes:deltacheck");
traverse(); // spin over tree counting up progenyDigests to find repeated geometry
OK_PROFILE("GInstancer::createInstancedMergedMeshes:traverse");
labelTree(); // recursive setRepeatIndex on the GNode tree for each of the repeated bits of geometry
OK_PROFILE("GInstancer::createInstancedMergedMeshes:labelTree");
makeMergedMeshAndInstancedBuffers(verbosity);
OK_PROFILE("GInstancer::createInstancedMergedMeshes:makeMergedMeshAndInstancedBuffers");
//if(t.deltaTime() > 0.1)
//t.dump("GInstancer::createInstancedMergedMeshes deltaTime > cut ");
}
/**
GInstancer::traverse
---------------------
DYB: minrep 120 removes repeats from headonPMT, calibration sources and RPC leaving just PMTs
**/
void GInstancer::traverse()
{
m_root = m_nodelib->getVolume(0);
assert(m_root);
// count occurences of distinct progeny digests (relative sub-tree identities) in m_digest_count
traverse_r(m_root, 0);
m_digest_count->sort(false); // descending count order, ie most common subtrees first
//m_digest_count->dump();
// collect digests of repeated pieces of geometry into m_repeat_candidates
findRepeatCandidates(m_repeat_min, m_vertex_min);
unsigned num_reps = getNumRepeats();
if(num_reps > 0 )
dumpRepeatCandidates(20u);
}
void GInstancer::traverse_r( GNode* node, unsigned int depth)
{
std::string& pdig = node->getProgenyDigest();
m_digest_count->add(pdig.c_str());
m_count++ ;
for(unsigned int i = 0; i < node->getNumChildren(); i++) traverse_r(node->getChild(i), depth + 1 );
}
/**
GInstancer::deltacheck
-----------------------
Check consistency of the level transforms
**/
void GInstancer::deltacheck()
{
m_root = m_nodelib->getVolume(0);
assert(m_root);
deltacheck_r(m_root, 0);
}
void GInstancer::deltacheck_r( GNode* node, unsigned int depth)
{
GVolume* volume = dynamic_cast<GVolume*>(node) ;
GMatrixF* gtransform = volume->getTransform();
// volumes levelTransform is set in AssimpGGeo and hails from the below with level -2
// aiMatrix4x4 AssimpNode::getLevelTransform(int level)
// looks to correspond to the placement of the LV within its PV
//GMatrixF* ltransform = volume->getLevelTransform();
GMatrixF* ctransform = volume->calculateTransform();
float delta = gtransform->largestDiff(*ctransform);
unsigned int nprogeny = node->getLastProgenyCount() ;
if(nprogeny > 0 )
LOG(debug)
<< " #progeny " << std::setw(6) << nprogeny
<< " delta*1e6 " << std::setprecision(6) << std::fixed << delta*1e6
<< " name " << node->getName()
;
assert(delta < 1e-6) ;
for(unsigned int i = 0; i < node->getNumChildren(); i++) deltacheck_r(node->getChild(i), depth + 1 );
}
struct GRepeat
{
unsigned repeat_min ;
unsigned vertex_min ;
unsigned index ;
std::string pdig ;
unsigned ndig ;
GNode* first ; // cannot const as collection is deferred
unsigned nprog ;
unsigned nvert ;
bool candidate ;
bool select ;
bool isListed(const std::vector<std::string>& pdigs_)
{
return std::find(pdigs_.begin(), pdigs_.end(), pdig ) != pdigs_.end() ;
}
GRepeat( unsigned repeat_min_, unsigned vertex_min_, unsigned index_, const std::string& pdig_, unsigned ndig_, GNode* first_ )
:
repeat_min(repeat_min_),
vertex_min(vertex_min_),
index(index_),
pdig(pdig_),
ndig(ndig_),
first(first_),
nprog(first->getLastProgenyCount()),
nvert(first->getProgenyNumVertices()),
// includes self when GNode.m_selfdigest is true
candidate(ndig > repeat_min && nvert > vertex_min ),
select(false)
{
}
std::string desc()
{
std::stringstream ss ;
ss << ( candidate ? " ** " : " " )
<< ( select ? " ## " : " " )
<< " idx " << std::setw(3) << index
<< " pdig " << std::setw(32) << pdig
<< " ndig " << std::setw(6) << ndig
<< " nprog " << std::setw(6) << nprog
<< " nvert " << std::setw(6) << nvert
<< " n " << first->getName()
;
return ss.str();
}
};
/**
GInstancer::findRepeatCandidates
----------------------------------
Suspect problem with allowing leaf repeaters is that digesta are not-specific enough,
so get bad matching.
Allowing leaf repeaters results in too many, so place vertex count reqirement too.
**/
void GInstancer::findRepeatCandidates(unsigned int repeat_min, unsigned int vertex_min)
{
unsigned int nall = m_digest_count->size() ;
std::vector<GRepeat> cands ;
// over distinct subtrees (ie progeny digests)
for(unsigned int i=0 ; i < nall ; i++)
{
std::pair<std::string,unsigned int>& kv = m_digest_count->get(i) ;
std::string& pdig = kv.first ;
unsigned int ndig = kv.second ; // number of occurences of the progeny digest
GNode* first = m_root->findProgenyDigest(pdig) ; // first node that matches the progeny digest
GRepeat cand(repeat_min, vertex_min, i, pdig, ndig , first );
cands.push_back(cand) ;
if(cand.candidate) m_repeat_candidates.push_back(pdig);
}
unsigned num_all = cands.size() ;
assert( num_all == nall );
// erase repeats that are enclosed within other repeats
// ie that have an ancestor which is also a repeat candidate
m_repeat_candidates.erase(
std::remove_if(m_repeat_candidates.begin(), m_repeat_candidates.end(), *this ),
m_repeat_candidates.end()
);
unsigned num_repcan = m_repeat_candidates.size() ;
LOG(info)
<< " nall " << nall
<< " repeat_min " << repeat_min
<< " vertex_min " << vertex_min
<< " num_repcan " << num_repcan
;
if(num_repcan > 0)
{
unsigned dmax = 20u ;
LOG(info)
<< " num_repcan " << num_repcan
<< " dmax " << dmax
;
std::cout << " (**) candidates fulfil repeat/vert cuts " << std::endl ;
std::cout << " (##) selected survive contained-repeat disqualification " << std::endl ;
for(unsigned i=0 ; i < std::min(num_all, dmax) ; i++)
{
GRepeat& cand = cands[i];
cand.select = cand.isListed(m_repeat_candidates) ;
std::cout << cand.desc() << std::endl;
}
}
}
bool GInstancer::operator()(const std::string& dig)
{
bool cr = isContainedRepeat(dig, 3);
if(cr && m_verbosity > 2)
LOG(info)
<< "GInstancer::operator() "
<< " pdig " << std::setw(32) << dig
<< " disallowd as isContainedRepeat "
;
return cr ;
}
bool GInstancer::isContainedRepeat( const std::string& pdig, unsigned int levels ) const
{
// for the first node that matches the *pdig* progeny digest
// look back *levels* ancestors to see if any of the immediate ancestors
// are also repeat candidates, if they are then this is a contained repeat
// and is thus disallowed in favor of the ancestor that contains it
GNode* node = m_root->findProgenyDigest(pdig) ;
std::vector<GNode*>& ancestors = node->getAncestors(); // ordered from root to parent
unsigned int asize = ancestors.size();
for(unsigned int i=0 ; i < std::min(levels, asize) ; i++)
{
GNode* a = ancestors[asize - 1 - i] ; // from back to start with parent
std::string& adig = a->getProgenyDigest();
if(std::find(m_repeat_candidates.begin(), m_repeat_candidates.end(), adig ) != m_repeat_candidates.end())
{
return true ;
}
}
return false ;
}
void GInstancer::dumpRepeatCandidates(unsigned dmax)
{
unsigned num_repcan = m_repeat_candidates.size() ;
LOG(info)
<< " num_repcan " << num_repcan
<< " dmax " << dmax
;
for(unsigned int i=0 ; i < std::min(num_repcan, dmax) ; i++) dumpRepeatCandidate(i) ;
}
void GInstancer::dumpRepeatCandidate(unsigned int index, bool verbose)
{
std::string pdig = m_repeat_candidates[index];
unsigned int ndig = m_digest_count->getCount(pdig.c_str());
GNode* first = m_root->findProgenyDigest(pdig) ; // first node that matches the progeny digest
std::vector<GNode*> placements = m_root->findAllProgenyDigest(pdig);
std::cout
<< " pdig " << std::setw(32) << pdig
<< " ndig " << std::setw(6) << std::dec << ndig
<< " nprog " << std::setw(6) << std::dec << first->getLastProgenyCount()
<< " placements " << std::setw(6) << placements.size()
<< " n " << first->getName()
<< std::endl
;
assert(placements.size() == ndig ); // restricting traverse to just selected causes this to fail
if(verbose)
{
for(unsigned int i=0 ; i < placements.size() ; i++)
{
GNode* place = placements[i] ;
GMatrix<float>* t = place->getTransform();
std::cout
<< " t " << t->brief()
<< std::endl
;
}
}
}
unsigned int GInstancer::getRepeatIndex(const std::string& pdig )
{
// repeat index corresponding to a digest
unsigned int index(0);
std::vector<std::string>::iterator it = std::find(m_repeat_candidates.begin(), m_repeat_candidates.end(), pdig );
if(it != m_repeat_candidates.end())
{
index = std::distance(m_repeat_candidates.begin(), it ) + 1; // 1-based index
LOG(debug)<<"GInstancer::getRepeatIndex "
<< std::setw(32) << pdig
<< " index " << index
;
}
return index ;
}
void GInstancer::labelTree() // hmm : doesnt label global volumes ?
{
m_labels = 0 ;
for(unsigned int i=0 ; i < m_repeat_candidates.size() ; i++)
{
std::string pdig = m_repeat_candidates[i];
unsigned int ridx = getRepeatIndex(pdig);
assert(ridx == i + 1 );
std::vector<GNode*> placements = m_root->findAllProgenyDigest(pdig);
// recursive labelling starting from the placements
for(unsigned int p=0 ; p < placements.size() ; p++)
{
labelRepeats_r(placements[p], ridx);
}
}
assert(m_root);
traverseGlobals_r(m_root, 0);
LOG((m_csgskiplv_count > 0 ? fatal : LEVEL))
<< " m_labels (count of non-zero setRepeatIndex) " << m_labels
<< " m_csgskiplv_count " << m_csgskiplv_count
<< " m_repeats_count " << m_repeats_count
<< " m_globals_count " << m_globals_count
<< " total_count : " << ( m_globals_count + m_repeats_count )
;
}
void GInstancer::labelRepeats_r( GNode* node, unsigned int ridx)
{
node->setRepeatIndex(ridx);
m_repeats_count += 1 ;
unsigned lvidx = node->getMeshIndex();
m_meshset[ridx].insert( lvidx ) ;
if( m_ok->isCSGSkipLV(lvidx) ) // --csgskiplv
{
GVolume* vol = dynamic_cast<GVolume*>(node);
vol->setCSGSkip(true);
m_csgskiplv[lvidx].push_back( node->getIndex() );
m_csgskiplv_count += 1 ;
}
if(ridx > 0)
{
LOG(debug)
<< " ridx " << std::setw(5) << ridx
<< " n " << node->getName()
;
m_labels++ ;
}
for(unsigned int i = 0; i < node->getNumChildren(); i++) labelRepeats_r(node->getChild(i), ridx );
}
/**
GInstancer::traverseGlobals_r
-------------------------------
Only recurses whilst in global territory with ridx == 0, as soon as hit a repeated
volume, with ridx > 0, stop recursing.
Skipping of an instanced LV is done here by setting a flag.
Currently trying to skip a global lv at this rather late juncture
leads to inconsistencies manifesting in a corrupted color buffer
(i recall that all global volumes are retained for index consistency in the merge of GMergedMesh GGeoLib)
so moved to simply editing the input GDML
Presumably could also do this by moving the skip earlier to the Geant4 X4 traverse
see notes/issues/torus_replacement_on_the_fly.rst
**/
void GInstancer::traverseGlobals_r( GNode* node, unsigned depth )
{
unsigned ridx = node->getRepeatIndex() ;
if( ridx > 0 ) return ;
assert( ridx == 0 );
m_globals_count += 1 ;
unsigned lvidx = node->getMeshIndex();
m_meshset[ridx].insert( lvidx ) ;
if( m_ok->isCSGSkipLV(lvidx) ) // --csgskiplv
{
assert(0 && "skipping of LV used globally, ie non-instanced, is not currently working ");
GVolume* vol = dynamic_cast<GVolume*>(node);
vol->setCSGSkip(true);
m_csgskiplv[lvidx].push_back( node->getIndex() );
m_csgskiplv_count += 1 ;
}
for(unsigned int i = 0; i < node->getNumChildren(); i++) traverseGlobals_r(node->getChild(i), depth + 1 );
}
std::vector<GNode*> GInstancer::getPlacements(unsigned ridx)
{
std::vector<GNode*> placements ;
if(ridx == 0)
{
placements.push_back(m_root);
}
else
{
assert(ridx >= 1); // ridx is a 1-based index
assert(ridx-1 < m_repeat_candidates.size());
std::string pdig = m_repeat_candidates[ridx-1];
placements = m_root->findAllProgenyDigest(pdig);
}
return placements ;
}
GNode* GInstancer::getRepeatExample(unsigned ridx)
{
std::vector<GNode*> placements = getPlacements(ridx);
std::string pdig = m_repeat_candidates[ridx-1];
GNode* node = m_root->findProgenyDigest(pdig) ; // first node that matches the progeny digest
assert(placements[0] == node);
return node ;
}
GNode* GInstancer::getLastRepeatExample(unsigned ridx)
{
std::vector<GNode*> placements = getPlacements(ridx);
std::string pdig = m_repeat_candidates[ridx-1];
GNode* node = m_root->findProgenyDigest(pdig) ; // first node that matches the progeny digest
assert(placements[0] == node);
GVolume* first = static_cast<GVolume*>(placements.front()) ;
GVolume* last = static_cast<GVolume*>(placements.back()) ;
LOG(info)
<< " ridx " << ridx
<< std::endl
<< " first.pt " << first->getPt()->desc()
<< std::endl
<< " last.pt " << last->getPt()->desc()
;
return placements.back() ;
}
/**
GInstancer::makeMergedMeshAndInstancedBuffers
----------------------------------------------
Populates m_geolib with merged meshes including the instancing buffers.
Using *last=true* is for the ndIdx of GParts(GPts) to match
those of GParts(NCSG) see notes/issues/x016.rst
**/
void GInstancer::makeMergedMeshAndInstancedBuffers(unsigned verbosity)
{
bool last = false ;
GNode* root = m_nodelib->getNode(0);
assert(root);
GNode* base = NULL ;
// passes thru to GMergedMesh::create with management of the mm in GGeoLib
GMergedMesh* mm0 = m_geolib->makeMergedMesh(0, base, root, verbosity );
std::vector<GNode*> placements = getPlacements(0); // just m_root
assert(placements.size() == 1 );
mm0->addInstancedBuffers(placements); // call for global for common structure
unsigned numRepeats = getNumRepeats();
unsigned numRidx = numRepeats + 1 ;
LOG(info)
<< " numRepeats " << numRepeats
<< " numRidx " << numRidx
;
for(unsigned ridx=1 ; ridx < numRidx ; ridx++) // 1-based index
{
GNode* rbase = last ? getLastRepeatExample(ridx) : getRepeatExample(ridx) ;
if(m_verbosity > 2)
LOG(info)
<< " ridx " << ridx
<< " rbase " << rbase
;
GMergedMesh* mm = m_geolib->makeMergedMesh(ridx, rbase, root, verbosity );
std::vector<GNode*> placements_ = getPlacements(ridx);
mm->addInstancedBuffers(placements_);
//mm->reportMeshUsage( ggeo, "GInstancer::CreateInstancedMergedMeshes reportMeshUsage (instanced)");
}
}
/**
GInstancer::dumpMeshset
-------------------------
Dumping the unique LVs in each repeater
**/
void GInstancer::dumpMeshset() const
{
unsigned numRepeats = getNumRepeats();
unsigned numRidx = numRepeats + 1 ;
LOG(info)
<< " numRepeats " << numRepeats
<< " numRidx " << numRidx
<< " (slot 0 for global non-instanced) "
;
typedef std::set<unsigned> SU ;
for(unsigned ridx=0 ; ridx < numRidx ; ridx++ )
{
if( m_meshset.find(ridx) == m_meshset.end() ) continue ;
const SU& ms = m_meshset.at(ridx);
std::cout << " ridx " << ridx
<< " ms " << ms.size()
<< " ( "
;
for(SU::const_iterator it=ms.begin() ; it != ms.end() ; it++ )
std::cout << *it << " " ;
std::cout << " ) " << std::endl ;
}
}
void GInstancer::dumpCSGSkips() const
{
LOG(info) ;
for( MUVU::const_iterator i = m_csgskiplv.begin() ; i != m_csgskiplv.end() ; i++ )
{
unsigned lvIdx = i->first ;
const VU& v = i->second ;
std::cout << " lvIdx " << lvIdx
<< " skip total : " << v.size()
<< " nodeIdx ( "
;
unsigned nj = v.size() ;
//for(VU::const_iterator j=v.begin() ; j != v.end() ; j++ ) std::cout << *j << " " ;
for( unsigned j=0 ; j < std::min( nj, 20u ) ; j++ ) std::cout << v[j] << " " ;
if( nj > 20u ) std::cout << " ... " ;
std::cout << " ) " << std::endl ;
}
}
void GInstancer::dump(const char* msg) const
{
LOG(info) << msg ;
dumpMeshset();
dumpCSGSkips();
}
| 28.071816 | 132 | 0.595598 | seriksen |
14c2d8a99bf1484b4974775491111f626e45feb3 | 3,468 | cpp | C++ | runtime/Cpp/runtime/src/ANTLRInputStream.cpp | charwliu/antlr4 | 1c987e77eaa2baf786023cfff437a409f4623221 | [
"BSD-3-Clause"
] | null | null | null | runtime/Cpp/runtime/src/ANTLRInputStream.cpp | charwliu/antlr4 | 1c987e77eaa2baf786023cfff437a409f4623221 | [
"BSD-3-Clause"
] | null | null | null | runtime/Cpp/runtime/src/ANTLRInputStream.cpp | charwliu/antlr4 | 1c987e77eaa2baf786023cfff437a409f4623221 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#include "Exceptions.h"
#include "misc/Interval.h"
#include "IntStream.h"
#include "support/StringUtils.h"
#include "support/CPPUtils.h"
#include "ANTLRInputStream.h"
using namespace antlr4;
using namespace antlrcpp;
using misc::Interval;
ANTLRInputStream::ANTLRInputStream(const std::string &input) {
InitializeInstanceFields();
load(input);
}
ANTLRInputStream::ANTLRInputStream(const char data_[], size_t numberOfActualCharsInArray)
: ANTLRInputStream(std::string(data_, numberOfActualCharsInArray)) {
}
ANTLRInputStream::ANTLRInputStream(std::istream &stream) {
InitializeInstanceFields();
load(stream);
}
void ANTLRInputStream::load(const std::string &input) {
// Remove the UTF-8 BOM if present.
const char bom[4] = "\xef\xbb\xbf";
if (input.compare(0, 3, bom, 3) == 0)
_data = antlrcpp::utfConverter.from_bytes(input.data() + 3, input.data() + input.size());
else
_data = antlrcpp::utfConverter.from_bytes(input);
p = 0;
}
void ANTLRInputStream::load(std::istream &stream) {
if (!stream.good() || stream.eof()) // No fail, bad or EOF.
return;
_data.clear();
std::string s((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
load(s);
}
void ANTLRInputStream::reset() {
p = 0;
}
void ANTLRInputStream::consume() {
if (p >= _data.size()) {
assert(LA(1) == IntStream::EOF);
throw IllegalStateException("cannot consume EOF");
}
if (p < _data.size()) {
p++;
}
}
size_t ANTLRInputStream::LA(ssize_t i) {
if (i == 0) {
return 0; // undefined
}
ssize_t position = (ssize_t)p;
if (i < 0) {
i++; // e.g., translate LA(-1) to use offset i=0; then _data[p+0-1]
if ((position + i - 1) < 0) {
return IntStream::EOF; // invalid; no char before first char
}
}
if ((position + i - 1) >= (ssize_t)_data.size()) {
return IntStream::EOF;
}
return _data[(size_t)(position + i - 1)];
}
size_t ANTLRInputStream::LT(ssize_t i) {
return LA(i);
}
size_t ANTLRInputStream::index() {
return p;
}
size_t ANTLRInputStream::size() {
return _data.size();
}
// Mark/release do nothing. We have entire buffer.
ssize_t ANTLRInputStream::mark() {
return -1;
}
void ANTLRInputStream::release(ssize_t /* marker */) {
}
void ANTLRInputStream::seek(size_t index) {
if (index <= p) {
p = index; // just jump; don't update stream state (line, ...)
return;
}
// seek forward, consume until p hits index or n (whichever comes first)
index = std::min(index, _data.size());
while (p < index) {
consume();
}
}
std::string ANTLRInputStream::getText(const Interval &interval) {
if (interval.a < 0 || interval.b < 0) {
return "";
}
size_t start = interval.a;
size_t stop = interval.b;
if (stop >= _data.size()) {
stop = _data.size() - 1;
}
size_t count = stop - start + 1;
if (start >= _data.size()) {
return "";
}
return antlrcpp::utfConverter.to_bytes(_data.substr(start, count));
}
std::string ANTLRInputStream::getSourceName() const {
if (name.empty()) {
return IntStream::UNKNOWN_SOURCE_NAME;
}
return name;
}
std::string ANTLRInputStream::toString() const {
return antlrcpp::utfConverter.to_bytes(_data);
}
void ANTLRInputStream::InitializeInstanceFields() {
p = 0;
}
| 22.230769 | 93 | 0.660323 | charwliu |