hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d28b40ae3f75e12d5cd823761b9cb61239e3d897 | 11,203 | cpp | C++ | src/sapi/sapi_transaction.cpp | glemercier/Core-Smart | 4ccc12a1b2a55cbad79ddee07449a5fdadf3082b | [
"MIT"
] | 67 | 2018-05-17T21:54:01.000Z | 2022-02-04T09:45:03.000Z | src/sapi/sapi_transaction.cpp | glemercier/Core-Smart | 4ccc12a1b2a55cbad79ddee07449a5fdadf3082b | [
"MIT"
] | 11 | 2018-06-23T11:27:51.000Z | 2021-02-20T17:54:18.000Z | src/sapi/sapi_transaction.cpp | glemercier/Core-Smart | 4ccc12a1b2a55cbad79ddee07449a5fdadf3082b | [
"MIT"
] | 43 | 2018-05-09T07:27:58.000Z | 2021-12-14T15:21:51.000Z | // Copyright (c) 2017 - 2020 - The SmartCash Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sapi/sapi_transaction.h"
#include "core_io.h"
#include "coins.h"
#include "consensus/validation.h"
#include "smartnode/instantx.h"
#include "validation.h"
extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
static bool transaction_send(HTTPRequest* req, const std::map<std::string, std::string> &mapPathParams, const UniValue &bodyParameter);
static bool transaction_check(HTTPRequest* req, const std::map<std::string, std::string> &mapPathParams, const UniValue &bodyParameter);
static bool transaction_create(HTTPRequest* req, const std::map<std::string, std::string> &mapPathParams, const UniValue &bodyParameter);
SAPI::EndpointGroup transactionEndpoints = {
"transaction",
{
{
"check/{txhash}", HTTPRequest::GET, UniValue::VNULL, transaction_check,
{
}
},
{
"send", HTTPRequest::POST, UniValue::VOBJ, transaction_send,
{
SAPI::BodyParameter(SAPI::Keys::rawtx, new SAPI::Validation::HexString()),
SAPI::BodyParameter(SAPI::Keys::instantpay, new SAPI::Validation::Bool(), true),
SAPI::BodyParameter(SAPI::Keys::overridefees, new SAPI::Validation::Bool(), true)
}
},
{
"create", HTTPRequest::POST, UniValue::VOBJ, transaction_create,
{
SAPI::BodyParameter(SAPI::Keys::inputs, new SAPI::Validation::Transactions()),
SAPI::BodyParameter(SAPI::Keys::outputs, new SAPI::Validation::Outputs()),
SAPI::BodyParameter(SAPI::Keys::locktime, new SAPI::Validation::UInt(), true),
}
}
}
};
static bool transaction_check(HTTPRequest* req, const std::map<std::string, std::string> &mapPathParams, const UniValue &bodyParameter)
{
if ( !mapPathParams.count("txhash") )
return SAPI::Error(req, SAPI::TxNotSpecified, "No hash specified. Use /transaction/check/<txhash>");
std::string hashStr = mapPathParams.at("txhash");
uint256 hash;
if( !ParseHashStr(hashStr, hash) )
return SAPI::Error(req, SAPI::TxNotSpecified, "Invalid hash specified. Use /transaction/check/<txhash>");
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, false))
return SAPI::Error(req, SAPI::TxNotFound, "No information available about the transaction");
string strHex = EncodeHexTx(tx, SERIALIZE_TRANSACTION_NO_WITNESS);
UniValue result(UniValue::VOBJ);
result.pushKV("hex", strHex);
uint256 txid = tx.GetHash();
result.pushKV("txid", txid.GetHex());
result.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION));
result.pushKV("version", tx.nVersion);
result.pushKV("locktime", (int64_t)tx.nLockTime);
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
else {
CTransaction txInput;
uint256 hashBlockIn;
if (!GetTransaction(txin.prevout.hash, txInput, Params().GetConsensus(), hashBlockIn, false))
return SAPI::Error(req, SAPI::TxNotFound, "No information available about one of the inputs.");
const CTxOut& txout = txInput.vout[txin.prevout.n];
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("value", ValueFromAmount(txout.nValue));
in.pushKV("n", (int64_t)txin.prevout.n);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
in.pushKV("scriptPubKey", o);
}
in.pushKV("sequence", (int64_t)txin.nSequence);
vin.push_back(in);
}
result.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.pushKV("value", ValueFromAmount(txout.nValue));
out.pushKV("n", (int64_t)i);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
vout.push_back(out);
}
result.pushKV("vout", vout);
if (!hashBlock.IsNull()){
LOCK(cs_main);
result.pushKV("blockhash", hashBlock.GetHex());
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
result.pushKV("height", pindex->nHeight);
result.pushKV("confirmations", 1 + chainActive.Height() - pindex->nHeight);
result.pushKV("blockTime", pindex->GetBlockTime());
} else {
result.pushKV("height", -1);
result.pushKV("confirmations", 0);
}
}
}
if(instantsend.HasTxLockRequest(tx.GetHash())){
UniValue instantPay(UniValue::VOBJ);
int nSignatures = instantsend.GetTransactionLockSignatures(tx.GetHash());
int nSignaturesMax = CTxLockRequest(tx).GetMaxSignatures();
bool fResult = instantsend.IsLockedInstantSendTransaction(tx.GetHash());
bool fTimeout = instantsend.IsTxLockCandidateTimedOut(tx.GetHash());
instantPay.pushKV("valid", fResult);
instantPay.pushKV("timedOut", fTimeout);
instantPay.pushKV("locksReceived", nSignatures);
instantPay.pushKV("locksMax", nSignaturesMax);
result.pushKV("instantPay", instantPay);
}
SAPI::WriteReply(req, result);
return true;
}
static bool transaction_send(HTTPRequest* req, const std::map<std::string, std::string> &mapPathParams, const UniValue &bodyParameter)
{
LOCK(cs_main);
std::string rawTx = bodyParameter[SAPI::Keys::rawtx].get_str();
bool fInstantSend = bodyParameter.exists(SAPI::Keys::instantpay) ? bodyParameter[SAPI::Keys::instantpay].get_bool() : false;
bool fOverrideFees = bodyParameter.exists(SAPI::Keys::overridefees) ? bodyParameter[SAPI::Keys::overridefees].get_bool() : false;
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, rawTx))
return SAPI::Error(req, SAPI::TxDecodeFailed, "TX decode failed");
uint256 hashTx = tx.GetHash();
CCoinsViewCache &view = *pcoinsTip;
bool fHaveChain = false;
for (size_t o = 0; !fHaveChain && o < tx.vout.size(); o++) {
const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
fHaveChain = !existingCoin.IsSpent();
}
bool fHaveMempool = mempool.exists(hashTx);
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
if (fInstantSend && !instantsend.ProcessTxLockRequest(tx, *g_connman)) {
return SAPI::Error(req, SAPI::TxNoValidInstantPay, "Not a valid InstantSend transaction");
}
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, !fOverrideFees)) {
if (state.IsInvalid()) {
return SAPI::Error(req, SAPI::TxRejected, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
return SAPI::Error(req, SAPI::TxMissingInputs, "Missing inputs");
}
return SAPI::Error(req, SAPI::TxRejected, state.GetRejectReason());
}
}
} else if (fHaveChain) {
return SAPI::Error(req, SAPI::TxAlreadyInBlockchain, "Transaction already in block chain");
}
if(!g_connman)
return SAPI::Error(req, SAPI::TxCantRelay, "Error: Peer-to-peer functionality missing or disabled");
g_connman->RelayTransaction(tx);
UniValue result(UniValue::VOBJ);
result.pushKV("txid", hashTx.GetHex());
SAPI::WriteReply(req, result);
return true;
}
static bool transaction_create(HTTPRequest* req, const std::map<std::string, std::string> &mapPathParams, const UniValue &bodyParameter)
{
UniValue inputs = bodyParameter[SAPI::Keys::inputs].get_array();
UniValue sendTo = bodyParameter[SAPI::Keys::outputs].get_obj();
CMutableTransaction rawTx;
if (bodyParameter.exists(SAPI::Keys::locktime)) {
rawTx.nLockTime = bodyParameter[SAPI::Keys::locktime].get_int64();
}
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
return SAPI::Error(req, SAPI::TxMissingVout, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
return SAPI::Error(req, SAPI::TxInvalidParameter, "Invalid parameter, vout must be positive");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
// set the sequence number if passed in the parameters object
const UniValue& sequenceObj = find_value(o, "sequence");
if (sequenceObj.isNum()) {
int64_t seqNr64 = sequenceObj.get_int64();
if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max())
return SAPI::Error(req, SAPI::TxInvalidParameter, "Invalid parameter, sequence number is out of range");
else
nSequence = (uint32_t)seqNr64;
}
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
vector<string> addrList = sendTo.getKeys();
BOOST_FOREACH(const string& name_, addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
} else {
CBitcoinAddress address(name_);
if (!address.IsValid())
return SAPI::Error(req, SAPI::TxInvalidParameter, string("Invalid SmartCash address: ") + name_);
if (setAddress.count(address))
return SAPI::Error(req, SAPI::TxInvalidParameter, string("Invalid parameter, duplicated address: ") + name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
UniValue result(UniValue::VOBJ);
result.pushKV("hex", EncodeHexTx(rawTx));
SAPI::WriteReply(req, result);
return true;
}
| 40.298561 | 137 | 0.63367 | [
"object",
"vector"
] |
d293ffcfdf5ef14d03cd749b5dc0042a63daf45b | 2,307 | cc | C++ | src/gtl.cc | mjansche/pynini | f2fa2cc5704f028d85c6a4ce1e0d51abb0599b77 | [
"Apache-2.0"
] | 17 | 2016-08-09T07:11:32.000Z | 2021-11-24T07:14:00.000Z | src/gtl.cc | mjansche/pynini | f2fa2cc5704f028d85c6a4ce1e0d51abb0599b77 | [
"Apache-2.0"
] | null | null | null | src/gtl.cc | mjansche/pynini | f2fa2cc5704f028d85c6a4ce1e0d51abb0599b77 | [
"Apache-2.0"
] | 3 | 2016-11-20T03:36:37.000Z | 2021-07-09T08:57:39.000Z | // 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.
//
// Copyright 2016 and onwards Google, Inc.
//
// For general information on the Pynini grammar compilation library, see
// pynini.opengrm.org.
#include <numeric>
#include "gtl.h"
namespace strings {
namespace internal {
// Computes size of joined string.
size_t GetResultSize(const std::vector<string> &elements, size_t s_size) {
const auto lambda = [](size_t partial, const string &right) {
return partial + right.size();
};
return (std::accumulate(elements.begin(), elements.end(), 0, lambda) +
s_size * (elements.size() - 1));
}
} // namespace internal
// Joins a vector of strings on a given delimiter.
string Join(const std::vector<string> &elements, const string &delim) {
string result;
if (elements.empty()) return result;
size_t s_size = delim.size();
result.reserve(internal::GetResultSize(elements, s_size));
auto it = elements.begin();
result.append(it->data(), it->size());
for (++it; it != elements.end(); ++it) {
result.append(delim.data(), s_size);
result.append(it->data(), it->size());
}
return result;
}
// Splits a string according to delimiter, skipping over consecutive
// delimiters.
std::vector<string> Split(const string &full, char delim) {
size_t prev = 0;
size_t found = full.find_first_of(delim);
size_t size = found - prev;
std::vector<string> result;
if (size > 0) result.push_back(full.substr(prev, size));
while (found != string::npos) {
prev = found + 1;
found = full.find_first_of(delim, prev);
size = found - prev;
if (size > 0) result.push_back(full.substr(prev, size));
}
return result;
}
std::vector<string> Split(const string &full, const string &delim) {
return Split(full, delim.c_str());
}
} // namespace strings
| 31.60274 | 75 | 0.692241 | [
"vector"
] |
d2946ab63697be1abc3012c119b4e3e0f64f75e0 | 6,120 | hpp | C++ | duds/hardware/devices/clocks/CppClockDriver.hpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | duds/hardware/devices/clocks/CppClockDriver.hpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | duds/hardware/devices/clocks/CppClockDriver.hpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | /*
* This file is part of the DUDS project. It is subject to the BSD-style
* license terms in the LICENSE file found in the top-level directory of this
* distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
* No part of DUDS, including this file, may be copied, modified, propagated,
* or distributed except according to the terms contained in the LICENSE file.
*
* Copyright (C) 2017 Jeff Jackowski
*/
#ifndef CPPCLOCKDRIVER_HPP
#define CPPCLOCKDRIVER_HPP
#include <duds/hardware/devices/clocks/Clock.hpp>
namespace duds { namespace hardware { namespace devices { namespace clocks {
/**
* The clock driver for C++ clocks that meet the requirements of the
* [TrivialClock](http://en.cppreference.com/w/cpp/concept/TrivialClock)
* concept. This concept only provides the time. It does not provide any
* information on the quality of the time, so this driver also only provides
* the time. The resulting time should be considered no better than a wild
* guess.
*
* @tparam CLK The clock class; it must be a TrivialClock.
* @tparam SVT Sample value type.
* @tparam SQT Sample quality type.
* @tparam TVT Time value type.
* @tparam TQT Time quality type.
*
* @author Jeff Jackowski
*/
template<class CLK, class SVT, class SQT, class TVT, class TQT>
class GenericCppClockDriver :
public duds::hardware::devices::clocks::GenericClockDriver<SVT, SQT, TVT, TQT> {
public:
// copied from base class; cannot use from derived classes
/** @copydoc GenericInstrumentDriver::Adapter */
typedef duds::hardware::GenericInstrumentAdapter<SVT, SQT, TVT, TQT>
Adapter;
/** @copydoc GenericInstrumentDriver::Measurement */
typedef duds::data::GenericMeasurement<SVT, SQT, TVT, TQT> Measurement;
/**
* The clock class.
*/
typedef CLK Clock;
protected:
/*
* The clock's accuracy; this value is not supplied by the C++ interface.
* @todo Assure accuracy is what is ment; clocks are a bit different.
*/
//SQT sampleAccuracy;
//TQT timeAccuracy;
/* The following seemed like a more elegant solution, but I can't get it
to work.
template <class Value>
void setValue(Value &value, const typename CLK::time_point &time) {
value = typename Value(
std::chrono::duration_cast<typename Value::duration>(
time.time_since_epoch())
);
}
//template <>
void setValue(duds::data::GenericValue &value,
const typename CLK::time_point &time
) {
value = duds::time::interstellar::FemtoTime(
std::chrono::time_point_cast<
duds::time::interstellar::FemtoTime,
duds::time::interstellar::FemtoClock,
typename CLK::duration
>(
time
)
);
}
template <class Sample>
void setSample(Sample &samp, const typename CLK::time_point &time) {
samp.resolution = (typename Sample::Quality)Clock::period::num /
(typename Sample::Quality)Clock::period::den;
samp.accuracy = samp.precision = samp.estError =
duds::data::unspecified<typename Sample::Quality>();
setValue(samp.value, time);
}
*/
public:
//GenericCppClockDriver() { }
/**
* Samples the time from the clock device without triggering a new
* measurement event.
* @param time The place to put the sampled time.
*/
virtual void sampleTime(typename Measurement::TimeSample &time) {
/* part of the more elegant way that doesn't compile.
typename CLK::time_point now = Clock::now();
setSample(time, now);
*/
time.accuracy = time.precision = time.estError =
duds::data::unspecified<TQT>();
time.resolution = (TQT)Clock::period::num / (TQT)Clock::period::den;
time.value = Clock::now();
}
/**
* Samples the time from this clock and the given clock, then sends the
* measurement event. The sample from this clock will be in the @a measured
* field of the @a Measurement object.
* @param clock The clock that will be sampled for the timestamp in the
* resulting measurement. If it is this clock, the clock will
* only be sampled once and the same time will be in both the
* @a measured and @a timestamp fields of the @a Measurement
* object. Different types may be used to hold the time in
* those fields so they might not evaluate as equal.
*/
virtual void sample(ClockDriver &clock) {
/* part of the more elegant way that doesn't compile.
std::shared_ptr<Measurement> m =
std::make_shared<Measurement>();
typename CLK::time_point now = Clock::now();
setSample(m->measured, now);
// if the supplied clock driver is this clock driver . . .
if (this == &clock) {
// sample the clock just once
setSample(m->timestamp, now);
} else {
// sample the other clock
clock.sampleTime(m->timestamp);
}
// send out the measurement
GenericClockDriver<SVT, SQT, TVT, TQT>::adp->recordMeasurement(m);
*/
// make a new Measurement, then fill it
std::shared_ptr<Measurement> m =
std::make_shared<Measurement>();
m->measured.accuracy = m->measured.precision = m->measured.estError =
duds::data::unspecified<SQT>();
m->measured.resolution = (SQT)Clock::period::num / (SQT)Clock::period::den;
typename Clock::time_point ctp = Clock::now();
m->measured.value = ctp;
// if the supplied clock driver is this clock driver . . .
if (this == &clock) {
// sample the clock just once
m->timestamp.value = ctp;
//std::chrono::time_point_cast
//<typename TVT::duration>(ctp);
m->timestamp.accuracy = m->timestamp.precision =
m->timestamp.estError = duds::data::unspecified<TQT>();
m->timestamp.resolution = (TQT)Clock::period::num /
(TQT)Clock::period::den;
} else {
// sample the other clock
clock.sampleTime(m->timestamp);
}
// send out the measurement
GenericClockDriver<SVT, SQT, TVT, TQT>::adp->signalMeasurement(m);
}
virtual bool unambiguous() const noexcept {
return false;
}
};
/**
* General use C++ clock driver type.
*/
typedef GenericCppClockDriver<
duds::time::interstellar::NanoClock, // could be FemtoClock
duds::data::GenericValue,
double,
duds::time::interstellar::NanoTime,
float
> CppClockDriver;
} } } }
#endif // #ifndef CPPCLOCKDRIVER_HPP
| 34.772727 | 80 | 0.696078 | [
"object"
] |
d29500746a1f0436d9bc42f1ebb07ba1c98a8095 | 3,704 | cpp | C++ | src/physics/ChLink.cpp | Milad-Rakhsha/Project-Chrono | 6ab7abcd532cfb3c5e3876478fdd49c7ab783f63 | [
"BSD-3-Clause"
] | 1 | 2020-02-16T16:52:08.000Z | 2020-02-16T16:52:08.000Z | src/physics/ChLink.cpp | Milad-Rakhsha/Project-Chrono | 6ab7abcd532cfb3c5e3876478fdd49c7ab783f63 | [
"BSD-3-Clause"
] | null | null | null | src/physics/ChLink.cpp | Milad-Rakhsha/Project-Chrono | 6ab7abcd532cfb3c5e3876478fdd49c7ab783f63 | [
"BSD-3-Clause"
] | null | null | null | //
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
///////////////////////////////////////////////////
//
// ChLink.cpp
//
// ------------------------------------------------
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include "physics/ChLink.h"
#include "physics/ChGlobal.h"
#include "physics/ChSystem.h"
#include "physics/ChExternalObject.h"
#include "core/ChMemory.h" // must be last include (memory leak debugger). In .cpp only.
namespace chrono
{
using namespace collision;
using namespace geometry;
// Register into the object factory, to enable run-time
// dynamic creation and persistence
ChClassRegister<ChLink> a_registration_ChLink;
// BUILDERS
ChLink::ChLink ()
{
Body1 = NULL;
Body2 = NULL;
react_force = VNULL;
react_torque = VNULL;
broken = false;
valid = true;
disabled = false;
SetIdentifier(CHGLOBALS().GetUniqueIntID()); // mark with unique ID
}
// DESTROYER
ChLink::~ChLink ()
{
}
void ChLink::Copy(ChLink* source)
{
// first copy the parent class data...
ChPhysicsItem::Copy(source);
Body1 = 0;
Body2 = 0;
system = 0;
react_force = source->react_force;
react_torque = source->react_torque;
broken = source->broken;
valid = source->valid;
disabled = source->disabled;
}
ChLink* ChLink::new_Duplicate () // inherited classes: Link* MyInheritedLink::new_Duplicate()
{
ChLink* m_l;
m_l = new ChLink; // inherited classes should write here: m_l = new MyInheritedLink;
m_l->Copy(this);
return (m_l);
}
void ChLink::Set2Dmode(int mode)
{
// Nothing specific to do on mask, 'cause base link.
// Chld classes can implement this method,
}
////////////////////////////////////
///
/// UPDATING PROCEDURES
///////// 1- UPDATE TIME
/////////
void ChLink::UpdateTime (double time)
{
ChTime = time;
}
/////////
///////// COMPLETE UPDATE
/////////
/////////
void ChLink::Update (double time)
{
// 1 -
UpdateTime(time);
}
void ChLink::Update ()
{
Update(ChTime); // use the same time
}
void ChLink::UpdateExternalGeometry ()
{
if (GetExternalObject())
GetExternalObject()->onChronoChanged();
}
/////////
///////// FILE I/O
/////////
// Define some link-specific flags for backward compatibility
#define LF_INACTIVE (1L << 0)
#define LF_BROKEN (1L << 2)
#define LF_DISABLED (1L << 4)
void ChLink::StreamOUT(ChStreamOutBinary& mstream)
{
// class version number
mstream.VersionWrite(11);
// serialize parent class too
ChPhysicsItem::StreamOUT(mstream);
// stream out all member data
mstream << disabled;
mstream << valid;
mstream << broken;
}
void ChLink::StreamIN(ChStreamInBinary& mstream)
{
// class version number
int version = mstream.VersionRead();
// deserialize parent class too
if (version <11)
{
ChObj::StreamIN(mstream);
}
if (version >= 11)
{
ChPhysicsItem::StreamIN(mstream);
}
// deserialize class data
if(version ==1)
{
int mylflag; // was 'long' in v.1 but 'long' streaming support is removed
mstream >> mylflag;
valid = !(mylflag & LF_INACTIVE);
disabled = (mylflag & LF_DISABLED)!=0;
broken = (mylflag & LF_BROKEN)!=0;
}
if(version >=2)
{
mstream >> disabled;
mstream >> valid;
mstream >> broken;
}
}
} // END_OF_NAMESPACE____
| 15.628692 | 96 | 0.600432 | [
"geometry",
"object"
] |
d29927ff61d7d29593d0d8e6999095e937d4ba22 | 28,722 | cpp | C++ | python/xmorphy.cpp | fakemoon123/XMorphy | 58ead04bccc3f134d8f3d52244629f46d38e9da0 | [
"MIT"
] | 29 | 2017-07-27T12:47:28.000Z | 2022-01-23T12:20:47.000Z | python/xmorphy.cpp | fakemoon123/XMorphy | 58ead04bccc3f134d8f3d52244629f46d38e9da0 | [
"MIT"
] | 1 | 2018-04-24T19:56:00.000Z | 2021-04-27T15:37:15.000Z | python/xmorphy.cpp | fakemoon123/XMorphy | 58ead04bccc3f134d8f3d52244629f46d38e9da0 | [
"MIT"
] | 5 | 2020-10-21T08:11:24.000Z | 2021-11-02T08:18:21.000Z | #include <iostream>
#include <string>
#include <vector>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <xmorphy/graphem/Token.h>
#include <xmorphy/graphem/Tokenizer.h>
#include <xmorphy/ml/TFDisambiguator.h>
#include <xmorphy/ml/TFMorphemicSplitter.h>
#include <xmorphy/ml/SingleWordDisambiguate.h>
#include <xmorphy/morph/Processor.h>
#include <xmorphy/morph/WordFormPrinter.h>
#include <xmorphy/tag/GraphemTag.h>
#include <xmorphy/tag/MorphTag.h>
#include <xmorphy/tag/PhemTag.h>
#include <xmorphy/tag/TokenTypeTag.h>
#include <xmorphy/tag/UniMorphTag.h>
#include <xmorphy/tag/UniSPTag.h>
#include <xmorphy/tag/AnalyzerTag.h>
namespace py = pybind11;
using namespace std;
X::UniMorphTag tagFromString(const std::string & s)
{
X::UniMorphTag result;
from_string(s, result);
return result;
}
struct MorphInfo
{
public:
std::string normal_form;
X::UniMorphTag tag = X::UniMorphTag::UNKN;
X::UniSPTag sp = X::UniSPTag::X;
double probability;
X::AnalyzerTag analyzer;
public:
const std::string & getNormalFrom() const
{
return normal_form;
}
void setNormalForm(const std::string & normal_form_)
{
normal_form = normal_form_;
}
const X::UniMorphTag & getTag() const
{
return tag;
}
void setTag(X::UniMorphTag tag_)
{
tag = tag_;
}
const X::UniSPTag & getSP() const
{
return sp;
}
void setSP(X::UniSPTag sp_) {
sp = sp_;
}
double getProbability() const
{
return probability;
}
void setProbability(double probability_)
{
probability = probability_;
}
const X::AnalyzerTag & getAnalyzerTag() const
{
return analyzer;
}
void setAnalyzerTag(X::AnalyzerTag analyzer_)
{
analyzer = analyzer_;
}
bool operator==(const MorphInfo & o) const
{
return std::tie(sp, tag, analyzer, probability, normal_form) ==
std::tie(o.sp, o.tag, o.analyzer, o.probability, o.normal_form);
}
bool operator!=(const MorphInfo & o) const
{
return !(*this == o);
}
bool operator<(const MorphInfo & o) const
{
return std::tie(sp, tag, analyzer, probability, normal_form) <
std::tie(o.sp, o.tag, o.analyzer, o.probability, o.normal_form);
}
bool operator>(const MorphInfo& o) const
{
return std::tie(sp, tag, analyzer, probability, normal_form) >
std::tie(o.sp, o.tag, o.analyzer, o.probability, o.normal_form);
}
};
struct WordForm
{
public:
std::string word_form;
std::vector<MorphInfo> infos;
X::TokenTypeTag token_type = X::TokenTypeTag::UNKN;
X::GraphemTag graphem_info = X::GraphemTag::UNKN;
std::vector<X::PhemTag> phem_info;
public:
bool operator==(const WordForm & o) const
{
if (o.infos.size() != infos.size())
return false;
for (size_t i = 0; i < o.infos.size(); ++i)
{
if (o.infos[i] != infos[i])
return false;
}
return std::tie(word_form, token_type, graphem_info) == std::tie(o.word_form, o.token_type, o.graphem_info);
}
bool operator!=(const WordForm & o) const
{
return !(*this == o);
}
bool operator<(const WordForm& o) const
{
if (word_form >= o.word_form)
return false;
if (infos.size() >= o.infos.size())
return false;
if (!(token_type < o.token_type))
return false;
return graphem_info < o.graphem_info;
}
bool operator>(const WordForm& o) const
{
if (word_form > o.word_form)
return true;
if (infos.size() > o.infos.size())
return true;
for (size_t i = 0; i < infos.size(); ++i) {
if (infos[i] < o.infos[i])
return true;
else if (infos[i] > o.infos[i])
return false;
}
return token_type > o.token_type;
}
const std::string & getWordFrom() const
{
return word_form;
}
void setWordForm(const std::string & word_form_)
{
word_form = word_form_;
}
const std::vector<MorphInfo> & getInfos() const
{
return infos;
}
void setInfos(const std::vector<MorphInfo> & infos_)
{
infos = infos_;
}
const X::TokenTypeTag & getTokenType() const
{
return token_type;
}
void setTokenType(X::TokenTypeTag token_type_)
{
token_type = token_type_;
}
const X::GraphemTag& getGraphemTag() const
{
return graphem_info;
}
void setGraphemTag(X::GraphemTag graphem_info_)
{
graphem_info = graphem_info_;
}
const std::vector<X::PhemTag> getPhemInfo() const
{
return phem_info;
}
void setPhemInfo(const std::vector<X::PhemTag> & phem_info_)
{
phem_info = phem_info_;
}
std::string toString() const
{
if (token_type & X::TokenTypeTag::SEPR)
return "";
std::ostringstream os;
for (const auto& mi : infos)
{
os << word_form << "\t";
os << mi.normal_form << "\t";
os << mi.sp << "\t";
os << mi.tag << "\t";
os << mi.analyzer;
os << "\n";
}
std::string result = os.str();
result.pop_back();
return result;
}
};
class MorphAnalyzer
{
private:
std::optional<X::Tokenizer> tok;
std::optional<X::Processor> analyzer;
std::optional<X::SingleWordDisambiguate> disamb;
std::optional<X::TFDisambiguator> context_disamb;
std::optional<X::TFMorphemicSplitter> splitter;
public:
MorphAnalyzer()
{
tok.emplace();
analyzer.emplace();
disamb.emplace();
context_disamb.emplace();
splitter.emplace();
}
bool isWordContainsInDictionary(const std::string& str)
{
return analyzer->isWordContainsInDictionary(X::UniString(str));
}
std::vector<std::string> getNonDictionaryWords(const std::string & str)
{
std::vector<std::string> result;
std::vector<X::TokenPtr> tokens = tok->analyze(X::UniString(str));
auto filtered_tokens = analyzer->getNonDictionaryWords(tokens);
for (const auto & token : filtered_tokens)
result.push_back(token->getInner().getRawString());
return result;
}
std::vector<WordForm> analyze(const std::string& str, bool disambiguate_single = false, bool disambiguate_context = false, bool morphemic_split = false)
{
std::vector<X::TokenPtr> tokens = tok->analyze(X::UniString(str));
std::vector<X::WordFormPtr> forms = analyzer->analyze(tokens);
//std::cerr << "STR:" << str << std::endl;
if (disambiguate_single)
disamb->disambiguate(forms);
if (disambiguate_context)
context_disamb->disambiguate(forms);
std::vector<WordForm> result;
for (auto wf_ptr : forms)
{
if (morphemic_split)
splitter->split(wf_ptr);
std::vector<MorphInfo> infos;
for (const auto & info : wf_ptr->getMorphInfo())
{
MorphInfo new_info{
.normal_form = info.normalForm.toLowerCase().getRawString(),
.tag = info.tag,
.sp = info.sp,
.probability = info.probability,
.analyzer = info.at,
};
infos.push_back(new_info);
}
WordForm new_word_form{
.word_form = wf_ptr->getWordForm().getRawString(),
.infos = std::move(infos),
.token_type = wf_ptr->getTokenType(),
.graphem_info = wf_ptr->getGraphemTag(),
.phem_info = wf_ptr->getPhemInfo(),
};
result.emplace_back(new_word_form);
}
return result;
}
WordForm analyzeSingleWord(const std::string & str, bool disambiguate = false, bool morphemic_split = false)
{
X::TokenPtr token = tok->analyzeSingleWord(X::UniString(str));
X::WordFormPtr form = analyzer->analyzeSingleToken(token);
X::Sentence sentence;
sentence.push_back(form);
if (disambiguate)
disamb->disambiguateSingleForm(form);
if (morphemic_split)
splitter->split(form);
std::vector<MorphInfo> infos;
for (const auto& info : form->getMorphInfo())
{
MorphInfo new_info{
.normal_form = info.normalForm.toLowerCase().getRawString(),
.tag = info.tag,
.sp = info.sp,
.probability = info.probability,
.analyzer = info.at,
};
infos.push_back(new_info);
}
WordForm new_word_form{
.word_form = form->getWordForm().getRawString(),
.infos = std::move(infos),
.token_type = form->getTokenType(),
.graphem_info = form->getGraphemTag(),
.phem_info = form->getPhemInfo(),
};
return new_word_form;
}
std::string morphemicSplit(const std::string & word, X::UniSPTag & speech_part, X::UniMorphTag & tag)
{
X::UniString uword(word);
auto upper_case_word = uword.toUpperCase();
auto phem_info = splitter->split(upper_case_word, speech_part, tag);
return {X::WordFormPrinter::writePhemInfo(uword.toLowerCase(), phem_info)};
}
std::vector<std::string> generateLexeme(const std::string & lemma, X::UniSPTag & speech_part, bool single_only, bool mult_only, bool only_dict, bool only_short)
{
auto parsed_forms = analyzer->generate(X::UniString(lemma));
std::vector<std::string> result;
std::unordered_set<X::UniString> filter;
bool ins_found = false;
bool acc_found = false;
bool nom_found = false;
for (const auto & form : parsed_forms)
{
if (form->sp != speech_part)
continue;
if (only_dict && form->at == X::AnalyzerTag::SUFF)
return {};
if (single_only && form->mt & X::UniMorphTag::Plur)
continue;
if (mult_only && form->mt & X::UniMorphTag::Sing)
continue;
if (form->sp == X::UniSPTag::NOUN)
{
if (form->mt & X::UniMorphTag::Act || form->mt & X::UniMorphTag::Part)
continue;
if (form->wordform != X::UniString("ПОЛУ") && form->wordform.startsWith(X::UniString("ПОЛУ")) && !form->normalform.startsWith(X::UniString("ПОЛУ")))
continue;
if (form->wordform.startsWith(X::UniString("ВПОЛУ")) && !form->normalform.startsWith(X::UniString("ВПОЛУ")))
continue;
if (form->wordform.startsWith(X::UniString("МАДМУА")) && !form->normalform.startsWith(X::UniString("МАДМУА")))
continue;
if (form->wordform.startsWith(X::UniString("ПОД")) && !form->normalform.startsWith(X::UniString("ПОД")))
continue;
if (form->wordform.startsWith(X::UniString("ТЫЩ")) && !form->normalform.startsWith(X::UniString("ТЫЩ")))
continue;
if (form->wordform.startsWith(X::UniString("БОЖ")) && form->normalform.startsWith(X::UniString("БОГ")))
continue;
if (form->wordform == X::UniString("ОБР"))
continue;
if (form->normalform == X::UniString("СТВОЛИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("ГОРБИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("ОСТРОВИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("ДОЖДИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("ДОМИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("ХОЛОДИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("ГОЛОСИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("КИРПИЧИНА") && form->mt.getGender() == X::UniMorphTag::Masc)
continue;
if (form->normalform == X::UniString("РОСТОК") && form->wordform != form->normalform && form->wordform.startsWith(X::UniString("РОСТОК")))
continue;
if (form->wordform == X::UniString("Ш"))
continue;
if (form->wordform == X::UniString("МАК") && form->mt.getCase() != X::UniMorphTag::Nom)
continue;
if (form->wordform == X::UniString("БАК") && form->mt.getCase() != X::UniMorphTag::Nom)
continue;
if (form->wordform == X::UniString("КОН") && form->mt.getCase() != X::UniMorphTag::Nom)
continue;
if (form->wordform == X::UniString("РИС") && form->mt.getCase() != X::UniMorphTag::Nom)
continue;
if (form->normalform == X::UniString("БАКТЕРОИД") && (form->wordform.endsWith(X::UniString("ОД")) || form->wordform.endsWith(X::UniString("ОДЫ"))))
continue;
if (form->wordform == X::UniString("БУКОВ") && form->normalform == X::UniString("БУКВА"))
continue;
if (form->wordform.startsWith(X::UniString("ХОЗЯВ")) && form->normalform == X::UniString("ХОЗЯИН"))
continue;
if (form->wordform.contains(X::UniString("БЭНД")) && !form->normalform.contains(X::UniString("БЭНД")))
continue;
if (form->wordform.startsWith(X::UniString("ШАБР")) && form->normalform == X::UniString("ШАБЕР"))
continue;
if (form->wordform == X::UniString("ОГНЬ"))
continue;
if (form->wordform == X::UniString("ВЕТР"))
continue;
// ДЕРЕВАМИ
if (form->normalform.endsWith(X::UniString("ДЕРЕВО")) && form->mt & X::UniMorphTag::Plur)
{
if (!form->wordform.contains(u'Ь'))
continue;
}
if (form->wordform == X::UniString("МАРИН") && form->mt & X::UniMorphTag::Sing)
continue;
if ((parsed_forms[0]->mt & X::UniMorphTag::Masc) && form->mt & X::UniMorphTag::Fem)
continue;
if ((parsed_forms[0]->mt & X::UniMorphTag::Fem) && form->mt & X::UniMorphTag::Masc)
continue;
if (form->mt & X::UniMorphTag::Acc && form->mt & X::UniMorphTag::Plur)
{
if (acc_found)
continue;
acc_found = true;
}
if (form->mt & X::UniMorphTag::Nom && form->mt & X::UniMorphTag::Plur)
{
if (nom_found)
continue;
nom_found = true;
}
if (form->mt & X::UniMorphTag::Ins && form->mt & X::UniMorphTag::Fem)
if (form->wordform.endsWith(X::UniString("ИЕЮ")))
continue;
if (form->mt & X::UniMorphTag::Ins)
{
if (ins_found && (
form->wordform.endsWith(X::UniString("ЕЮ")) || form->wordform.endsWith(X::UniString("ОЮ"))
|| form->wordform.endsWith(X::UniString("ОМ")) || form->wordform.endsWith(X::UniString("ОЙ"))
))
continue;
ins_found = true;
}
}
if (form->sp == X::UniSPTag::ADJ)
{
if (form->mt & X::UniMorphTag::Short && !only_short)
continue;
if (!(form->mt & X::UniMorphTag::Short) && only_short)
continue;
if (form->wordform.startsWith(X::UniString("НАИ")) && !form->normalform.startsWith(X::UniString("НАИ")))
continue;
if (form->wordform.startsWith(X::UniString("ПО")) && !form->normalform.startsWith(X::UniString("ПО")))
continue;
}
if (form->wordform.find('-') != std::string::npos && form->normalform.find('-') == std::string::npos)
continue;
if (form->wordform.find('-') == std::string::npos && form->normalform.find('-') != std::string::npos)
continue;
if (form->sp == X::UniSPTag::VERB && form->mt & X::UniMorphTag::Part)
continue;
if (form->mt & X::UniMorphTag::Conv)
continue;
result.emplace_back(form->wordform.getRawString());
}
return result;
}
};
PYBIND11_MODULE(pyxmorphy, m) {
py::class_<X::UniSPTag>(m, "UniSPTag")
.def_readonly_static("X", &X::UniSPTag::X)
.def_readonly_static("ADJ", &X::UniSPTag::ADJ)
.def_readonly_static("ADV", &X::UniSPTag::ADV)
.def_readonly_static("INTJ", &X::UniSPTag::INTJ)
.def_readonly_static("NOUN", &X::UniSPTag::NOUN)
.def_readonly_static("PROPN", &X::UniSPTag::PROPN)
.def_readonly_static("VERB", &X::UniSPTag::VERB)
.def_readonly_static("ADP", &X::UniSPTag::ADP)
.def_readonly_static("AUX", &X::UniSPTag::AUX)
.def_readonly_static("CONJ", &X::UniSPTag::CONJ)
.def_readonly_static("SCONJ", &X::UniSPTag::SCONJ)
.def_readonly_static("DET", &X::UniSPTag::DET)
.def_readonly_static("NUM", &X::UniSPTag::NUM)
.def_readonly_static("PART", &X::UniSPTag::PART)
.def_readonly_static("PRON", &X::UniSPTag::PRON)
.def_readonly_static("PUNCT", &X::UniSPTag::PUNCT)
.def_readonly_static("H", &X::UniSPTag::H)
.def_readonly_static("R", &X::UniSPTag::R)
.def_readonly_static("Q", &X::UniSPTag::Q)
.def_readonly_static("SYM", &X::UniSPTag::SYM)
.def("__str__", &X::UniSPTag::toString)
.def("__eq__", &X::UniSPTag::operator==)
.def("__ne__", &X::UniSPTag::operator!=)
.def("__lt__", &X::UniSPTag::operator<)
.def("__gt__", &X::UniSPTag::operator>)
.def(py::init<const std::string &>());
py::class_<X::UniMorphTag>(m, "UniMorphTag")
.def_readonly_static("UNKN", &X::UniMorphTag::UNKN)
.def_readonly_static("Masc", &X::UniMorphTag::Masc)
.def_readonly_static("Fem", &X::UniMorphTag::Fem)
.def_readonly_static("Neut", &X::UniMorphTag::Neut)
.def_readonly_static("Anim", &X::UniMorphTag::Anim)
.def_readonly_static("Inan", &X::UniMorphTag::Inan)
.def_readonly_static("Sing", &X::UniMorphTag::Sing)
.def_readonly_static("Plur", &X::UniMorphTag::Plur)
.def_readonly_static("Ins", &X::UniMorphTag::Ins)
.def_readonly_static("Acc", &X::UniMorphTag::Acc)
.def_readonly_static("Nom", &X::UniMorphTag::Nom)
.def_readonly_static("Dat", &X::UniMorphTag::Dat)
.def_readonly_static("Gen", &X::UniMorphTag::Gen)
.def_readonly_static("Loc", &X::UniMorphTag::Loc)
.def_readonly_static("Voc", &X::UniMorphTag::Voc)
.def_readonly_static("Cmp", &X::UniMorphTag::Cmp)
.def_readonly_static("Sup", &X::UniMorphTag::Sup)
.def_readonly_static("Pos", &X::UniMorphTag::Pos)
.def_readonly_static("Fin", &X::UniMorphTag::Fin)
.def_readonly_static("Inf", &X::UniMorphTag::Inf)
.def_readonly_static("Conv", &X::UniMorphTag::Conv)
.def_readonly_static("Part", &X::UniMorphTag::Part)
.def_readonly_static("Imp", &X::UniMorphTag::Imp)
.def_readonly_static("Ind", &X::UniMorphTag::Ind)
.def_readonly_static("_1", &X::UniMorphTag::_1)
.def_readonly_static("_2", &X::UniMorphTag::_2)
.def_readonly_static("_3", &X::UniMorphTag::_3)
.def_readonly_static("Fut", &X::UniMorphTag::Fut)
.def_readonly_static("Past", &X::UniMorphTag::Past)
.def_readonly_static("Pres", &X::UniMorphTag::Pres)
.def_readonly_static("Notpast", &X::UniMorphTag::Notpast)
.def_readonly_static("Short", &X::UniMorphTag::Short)
.def_readonly_static("Act", &X::UniMorphTag::Act)
.def_readonly_static("Pass", &X::UniMorphTag::Pass)
.def_readonly_static("Mid", &X::UniMorphTag::Mid)
.def_readonly_static("Digit", &X::UniMorphTag::Digit)
.def("__eq__", &X::UniMorphTag::operator==)
.def("__ne__", &X::UniMorphTag::operator!=)
.def("__lt__", &X::UniMorphTag::operator<)
.def("__gt__", &X::UniMorphTag::operator>)
.def("__str__", &X::UniMorphTag::toString)
.def_static("from_string", tagFromString)
.def("get_case", py::overload_cast<>(&X::UniMorphTag::getCase, py::const_))
.def("get_number", py::overload_cast<>(&X::UniMorphTag::getNumber, py::const_))
.def("get_gender", py::overload_cast<>(&X::UniMorphTag::getGender, py::const_))
.def("get_tense", py::overload_cast<>(&X::UniMorphTag::getTense, py::const_))
.def("get_animacy", py::overload_cast<>(&X::UniMorphTag::getAnimacy, py::const_));
py::class_<X::GraphemTag>(m, "GraphemTag")
.def_readonly_static("UNKN", &X::GraphemTag::UNKN)
.def_readonly_static("CYRILLIC", &X::GraphemTag::CYRILLIC)
.def_readonly_static("LATIN", &X::GraphemTag::LATIN)
.def_readonly_static("UPPER_CASE", &X::GraphemTag::UPPER_CASE)
.def_readonly_static("LOWER_CASE", &X::GraphemTag::LOWER_CASE)
.def_readonly_static("MIXED", &X::GraphemTag::MIXED)
.def_readonly_static("CAP_START", &X::GraphemTag::CAP_START)
.def_readonly_static("ABBR", &X::GraphemTag::ABBR)
.def_readonly_static("NAM_ENT", &X::GraphemTag::NAM_ENT)
.def_readonly_static("MULTI_WORD", &X::GraphemTag::MULTI_WORD)
.def_readonly_static("SINGLE_WORD", &X::GraphemTag::SINGLE_WORD)
.def_readonly_static("COMMA", &X::GraphemTag::COMMA)
.def_readonly_static("DOT", &X::GraphemTag::DOT)
.def_readonly_static("COLON", &X::GraphemTag::COLON)
.def_readonly_static("SEMICOLON", &X::GraphemTag::SEMICOLON)
.def_readonly_static("QUESTION_MARK", &X::GraphemTag::QUESTION_MARK)
.def_readonly_static("EXCLAMATION_MARK", &X::GraphemTag::EXCLAMATION_MARK)
.def_readonly_static("THREE_DOTS", &X::GraphemTag::THREE_DOTS)
.def_readonly_static("QUOTE", &X::GraphemTag::QUOTE)
.def_readonly_static("DASH", &X::GraphemTag::DASH)
.def_readonly_static("PARENTHESIS_L", &X::GraphemTag::PARENTHESIS_L)
.def_readonly_static("PARENTHESIS_R", &X::GraphemTag::PARENTHESIS_R)
.def_readonly_static("UNCOMMON_PUNCT", &X::GraphemTag::UNCOMMON_PUNCT)
.def_readonly_static("PUNCT_GROUP", &X::GraphemTag::PUNCT_GROUP)
.def_readonly_static("LOWER_DASH", &X::GraphemTag::LOWER_DASH)
.def_readonly_static("DECIMAL", &X::GraphemTag::DECIMAL)
.def_readonly_static("BINARY", &X::GraphemTag::BINARY)
.def_readonly_static("OCT", &X::GraphemTag::OCT)
.def_readonly_static("HEX", &X::GraphemTag::HEX)
.def_readonly_static("SPACE", &X::GraphemTag::SPACE)
.def_readonly_static("TAB", &X::GraphemTag::TAB)
.def_readonly_static("NEW_LINE", &X::GraphemTag::NEW_LINE)
.def_readonly_static("CR", &X::GraphemTag::CR)
.def_readonly_static("SINGLE_SEP", &X::GraphemTag::SINGLE_SEP)
.def_readonly_static("MULTI_SEP", &X::GraphemTag::MULTI_SEP)
.def("__eq__", &X::GraphemTag::operator==)
.def("__ne__", &X::GraphemTag::operator!=)
.def("__lt__", &X::GraphemTag::operator<)
.def("__gt__", &X::GraphemTag::operator>)
.def("__str__", &X::GraphemTag::toString);
py::class_<X::AnalyzerTag>(m, "AnalyzerTag")
.def_readonly_static("UNKN", &X::AnalyzerTag::UNKN)
.def_readonly_static("DICT", &X::AnalyzerTag::DICT)
.def_readonly_static("PREF", &X::AnalyzerTag::PREF)
.def_readonly_static("SUFF", &X::AnalyzerTag::SUFF)
.def_readonly_static("HYPH", &X::AnalyzerTag::HYPH)
.def("__eq__", &X::AnalyzerTag::operator==)
.def("__ne__", &X::AnalyzerTag::operator!=)
.def("__lt__", &X::AnalyzerTag::operator<)
.def("__gt__", &X::AnalyzerTag::operator>)
.def("__str__", &X::AnalyzerTag::toString);
py::class_<X::TokenTypeTag>(m, "TokenTypeTag")
.def_readonly_static("UNKN", &X::TokenTypeTag::UNKN)
.def_readonly_static("WORD", &X::TokenTypeTag::WORD)
.def_readonly_static("PNCT", &X::TokenTypeTag::PNCT)
.def_readonly_static("SEPR", &X::TokenTypeTag::SEPR)
.def_readonly_static("NUMB", &X::TokenTypeTag::NUMB)
.def_readonly_static("WRNM", &X::TokenTypeTag::WRNM)
.def_readonly_static("HIER", &X::TokenTypeTag::HIER)
.def("__eq__", &X::TokenTypeTag::operator==)
.def("__ne__", &X::TokenTypeTag::operator!=)
.def("__lt__", &X::TokenTypeTag::operator<)
.def("__gt__", &X::TokenTypeTag::operator>)
.def("__str__", &X::TokenTypeTag::toString);
py::class_<X::PhemTag>(m, "PhemTag")
.def_readonly_static("UNKN", &X::PhemTag::UNKN)
.def_readonly_static("PREF", &X::PhemTag::PREF)
.def_readonly_static("ROOT", &X::PhemTag::ROOT)
.def_readonly_static("SUFF", &X::PhemTag::SUFF)
.def_readonly_static("END", &X::PhemTag::END)
.def_readonly_static("LINK", &X::PhemTag::LINK)
.def_readonly_static("HYPH", &X::PhemTag::HYPH)
.def_readonly_static("POSTFIX", &X::PhemTag::POSTFIX)
.def_readonly_static("B_SUFF", &X::PhemTag::B_SUFF)
.def_readonly_static("B_PREF", &X::PhemTag::B_PREF)
.def_readonly_static("B_ROOT", &X::PhemTag::B_ROOT)
.def("__eq__", &X::PhemTag::operator==)
.def("__ne__", &X::PhemTag::operator!=)
.def("__lt__", &X::PhemTag::operator<)
.def("__gt__", &X::PhemTag::operator>)
.def("__str__", &X::PhemTag::toString);
py::class_<MorphInfo>(m, "MorphInfo")
.def(py::init<>())
.def_property("normal_form", &MorphInfo::getNormalFrom, &MorphInfo::setNormalForm)
.def_property("sp", &MorphInfo::getSP, &MorphInfo::setSP)
.def_property("tag", &MorphInfo::getTag, &MorphInfo::setTag)
.def_property("probability", &MorphInfo::getProbability, &MorphInfo::setProbability)
.def_property("analyzer_tag", &MorphInfo::getAnalyzerTag, &MorphInfo::setAnalyzerTag)
.def("__eq__", &MorphInfo::operator==)
.def("__ne__", &MorphInfo::operator!=)
.def("__lt__", &MorphInfo::operator<)
.def("__gt__", &MorphInfo::operator>);
py::class_<WordForm>(m, "WordForm")
.def(py::init<>())
.def_property("word_form", &WordForm::getWordFrom, &WordForm::setWordForm)
.def_property("infos", &WordForm::getInfos, &WordForm::setInfos)
.def_property("token_type", &WordForm::getTokenType, &WordForm::setInfos)
.def_property("graphem_info", &WordForm::getGraphemTag, &WordForm::setGraphemTag)
.def_property("phem_info", &WordForm::getPhemInfo, &WordForm::setPhemInfo)
.def("__eq__", &WordForm::operator==)
.def("__ne__", &WordForm::operator!=)
.def("__lt__", &WordForm::operator<)
.def("__gt__", &WordForm::operator>)
.def("__str__", &WordForm::toString);
py::class_<MorphAnalyzer>(m, "MorphAnalyzer")
.def(py::init<>())
.def("analyze", &MorphAnalyzer::analyze)
.def("analyze_single_word", &MorphAnalyzer::analyzeSingleWord)
.def("is_dictionary_word", &MorphAnalyzer::isWordContainsInDictionary)
.def("get_non_dictionary_words", &MorphAnalyzer::getNonDictionaryWords)
.def("morphemic_split", &MorphAnalyzer::morphemicSplit)
.def("generate_lexeme", &MorphAnalyzer::generateLexeme);
}
| 38.34713 | 164 | 0.57402 | [
"vector"
] |
d29a5c63efe62cccf4d050135822f71ed3581df6 | 6,052 | cpp | C++ | fem/tmop/tmop_pa_da3.cpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | fem/tmop/tmop_pa_da3.cpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | fem/tmop/tmop_pa_da3.cpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "../tmop.hpp"
#include "tmop_pa.hpp"
#include "../../general/forall.hpp"
#include "../../linalg/kernels.hpp"
namespace mfem
{
MFEM_REGISTER_TMOP_KERNELS(void, DatcSize,
const int NE,
const int ncomp,
const int sizeidx,
const DenseMatrix &w_,
const Array<double> &b_,
const Vector &x_,
DenseTensor &j_,
const int d1d,
const int q1d)
{
MFEM_VERIFY(ncomp==1,"");
constexpr int DIM = 3;
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
MFEM_VERIFY(D1D <= Q1D, "");
const auto b = Reshape(b_.Read(), Q1D, D1D);
const auto W = Reshape(w_.Read(), DIM,DIM);
const auto X = Reshape(x_.Read(), D1D, D1D, D1D, ncomp, NE);
auto J = Reshape(j_.Write(), DIM,DIM, Q1D,Q1D,Q1D, NE);
const double infinity = std::numeric_limits<double>::infinity();
MFEM_VERIFY(sizeidx == 0,"");
MFEM_VERIFY(MFEM_CUDA_BLOCKS==256,"");
MFEM_FORALL_3D(e, NE, Q1D, Q1D, Q1D,
{
const int D1D = T_D1D ? T_D1D : d1d;
const int Q1D = T_Q1D ? T_Q1D : q1d;
constexpr int MQ1 = T_Q1D ? T_Q1D : T_MAX;
constexpr int MD1 = T_D1D ? T_D1D : T_MAX;
constexpr int MDQ = (MQ1 > MD1) ? MQ1 : MD1;
MFEM_SHARED double sB[MQ1*MD1];
MFEM_SHARED double sm0[MDQ*MDQ*MDQ];
MFEM_SHARED double sm1[MDQ*MDQ*MDQ];
kernels::internal::LoadB<MD1,MQ1>(D1D,Q1D,b,sB);
ConstDeviceMatrix B(sB, D1D, Q1D);
DeviceCube DDD(sm0, MD1,MD1,MD1);
DeviceCube DDQ(sm1, MD1,MD1,MQ1);
DeviceCube DQQ(sm0, MD1,MQ1,MQ1);
DeviceCube QQQ(sm1, MQ1,MQ1,MQ1);
kernels::internal::LoadX(e,D1D,sizeidx,X,DDD);
double min;
MFEM_SHARED double min_size[MFEM_CUDA_BLOCKS];
DeviceTensor<3,double> M((double*)(min_size),D1D,D1D,D1D);
const DeviceTensor<3,const double> D((double*)(DDD+sizeidx),D1D,D1D,D1D);
MFEM_FOREACH_THREAD(t,x,MFEM_CUDA_BLOCKS) { min_size[t] = infinity; }
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dz,z,D1D)
{
MFEM_FOREACH_THREAD(dy,y,D1D)
{
MFEM_FOREACH_THREAD(dx,x,D1D)
{
M(dx,dy,dz) = D(dx,dy,dz);
}
}
}
MFEM_SYNC_THREAD;
for (int wrk = MFEM_CUDA_BLOCKS >> 1; wrk > 0; wrk >>= 1)
{
MFEM_FOREACH_THREAD(t,x,MFEM_CUDA_BLOCKS)
{ if (t < wrk) { min_size[t] = fmin(min_size[t], min_size[t+wrk]); } }
MFEM_SYNC_THREAD;
}
min = min_size[0];
kernels::internal::EvalX(D1D,Q1D,B,DDD,DDQ);
kernels::internal::EvalY(D1D,Q1D,B,DDQ,DQQ);
kernels::internal::EvalZ(D1D,Q1D,B,DQQ,QQQ);
MFEM_FOREACH_THREAD(qx,x,Q1D)
{
MFEM_FOREACH_THREAD(qy,y,Q1D)
{
MFEM_FOREACH_THREAD(qz,z,Q1D)
{
double T;
kernels::internal::PullEval(qx,qy,qz,QQQ,T);
const double shape_par_vals = T;
const double size = fmax(shape_par_vals, min);
const double alpha = std::pow(size, 1.0/DIM);
for (int i = 0; i < DIM; i++)
{
for (int j = 0; j < DIM; j++)
{
J(i,j,qx,qy,qz,e) = alpha * W(i,j);
}
}
}
}
}
});
}
// PA.Jtr Size = (dim, dim, PA.ne*PA.nq);
void DiscreteAdaptTC::ComputeAllElementTargets(const FiniteElementSpace &pa_fes,
const IntegrationRule &ir,
const Vector &xe,
DenseTensor &Jtr) const
{
MFEM_VERIFY(target_type == IDEAL_SHAPE_GIVEN_SIZE ||
target_type == GIVEN_SHAPE_AND_SIZE,"");
MFEM_VERIFY(tspec_fesv, "No target specifications have been set.");
const FiniteElementSpace *fes = tspec_fesv;
// Cases that are not implemented below
if (skewidx != -1 ||
aspectratioidx != -1 ||
orientationidx != -1 ||
fes->GetMesh()->Dimension() != 3 ||
sizeidx == -1)
{
return ComputeAllElementTargets_Fallback(pa_fes, ir, xe, Jtr);
}
const Mesh *mesh = fes->GetMesh();
const int NE = mesh->GetNE();
// Quick return for empty processors:
if (NE == 0) { return; }
const int dim = mesh->Dimension();
MFEM_VERIFY(mesh->GetNumGeometries(dim) <= 1,
"mixed meshes are not supported");
MFEM_VERIFY(!fes->IsVariableOrder(), "variable orders are not supported");
const FiniteElement &fe = *fes->GetFE(0);
const DenseMatrix &W = Geometries.GetGeomToPerfGeomJac(fe.GetGeomType());
const DofToQuad::Mode mode = DofToQuad::TENSOR;
const DofToQuad &maps = fe.GetDofToQuad(ir, mode);
const Array<double> &B = maps.B;
const int D1D = maps.ndof;
const int Q1D = maps.nqpt;
Vector tspec_e;
const ElementDofOrdering ordering = ElementDofOrdering::LEXICOGRAPHIC;
const Operator *R = fes->GetElementRestriction(ordering);
MFEM_VERIFY(R,"");
MFEM_VERIFY(R->Height() == NE*ncomp*D1D*D1D*D1D,"");
tspec_e.SetSize(R->Height(), Device::GetDeviceMemoryType());
tspec_e.UseDevice(true);
tspec.UseDevice(true);
R->Mult(tspec, tspec_e);
const int id = (D1D << 4 ) | Q1D;
MFEM_LAUNCH_TMOP_KERNEL(DatcSize,id,NE,ncomp,sizeidx,W,B,tspec_e,Jtr);
}
} // namespace mfem
| 35.186047 | 80 | 0.579147 | [
"mesh",
"vector"
] |
d2a80f8b31bf53a6696801601b176abc29cfc769 | 1,022 | hpp | C++ | include/ClientLib/Components/LocalPlayerControlledComponent.hpp | DigitalPulseSoftware/BurgWar | a4d7418c2b639e26bc0fed89ac0c45357f4ac7ba | [
"MIT"
] | 45 | 2018-09-29T14:16:04.000Z | 2022-03-10T18:53:58.000Z | include/ClientLib/Components/LocalPlayerControlledComponent.hpp | Walimouche/BurgWar | 4517ae739945dae2838313b72d0fa854bb27f87c | [
"MIT"
] | 46 | 2019-12-22T17:29:41.000Z | 2022-03-20T14:15:06.000Z | include/ClientLib/Components/LocalPlayerControlledComponent.hpp | Walimouche/BurgWar | 4517ae739945dae2838313b72d0fa854bb27f87c | [
"MIT"
] | 19 | 2018-09-29T11:53:25.000Z | 2022-01-14T17:00:07.000Z | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef BURGWAR_CLIENTLIB_COMPONENTS_LOCALPLAYERCONTROLLED_HPP
#define BURGWAR_CLIENTLIB_COMPONENTS_LOCALPLAYERCONTROLLED_HPP
#include <ClientLib/Export.hpp>
#include <CoreLib/Player.hpp>
#include <NDK/Component.hpp>
#include <vector>
namespace bw
{
class ClientMatch;
class BURGWAR_CLIENTLIB_API LocalPlayerControlledComponent : public Ndk::Component<LocalPlayerControlledComponent>
{
public:
inline LocalPlayerControlledComponent(ClientMatch& clientMatch, Nz::UInt8 localPlayerIndex);
~LocalPlayerControlledComponent() = default;
inline ClientMatch& GetClientMatch() const;
inline Nz::UInt8 GetLocalPlayerIndex() const;
static Ndk::ComponentIndex componentIndex;
private:
ClientMatch& m_clientMatch;
Nz::UInt8 m_localPlayerIndex;
};
}
#include <ClientLib/Components/LocalPlayerControlledComponent.inl>
#endif
| 26.205128 | 115 | 0.80137 | [
"vector"
] |
d2a86233f254a8d923aa7bd3ee95eb16eb51f2f6 | 3,097 | hpp | C++ | phylanx/plugins/keras_support/l2_normalize_operation.hpp | Yeahhhh/phylanx | b6b0843f9b2e54c6d0abea24c04321414d2b67b9 | [
"BSL-1.0"
] | 1 | 2019-08-17T21:19:57.000Z | 2019-08-17T21:19:57.000Z | phylanx/plugins/keras_support/l2_normalize_operation.hpp | tapaswenipathak/phylanx | 62859f2b25d31ba469df64801401c996261163a9 | [
"BSL-1.0"
] | null | null | null | phylanx/plugins/keras_support/l2_normalize_operation.hpp | tapaswenipathak/phylanx | 62859f2b25d31ba469df64801401c996261163a9 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2019 Bita Hasheminezhad
// Copyright (c) 2019 Hartmut Kaiser
//
// 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)
#if !defined(PHYLANX_PLUGINS_KERAS_SUPPORT_L2_NORMALIZE_OPERATION)
#define PHYLANX_PLUGINS_KERAS_SUPPORT_L2_NORMALIZE_OPERATION
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/base_primitive.hpp>
#include <phylanx/execution_tree/primitives/primitive_component_base.hpp>
#include <phylanx/ir/node_data.hpp>
#include <hpx/lcos/future.hpp>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace phylanx { namespace execution_tree { namespace primitives {
/// \brief Returns an array of the same shape which is l2 normalized
///
/// \param a The scalar, vector, matrix, or tensor to perform l2
/// normalization over
/// \param axis Optional. The default is None (normalizing over the whole
/// array).
/// Immitates the functionality of https://keras.io/backend/#l2_normalize
class l2_normalize_operation
: public primitive_component_base
, public std::enable_shared_from_this<l2_normalize_operation>
{
protected:
hpx::future<primitive_argument_type> eval(
primitive_arguments_type const& operands,
primitive_arguments_type const& args,
eval_context ctx) const override;
using val_type = double;
using arg_type = ir::node_data<val_type>;
public:
static match_pattern_type const match_data;
l2_normalize_operation() = default;
l2_normalize_operation(primitive_arguments_type&& operands,
std::string const& name, std::string const& codename);
private:
primitive_argument_type l2_normalize0d() const;
primitive_argument_type l2_normalize1d(arg_type&& arg) const;
primitive_argument_type l2_normalize2d_axis0(arg_type&& arg) const;
primitive_argument_type l2_normalize2d_axis1(arg_type&& arg) const;
primitive_argument_type l2_normalize2d_flatten(arg_type&& arg) const;
primitive_argument_type l2_normalize2d(
arg_type&& arg, std::int64_t axis) const;
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
primitive_argument_type l2_normalize3d_axis0(arg_type&& arg) const;
primitive_argument_type l2_normalize3d_axis1(arg_type&& arg) const;
primitive_argument_type l2_normalize3d_axis2(arg_type&& arg) const;
primitive_argument_type l2_normalize3d_flatten(arg_type&& arg) const;
primitive_argument_type l2_normalize3d(
arg_type&& arg, std::int64_t axis) const;
#endif
};
inline primitive create_l2_normalize_operation(hpx::id_type const& locality,
primitive_arguments_type&& operands,
std::string const& name = "", std::string const& codename = "")
{
return create_primitive_component(
locality, "l2_normalize", std::move(operands), name, codename);
}
}}}
#endif
| 37.768293 | 80 | 0.721989 | [
"shape",
"vector"
] |
d2a8a4ea4d7e2337ba5e7a3a5797f5d62aada789 | 8,204 | cc | C++ | ash/common/session/session_controller_unittest.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | ash/common/session/session_controller_unittest.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | ash/common/session/session_controller_unittest.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 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 "ash/common/session/session_controller.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "ash/common/session/session_controller.h"
#include "ash/common/session/session_state_observer.h"
#include "ash/public/interfaces/session_controller.mojom.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "components/user_manager/user_type.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace ash {
namespace {
class TestSessionStateObserver : public SessionStateObserver {
public:
TestSessionStateObserver() : active_account_id_(EmptyAccountId()) {}
~TestSessionStateObserver() override {}
// SessionStateObserver:
void ActiveUserChanged(const AccountId& account_id) override {
active_account_id_ = account_id;
}
void UserAddedToSession(const AccountId& account_id) override {
user_session_account_ids_.push_back(account_id);
}
void SessionStateChanged(session_manager::SessionState state) override {
state_ = state;
}
std::string GetUserSessionEmails() const {
std::string emails;
for (const auto& account_id : user_session_account_ids_) {
emails += account_id.GetUserEmail() + ",";
}
return emails;
}
session_manager::SessionState state() const { return state_; }
const AccountId& active_account_id() const { return active_account_id_; }
const std::vector<AccountId>& user_session_account_ids() const {
return user_session_account_ids_;
}
private:
session_manager::SessionState state_ = session_manager::SessionState::UNKNOWN;
AccountId active_account_id_;
std::vector<AccountId> user_session_account_ids_;
DISALLOW_COPY_AND_ASSIGN(TestSessionStateObserver);
};
void FillDefaultSessionInfo(mojom::SessionInfo* info) {
info->max_users = 123;
info->can_lock_screen = true;
info->should_lock_screen_automatically = true;
info->add_user_session_policy = AddUserSessionPolicy::ALLOWED;
info->state = session_manager::SessionState::LOGIN_PRIMARY;
}
class SessionControllerTest : public testing::Test {
public:
SessionControllerTest() {}
~SessionControllerTest() override {}
// testing::Test:
void SetUp() override {
controller_ = base::MakeUnique<SessionController>();
controller_->AddSessionStateObserver(&observer_);
}
void TearDown() override {
controller_->RemoveSessionStateObserver(&observer_);
}
void SetSessionInfo(const mojom::SessionInfo& info) {
mojom::SessionInfoPtr info_ptr = mojom::SessionInfo::New();
*info_ptr = info;
controller_->SetSessionInfo(std::move(info_ptr));
}
void UpdateSession(uint32_t session_id, const std::string& email) {
mojom::UserSessionPtr session = mojom::UserSession::New();
session->session_id = session_id;
session->type = user_manager::USER_TYPE_REGULAR;
session->account_id = AccountId::FromUserEmail(email);
session->display_name = email;
session->display_email = email;
controller_->UpdateUserSession(std::move(session));
}
std::string GetUserSessionEmails() const {
std::string emails;
for (const auto& session : controller_->GetUserSessions()) {
emails += session->display_email + ",";
}
return emails;
}
SessionController* controller() { return controller_.get(); }
const TestSessionStateObserver* observer() const { return &observer_; }
private:
std::unique_ptr<SessionController> controller_;
TestSessionStateObserver observer_;
DISALLOW_COPY_AND_ASSIGN(SessionControllerTest);
};
// Tests that the simple session info is reflected properly.
TEST_F(SessionControllerTest, SimpleSessionInfo) {
mojom::SessionInfo info;
FillDefaultSessionInfo(&info);
SetSessionInfo(info);
EXPECT_EQ(123, controller()->GetMaximumNumberOfLoggedInUsers());
EXPECT_TRUE(controller()->CanLockScreen());
EXPECT_TRUE(controller()->ShouldLockScreenAutomatically());
info.can_lock_screen = false;
SetSessionInfo(info);
EXPECT_FALSE(controller()->CanLockScreen());
EXPECT_TRUE(controller()->ShouldLockScreenAutomatically());
info.should_lock_screen_automatically = false;
SetSessionInfo(info);
EXPECT_FALSE(controller()->CanLockScreen());
EXPECT_FALSE(controller()->ShouldLockScreenAutomatically());
}
// Tests that AddUserSessionPolicy is set properly.
TEST_F(SessionControllerTest, AddUserPolicy) {
const AddUserSessionPolicy kTestCases[] = {
AddUserSessionPolicy::ALLOWED,
AddUserSessionPolicy::ERROR_NOT_ALLOWED_PRIMARY_USER,
AddUserSessionPolicy::ERROR_NO_ELIGIBLE_USERS,
AddUserSessionPolicy::ERROR_MAXIMUM_USERS_REACHED,
};
mojom::SessionInfo info;
FillDefaultSessionInfo(&info);
for (const auto& policy : kTestCases) {
info.add_user_session_policy = policy;
SetSessionInfo(info);
EXPECT_EQ(policy, controller()->GetAddUserPolicy())
<< "Test case policy=" << static_cast<int>(policy);
}
}
// Tests that session state can be set and reflected properly.
TEST_F(SessionControllerTest, SessionState) {
const struct {
session_manager::SessionState state;
bool expected_is_screen_locked;
bool expected_is_user_session_blocked;
} kTestCases[] = {
{session_manager::SessionState::OOBE, false, true},
{session_manager::SessionState::LOGIN_PRIMARY, false, true},
{session_manager::SessionState::LOGGED_IN_NOT_ACTIVE, false, true},
{session_manager::SessionState::ACTIVE, false, false},
{session_manager::SessionState::LOCKED, true, true},
{session_manager::SessionState::LOGIN_SECONDARY, false, true},
};
mojom::SessionInfo info;
FillDefaultSessionInfo(&info);
for (const auto& test_case : kTestCases) {
info.state = test_case.state;
SetSessionInfo(info);
EXPECT_EQ(test_case.state, controller()->GetSessionState())
<< "Test case state=" << static_cast<int>(test_case.state);
EXPECT_EQ(observer()->state(), controller()->GetSessionState())
<< "Test case state=" << static_cast<int>(test_case.state);
EXPECT_EQ(test_case.expected_is_screen_locked,
controller()->IsScreenLocked())
<< "Test case state=" << static_cast<int>(test_case.state);
EXPECT_EQ(test_case.expected_is_user_session_blocked,
controller()->IsUserSessionBlocked())
<< "Test case state=" << static_cast<int>(test_case.state);
}
}
// Tests that user sessions can be set and updated.
TEST_F(SessionControllerTest, UserSessions) {
EXPECT_FALSE(controller()->IsActiveUserSessionStarted());
UpdateSession(1u, "user1@test.com");
EXPECT_TRUE(controller()->IsActiveUserSessionStarted());
EXPECT_EQ("user1@test.com,", GetUserSessionEmails());
EXPECT_EQ(GetUserSessionEmails(), observer()->GetUserSessionEmails());
UpdateSession(2u, "user2@test.com");
EXPECT_TRUE(controller()->IsActiveUserSessionStarted());
EXPECT_EQ("user1@test.com,user2@test.com,", GetUserSessionEmails());
EXPECT_EQ(GetUserSessionEmails(), observer()->GetUserSessionEmails());
UpdateSession(1u, "user1_changed@test.com");
EXPECT_EQ("user1_changed@test.com,user2@test.com,", GetUserSessionEmails());
// TODO(xiyuan): Verify observer gets the updated user session info.
}
// Tests that user sessions can be ordered.
TEST_F(SessionControllerTest, ActiveSession) {
UpdateSession(1u, "user1@test.com");
UpdateSession(2u, "user2@test.com");
std::vector<uint32_t> order = {1u, 2u};
controller()->SetUserSessionOrder(order);
EXPECT_EQ("user1@test.com,user2@test.com,", GetUserSessionEmails());
EXPECT_EQ("user1@test.com", observer()->active_account_id().GetUserEmail());
order = {2u, 1u};
controller()->SetUserSessionOrder(order);
EXPECT_EQ("user2@test.com,user1@test.com,", GetUserSessionEmails());
EXPECT_EQ("user2@test.com", observer()->active_account_id().GetUserEmail());
order = {1u, 2u};
controller()->SetUserSessionOrder(order);
EXPECT_EQ("user1@test.com,user2@test.com,", GetUserSessionEmails());
EXPECT_EQ("user1@test.com", observer()->active_account_id().GetUserEmail());
}
} // namespace
} // namespace ash
| 34.616034 | 80 | 0.739639 | [
"vector"
] |
d2aa95906a20d2e7a5c4d282e60d4f7205660c3f | 5,948 | hpp | C++ | modules/sqlite/Common.hpp | dracc/VCMP-SqMod | d3e6adea147f5b2cae5119ddd6028833aa625c09 | [
"MIT"
] | null | null | null | modules/sqlite/Common.hpp | dracc/VCMP-SqMod | d3e6adea147f5b2cae5119ddd6028833aa625c09 | [
"MIT"
] | null | null | null | modules/sqlite/Common.hpp | dracc/VCMP-SqMod | d3e6adea147f5b2cae5119ddd6028833aa625c09 | [
"MIT"
] | null | null | null | #ifndef _SQSQLITE_COMMON_HPP_
#define _SQSQLITE_COMMON_HPP_
// ------------------------------------------------------------------------------------------------
#include "Base/Utility.hpp"
// ------------------------------------------------------------------------------------------------
#include <sqlite3.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Forward declarations.
*/
class Connection;
class Statement;
class Column;
class Transaction;
/* ------------------------------------------------------------------------------------------------
* SOFTWARE INFORMATION
*/
#define SQSQLITE_NAME "Squirrel SQLite Module"
#define SQSQLITE_AUTHOR "Sandu Liviu Catalin (S.L.C)"
#define SQSQLITE_COPYRIGHT "Copyright (C) 2018 Sandu Liviu Catalin"
#define SQSQLITE_HOST_NAME "SqModSQLiteHost"
#define SQSQLITE_VERSION 001
#define SQSQLITE_VERSION_STR "0.0.1"
#define SQSQLITE_VERSION_MAJOR 0
#define SQSQLITE_VERSION_MINOR 0
#define SQSQLITE_VERSION_PATCH 1
/* ------------------------------------------------------------------------------------------------
* Handle validation.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
#define SQMOD_THROW_CURRENT(x, a) (x).ThrowCurrent(a, __FILE__, __LINE__)
#define SQMOD_VALIDATE(x) (x).Validate(__FILE__, __LINE__)
#define SQMOD_VALIDATE_CREATED(x) (x).ValidateCreated(__FILE__, __LINE__)
#define SQMOD_VALIDATE_PARAM(x, i) (x).ValidateParam((i), __FILE__, __LINE__)
#define SQMOD_VALIDATE_COLUMN(x, i) (x).ValidateColumn((i), __FILE__, __LINE__)
#define SQMOD_VALIDATE_ROW(x) (x).ValidateRow(__FILE__, __LINE__)
#define SQMOD_GET_VALID(x) (x).GetValid(__FILE__, __LINE__)
#define SQMOD_GET_CREATED(x) (x).GetCreated(__FILE__, __LINE__)
#else
#define SQMOD_THROW_CURRENT(x, a) (x).ThrowCurrent(a)
#define SQMOD_VALIDATE(x) (x).Validate()
#define SQMOD_VALIDATE_CREATED(x) (x).ValidateCreated()
#define SQMOD_VALIDATE_PARAM(x, i) (x).ValidateParam((i))
#define SQMOD_VALIDATE_COLUMN(x, i) (x).ValidateColumn((i))
#define SQMOD_VALIDATE_ROW(x) (x).ValidateRow()
#define SQMOD_GET_VALID(x) (x).GetValid()
#define SQMOD_GET_CREATED(x) (x).GetCreated()
#endif // _DEBUG
/* ------------------------------------------------------------------------------------------------
* Helper macros for architecture differences.
*/
#ifdef _SQ64
#define sqlite3_bind_integer sqlite3_bind_int64
#define sqlite3_column_integer sqlite3_column_int64
#else
#define sqlite3_bind_integer sqlite3_bind_int
#define sqlite3_column_integer sqlite3_column_int
#endif
/* ------------------------------------------------------------------------------------------------
* Forward declarations.
*/
struct ConnHnd;
struct StmtHnd;
/* ------------------------------------------------------------------------------------------------
* Common typedefs.
*/
typedef SharedPtr< ConnHnd > ConnRef;
typedef SharedPtr< StmtHnd > StmtRef;
/* ------------------------------------------------------------------------------------------------
* Obtain a script object from a connection handle. (meant to avoid having to include the header)
*/
Object GetConnectionObj(const ConnRef & conn);
/* ------------------------------------------------------------------------------------------------
* Obtain a script object from a statement handle. (meant to avoid having to include the header)
*/
Object GetStatementObj(const StmtRef & stmt);
/* ------------------------------------------------------------------------------------------------
* Generate a formatted query.
*/
CSStr QFmtStr(CSStr str, ...);
/* ------------------------------------------------------------------------------------------------
* Tests if a certain query string is empty.
*/
bool IsQueryEmpty(CSStr str);
/* ------------------------------------------------------------------------------------------------
* Retrieve the string representation of a certain status code.
*/
CSStr GetErrStr(Int32 status);
/* ------------------------------------------------------------------------------------------------
* Set a specific heap limit.
*/
void SetSoftHeapLimit(Int32 limit);
/* ------------------------------------------------------------------------------------------------
* Release the specified amount of memory.
*/
Int32 ReleaseMemory(Int32 bytes);
/* ------------------------------------------------------------------------------------------------
* Retrieve the current memory usage.
*/
Object GetMemoryUsage();
/* ------------------------------------------------------------------------------------------------
* Retrieve the memory high watermark.
*/
Object GetMemoryHighwaterMark(bool reset);
/* ------------------------------------------------------------------------------------------------
* Retrieve the escaped version of the specified string.
*/
CSStr EscapeString(StackStrF & str);
/* ------------------------------------------------------------------------------------------------
* Retrieve the escaped version of the specified string using the supplied format specifier.
*/
CCStr EscapeStringEx(SQChar spec, StackStrF & str);
/* ------------------------------------------------------------------------------------------------
* Convert the values from the specified array to a list of column names string.
*/
CCStr ArrayToQueryColumns(Array & arr);
/* ------------------------------------------------------------------------------------------------
* Convert the keys from the specified array to a list of column names string.
*/
CCStr TableToQueryColumns(Table & tbl);
} // Namespace:: SqMod
#endif // _SQSQLITE_COMMON_HPP_
| 39.919463 | 99 | 0.458642 | [
"object"
] |
d2ac4d0f374554a428ad6e2e890ba06d50ff3d6d | 2,307 | cpp | C++ | example-01/vector_addition.cpp | joeatodd/SYCL-For-CUDA-Examples | aad6720cf052fb12557a14758d0e7f7adc151f30 | [
"Apache-2.0"
] | 41 | 2020-06-02T13:31:03.000Z | 2022-02-07T10:46:55.000Z | example-01/vector_addition.cpp | joeatodd/SYCL-For-CUDA-Examples | aad6720cf052fb12557a14758d0e7f7adc151f30 | [
"Apache-2.0"
] | 7 | 2020-06-03T16:21:33.000Z | 2021-06-27T14:48:11.000Z | example-01/vector_addition.cpp | joeatodd/SYCL-For-CUDA-Examples | aad6720cf052fb12557a14758d0e7f7adc151f30 | [
"Apache-2.0"
] | 12 | 2020-06-13T10:02:22.000Z | 2022-01-08T02:47:27.000Z | /**
* SYCL FOR CUDA : Vector Addition Example
*
* Copyright 2020 Codeplay Software 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.
*
* @File: vector_addition.cpp
*/
#include <algorithm>
#include <iostream>
#include <vector>
#include <CL/sycl.hpp>
class CUDASelector : public sycl::device_selector {
public:
int operator()(const sycl::device &device) const override {
if(device.get_platform().get_backend() == sycl::backend::cuda){
std::cout << " CUDA device found " << std::endl;
return 1;
} else{
return -1;
}
}
};
int main(int argc, char *argv[]) {
constexpr const size_t N = 100000;
const sycl::range VecSize{N};
sycl::buffer<double> bufA{VecSize};
sycl::buffer<double> bufB{VecSize};
sycl::buffer<double> bufC{VecSize};
// Initialize input data
{
const auto dwrite_t = sycl::access::mode::discard_write;
auto h_a = bufA.get_access<dwrite_t>();
auto h_b = bufB.get_access<dwrite_t>();
for (int i = 0; i < N; i++) {
h_a[i] = sin(i) * sin(i);
h_b[i] = cos(i) * cos(i);
}
}
sycl::queue myQueue{CUDASelector()};
// Command Group creation
auto cg = [&](sycl::handler &h) {
const auto read_t = sycl::access::mode::read;
const auto write_t = sycl::access::mode::write;
auto a = bufA.get_access<read_t>(h);
auto b = bufB.get_access<read_t>(h);
auto c = bufC.get_access<write_t>(h);
h.parallel_for(VecSize,
[=](sycl::id<1> i) { c[i] = a[i] + b[i]; });
};
myQueue.submit(cg);
{
const auto read_t = sycl::access::mode::read;
auto h_c = bufC.get_access<read_t>();
double sum = 0.0f;
for (int i = 0; i < N; i++) {
sum += h_c[i];
}
std::cout << "Sum is : " << sum << std::endl;
}
return 0;
}
| 26.215909 | 79 | 0.622887 | [
"vector"
] |
d2b9ed5133a5a0ad1c99570209aeb8b4d4947291 | 26,472 | hpp | C++ | src/Overseer/src/spatial/bits/spatial_manhattan_neighbor.hpp | bacahillsmu/benbot | f6eeadac99690c5c2a5575d8c0d661e6bed3b604 | [
"MIT"
] | 10 | 2017-09-25T18:00:38.000Z | 2018-02-12T06:09:30.000Z | src/Overseer/src/spatial/bits/spatial_manhattan_neighbor.hpp | bacahillsmu/benbot | f6eeadac99690c5c2a5575d8c0d661e6bed3b604 | [
"MIT"
] | 4 | 2017-09-25T18:23:41.000Z | 2018-01-24T19:33:59.000Z | src/Overseer/src/spatial/bits/spatial_manhattan_neighbor.hpp | bacahillsmu/benbot | f6eeadac99690c5c2a5575d8c0d661e6bed3b604 | [
"MIT"
] | 1 | 2021-07-08T21:48:28.000Z | 2021-07-08T21:48:28.000Z | // -*- C++ -*-
//
// Copyright Sylvain Bougerel 2009 - 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file COPYING or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
* \file spatial_neighbor.hpp
* Contains the definition of manhattan neighbor iterators. These iterators
* walk through all items in the container in order from the closest to the
* furthest away from a given key, using a manhattan metric.
*
* \see neighbor_iterator
*/
#ifndef SPATIAL_MANHATTAN_NEIGHBOR_HPP
#define SPATIAL_MANHATTAN_NEIGHBOR_HPP
#include "spatial_neighbor.hpp"
namespace spatial
{
/**
* Facilitate the creation of neighbor iterator that works with a manhattan
* metric.
*
* This class has an associated group of functions designed to
* initialize the iterator position at the beginning, end, lower bound or
* upper bound of the container to iterate.
*
* \tparam Ct The container to iterate.
* \tparam DistanceType The type used to represent the distance, it must be a
* primitive arithmetic type.
* \tparam Diff The difference functor that will compute the difference
* between 2 key element in the container, along a specific dimension. See
* \difference for further explanation.
*/
///@{
template <typename Ct, typename DistanceType, typename Diff
= typename details::with_builtin_difference<Ct>::type>
class manhattan_neighbor_iterator
: public neighbor_iterator<Ct, manhattan<Ct, DistanceType, Diff> >
{
// Check that DistanceType is a fundamental arithmetic type
typedef typename enable_if<import::is_arithmetic<DistanceType> >::type
check_concept_distance_type_is_arithmetic;
public:
manhattan_neighbor_iterator() { }
template <typename AnyDistanceType>
manhattan_neighbor_iterator
(const neighbor_iterator
<Ct, manhattan<Ct, AnyDistanceType, Diff> >& other)
: neighbor_iterator<Ct, manhattan<Ct, DistanceType, Diff> >
(other.rank(), other.key_comp(), other.metric(),
other.target_key(), other.node_dim, other.node,
static_cast<AnyDistanceType>(other.distance())) { }
};
template <typename Ct, typename DistanceType, typename Diff>
class manhattan_neighbor_iterator<const Ct, DistanceType, Diff>
: public neighbor_iterator<const Ct, manhattan<Ct, DistanceType, Diff> >
{
// Some concept checking performed here
typedef enable_if<import::is_arithmetic<DistanceType> >
check_concept_distance_type_is_arithmetic;
public:
manhattan_neighbor_iterator() { }
template <typename AnyDistanceType>
manhattan_neighbor_iterator
(const neighbor_iterator
<const Ct, manhattan<Ct, AnyDistanceType, Diff> >& other)
: neighbor_iterator<const Ct, manhattan<Ct, DistanceType, Diff> >
(other.rank(), other.key_comp(), other.metric(),
other.target_key(), other.node_dim, other.node,
static_cast<AnyDistanceType>(other.distance())) { }
template <typename AnyDistanceType>
manhattan_neighbor_iterator
(const neighbor_iterator
<Ct, manhattan<Ct, AnyDistanceType, Diff> >& other)
: neighbor_iterator<const Ct, manhattan<Ct, DistanceType, Diff> >
(other.rank(), other.key_comp(), other.metric(),
other.target_key(), other.node_dim, other.node,
static_cast<AnyDistanceType>(other.distance())) { }
};
///@}
/**
* Facilitate the creation of an iterator range representing a sequence from
* closest to furthest from the target key position, in manhattan space.
*
* This class has an associated group of functions designed to
* initialize the iterator position at the beginning, end, lower bound or
* upper bound of the container to iterate.
*
* \tparam Ct The container to iterator.
* \tparam DistanceType The type used to represent the distance, it must be a
* primitive arithmetic type.
* \tparam Diff The difference functor that will compute the difference
* between 2 key element in the container, along a specific dimension. See
* \difference for further explanation.
*/
///@{
template <typename Ct, typename DistanceType, typename Diff
= typename details::with_builtin_difference<Ct>::type>
class manhattan_neighbor_iterator_pair
: public neighbor_iterator_pair<Ct, manhattan<Ct, DistanceType, Diff> >
{
// Some concept checking performed here
typedef enable_if<import::is_arithmetic<DistanceType> >
check_concept_distance_type_is_arithmetic;
public:
manhattan_neighbor_iterator_pair() { }
manhattan_neighbor_iterator_pair
(const manhattan_neighbor_iterator<Ct, DistanceType, Diff>& a,
const manhattan_neighbor_iterator<Ct, DistanceType, Diff>& b)
: neighbor_iterator_pair<Ct, manhattan<Ct, DistanceType, Diff> >
(a, b) { }
template <typename AnyDistanceType>
manhattan_neighbor_iterator_pair
(const neighbor_iterator_pair
<Ct, manhattan<Ct, AnyDistanceType, Diff> >& other)
: neighbor_iterator_pair<Ct, manhattan<Ct, DistanceType, Diff> >
(manhattan_neighbor_iterator_pair<Ct, DistanceType, Diff>
(other.first, other.second)) { }
};
template <typename Ct, typename DistanceType, typename Diff>
class manhattan_neighbor_iterator_pair<const Ct, DistanceType, Diff>
: public neighbor_iterator_pair
<const Ct, manhattan<Ct, DistanceType, Diff> >
{
// Some concept checking performed here
typedef enable_if<import::is_arithmetic<DistanceType> >
check_concept_distance_type_is_arithmetic;
public:
manhattan_neighbor_iterator_pair() { }
manhattan_neighbor_iterator_pair
(const manhattan_neighbor_iterator<const Ct, DistanceType, Diff>& a,
const manhattan_neighbor_iterator<const Ct, DistanceType, Diff>& b)
: neighbor_iterator_pair<const Ct, manhattan<Ct, DistanceType, Diff> >
(a, b) { }
template <typename AnyDistanceType>
manhattan_neighbor_iterator_pair
(const neighbor_iterator_pair
<const Ct, manhattan<Ct, AnyDistanceType, Diff> >& other)
: neighbor_iterator_pair<const Ct, manhattan<Ct, DistanceType, Diff> >
(manhattan_neighbor_iterator_pair<const Ct, DistanceType, Diff>
(other.first, other.second)) { }
template <typename AnyDistanceType>
manhattan_neighbor_iterator_pair
(const neighbor_iterator_pair
<Ct, manhattan<Ct, AnyDistanceType, Diff> >& other)
: neighbor_iterator_pair<const Ct, manhattan<Ct, DistanceType, Diff> >
(manhattan_neighbor_iterator_pair<const Ct, DistanceType, Diff>
(other.first, other.second)) { }
};
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing to
* the nearest neighbor of \c target.
*
* \param container The container to iterate.
* \param diff A model of \difference.
* \param target Search for element in container closest to target.
*
* The search will occur in manhattan space, where distance are computed in
* double, by default. However distances can be expressed in any arithmetic
* type by simply assigning the result to an similar iterator using a
* different distance type:
*
* \code
* manhattan_neighbor_iterator<Ct, float, Diff> my_float_nearest_iterator
* = manhattan_neighbor_begin(container, diff(), target);
* \endcode
*/
///@{
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator<Ct, double, Diff>
manhattan_neighbor_begin
(Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_begin
(container, manhattan<Ct, double, Diff>(diff), target);
}
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator<const Ct, double, Diff>
manhattan_neighbor_begin
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_begin
(container, manhattan<Ct, double, Diff>(diff), target);
}
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator<const Ct, double, Diff>
manhattan_neighbor_cbegin
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_begin
(container, manhattan<Ct, double, Diff>(diff), target);
}
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing to
* the nearest neighbor of \c target.
*
* The search will occur in manhattan space, where distance are computed in
* double, by default. However distances can be expressed in any arithmetic
* type by simply assigning the result to an similar iterator using a
* different distance type:
*
* \code
* manhattan_neighbor_iterator<Ct, float> my_float_nearest_iterator
* = manhattan_neighbor_begin(container, target);
* \endcode
*
* \param container The container to iterate.
* \param target Search for element in container closest to target.
*/
///@{
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator<Ct, double> >::type
manhattan_neighbor_begin
(Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_begin
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator<const Ct, double> >::type
manhattan_neighbor_begin
(const Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_begin
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator<const Ct, double> >::type
manhattan_neighbor_cbegin
(const Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_begin
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing
* past-the-end.
*
* The search will occur in manhattan space, where distance are computed in
* double, by default. However distances can be expressed in any arithmetic
* type by simply assigning the result to an similar iterator using a
* different distance type:
*
* \code
* manhattan_neighbor_iterator<Ct, float, Diff> my_float_nearest_iterator
* = manhattan_neighbor_end(container, diff(), target);
* \endcode
*
* \param container The container to iterate.
* \param diff A model of \difference.
* \param target Search for element in container closest to target.
*/
///@{
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator<Ct, double, Diff>
manhattan_neighbor_end
(Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_end
(container, manhattan<Ct, double, Diff>(diff), target);
}
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator<const Ct, double, Diff>
manhattan_neighbor_end
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_end
(container, manhattan<Ct, double, Diff>(diff), target);
}
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator<const Ct, double, Diff>
manhattan_neighbor_cend
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_end
(container, manhattan<Ct, double, Diff>(diff), target);
}
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing
* past-the-end.
*
* The search will occur in manhattan space, where distance are computed in
* double, by default. However distances can be expressed in any arithmetic
* type by simply assigning the result to an similar iterator using a
* different distance type:
*
* \code
* manhattan_neighbor_iterator<Ct, float> my_float_nearest_iterator
* = manhattan_neighbor_end(container, target);
* \endcode
*
* \param container The container to iterate.
* \param target Search for element in container closest to target.
*/
///@{
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator<Ct, double> >::type
manhattan_neighbor_end
(Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_end
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator<const Ct, double> >::type
manhattan_neighbor_end
(const Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_end
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator<const Ct, double> >::type
manhattan_neighbor_cend
(const Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_end
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing
* to the closest element to \c target that is a least as far as \c bound.
*
* \param container The container to iterate.
* \param diff A model of \difference.
* \param target Search for element in container closest to target.
* \param bound The minimum distance at which a neighbor should be found.
*/
///@{
template <typename Ct, typename Diff, typename DistanceType>
inline typename
enable_if<import::is_arithmetic<DistanceType>,
manhattan_neighbor_iterator<Ct, DistanceType, Diff> >::type
manhattan_neighbor_lower_bound
(Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_lower_bound
(container, manhattan<Ct, DistanceType, Diff>(diff), target, bound);
}
template <typename Ct, typename Diff, typename DistanceType>
inline typename
enable_if<import::is_arithmetic<DistanceType>,
manhattan_neighbor_iterator<const Ct, DistanceType, Diff> >::type
manhattan_neighbor_lower_bound
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_lower_bound
(container, manhattan<Ct, DistanceType, Diff>(diff), target, bound);
}
template <typename Ct, typename Diff, typename DistanceType>
inline typename
enable_if<import::is_arithmetic<DistanceType>,
manhattan_neighbor_iterator<const Ct, DistanceType, Diff> >::type
manhattan_neighbor_clower_bound
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_lower_bound
(container, manhattan<Ct, DistanceType, Diff>(diff), target, bound);
}
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing
* to the closest element to \c target that is a least as far as \c bound.
*
* \param container The container to iterate.
* \param target Search for element in container closest to target.
* \param bound The minimum distance at which an element should be found.
*/
///@{
template <typename Ct, typename DistanceType>
inline typename
enable_if_c<details::is_compare_builtin<Ct>::value
&& import::is_arithmetic<DistanceType>::value,
manhattan_neighbor_iterator<Ct, DistanceType> >::type
manhattan_neighbor_lower_bound
(Ct& container,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_lower_bound
(container,
manhattan<Ct, DistanceType, typename
details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target, bound);
}
template <typename Ct, typename DistanceType>
inline typename
enable_if_c<details::is_compare_builtin<Ct>::value
&& import::is_arithmetic<DistanceType>::value,
manhattan_neighbor_iterator<const Ct, DistanceType> >::type
manhattan_neighbor_lower_bound
(const Ct& container,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_lower_bound
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target, bound);
}
template <typename Ct, typename DistanceType>
inline typename
enable_if_c<details::is_compare_builtin<Ct>::value
&& import::is_arithmetic<DistanceType>::value,
manhattan_neighbor_iterator<const Ct, DistanceType> >::type
manhattan_neighbor_clower_bound
(const Ct& container,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_lower_bound
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target, bound);
}
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing
* to the closest element to \c target that further than \c bound.
*
* \param container The container to iterate.
* \param diff A model of \difference.
* \param target Search for element in container closest to target.
* \param bound The minimum distance at which a neighbor should be found.
*/
///@{
template <typename Ct, typename Diff, typename DistanceType>
inline typename
enable_if<import::is_arithmetic<DistanceType>,
manhattan_neighbor_iterator<Ct, DistanceType, Diff> >::type
manhattan_neighbor_upper_bound
(Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_upper_bound
(container, manhattan<Ct, DistanceType, Diff>(diff), target, bound);
}
template <typename Ct, typename Diff, typename DistanceType>
inline typename
enable_if<import::is_arithmetic<DistanceType>,
manhattan_neighbor_iterator<const Ct, DistanceType, Diff> >::type
manhattan_neighbor_upper_bound
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_upper_bound
(container, manhattan<Ct, DistanceType, Diff>(diff), target, bound);
}
template <typename Ct, typename Diff, typename DistanceType>
inline typename
enable_if<import::is_arithmetic<DistanceType>,
manhattan_neighbor_iterator<const Ct, DistanceType, Diff> >::type
manhattan_neighbor_cupper_bound
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_upper_bound
(container, manhattan<Ct, DistanceType, Diff>(diff), target, bound);
}
///@}
/**
* Returns a \ref manhattan_neighbor_iterator pointing
* to the closest element to \c target that is further than \c bound.
*
* \param container The container to iterate.
* \param target Search for element in container closest to target.
* \param bound The minimum distance at which an element should be found.
*/
///@{
template <typename Ct, typename DistanceType>
inline typename
enable_if_c<details::is_compare_builtin<Ct>::value
&& import::is_arithmetic<DistanceType>::value,
manhattan_neighbor_iterator<Ct, DistanceType> >::type
manhattan_neighbor_upper_bound
(Ct& container,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_upper_bound
(container,
manhattan<Ct, DistanceType, typename
details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target, bound);
}
template <typename Ct, typename DistanceType>
inline typename
enable_if_c<details::is_compare_builtin<Ct>::value
&& import::is_arithmetic<DistanceType>::value,
manhattan_neighbor_iterator<const Ct, DistanceType> >::type
manhattan_neighbor_upper_bound
(const Ct& container,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_upper_bound
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target, bound);
}
template <typename Ct, typename DistanceType>
inline typename
enable_if_c<details::is_compare_builtin<Ct>::value
&& import::is_arithmetic<DistanceType>::value,
manhattan_neighbor_iterator<const Ct, DistanceType> >::type
manhattan_neighbor_cupper_bound
(const Ct& container,
const typename container_traits<Ct>::key_type& target,
DistanceType bound)
{
return neighbor_upper_bound
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target, bound);
}
///@}
/**
* Make a pair of iterators spanning the range of iterable element in \c
* container from the closest to the furthest to \c target
*
* \param container The container to iterate.
* \param diff A model of \difference.
* \param target Search for element in container closest to target.
*
* The search will occur in manhattan space, where distance are computed in
* double, by default. However distances can be expressed in any arithmetic
* type by simply assigning the result to an similar iterator using a
* different distance type:
*
* \code
* manhattan_neighbor_iterator_pair<Ct, float, Diff> my_float_iterator_pair
* = manhattan_neighbor_range(container, diff(), target);
* \endcode
*/
///@{
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator_pair<Ct, double, Diff>
manhattan_neighbor_range
(Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_range
(container, manhattan<Ct, double, Diff>(diff), target);
}
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator_pair<const Ct, double, Diff>
manhattan_neighbor_range
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_range
(container, manhattan<Ct, double, Diff>(diff), target);
}
template <typename Ct, typename Diff>
inline manhattan_neighbor_iterator_pair<const Ct, double, Diff>
manhattan_neighbor_crange
(const Ct& container, const Diff& diff,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_range
(container, manhattan<Ct, double, Diff>(diff), target);
}
///@}
/**
* Make a pair of iterators spanning the range of iterable elements in \c
* container from the closest to the furthest to \c target.
*
* The search will occur in manhattan space, where distance are computed in
* double, by default. However distances can be expressed in any arithmetic
* type by simply assigning the result to an similar iterator using a
* different distance type:
*
* \code
* manhattan_neighbor_iterator_pair<Ct, float> my_float_iterator_pair
* = manhattan_neighbor_range(container, target);
* \endcode
*
* \param container The container to iterate.
* \param target Search for element in container closest to target.
*/
///@{
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator_pair<Ct, double> >::type
manhattan_neighbor_range
(Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_range
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator_pair<const Ct, double> >::type
manhattan_neighbor_range
(const Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_range
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
template <typename Ct>
inline typename
enable_if<details::is_compare_builtin<Ct>,
manhattan_neighbor_iterator_pair<const Ct, double> >::type
manhattan_neighbor_crange
(const Ct& container,
const typename container_traits<Ct>::key_type& target)
{
return neighbor_range
(container,
manhattan<Ct, double,
typename details::with_builtin_difference<Ct>::type>
(details::with_builtin_difference<Ct>()(container)),
target);
}
///@}
} // namespace spatial
#endif // SPATIAL_MANHATTAN_NEIGHBOR_HPP
| 35.108753 | 80 | 0.704065 | [
"model"
] |
d2bbc1949fcd47eb99fc29045e70f173399b640f | 4,468 | cpp | C++ | StandaloneTuvok/CmdRenderer.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | StandaloneTuvok/CmdRenderer.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | StandaloneTuvok/CmdRenderer.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | // Disable checked iterators on Windows.
#ifndef _DEBUG
# undef _SECURE_SCL
# define _SECURE_SCL 0
#endif
#ifdef _WIN32
// CRT's memory leak detection on windows
#if defined(DEBUG) || defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif
#endif
#include <StdTuvokDefines.h>
#include <tclap/CmdLine.h>
#include "Renderer/GL/GLRenderer.h"
#include "IO/IOManager.h"
#include "GLContext.h"
#include "SmallImage.h"
#include "Renderer/ContextIdentification.h"
#define SHADER_PATH "Shaders"
bool SaveFBOToDisk(const std::string& filename)
{
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
SmallImage s(viewport[2], viewport[3], 4);
uint8_t* pixels = s.GetDataPtrRW();
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, viewport[2], viewport[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glReadBuffer(GL_BACK);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, viewport[2], viewport[3], 0); // faster than glReadPixels, so use this to copy from backbuffer
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]);
return s.SaveToBMPFile(filename);
}
int main(int argc, char * argv[])
{
#ifdef _WIN32
// CRT's memory leak detection on windows
#if defined(DEBUG) || defined(_DEBUG)
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
#endif
#endif
std::string filename;
try
{
TCLAP::CmdLine cmd("rendering test program");
TCLAP::ValueArg<std::string> dset("d", "dataset", "Dataset to render.", true, "", "filename");
cmd.add(dset);
cmd.parse(argc, argv);
filename = dset.getValue();
}
catch (const TCLAP::ArgException & e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
return EXIT_FAILURE;
}
try
{
GLContext context(1920, 1200, 32, 24, 8, true, &std::wcerr);
if (!context.isValid() || !context.set()) return EXIT_FAILURE;
GLenum err = glewInit();
if (err != GLEW_OK)
{
std::cerr << "Error initializing GLEW: " << glewGetErrorString(err) << "\n";
return EXIT_FAILURE;
}
tuvok::Controller::Instance().DebugOut()->SetOutput(true, true, true, true);
// Convert the data into a UVF if necessary
if ( SysTools::ToLowerCase(SysTools::GetExt(filename)) != "uvf" ) {
std::string uvf_file = SysTools::RemoveExt(filename) + ".uvf";
const std::string tmpdir = "/tmp/";
const bool quantize8 = false;
tuvok::Controller::Instance().IOMan()->ConvertDataset(filename, uvf_file, tmpdir, true, 256, 4, quantize8);
filename = uvf_file;
}
// tuvok::AbstrRenderer * renderer = tuvok::Controller::Instance().RequestNewVolumeRenderer(tuvok::MasterController::OPENGL_SBVR,
// false, false, false, false, false);
std::shared_ptr<tuvok::LuaScripting> ss =
tuvok::Controller::Instance().LuaScript();
tuvok::LuaClassInstance inst = ss->cexecRet<tuvok::LuaClassInstance>(
"tuvok.renderer.new",
int(tuvok::MasterController::OPENGL_SBVR), false, false,
false, false, false);
tuvok::AbstrRenderer* renderer =
inst.getRawPointer<tuvok::AbstrRenderer>(ss);
//renderer->LoadDataset(filename);
//renderer->AddShaderPath(SHADER_PATH);
//renderer->Initialize(tuvok::GLContextID::Current());
//renderer->Resize(UINTVECTOR2(1920, 1200));
//const std::vector<tuvok::RenderRegion*> & rr = renderer->GetRenderRegions();
//renderer->SetRendererTarget(tuvok::AbstrRenderer::RT_HEADLESS);
FLOATMATRIX4 rm;
rm.RotationX(45.0);
//renderer->SetRotation(rr[0], rm);
//renderer->Paint();
SaveFBOToDisk("image.bmp");
//renderer->Cleanup();
tuvok::Controller::Instance().ReleaseVolumeRenderer(renderer);
context.restorePrevious();
}
catch (const std::exception & e)
{
std::cerr << "Exception: " << e.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 31.027778 | 146 | 0.671441 | [
"render",
"vector"
] |
d2bccd8cf487f4d91d54a2498c9593da7e574902 | 181 | cpp | C++ | lang/C++/casting-out-nines-3.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2018-11-09T22:08:38.000Z | 2018-11-09T22:08:38.000Z | lang/C++/casting-out-nines-3.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/casting-out-nines-3.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2018-11-09T22:08:40.000Z | 2018-11-09T22:08:40.000Z | struct ran {
const int base;
std::vector<int> rs;
ran(const int base) : base(base) { for (int nz=0; nz<base-1; nz++) if(SumDigits(nz) == SumDigits(nz*nz)) rs.push_back(nz); }
};
| 30.166667 | 125 | 0.635359 | [
"vector"
] |
d2bd19ddfd14b480c9668d7e3543f52d3bac8048 | 1,055 | cpp | C++ | GeeksForGeeks/Longest Common Prefix in an Array.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/Longest Common Prefix in an Array.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/Longest Common Prefix in an Array.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <bitset>
#include <climits>
#include <list>
#include <queue>
#include <stack>
#include <utility>
using namespace std;
#define INF 1e7
// STRING
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<string> ve(n);
int smi = INT_MAX, ss;
for(int i = 0; i < n; i++){
cin >> ve[i];
ss = ve[i].size();
smi = min(smi, ss);
}
int flag = 0, i;
for( i = 0; i < smi; i++){
for(int j = 1; j < n; j++){
if(ve[j][i] != ve[j - 1][i]){
flag = 1;
break;
}
}
if(flag){
break;
}
}
if(i == 0)
cout << -1 << endl;
else
cout << ve[0].substr(0, i) << endl;
}
return 0;
} | 20.288462 | 47 | 0.420853 | [
"vector"
] |
d2c43984d51d333112325ec5cb4100592929c4e1 | 1,745 | cpp | C++ | PERMPAL.cpp | yashji9/COMPETITIVE-PROGRAMMING | 5c7a255be9b01001ddcde8ca4e6ff4bcb1c62f0f | [
"MIT"
] | 2 | 2018-01-18T13:39:48.000Z | 2018-09-18T09:27:07.000Z | PERMPAL.cpp | yashji9/COMPETITIVE-PROGRAMMING | 5c7a255be9b01001ddcde8ca4e6ff4bcb1c62f0f | [
"MIT"
] | null | null | null | PERMPAL.cpp | yashji9/COMPETITIVE-PROGRAMMING | 5c7a255be9b01001ddcde8ca4e6ff4bcb1c62f0f | [
"MIT"
] | 2 | 2018-09-30T19:12:02.000Z | 2018-10-01T09:31:55.000Z | #include<bits/stdc++.h>
using namespace std;
int main()
{
long int t;
cin>>t;
while(t--)
{
string s;
vector<long int>v[26];
cin>>s;
long int cnt[26]={0},si[26]={0},ei[26]={0};
for(long int i=0;s[i]!='\0';i++)
{
cnt[s[i]-'a']++;
v[s[i]-'a'].push_back(i+1);
}
vector<long int> ans(100005);
long int cntodd=0,oddpos=-1;
for(int i=0;i<26;i++)
{
if(cnt[i]%2!=0)
{
cntodd++;
oddpos=i;
}
}
if(cntodd>1)
cout<<"-1"<<endl;
else
{
//si[0]=0;
long int len=s.length();
long int k=0;
for(int i=0;i<26;i++)
{
if(cnt[i]>1&&cnt[i]%2==0)
{
for(long int j=0;j<cnt[i];j+=2)
{
ans[k]=v[i][j];
ans[len-k-1]=v[i][j+1];
k++;
}
}
}
if(cntodd)
{long int pp=cnt[oddpos];
for(long int i=0;i<pp;i+=2)
{
ans[k]=v[oddpos][i];
cnt[oddpos]--;
// cout<<v[oddpos][i]<<" "<<cnt[oddpos]<<endl;
if(cnt[oddpos]>0)
{
ans[len-k-1]=v[oddpos][i+1];
cnt[oddpos]--;
}
k++;
}
}
for(long int i=0;i<len;i++)
cout<<ans[i]<<" ";
cout<<endl;
}
}
}
| 25.289855 | 64 | 0.285387 | [
"vector"
] |
d2cb693be71795ebad4f9712d29d9e0043388a1b | 12,248 | cpp | C++ | k5lib.cpp | iboukris/webgss | 0e4732e2f7b4de111eafc60b5876aedcc3577f97 | [
"MIT"
] | 1 | 2021-12-26T22:17:24.000Z | 2021-12-26T22:17:24.000Z | k5lib.cpp | iboukris/webgss | 0e4732e2f7b4de111eafc60b5876aedcc3577f97 | [
"MIT"
] | null | null | null | k5lib.cpp | iboukris/webgss | 0e4732e2f7b4de111eafc60b5876aedcc3577f97 | [
"MIT"
] | null | null | null | // MIT Licensed, see LICENSE file
// Copyright (c) 2021 Isaac Boukris <iboukris@gmail.com>
#include <iostream>
#include <string>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <sanitizer/lsan_interface.h>
#include "k5drv.h"
using namespace std;
struct k5libHandle
{
virtual emscripten::val step(string msg) = 0;
virtual ~k5libHandle() {}
};
struct kdcExchangeHandle : k5libHandle
{
krb5_context kctx;
krb5_ccache ccache;
kdcExchangeHandle(krb5_context ctx) :
kctx(ctx), ccache(NULL) {}
virtual krb5_error_code libStep(krb5_data &reply,
krb5_data &request,
krb5_data &realm) = 0;
emscripten::val step(string msg) {
krb5_error_code ret;
vector<uint8_t> rep, req, rlm;
krb5_data reply = {}, request = {}, realm = {};
emscripten::val obj = emscripten::val::object();
obj.set("status", "error");
ret = decode_kkdcp_message(kctx, msg, rep);
if (ret) {
log_k5err(kctx, "decode_kkdcp_message", ret);
return obj;
}
reply.data = (char *) rep.data();
reply.length = rep.size();
ret = libStep(reply, request, realm);
if (ret) {
log_k5err(kctx, "libStep", ret);
return obj;
}
if (request.length == 0) {
const char *ccname = krb5_cc_get_name(kctx, ccache);
if (ccname == NULL || *ccname == NULL) {
cerr << "failed to get ccache name" << endl;
return obj;
}
string ccache_str = string("MEMORY:") + ccname;
ret = ccache_to_buffer(ccache_str, msg);
krb5_cc_destroy(kctx, ccache);
ccache = NULL;
if (ret) {
log_k5err(kctx, "ccache_to_buffer", ret);
return obj;
}
obj.set("status", "ok");
obj.set("creds", emscripten::val::array(msg.begin(), msg.end()));
return obj;
}
req.assign(request.data, request.data + request.length);
rlm.assign(realm.data, realm.data + realm.length);
krb5_free_data_contents(kctx, &request);
krb5_free_data_contents(kctx, &realm);
ret = encode_kkdcp_message(kctx, req, rlm, msg);
if (ret) {
log_k5err(kctx, "encode_kkdcp_message", ret);
return obj;
}
obj.set("status", "continue");
obj.set("token", emscripten::val::array(msg.begin(), msg.end()));
return obj;
}
virtual ~kdcExchangeHandle() {
if (ccache != NULL)
krb5_cc_destroy(kctx, ccache);
krb5_free_context(kctx);
}
};
struct initCredsHandle : kdcExchangeHandle
{
krb5_init_creds_context icc;
krb5_get_init_creds_opt *gic_opts;
initCredsHandle(krb5_context ctx) :
kdcExchangeHandle(ctx), icc(NULL), gic_opts(NULL) {}
krb5_error_code libStep(krb5_data &reply,
krb5_data &request,
krb5_data &realm) {
krb5_error_code ret;
unsigned int flags = 0;
ret = krb5_init_creds_step(kctx, icc, &reply, &request, &realm, &flags);
if (ret) {
log_k5err(kctx, "krb5_init_creds_step", ret);
return ret;
}
if ((flags & KRB5_INIT_CREDS_STEP_FLAG_CONTINUE) == 0)
assert(request.length == 0 && realm.length == 0);
else
assert(request.length != 0 && realm.length != 0);
return 0;
}
~initCredsHandle() {
krb5_init_creds_free(kctx, icc);
krb5_get_init_creds_opt_free(kctx, gic_opts);
}
};
k5libHandle* initCreds(string princ, string pwd)
{
krb5_error_code ret;
krb5_context kctx;
krb5_principal p;
ret = krb5_init_context(&kctx);
if (ret) {
fprintf(stderr, "initCreds: krb5_init_context() failed\n");
return NULL;
}
initCredsHandle *ctx = new initCredsHandle(kctx);
ret = krb5_get_init_creds_opt_alloc(ctx->kctx, &ctx->gic_opts);
if (ret) {
log_k5err(ctx->kctx, "krb5_get_init_creds_opt_alloc", ret);
delete ctx;
return NULL;
}
ret = krb5_cc_new_unique(ctx->kctx, "MEMORY", NULL, &ctx->ccache);
if (ret) {
log_k5err(ctx->kctx, "krb5_cc_new_unique", ret);
delete ctx;
return NULL;
}
ret = krb5_parse_name(ctx->kctx, princ.c_str(), &p);
if (ret) {
log_k5err(ctx->kctx, "krb5_parse_name", ret);
delete ctx;
return NULL;
}
ret = krb5_cc_initialize(ctx->kctx, ctx->ccache, p);
if (ret) {
log_k5err(ctx->kctx, "krb5_cc_initialize", ret);
krb5_free_principal(ctx->kctx, p);
delete ctx;
return NULL;
}
ret = krb5_get_init_creds_opt_set_in_ccache(ctx->kctx, ctx->gic_opts, ctx->ccache);
if (ret) {
log_k5err(ctx->kctx, "krb5_get_init_creds_opt_set_in_ccache", ret);
krb5_free_principal(ctx->kctx, p);
delete ctx;
return NULL;
}
ret = krb5_get_init_creds_opt_set_out_ccache(ctx->kctx, ctx->gic_opts, ctx->ccache);
if (ret) {
log_k5err(ctx->kctx, "krb5_get_init_creds_opt_set_out_ccache", ret);
krb5_free_principal(ctx->kctx, p);
delete ctx;
return NULL;
}
ret = krb5_init_creds_init(ctx->kctx, p, NULL, NULL, 0, ctx->gic_opts, &ctx->icc);
krb5_free_principal(ctx->kctx, p);
if (ret) {
log_k5err(ctx->kctx, "krb5_init_creds_init", ret);
delete ctx;
return NULL;
}
ret = krb5_init_creds_set_password(ctx->kctx, ctx->icc, pwd.c_str());
if (ret) {
log_k5err(ctx->kctx, "krb5_init_creds_set_password", ret);
delete ctx;
return NULL;
}
return ctx;
}
struct tktCredsHandle : kdcExchangeHandle
{
krb5_tkt_creds_context tcc;
tktCredsHandle(krb5_context ctx) :
kdcExchangeHandle(ctx), tcc(NULL) {}
krb5_error_code libStep(krb5_data &reply,
krb5_data &request,
krb5_data &realm) {
krb5_error_code ret;
unsigned int flags = 0;
ret = krb5_tkt_creds_step(kctx, tcc, &reply, &request, &realm, &flags);
if (ret) {
log_k5err(kctx, "krb5_init_creds_step", ret);
return ret;
}
if ((flags & KRB5_TKT_CREDS_STEP_FLAG_CONTINUE) == 0)
assert(request.length == 0 && realm.length == 0);
else
assert(request.length != 0 && realm.length != 0);
return 0;
}
~tktCredsHandle() {
krb5_tkt_creds_free(kctx, tcc);
}
};
k5libHandle* tktCreds(string gssCreds, string server)
{
krb5_error_code ret;
krb5_context kctx;
krb5_creds creds = {};
krb5_principal p, p2;
ret = krb5_init_context(&kctx);
if (ret) {
fprintf(stderr, "initCreds: krb5_init_context() failed\n");
return NULL;
}
tktCredsHandle *ctx = new tktCredsHandle(kctx);
ret = krb5_cc_new_unique(kctx, "MEMORY", NULL, &ctx->ccache);
if (ret) {
log_k5err(ctx->kctx, "krb5_cc_new_unique", ret);
delete ctx;
return NULL;
}
const char *ccname = krb5_cc_get_name(kctx, ctx->ccache);
if (ccname == NULL || *ccname == NULL) {
cerr << "failed to get ccache name" << endl;
delete ctx;
return NULL;
}
string ccache_str = string("MEMORY:") + ccname;
ret = buffer_to_ccache(gssCreds, ccache_str);
if (ret) {
fprintf(stderr, "initCreds: buffer_to_ccache() failed\n");
delete ctx;
return NULL;
}
ret = krb5_parse_name(ctx->kctx, server.c_str(), &p);
if (ret) {
log_k5err(ctx->kctx, "krb5_parse_name", ret);
delete ctx;
return NULL;
}
ret = krb5_cc_get_principal(ctx->kctx, ctx->ccache, &p2);
if (ret) {
log_k5err(ctx->kctx, "krb5_cc_get_principal", ret);
krb5_free_principal(ctx->kctx, p);
delete ctx;
return NULL;
}
creds.client = p2;
creds.server = p;
ret = krb5_tkt_creds_init(ctx->kctx, ctx->ccache, &creds, 0, &ctx->tcc);
krb5_free_principal(ctx->kctx, p);
krb5_free_principal(ctx->kctx, p2);
if (ret) {
log_k5err(ctx->kctx, "krb5_tkt_creds_init", ret);
delete ctx;
return NULL;
}
return ctx;
}
struct gssCredsHandle : k5libHandle
{
gss_cred_id_t gss_creds;
gss_name_t target_name;
gss_ctx_id_t gss_ctx;
gssCredsHandle(gss_cred_id_t gss_creds, gss_name_t target_name) :
gss_creds(gss_creds), target_name(target_name), gss_ctx(NULL) {}
emscripten::val step(string msg) {
OM_uint32 minor, major;
OM_uint32 ret_flags = 0, flags = GSS_C_MUTUAL_FLAG;
gss_buffer_desc token = {};
gss_buffer_desc out = {};
vector<uint8_t> data;
emscripten::val obj = emscripten::val::object();
obj.set("status", "error");
if (!msg.empty()) {
data.assign(msg.begin(), msg.end());
token.value = data.data();
token.length = data.size();
}
major = gss_init_sec_context(&minor, gss_creds, &gss_ctx, target_name,
&mech_spnego, flags, GSS_C_INDEFINITE,
GSS_C_NO_CHANNEL_BINDINGS, &token, NULL,
&out, &ret_flags, NULL);
if (GSS_ERROR(major)) {
log_gsserr("gss_init_sec_context", major, minor);
return obj;
}
if (out.length != 0) {
string data((const char*)out.value, out.length);
obj.set("token", emscripten::val::array(data.begin(), data.end()));
gss_release_buffer(&minor, &out);
}
if (major == GSS_S_COMPLETE && !(ret_flags & GSS_C_MUTUAL_FLAG)) {
cerr << "mutual auth failed" << endl;
return obj;
}
obj.set("status", major == GSS_S_COMPLETE ? "ok" : "continue");
return obj;
}
~gssCredsHandle() {
OM_uint32 min;
if (target_name != GSS_C_NO_NAME)
gss_release_name(&min, &target_name);
if (gss_creds != GSS_C_NO_CREDENTIAL)
gss_release_cred(&min, &gss_creds);
if (gss_ctx != GSS_C_NO_CONTEXT)
gss_delete_sec_context(&min, &gss_ctx, GSS_C_NO_BUFFER);
}
};
k5libHandle* gssCreds(string in_creds, string target)
{
OM_uint32 minor, major;
gss_name_t target_name;
gss_buffer_desc tname_buffer = {};
gss_buffer_desc creds_buffer = {};
gss_cred_id_t creds = GSS_C_NO_CREDENTIAL;
vector<uint8_t> data;
data.assign(target.begin(), target.end());
tname_buffer.value = (void *) data.data();
tname_buffer.length = data.size();
/* GSS_C_NT_HOSTBASED_SERVICE doesn't play nice with short names */
major = gss_import_name(&minor, &tname_buffer, GSS_C_NT_USER_NAME,
&target_name);
if (GSS_ERROR(major)) {
log_gsserr("gss_import_name", major, minor);
return NULL;
}
data.assign(in_creds.begin(), in_creds.end());
creds_buffer.value = (void *) data.data();
creds_buffer.length = data.size();
major = gss_import_cred(&minor, &creds_buffer, &creds);
if (GSS_ERROR(major)) {
log_gsserr("gss_import_cred", major, minor);
return NULL;
}
gssCredsHandle *ctx = new gssCredsHandle(creds, target_name);
return ctx;
}
static void set_krb5_trace(bool val) {
setenv("KRB5_TRACE", val ? "/dev/stderr" : "/dev/null", 1);
}
static void leak_check() {
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
__lsan_do_leak_check();
#endif
#endif
}
using namespace emscripten;
EMSCRIPTEN_BINDINGS(k5lib_driver) {
class_<k5libHandle>("k5libHandle").function("step", &k5libHandle::step);
emscripten::function("initCreds", &initCreds, allow_raw_pointers());
emscripten::function("tktCreds", &tktCreds, allow_raw_pointers());
emscripten::function("gssCreds", &gssCreds, allow_raw_pointers());
emscripten::function("setKrb5Trace", &set_krb5_trace);
emscripten::function("doLeakCheck", &leak_check);
}
| 27.710407 | 88 | 0.589811 | [
"object",
"vector"
] |
d2d1b4454883bd8bf1ebcd1de4c2c568a24e6012 | 1,907 | cpp | C++ | third_party/WebKit/Source/core/css/StyleRuleKeyframe.cpp | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | third_party/WebKit/Source/core/css/StyleRuleKeyframe.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | third_party/WebKit/Source/core/css/StyleRuleKeyframe.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "core/css/StyleRuleKeyframe.h"
#include "core/css/StylePropertySet.h"
#include "core/css/parser/CSSParser.h"
#include "wtf/text/StringBuilder.h"
namespace blink {
StyleRuleKeyframe::StyleRuleKeyframe(PassOwnPtr<Vector<double>> keys, PassRefPtrWillBeRawPtr<StylePropertySet> properties)
: StyleRuleBase(Keyframe)
, m_properties(properties)
, m_keys(*keys)
{
}
String StyleRuleKeyframe::keyText() const
{
ASSERT(!m_keys.isEmpty());
StringBuilder keyText;
for (unsigned i = 0; i < m_keys.size(); ++i) {
if (i)
keyText.append(',');
keyText.appendNumber(m_keys.at(i) * 100);
keyText.append('%');
}
return keyText.toString();
}
bool StyleRuleKeyframe::setKeyText(const String& keyText)
{
ASSERT(!keyText.isNull());
OwnPtr<Vector<double>> keys = CSSParser::parseKeyframeKeyList(keyText);
if (!keys || keys->isEmpty())
return false;
m_keys = *keys;
return true;
}
const Vector<double>& StyleRuleKeyframe::keys() const
{
return m_keys;
}
MutableStylePropertySet& StyleRuleKeyframe::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
return *toMutableStylePropertySet(m_properties.get());
}
String StyleRuleKeyframe::cssText() const
{
StringBuilder result;
result.append(keyText());
result.appendLiteral(" { ");
String decls = m_properties->asText();
result.append(decls);
if (!decls.isEmpty())
result.append(' ');
result.append('}');
return result.toString();
}
DEFINE_TRACE_AFTER_DISPATCH(StyleRuleKeyframe)
{
visitor->trace(m_properties);
StyleRuleBase::traceAfterDispatch(visitor);
}
} // namespace blink
| 23.8375 | 122 | 0.692711 | [
"vector"
] |
d2d2fc1b8c5dc591d538367ea561f483681cc38f | 2,638 | cpp | C++ | app/drawable/DrawableFactory.cpp | mattjr/benthicQT | bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8 | [
"Apache-2.0"
] | 9 | 2016-06-07T09:38:03.000Z | 2021-11-25T17:30:59.000Z | app/drawable/DrawableFactory.cpp | mattjr/benthicQT | bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8 | [
"Apache-2.0"
] | null | null | null | app/drawable/DrawableFactory.cpp | mattjr/benthicQT | bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8 | [
"Apache-2.0"
] | 4 | 2016-06-16T16:55:33.000Z | 2019-04-29T02:34:46.000Z | /* Copyright 2010 NVIDIA 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.
*
* Developed by Mustard Seed Software, LLC
* http://mseedsoft.com
* Modified by Matthew Johnson-Roberson
* from original source: Visualize Physics - Wave
* Copyright (C) 2012 Matthew Johnson-Roberson
* See COPYING for license details
*/
#include <QtCore>
#include "DrawableFactory.h"
#include "Barrier.h"
#include "BarrierGeom.h"
#include "MeshFile.h"
#include "MeshGeom.h"
#include "BQTDebug.h"
namespace ews {
namespace app {
namespace drawable {
using namespace ews::app::model;
using namespace ews::util::debug;
DrawableFactory& DrawableFactory::instance() {
static DrawableFactory singleton;
return singleton;
}
DrawableQtAdapter* DrawableFactory::createDrawableFor(QObject& data) {
// Currently only a loose mapping between object data and drawable type is
// maintained, hense the switching on type.
QString name(data.metaObject()->className());
// qDebug() << "Selecting drawable for" << name;
DrawableQtAdapter* retval = NULL;
if(data.inherits(Barrier::staticMetaObject.className())) {
Barrier* barrier = qobject_cast<Barrier*>(&data);
BarrierGeom* geom = new BarrierGeom(*barrier);
retval = geom;
} else if(data.inherits(MeshFile::staticMetaObject.className())) {
MeshFile* mesh = qobject_cast<MeshFile*>(&data);
MeshGeom* geom = new MeshGeom(*mesh);
retval = geom;
}
if(!retval) {
qWarning() << "No drawable found for" << name;
}
else {
retval->setName((data.objectName() + "Geom").toStdString());
}
return retval;
}
}
}
}
| 33.392405 | 90 | 0.573541 | [
"mesh",
"object",
"model"
] |
d2d534b7e8145560fc09c0d4fa65d20944018509 | 51,091 | cpp | C++ | src/Application.cpp | zmeadows/lldbg | 2445690d48fb6f9847ec7c3aa16379135fdeb78b | [
"MIT"
] | 77 | 2019-02-05T14:06:56.000Z | 2022-03-25T13:31:33.000Z | src/Application.cpp | zmeadows/lldbg | 2445690d48fb6f9847ec7c3aa16379135fdeb78b | [
"MIT"
] | 5 | 2020-06-30T17:44:01.000Z | 2021-09-27T18:11:11.000Z | src/Application.cpp | zmeadows/lldbg | 2445690d48fb6f9847ec7c3aa16379135fdeb78b | [
"MIT"
] | 11 | 2019-04-26T00:27:31.000Z | 2022-03-18T10:22:17.000Z | #include "Application.hpp"
#include <cassert>
#include <chrono>
#include <filesystem>
#include <iostream>
#include <map>
#include <queue>
#include <thread>
#include <unordered_set>
#include "Defer.hpp"
#include "Log.hpp"
#include "StringBuffer.hpp"
#include "fmt/format.h"
namespace fs = std::filesystem;
static std::map<std::string, std::string> s_debug_stream;
// NOTE: remember this is updated once per frame and currently variables are never removed
#define DEBUG_STREAM(x) \
{ \
const std::string xkey = std::string(#x); \
auto it = s_debug_stream.find(xkey); \
const std::string xstr = fmt::format("{}", x); \
if (it != s_debug_stream.end()) { \
it->second = xstr; \
} \
else { \
s_debug_stream[xkey] = xstr; \
} \
}
static std::pair<fs::path, int> resolve_breakpoint(lldb::SBBreakpointLocation location)
{
lldb::SBAddress address = location.GetAddress();
lldb::SBLineEntry line_entry = address.GetLineEntry();
const char* filename = line_entry.GetFileSpec().GetFilename();
const char* directory = line_entry.GetFileSpec().GetDirectory();
if (filename == nullptr || directory == nullptr) {
LOG(Error) << "Failed to read breakpoint location after thread halted";
return {fs::path(), -1};
}
else {
return {fs::path(directory) / fs::path(filename), line_entry.GetLine()};
}
}
static std::pair<bool, bool> process_is_finished(lldb::SBProcess& process)
{
if (!process.IsValid()) {
return {false, false};
}
const lldb::StateType state = process.GetState();
const bool exited = state == lldb::eStateExited;
const bool failed = state == lldb::eStateCrashed;
return {exited || failed, !failed};
}
static bool process_is_running(lldb::SBProcess& process)
{
return process.IsValid() && process.GetState() == lldb::eStateRunning;
}
static bool process_is_stopped(lldb::SBProcess& process)
{
const auto state = process.GetState();
return process.IsValid() && (state == lldb::eStateStopped || state == lldb::eStateUnloaded);
}
static void stop_process(lldb::SBProcess& process)
{
if (!process.IsValid()) {
LOG(Warning) << "Attempted to stop an invalid process.";
return;
}
if (process_is_stopped(process)) {
LOG(Warning) << "Attempted to stop an already-stopped process.";
return;
}
lldb::SBError err = process.Stop();
if (err.Fail()) {
LOG(Error) << "Failed to stop the process, encountered the following error: "
<< err.GetCString();
return;
}
}
/*
static void continue_process(lldb::SBProcess& process)
{
if (!process.IsValid()) {
LOG(Warning) << "Attempted to continue an invalid process.";
return;
}
if (process_is_running(process)) {
LOG(Warning) << "Attempted to continue an already-running process.";
return;
}
lldb::SBError err = process.Continue();
if (err.Fail()) {
LOG(Error) << "Failed to continue the process, encountered the following error: "
<< err.GetCString();
return;
}
}
*/
static void kill_process(lldb::SBProcess& process)
{
if (!process.IsValid()) {
LOG(Warning) << "Attempted to kill an invalid process.";
return;
}
if (process_is_finished(process).first) {
LOG(Warning) << "Attempted to kill an already-finished process.";
return;
}
lldb::SBError err = process.Kill();
if (err.Fail()) {
LOG(Error) << "Failed to kill the process, encountered the following error: \n\t"
<< err.GetCString();
return;
}
}
static std::string build_string(const char* cstr)
{
return cstr ? std::string(cstr) : std::string();
}
static void glfw_error_callback(int error, const char* description)
{
StringBuffer buffer;
buffer.format("GLFW Error {}: {}\n", error, description);
LOG(Error) << buffer.data();
}
// A convenience struct for extracting pertinent display information from an lldb::SBFrame
struct StackFrame {
FileHandle file_handle;
std::string function_name;
int line;
int column;
private:
StackFrame(FileHandle _file_handle, int _line, int _column, std::string&& _function_name)
: file_handle(_file_handle),
function_name(std::move(_function_name)),
line(_line),
column(_column)
{
}
public:
static std::optional<StackFrame> create(lldb::SBFrame frame)
{
lldb::SBFileSpec spec = frame.GetLineEntry().GetFileSpec();
fs::path filename = fs::path(build_string(spec.GetFilename()));
fs::path directory = fs::path(build_string(spec.GetDirectory()));
if (!fs::exists(directory)) {
// LOG(Warning) << "Directory specified by lldb stack frame doesn't exist: " <<
// directory; LOG(Warning) << "Filepath specified: " << filename;
return {};
}
if (auto handle = FileHandle::create(directory / filename); handle.has_value()) {
return StackFrame(*handle, (int)frame.GetLineEntry().GetLine(),
(int)frame.GetLineEntry().GetColumn(),
build_string(frame.GetDisplayFunctionName()));
}
else {
LOG(Warning) << "Filepath corresponding to lldb stack frame doesn't exist: "
<< directory / filename;
return {};
}
}
};
static bool FileTreeNode(const char* label)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetID(label);
ImVec2 pos = window->DC.CursorPos;
ImRect bb(pos, ImVec2(pos.x + ImGui::GetContentRegionAvail().x,
pos.y + g.FontSize + g.Style.FramePadding.y * 2));
bool opened = ImGui::TreeNodeBehaviorIsOpen(id);
bool hovered, held;
if (ImGui::ButtonBehavior(bb, id, &hovered, &held, true))
window->DC.StateStorage->SetInt(id, opened ? 0 : 1);
if (hovered || held)
window->DrawList->AddRectFilled(
bb.Min, bb.Max,
ImGui::GetColorU32(held ? ImGuiCol_HeaderActive : ImGuiCol_HeaderHovered));
// Icon, text
float button_sz = g.FontSize + g.Style.FramePadding.y * 2;
window->DrawList->AddRectFilled(pos, ImVec2(pos.x + button_sz, pos.y + button_sz),
opened ? ImColor(51, 105, 173) : ImColor(42, 79, 130));
const auto label_location =
ImVec2(pos.x + button_sz + g.Style.ItemInnerSpacing.x, pos.y + g.Style.FramePadding.y);
ImGui::RenderText(label_location, label);
ImGui::ItemSize(bb, g.Style.FramePadding.y);
ImGui::ItemAdd(bb, id);
if (opened) ImGui::TreePush(label);
return opened;
}
static bool Splitter(const char* name, bool split_vertically, float thickness, float* size1,
float* size2, float min_size1, float min_size2, float splitter_long_axis_size)
{
using namespace ImGui;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetID(name);
ImRect bb;
bb.Min =
window->DC.CursorPos + (split_vertically ? ImVec2(*size1, 0.0f) : ImVec2(0.0f, *size1));
bb.Max = bb.Min + CalcItemSize(split_vertically ? ImVec2(thickness, splitter_long_axis_size)
: ImVec2(splitter_long_axis_size, thickness),
0.0f, 0.0f);
return SplitterBehavior(bb, id, split_vertically ? ImGuiAxis_X : ImGuiAxis_Y, size1, size2,
min_size1, min_size2, 0.0f);
}
static void draw_open_files(Application& app)
{
bool closed_tab = false;
app.open_files.for_each_open_file([&](FileHandle handle, bool is_focused) {
auto action = OpenFiles::Action::Nothing;
// we programmatically set the focused tab if manual tab change requested
// for example when the user clicks an entry in the stack trace or file explorer
auto tab_flags = ImGuiTabItemFlags_None;
if (app.ui.request_manual_tab_change && is_focused) {
tab_flags = ImGuiTabItemFlags_SetSelected;
app.file_viewer.show(handle);
}
bool keep_tab_open = true;
if (ImGui::BeginTabItem(handle.filename().c_str(), &keep_tab_open, tab_flags)) {
ImGui::BeginChild("FileContents");
if (!app.ui.request_manual_tab_change && !is_focused) {
// user selected tab directly with mouse
action = OpenFiles::Action::ChangeFocusTo;
app.file_viewer.show(handle);
}
std::optional<int> clicked_line = app.file_viewer.render();
if (clicked_line.has_value()) {
std::optional<FileHandle> focus_handle = app.open_files.focus();
if (focus_handle.has_value()) {
const fs::path filepath = focus_handle->filepath();
StringBuffer breakpoint_command;
breakpoint_command.format("breakpoint set --file {} --line {}",
filepath.c_str(), *clicked_line);
run_lldb_command(app, breakpoint_command.data());
}
}
ImGui::EndChild();
ImGui::EndTabItem();
}
if (!keep_tab_open) { // user closed tab with mouse
closed_tab = true;
action = OpenFiles::Action::Close;
}
return action;
});
app.ui.request_manual_tab_change = false;
if (closed_tab && app.open_files.size() > 0) {
auto focus_handle = app.open_files.focus();
if (!focus_handle.has_value()) {
LOG(Error) << "Invalid logic encountered when user requested tab close.";
}
else {
app.file_viewer.show(*focus_handle);
}
}
}
static void manually_open_and_or_focus_file(UserInterface& ui, OpenFiles& open_files,
FileHandle handle)
{
if (auto focus = open_files.focus(); focus.has_value() && (*focus == handle)) {
return; // already focused
}
open_files.open(handle);
ui.request_manual_tab_change = true;
}
static void manually_open_and_or_focus_file(UserInterface& ui, OpenFiles& open_files,
const char* filepath)
{
if (auto handle = FileHandle::create(filepath); handle.has_value()) {
manually_open_and_or_focus_file(ui, open_files, *handle);
}
else {
LOG(Warning) << "Failed to switch focus to file because it could not be located: "
<< filepath;
}
}
static void draw_file_browser(Application& app, FileBrowserNode* node_to_draw, size_t depth)
{
assert(node_to_draw);
if (node_to_draw->is_directory()) {
const char* tree_node_label =
depth == 0 ? node_to_draw->filepath() : node_to_draw->filename();
if (FileTreeNode(tree_node_label)) {
for (auto& child_node : node_to_draw->children()) {
draw_file_browser(app, child_node.get(), depth + 1);
}
ImGui::TreePop();
}
}
else {
if (ImGui::Selectable(node_to_draw->filename())) {
manually_open_and_or_focus_file(app.ui, app.open_files, node_to_draw->filepath());
}
}
}
static std::optional<lldb::SBTarget> find_target(lldb::SBDebugger& debugger)
{
if (debugger.GetNumTargets() > 0) {
auto target = debugger.GetSelectedTarget();
if (!target.IsValid()) {
LOG(Warning) << "Selected target is invalid";
return {};
}
else {
return target;
}
}
else {
return {};
}
}
static std::optional<lldb::SBProcess> find_process(lldb::SBDebugger& debugger)
{
auto target = find_target(debugger);
if (!target.has_value()) return {};
lldb::SBProcess process = target->GetProcess();
if (process.IsValid()) {
return process;
}
else {
return {};
}
}
static lldb::SBCommandReturnObject run_lldb_command(lldb::SBDebugger& debugger,
LLDBCommandLine& cmdline,
const lldb::SBListener& listener,
const char* command,
bool hide_from_history = false)
{
if (auto unaliased_cmd = cmdline.expand_and_unalias_command(command);
unaliased_cmd.has_value()) {
LOG(Debug) << "Unaliased command: " << *unaliased_cmd;
}
auto target_before = find_target(debugger);
lldb::SBCommandReturnObject ret = cmdline.run_command(command, hide_from_history);
auto target_after = find_target(debugger);
const bool added_new_target = !target_before && target_after;
const bool switched_target = target_before && target_after && (*target_before != *target_after);
if (added_new_target || switched_target) {
constexpr auto target_listen_flags = lldb::SBTarget::eBroadcastBitBreakpointChanged |
lldb::SBTarget::eBroadcastBitWatchpointChanged;
target_after->GetBroadcaster().AddListener(listener, target_listen_flags);
}
switch (ret.GetStatus()) {
case lldb::eReturnStatusInvalid:
LOG(Debug) << "\t => eReturnStatusInvalid";
break;
case lldb::eReturnStatusSuccessFinishNoResult:
LOG(Debug) << "\t => eReturnStatusSuccessFinishNoResult";
break;
case lldb::eReturnStatusSuccessFinishResult:
LOG(Debug) << "\t => eReturnStatusSuccessFinishResult";
break;
case lldb::eReturnStatusSuccessContinuingNoResult:
LOG(Debug) << "\t => eReturnStatusSuccessContinuingNoResult";
break;
case lldb::eReturnStatusSuccessContinuingResult:
LOG(Debug) << "\t => eReturnStatusSuccessContinuingResult";
break;
case lldb::eReturnStatusStarted:
LOG(Debug) << "\t => eReturnStatusStarted";
break;
case lldb::eReturnStatusFailed:
LOG(Debug) << "\t => eReturnStatusFailed";
break;
case lldb::eReturnStatusQuit:
LOG(Debug) << "\t => eReturnStatusQuit";
break;
default:
LOG(Debug) << "unknown lldb command return status encountered.";
break;
}
return ret;
}
lldb::SBCommandReturnObject run_lldb_command(Application& app, const char* command,
bool hide_from_history)
{
return run_lldb_command(app.debugger, app.cmdline, app.listener, command, hide_from_history);
}
static void draw_control_bar(lldb::SBDebugger& debugger, LLDBCommandLine& cmdline,
const lldb::SBListener& listener, const UserInterface& ui)
{
auto target = find_target(debugger);
if (target.has_value()) {
// TODO: show rightmost chunk of path in case it is too long to fit on screen
lldb::SBFileSpec fs = target->GetExecutable();
StringBuffer target_description;
const char* target_directory = fs.GetDirectory();
const char* target_filename = fs.GetFilename();
if (target_directory != nullptr && target_filename != nullptr) {
target_description.format("Target: {}/{}", target_directory, target_filename);
}
else {
target_description.format("Target: Unknown/Invalid (?)");
}
ImGui::TextUnformatted(target_description.data());
}
auto process = find_process(debugger);
if (process.has_value()) {
StringBuffer process_description;
const char* process_state = lldb::SBDebugger::StateAsCString(process->GetState());
process_description.format("Process State: {}", process_state);
ImGui::TextUnformatted(process_description.data());
}
else if (target.has_value()) {
ImGui::TextUnformatted("Process State: Unlaunched");
}
if (!target.has_value()) {
if (ImGui::Button("choose target")) {
// TODO: use https://github.com/aiekick/ImGuiFileDialog
LOG(Warning) << "choose target button not yet implemented";
}
}
else if (!process.has_value()) {
if (ImGui::Button("run")) {
run_lldb_command(debugger, cmdline, listener, "run");
}
}
else if (process_is_stopped(*process)) {
if (ImGui::Button("continue")) {
run_lldb_command(debugger, cmdline, listener, "continue");
}
ImGui::SameLine();
if (ImGui::Button("step over")) {
const uint32_t nthreads = process->GetNumThreads();
if (ui.viewed_thread_index < nthreads) {
lldb::SBThread th = process->GetThreadAtIndex(ui.viewed_thread_index);
th.StepOver();
}
}
if (ImGui::Button("step into")) {
const uint32_t nthreads = process->GetNumThreads();
if (ui.viewed_thread_index < nthreads) {
lldb::SBThread th = process->GetThreadAtIndex(ui.viewed_thread_index);
th.StepInto();
}
}
ImGui::SameLine();
if (ImGui::Button("step instr.")) {
LOG(Warning) << "Step over unimplemented";
}
}
else if (process_is_running(*process)) {
if (ImGui::Button("stop")) {
stop_process(*process);
}
}
else if (const auto [finished, _] = process_is_finished(*process); finished) {
if (ImGui::Button("restart")) {
run_lldb_command(debugger, cmdline, listener, "run");
}
}
else {
LOG(Error) << "Unknown/Invalid session state encountered!";
}
}
static void draw_file_viewer(Application& app)
{
ImGui::BeginChild("FileViewer", ImVec2(app.ui.file_viewer_width, app.ui.file_viewer_height));
if (ImGui::BeginTabBar("##FileViewerTabs",
ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_NoTooltip)) {
Defer(ImGui::EndTabBar());
if (app.open_files.size() == 0) {
if (ImGui::BeginTabItem("about")) {
Defer(ImGui::EndTabItem());
ImGui::TextUnformatted("This is a GUI for lldb.");
}
}
else {
draw_open_files(app);
}
}
ImGui::EndChild();
}
static void draw_console(Application& app)
{
ImGui::BeginChild("LogConsole",
ImVec2(app.ui.file_viewer_width,
app.ui.console_height - 2 * ImGui::GetFrameHeightWithSpacing()));
if (ImGui::BeginTabBar("##ConsoleLogTabs", ImGuiTabBarFlags_None)) {
if (ImGui::BeginTabItem("console")) {
ImGui::BeginChild("ConsoleEntries");
for (const CommandLineEntry& entry : app.cmdline.get_history()) {
ImGui::TextColored(ImVec4(255, 0, 0, 255), "> %s", entry.input.c_str());
if (!entry.succeeded) {
ImGui::Text("error: %s is not a valid command.", entry.input.c_str());
continue;
}
if (entry.output.size() > 0) {
ImGui::TextUnformatted(entry.output.c_str());
}
}
// later in this method we scroll to the bottom of the command history if
// a command was run last frame, so that the user can immediately see the output.
const bool should_auto_scroll_command_window =
app.ui.ran_command_last_frame || app.ui.window_resized_last_frame;
auto command_input_callback = [](ImGuiTextEditCallbackData*) -> int {
return 0; // TODO: scroll command line history with up/down arrows
};
const ImGuiInputTextFlags command_input_flags = ImGuiInputTextFlags_EnterReturnsTrue;
// keep console input focused unless user is doing something else
if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) &&
!ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0)) {
ImGui::SetKeyboardFocusHere(0);
}
// TODO: resize input_buf when necessary?
static char input_buf[2048];
if (ImGui::InputText("lldb console", input_buf, 2048, command_input_flags,
command_input_callback)) {
run_lldb_command(app, input_buf);
memset(input_buf, 0, sizeof(input_buf));
input_buf[0] = '\0';
app.ui.ran_command_last_frame = true;
}
// Always keep keyboard input focused on the lldb console input box unless
// some other disrupting action is occuring
if (ImGui::IsItemHovered() ||
(ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow) &&
!ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) {
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
}
if (should_auto_scroll_command_window) {
ImGui::SetScrollHere(1.0f);
app.ui.ran_command_last_frame = false;
}
ImGui::EndChild();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("log")) {
ImGui::BeginChild("LogEntries");
Logger::get_instance()->for_each_message([](const LogMessage& entry) -> void {
const char* msg = entry.message.c_str();
switch (entry.level) {
case LogLevel::Verbose: {
ImGui::TextColored(ImVec4(78.f / 255.f, 78.f / 255.f, 78.f / 255.f, 255.f),
"[VERBOSE]");
break;
}
case LogLevel::Debug: {
ImGui::TextColored(
ImVec4(52.f / 255.f, 56.f / 255.f, 176.f / 255.f, 255.f / 255.f),
"[DEBUG]");
break;
}
case LogLevel::Info: {
ImGui::TextColored(
ImVec4(225.f / 255.f, 225.f / 255.f, 225.f / 255.f, 255.f / 255.f),
"[INFO]");
break;
}
case LogLevel::Warning: {
ImGui::TextColored(
ImVec4(216.f / 255.f, 129.f / 255.f, 42.f / 255.f, 255.f / 255.f),
"[WARNING]");
break;
}
case LogLevel::Error: {
ImGui::TextColored(
ImVec4(212.f / 255.f, 67.f / 255.f, 67.f / 255.f, 255.f / 255.f),
"[ERROR]");
break;
}
}
ImGui::SameLine();
ImGui::TextWrapped("%s", msg);
});
static size_t last_seen_messages = 0;
const size_t seen_messages = Logger::get_instance()->message_count();
if (seen_messages > last_seen_messages) {
last_seen_messages = seen_messages;
ImGui::SetScrollHere(1.0f);
}
ImGui::EndChild();
ImGui::EndTabItem();
}
// TODO: these quantities need to be reset whenever the target is reset or process is
// re-launched
static size_t last_stdout_size = 0;
static size_t last_stderr_size = 0;
if (ImGui::BeginTabItem("stdout")) {
ImGui::BeginChild("StdOUTEntries");
ImGui::TextUnformatted(app._stdout.get());
if (app._stdout.size() > last_stdout_size) {
ImGui::SetScrollHere(1.0f);
}
last_stdout_size = app._stdout.size();
ImGui::EndChild();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("stderr")) {
ImGui::BeginChild("StdERREntries");
ImGui::TextUnformatted(app._stderr.get());
if (app._stderr.size() > last_stderr_size) {
ImGui::SetScrollHere(1.0f);
}
last_stderr_size = app._stderr.size();
ImGui::EndChild();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::EndChild();
}
static void draw_threads(UserInterface& ui, std::optional<lldb::SBProcess> process,
float stack_height)
{
ImGui::BeginChild(
"#ThreadsChild",
ImVec2(ui.window_width - ui.file_browser_width - ui.file_viewer_width, stack_height));
Defer(ImGui::EndChild());
// TODO: be consistent about whether or not to use Defer
// TODO: add columns with stop reason and other potential information
if (ImGui::BeginTabBar("#ThreadsTabs", ImGuiTabBarFlags_None)) {
Defer(ImGui::EndTabBar());
if (ImGui::BeginTabItem("threads")) {
Defer(ImGui::EndTabItem());
if (process.has_value() && process_is_stopped(*process)) {
const uint32_t nthreads = process->GetNumThreads();
if (ui.viewed_thread_index >= nthreads) {
ui.viewed_thread_index = nthreads - 1;
LOG(Warning) << "detected/fixed overflow of ui.viewed_thread_index";
}
StringBuffer thread_label;
for (uint32_t i = 0; i < nthreads; i++) {
lldb::SBThread th = process->GetThreadAtIndex(i);
if (!th.IsValid()) {
LOG(Warning) << "Encountered invalid thread";
continue;
}
const char* thread_name = th.GetName();
if (thread_name == nullptr) {
LOG(Warning) << "Skipping thread with null name";
continue;
}
thread_label.format("Thread {}: {}", i, th.GetName());
if (ImGui::Selectable(thread_label.data(), i == ui.viewed_thread_index)) {
ui.viewed_thread_index = i;
}
thread_label.clear();
}
}
}
}
}
static void draw_stack_trace(UserInterface& ui, OpenFiles& open_files,
std::optional<lldb::SBProcess> process, float stack_height)
{
ImGui::BeginChild("#StackTraceChild", ImVec2(0, stack_height));
if (ImGui::BeginTabBar("##StackTraceTabs", ImGuiTabBarFlags_None)) {
if (ImGui::BeginTabItem("stack trace")) {
if (process.has_value() && process_is_stopped(*process)) {
ImGui::Columns(3, "##StackTraceColumns");
ImGui::Separator();
ImGui::Text("FUNCTION");
ImGui::NextColumn();
ImGui::Text("FILE");
ImGui::NextColumn();
ImGui::Text("LINE");
ImGui::NextColumn();
ImGui::Separator();
lldb::SBThread viewed_thread = process->GetThreadAtIndex(ui.viewed_thread_index);
const uint32_t nframes = viewed_thread.GetNumFrames();
if (ui.viewed_frame_index >= nframes) {
ui.viewed_frame_index = nframes - 1;
}
for (uint32_t i = 0; i < viewed_thread.GetNumFrames(); i++) {
auto frame = StackFrame::create(viewed_thread.GetFrameAtIndex(i));
if (!frame) continue;
if (ImGui::Selectable(frame->function_name.c_str(), i == ui.viewed_frame_index,
ImGuiSelectableFlags_SpanAllColumns)) {
manually_open_and_or_focus_file(ui, open_files, frame->file_handle);
ui.viewed_frame_index = i;
}
ImGui::NextColumn();
ImGui::TextUnformatted(frame->file_handle.filename().c_str());
ImGui::NextColumn();
StringBuffer linebuf;
linebuf.format("{}", (int)frame->line);
ImGui::TextUnformatted(linebuf.data());
ImGui::NextColumn();
}
ImGui::Columns(1);
}
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::EndChild();
}
// TODO: add max depth?
static void draw_local_recursive(lldb::SBValue local)
{
const char* local_type = local.GetDisplayTypeName();
const char* local_name = local.GetName();
const char* local_value = local.GetValue();
if (!local_type || !local_name) {
return;
}
StringBuffer children_node_label;
children_node_label.format("{}##Children_{}", local_name, local.GetID());
if (local.MightHaveChildren()) {
if (ImGui::TreeNode(children_node_label.data())) {
ImGui::NextColumn();
ImGui::TextUnformatted(local_type);
ImGui::NextColumn();
ImGui::TextUnformatted("...");
ImGui::NextColumn();
// TODO: figure out best way to handle very long children list
for (uint32_t i = 0; i < local.GetNumChildren(100); i++) {
draw_local_recursive(local.GetChildAtIndex(i));
}
ImGui::TreePop();
}
else {
ImGui::NextColumn();
ImGui::TextUnformatted(local_type);
ImGui::NextColumn();
ImGui::TextUnformatted("...");
ImGui::NextColumn();
}
}
else {
ImGui::TextUnformatted(local_name);
ImGui::NextColumn();
ImGui::TextUnformatted(local_type);
ImGui::NextColumn();
if (local_value) {
ImGui::TextUnformatted(local_value);
}
else {
ImGui::TextUnformatted("unknown");
}
ImGui::NextColumn();
}
}
static void draw_locals_and_registers(UserInterface& ui, std::optional<lldb::SBProcess> process,
float stack_height)
{
ImGui::BeginChild("#LocalsChild", ImVec2(0, stack_height));
if (ImGui::BeginTabBar("##LocalsTabs", ImGuiTabBarFlags_None)) {
if (ImGui::BeginTabItem("locals")) {
if (process.has_value() && process_is_stopped(*process)) {
ImGui::Columns(3, "##LocalsColumns");
ImGui::Separator();
ImGui::Text("NAME");
ImGui::NextColumn();
ImGui::Text("TYPE");
ImGui::NextColumn();
ImGui::Text("VALUE");
ImGui::NextColumn();
ImGui::Separator();
lldb::SBThread viewed_thread = process->GetThreadAtIndex(ui.viewed_thread_index);
lldb::SBFrame frame = viewed_thread.GetFrameAtIndex(ui.viewed_frame_index);
lldb::SBValueList locals = frame.GetVariables(true, true, true, true);
// TODO: select entire row like in stack trace
for (uint32_t i = 0; i < locals.GetSize(); i++) {
draw_local_recursive(locals.GetValueAtIndex(i));
}
ImGui::Columns(1);
}
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("registers")) {
if (process.has_value() && process_is_stopped(*process)) {
lldb::SBThread viewed_thread = process->GetThreadAtIndex(ui.viewed_thread_index);
lldb::SBFrame frame = viewed_thread.GetFrameAtIndex(ui.viewed_frame_index);
if (viewed_thread.IsValid() && frame.IsValid()) {
lldb::SBValueList register_collections = frame.GetRegisters();
for (uint32_t i = 0; i < register_collections.GetSize(); i++) {
lldb::SBValue regcol = register_collections.GetValueAtIndex(i);
const char* collection_name = regcol.GetName();
if (!collection_name) {
LOG(Warning) << "Skipping over invalid/un-named register collection";
continue;
}
StringBuffer reg_coll_name;
reg_coll_name.format("{}##RegisterCollection", collection_name);
if (ImGui::TreeNode(reg_coll_name.data())) {
for (uint32_t i = 0; i < regcol.GetNumChildren(); i++) {
lldb::SBValue reg = regcol.GetChildAtIndex(i);
const char* reg_name = reg.GetName();
const char* reg_value = reg.GetValue();
if (!reg_name || !reg_value) {
LOG(Warning) << "skipping invalid register";
continue;
}
ImGui::Text("%s = %s", reg_name, reg_value);
}
ImGui::TreePop();
}
}
}
}
ImGui::EndTabItem();
}
ImGui::EndTabBar();
// ImGui::SameLine(ImGui::GetWindowWidth() - 150);
// ImGui::Checkbox("use hexadecimal", &use_hex_locals);
}
ImGui::EndChild();
}
static void draw_breakpoints_and_watchpoints(UserInterface& ui, OpenFiles& open_files,
std::optional<lldb::SBTarget> target,
float stack_height)
{
ImGui::BeginChild("#BreakWatchPointChild", ImVec2(0, stack_height));
if (ImGui::BeginTabBar("##BreakWatchPointTabs", ImGuiTabBarFlags_None)) {
Defer(ImGui::EndTabBar());
if (ImGui::BeginTabItem("breakpoints")) {
Defer(ImGui::EndTabItem());
// TODO: show hit count and column number as well
if (target.has_value()) {
ImGui::Columns(2);
ImGui::Separator();
ImGui::Text("FILE");
ImGui::NextColumn();
ImGui::Text("LINE");
ImGui::NextColumn();
ImGui::Separator();
Defer(ImGui::Columns(1));
const uint32_t nbreakpoints = target->GetNumBreakpoints();
if (ui.viewed_breakpoint_index >= nbreakpoints) {
ui.viewed_breakpoint_index = nbreakpoints - 1;
}
for (uint32_t i = 0; i < nbreakpoints; i++) {
lldb::SBBreakpoint breakpoint = target->GetBreakpointAtIndex(i);
if (!breakpoint.IsValid() || breakpoint.GetNumLocations() == 0) {
lldb::SBStream stm;
breakpoint.GetDescription(stm);
LOG(Error) << "Invalid breakpoint encountered with description:\n"
<< stm.GetData();
continue;
}
lldb::SBBreakpointLocation location = breakpoint.GetLocationAtIndex(0);
if (!location.IsValid()) {
LOG(Error) << "Invalid breakpoint location encountered with "
<< breakpoint.GetNumLocations() << " locations!";
continue;
}
lldb::SBAddress address = location.GetAddress();
if (!address.IsValid()) {
LOG(Error) << "Invalid breakpoint address encountered!";
continue;
}
lldb::SBLineEntry line_entry = address.GetLineEntry();
if (!line_entry.IsValid()) {
LOG(Error) << "Invalid line entry encountered!";
continue;
}
const char* filename = line_entry.GetFileSpec().GetFilename();
const char* directory = line_entry.GetFileSpec().GetDirectory();
if (filename == nullptr || directory == nullptr) {
LOG(Error) << "invalid/unspecified filepath encountered for breakpoint";
continue;
}
if (ImGui::Selectable(filename, i == ui.viewed_breakpoint_index,
ImGuiSelectableFlags_SpanAllColumns)) {
fs::path breakpoint_filepath = fs::path(directory) / fs::path(filename);
manually_open_and_or_focus_file(ui, open_files,
breakpoint_filepath.c_str());
ui.viewed_breakpoint_index = i;
}
ImGui::NextColumn();
StringBuffer line_buf;
line_buf.format("{}", line_entry.GetLine());
ImGui::TextUnformatted(line_buf.data());
ImGui::NextColumn();
}
}
}
if (ImGui::BeginTabItem("watchpoints")) {
Defer(ImGui::EndTabItem());
// TODO: add actual watch points
for (int i = 0; i < 4; i++) {
StringBuffer label;
label.format("Watch {}", i);
if (ImGui::Selectable(label.data(), i == 0)) {
// blah
}
}
}
}
ImGui::EndChild();
}
static void draw_debug_stream_popup(UserInterface& ui)
{
ImGui::SetNextWindowPos(ImVec2(ui.window_width / 2.f, ui.window_height / 2.f),
ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(200, 200), ImGuiCond_FirstUseEver);
ImGui::PushFont(ui.font);
if (ImGui::Begin("Debug Stream", 0)) {
for (const auto& [xkey, xstr] : s_debug_stream) {
StringBuffer debug_line;
debug_line.format("{} : {}", xkey, xstr);
ImGui::TextUnformatted(debug_line.data());
}
}
ImGui::PopFont();
ImGui::End();
}
__attribute__((flatten)) static void draw(Application& app)
{
auto& ui = app.ui;
auto& open_files = app.open_files;
ImGui::SetNextWindowPos(ImVec2(0.f, 0.f), ImGuiCond_Always);
ImGui::SetNextWindowSize(ImVec2(ui.window_width, ui.window_height), ImGuiCond_Always);
static constexpr auto main_window_flags =
ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoTitleBar;
ImGui::Begin("lldbg", 0, main_window_flags);
ImGui::PushFont(ui.font);
{
Splitter("##S1", true, 3.0f, &ui.file_browser_width, &ui.file_viewer_width,
0.05 * ui.window_width, 0.05 * ui.window_width, ui.window_height);
ImGui::BeginGroup();
ImGui::BeginChild("ControlBarAndFileBrowser", ImVec2(ui.file_browser_width, 0));
draw_control_bar(app.debugger, app.cmdline, app.listener, app.ui);
ImGui::Separator();
draw_file_browser(app, app.file_browser.get(), 0);
ImGui::EndChild();
ImGui::EndGroup();
}
ImGui::SameLine();
{
Splitter("##S2", false, 3.0f, &ui.file_viewer_height, &ui.console_height,
0.1 * ui.window_height, 0.1 * ui.window_height, ui.file_viewer_width);
ImGui::BeginGroup();
draw_file_viewer(app);
ImGui::Spacing();
draw_console(app);
ImGui::EndGroup();
}
ImGui::SameLine();
{
ImGui::BeginGroup();
// TODO: let locals tab have all the expanded space
const float stack_height = (ui.window_height - 2 * ImGui::GetFrameHeightWithSpacing()) / 4;
draw_threads(ui, find_process(app.debugger), stack_height);
draw_stack_trace(ui, open_files, find_process(app.debugger), stack_height);
draw_locals_and_registers(ui, find_process(app.debugger), stack_height);
draw_breakpoints_and_watchpoints(ui, open_files, find_target(app.debugger), stack_height);
ImGui::EndGroup();
}
ImGui::PopFont();
ImGui::End();
draw_debug_stream_popup(ui);
}
static void handle_lldb_events(lldb::SBDebugger& debugger, lldb::SBListener& listener,
UserInterface& ui, OpenFiles& open_files, FileViewer& file_viewer)
{
lldb::SBEvent event;
while (true) {
const bool event_found = listener.GetNextEvent(event);
if (!event_found) break;
if (!event.IsValid()) {
LOG(Warning) << "Invalid event found.";
continue;
}
lldb::SBStream event_description;
event.GetDescription(event_description);
LOG(Verbose) << "Event Description => " << event_description.GetData();
auto target = find_target(debugger);
auto process = find_process(debugger);
if (target.has_value() && event.BroadcasterMatchesRef(target->GetBroadcaster())) {
LOG(Debug) << "Found target event";
file_viewer.synchronize_breakpoint_cache(*target);
}
else if (process.has_value() && event.BroadcasterMatchesRef(process->GetBroadcaster())) {
const lldb::StateType new_state = lldb::SBProcess::GetStateFromEvent(event);
const char* state_descr = lldb::SBDebugger::StateAsCString(new_state);
if (state_descr) {
LOG(Debug) << "Found process event with new state: " << state_descr;
}
// For now we find the first (if any) stopped thread and construct a StopInfo.
if (new_state == lldb::eStateStopped) {
const uint32_t nthreads = process->GetNumThreads();
for (uint32_t i = 0; i < nthreads; i++) {
lldb::SBThread th = process->GetThreadAtIndex(i);
switch (th.GetStopReason()) {
case lldb::eStopReasonBreakpoint: {
// https://lldb.llvm.org/cpp_reference/classlldb_1_1SBThread.html#af284261156e100f8d63704162f19ba76
assert(th.GetStopReasonDataCount() == 2);
lldb::break_id_t breakpoint_id = th.GetStopReasonDataAtIndex(0);
lldb::SBBreakpoint breakpoint =
target->FindBreakpointByID(breakpoint_id);
lldb::break_id_t location_id = th.GetStopReasonDataAtIndex(1);
lldb::SBBreakpointLocation location =
breakpoint.FindLocationByID(location_id);
const auto [filepath, linum] = resolve_breakpoint(location);
manually_open_and_or_focus_file(ui, open_files, filepath.c_str());
file_viewer.set_highlight_line(linum);
break;
}
default: {
continue;
}
}
}
}
else if (new_state == lldb::eStateRunning) {
file_viewer.unset_highlight_line();
}
}
else {
// TODO: print event description
LOG(Debug) << "Found non-target/process event";
}
}
}
static void tick(Application& app)
{
handle_lldb_events(app.debugger, app.listener, app.ui, app.open_files, app.file_viewer);
UserInterface& ui = app.ui;
DEBUG_STREAM(ui.window_width);
DEBUG_STREAM(ui.window_height);
DEBUG_STREAM(ui.file_browser_width);
DEBUG_STREAM(ui.file_viewer_width);
DEBUG_STREAM(ui.file_viewer_height);
DEBUG_STREAM(ui.console_height);
DEBUG_STREAM(app.fps_timer.current_fps());
draw(app);
}
static void update_window_dimensions(UserInterface& ui)
{
int new_width = -1;
int new_height = -1;
glfwGetFramebufferSize(ui.window, &new_width, &new_height);
assert(new_width > 0 && new_height > 0);
ui.window_resized_last_frame = new_width != ui.window_width || new_height != ui.window_height;
if (ui.window_resized_last_frame) {
// re-scale the size of the invididual panels to account for window resize
ui.file_browser_width *= new_width / ui.window_width;
ui.file_viewer_width *= new_width / ui.window_width;
ui.file_viewer_height *= new_height / ui.window_height;
ui.console_height *= new_height / ui.window_height;
ui.window_width = new_width;
ui.window_height = new_height;
}
}
int main_loop(Application& app)
{
while (!glfwWindowShouldClose(app.ui.window)) {
glfwPollEvents();
// TODO: switch to OpenGL 3 for performance
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
tick(app);
ImGui::Render();
glViewport(0, 0, app.ui.window_width, app.ui.window_height);
static const ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
glFinish();
glfwSwapBuffers(app.ui.window);
// TODO: develop bettery strategy for when to read stdout,
// possible upon receiving certain types of LLDBEvent?
if (app.ui.frames_rendered % 10 == 0) {
if (auto process = find_process(app.debugger); process.has_value()) {
app._stdout.update(*process);
app._stderr.update(*process);
}
}
update_window_dimensions(app.ui);
app.fps_timer.wait_for_frame_duration(1.75 * 16666);
app.fps_timer.frame_end();
app.ui.frames_rendered++;
}
return EXIT_SUCCESS;
}
std::optional<UserInterface> UserInterface::init(void)
{
UserInterface ui;
glfwSetErrorCallback(glfw_error_callback);
if (glfwInit() != GLFW_TRUE) {
return {};
}
// TODO: use function to choose initial window resolution based on display resolution
ui.window = glfwCreateWindow(1920, 1080, "lldbg", nullptr, nullptr);
if (ui.window == nullptr) {
glfwTerminate();
return {};
}
ui.window_width = 1920.f;
ui.window_height = 1080.f;
ui.file_browser_width = ui.window_width * 0.15f;
ui.file_viewer_width = ui.window_width * 0.52f;
ui.file_viewer_height = ui.window_height * 0.6f;
ui.console_height = ui.window_height * 0.4f;
glfwMakeContextCurrent(ui.window);
glfwSwapInterval(0); // disable vsync
const GLenum err = glewInit();
if (err != GLEW_OK) {
fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
return {};
}
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.Fonts->AddFontDefault();
static const std::string font_path = fmt::format("{}/ttf/Hack-Regular.ttf", LLDBG_ASSETS_DIR);
ui.font = io.Fonts->AddFontFromFileTTF(font_path.c_str(), 15.0f);
ImGui::StyleColorsDark();
// ImGui::StyleColorsClassic();
// disable all 'rounding' of corners in the UI
ImGuiStyle& style = ImGui::GetStyle();
style.WindowRounding = 0.0f;
style.ChildRounding = 0.0f;
style.FrameRounding = 0.0f;
style.GrabRounding = 0.0f;
style.PopupRounding = 0.0f;
style.ScrollbarRounding = 0.0f;
style.TabRounding = 0.0f;
ImGui_ImplGlfw_InitForOpenGL(ui.window, true);
ImGui_ImplOpenGL2_Init();
return ui;
}
Application::Application(const UserInterface& ui_, std::optional<fs::path> workdir)
: debugger(lldb::SBDebugger::Create()),
listener(debugger.GetListener()),
cmdline(debugger),
_stdout(StreamBuffer::StreamSource::StdOut),
_stderr(StreamBuffer::StreamSource::StdErr),
file_browser(FileBrowserNode::create(workdir)),
ui(ui_)
{
}
Application::~Application()
{
if (auto process = find_process(this->debugger); process.has_value() && process->IsValid()) {
LOG(Warning) << "Found active process while closing Application.";
kill_process(*process);
}
if (auto target = find_target(this->debugger); target.has_value() && target->IsValid()) {
LOG(Warning) << "Found active target while closing Application.";
this->debugger.DeleteTarget(*target);
}
if (this->debugger.IsValid()) {
lldb::SBDebugger::Destroy(this->debugger);
this->debugger.Clear();
}
else {
LOG(Warning) << "Found invalid lldb::SBDebugger while closing Application.";
}
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(this->ui.window);
glfwTerminate();
}
| 37.238338 | 128 | 0.544382 | [
"render"
] |
d2d5d6873546520e5a1a6d01ef59043f4dd9cc0a | 15,160 | cpp | C++ | src/inlet_connection.cpp | samuelpowell/liblsl | 92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3 | [
"MIT"
] | null | null | null | src/inlet_connection.cpp | samuelpowell/liblsl | 92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3 | [
"MIT"
] | null | null | null | src/inlet_connection.cpp | samuelpowell/liblsl | 92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <boost/bind.hpp>
#include "cast.h"
#include "inlet_connection.h"
#include "api_config.h"
// === implementation of the inlet_connection class ===
using namespace lsl;
using namespace lslboost::asio;
/**
* Construct a new inlet connection.
* @param info A resolved stream info object (as coming from one of the resolver functions).
* It is possible -- but highly discouraged -- to initialize a connection with an unresolved (i.e. made-up) stream_info; in this case,
* a connection will be resolved alongside based on the provided info, but will only succeed if the channel count and channel format
* match the one that is provided.
* @param recover Try to silently recover lost streams that are recoverable (=those that that have a source_id set).
* In all other cases (recover is false or the stream is not recoverable) a lost_error is thrown where indicated if the stream's source is lost (e.g., due to an app or computer crash).
*/
inlet_connection::inlet_connection(const stream_info_impl &info, bool recover):
type_info_(info), host_info_(info), tcp_protocol_(tcp::v4()), udp_protocol_(udp::v4()),
recovery_enabled_(recover), lost_(false), shutdown_(false),
last_receive_time_(lsl_clock()), active_transmissions_(0) {
// if the given stream_info is already fully resolved...
if (!host_info_.v4address().empty() || !host_info_.v6address().empty()) {
// check LSL protocol version (we strictly forbid incompatible protocols instead of risking silent failure)
if (type_info_.version()/100 > api_config::get_instance()->use_protocol_version()/100)
throw std::runtime_error((std::string("The received stream (")+=host_info_.name()) += ") uses a newer protocol version than this inlet. Please update.");
// select TCP/UDP protocol versions
if (api_config::get_instance()->allow_ipv6()) {
// if IPv6 is optionally allowed...
if (host_info_.v4address().empty() || !host_info_.v4data_port() || !host_info_.v4service_port()) {
// then use it but only iff there are problems with the IPv4 connection data
tcp_protocol_ = tcp::v6();
udp_protocol_ = udp::v6();
} else {
// (otherwise stick to IPv4)
tcp_protocol_ = tcp::v4();
udp_protocol_ = udp::v4();
}
} else {
// otherwise use the protocol type that is selected in the config
tcp_protocol_ = api_config::get_instance()->allow_ipv4() ? tcp::v4() : tcp::v6();
udp_protocol_ = api_config::get_instance()->allow_ipv4() ? udp::v4() : udp::v6();
}
if (recovery_enabled_ && type_info_.source_id().empty()) {
// we cannot correctly recover streams which don't have a unique source id
std::clog << "Note: The stream named '" << host_info_.name() << "' could not be recovered automatically if its provider crashed because it does not specify a unique data source ID." << std::endl;
recovery_enabled_ = false;
}
} else {
// the actual endpoint is not known yet -- we need to discover it later on the fly
// check that all the necessary information for this has been fully specified
if (type_info_.name().empty() && type_info_.type().empty() && type_info_.source_id().empty())
throw std::invalid_argument("When creating an inlet with a constructed (instead of resolved) stream_info, you must assign at least the name, type or source_id of the desired stream.");
if (type_info_.channel_count() == 0)
throw std::invalid_argument("When creating an inlet with a constructed (instead of resolved) stream_info, you must assign a nonzero channel count.");
if (type_info_.channel_format() == cft_undefined)
throw std::invalid_argument("When creating an inlet with a constructed (instead of resolved) stream_info, you must assign a channel format.");
// use the protocol that is specified in the config
tcp_protocol_ = api_config::get_instance()->allow_ipv4() ? tcp::v4() : tcp::v6();
udp_protocol_ = api_config::get_instance()->allow_ipv4() ? udp::v4() : udp::v6();
// assign initial dummy endpoints
host_info_.v4address("127.0.0.1");
host_info_.v6address("::1");
host_info_.v4data_port(49999);
host_info_.v4service_port(49999);
host_info_.v6data_port(49999);
host_info_.v6service_port(49999);
// recovery must generally be enabled
recovery_enabled_ = true;
}
}
/// Engage the connection and its recovery watchdog thread.
void inlet_connection::engage() {
if (recovery_enabled_)
watchdog_thread_ = lslboost::thread(&inlet_connection::watchdog_thread,this);
}
/// Disengage the connection and all its resolver capabilities (including the watchdog).
void inlet_connection::disengage() {
// shut down the connection
{
lslboost::lock_guard<lslboost::mutex> lock(shutdown_mut_);
shutdown_ = true;
}
shutdown_cond_.notify_all();
// cancel all operations (resolver, streams, ...)
resolver_.cancel();
cancel_and_shutdown();
// and wait for the watchdog to finish
if (recovery_enabled_)
watchdog_thread_.join();
}
// === external accessors for connection properties ===
// get the TCP endpoint from the info (according to our configured protocol)
tcp::endpoint inlet_connection::get_tcp_endpoint() {
lslboost::shared_lock<lslboost::shared_mutex> lock(host_info_mut_);
if(tcp_protocol_ == tcp::v4()) {
std::string address = host_info_.v4address();
uint16_t port = host_info_.v4data_port();
return tcp::endpoint(ip::make_address(address), port);
//This more complicated procedure is required when the address is an ipv6 link-local address.
//Simplified from https://stackoverflow.com/questions/10286042/using-lslboost-to-accept-on-ipv6-link-scope-address
//It does not hurt when the address is not link-local.
} else {
std::string address = host_info_.v6address();
std::string port = to_string(host_info_.v6data_port());
io_context io;
ip::tcp::resolver resolver(io);
ip::tcp::resolver::results_type res = resolver.resolve(address, port);
if(res.size() == 0) {
throw lost_error("Unable to resolve tcp stream at address: " + address + ", port: " + port);
}
//assuming first (typically only) element in list is valid.
return *res.begin();
}
}
// get the UDP endpoint from the info (according to our configured protocol)
udp::endpoint inlet_connection::get_udp_endpoint() {
lslboost::shared_lock<lslboost::shared_mutex> lock(host_info_mut_);
if(udp_protocol_ == udp::v4()) {
std::string address = host_info_.v4address();
uint16_t port = host_info_.v4service_port();
return udp::endpoint(ip::make_address(address), port);
//This more complicated procedure is required when the address is an ipv6 link-local address.
//Simplified from https://stackoverflow.com/questions/10286042/using-lslboost-to-accept-on-ipv6-link-scope-address
//It does not hurt when the address is not link-local.
} else {
std::string address = host_info_.v6address();
std::string port = to_string(host_info_.v6service_port());
io_context io;
ip::udp::resolver resolver(io);
ip::udp::resolver::results_type res = resolver.resolve(address, port);
if(res.size() == 0) {
throw lost_error("Unable to resolve udp stream at address: " + address + ", port: " + port);
}
//assuming first (typically only) element in list is valid.
return *res.begin();
}
}
// get the hostname from the info
std::string inlet_connection::get_hostname() {
lslboost::shared_lock<lslboost::shared_mutex> lock(host_info_mut_);
return host_info_.hostname();
}
/// get the current stream UID (may change between crashes/reconnects)
std::string inlet_connection::current_uid() {
lslboost::shared_lock<lslboost::shared_mutex> lock(host_info_mut_);
return host_info_.uid();
}
/// get the current nominal sampling rate (might change between crashes/reconnects)
double inlet_connection::current_srate() {
lslboost::shared_lock<lslboost::shared_mutex> lock(host_info_mut_);
return host_info_.nominal_srate();
}
// === connection recovery logic ===
/// Performs the actual work of attempting a recovery.
void inlet_connection::try_recover() {
if (recovery_enabled_) {
try {
lslboost::lock_guard<lslboost::mutex> lock(recovery_mut_);
// first create the query string based on the known stream information
std::ostringstream query;
{
lslboost::shared_lock<lslboost::shared_mutex> lock(host_info_mut_);
// construct query according to the fields that are present in the stream_info
const char *channel_format_strings[] = {"undefined","float32","double64","string","int32","int16","int8","int64"};
query << "channel_count='" << host_info_.channel_count() << "'";
if (!host_info_.name().empty())
query << " and name='" << host_info_.name() << "'";
if (!host_info_.type().empty())
query << " and type='" << host_info_.type() << "'";
// for floating point values, str2double(double2str(fpvalue)) == fpvalue is most
// likely wrong and might lead to streams not being resolved.
// We accept that a lost stream might be replaced by a stream from the same host
// with the same type, channel type and channel count but a different srate
/*if (host_info_.nominal_srate() > 0)
query << " and nominal_srate='" << host_info_.nominal_srate() << "'";
*/
if (!host_info_.source_id().empty())
query << " and source_id='" << host_info_.source_id() << "'";
query << " and channel_format='" << channel_format_strings[host_info_.channel_format()] << "'";
}
// attempt a recovery
for (int attempt=0;;attempt++) {
// issue the resolve (blocks until it is either cancelled or got at least one matching streaminfo and has waited for a certain timeout)
std::vector<stream_info_impl> infos = resolver_.resolve_oneshot(query.str(),1,FOREVER,attempt==0 ? 1.0 : 5.0);
if (!infos.empty()) {
// got a result
lslboost::unique_lock<lslboost::shared_mutex> lock(host_info_mut_);
// check if any of the returned streams is the one that we're currently connected to
for (std::size_t k=0;k<infos.size();k++)
if (infos[k].uid() == host_info_.uid())
return; // in this case there is no need to recover (we're still fine)
// otherwise our stream is gone and we indeed need to recover:
// ensure that the query result is unique (since someone might have used a non-unique stream ID)
if (infos.size() == 1) {
// update the endpoint
host_info_ = infos[0];
// cancel all cancellable operations registered with this connection
cancel_all_registered();
// invoke any callbacks associated with a connection recovery
lslboost::lock_guard<lslboost::mutex> lock(onrecover_mut_);
for(std::map<void*,lslboost::function<void()> >::iterator i=onrecover_.begin(),e=onrecover_.end();i!=e;i++)
(i->second)();
} else {
// there are multiple possible streams to connect to in a recovery attempt: we warn and re-try
// this is because we don't want to randomly connect to the wrong source without the user knowing about it;
// the correct action (if this stream shall indeed have multiple instances) is to change the user code and
// make its source_id unique, or remove the source_id altogether if that's not possible (therefore disabling the ability to recover)
std::clog << "Found multiple streams with name='" << host_info_.name() << "' and source_id='" << host_info_.source_id() << "'. Cannot recover unless all but one are closed." << std::endl;
continue;
}
} else {
// cancelled
}
break;
}
} catch(std::exception &e) {
std::cerr << "A recovery attempt encountered an unexpected error: " << e.what() << std::endl;
}
}
}
/// A thread that periodically re-resolves the stream and checks if it has changed its location
void inlet_connection::watchdog_thread() {
while(!lost_ && !shutdown_) {
try {
// we only try to recover if a) there are active transmissions and b) we haven't seen new data for some time
{
lslboost::unique_lock<lslboost::mutex> lock(client_status_mut_);
if ((active_transmissions_ > 0) && (lsl_clock() - last_receive_time_ > api_config::get_instance()->watchdog_time_threshold())) {
lock.unlock();
try_recover();
}
}
// instead of sleeping we're waiting on a condition variable for the sleep duration
// so that the watchdog can be cancelled conveniently
{
lslboost::unique_lock<lslboost::mutex> lock(shutdown_mut_);
shutdown_cond_.wait_for(lock,lslboost::chrono::duration<double>(api_config::get_instance()->watchdog_check_interval()), lslboost::bind(&inlet_connection::shutdown,this));
}
} catch(std::exception &e) {
std::cerr << "Unexpected hiccup in the watchdog thread: " << e.what() << std::endl;
}
}
}
/// Issue a recovery attempt if a connection loss was detected.
void inlet_connection::try_recover_from_error() {
if (!shutdown_) {
if (!recovery_enabled_) {
// if the stream is irrecoverable it is now lost,
// so we need to notify the other inlet components
lost_ = true;
try {
lslboost::lock_guard<lslboost::mutex> lock(client_status_mut_);
for(std::map<void*,lslboost::condition_variable*>::iterator i=onlost_.begin(),e=onlost_.end();i!=e;i++)
i->second->notify_all();
} catch(std::exception &e) {
std::cerr << "Unexpected problem while trying to issue a connection loss notification: " << e.what() << std::endl;
}
throw lost_error("The stream read by this inlet has been lost. To recover, you need to re-resolve the source and re-create the inlet.");
} else
try_recover();
}
}
// === client status updates ===
/// Indicate that a transmission is now active.
void inlet_connection::acquire_watchdog() {
lslboost::lock_guard<lslboost::mutex> lock(client_status_mut_);
active_transmissions_++;
}
/// Indicate that a transmission has just completed.
void inlet_connection::release_watchdog() {
lslboost::lock_guard<lslboost::mutex> lock(client_status_mut_);
active_transmissions_--;
}
/// Update the time when the last content was received from the source
void inlet_connection::update_receive_time(double t) {
lslboost::lock_guard<lslboost::mutex> lock(client_status_mut_);
last_receive_time_ = t;
}
/// Register a condition variable that should be notified when a connection is lost
void inlet_connection::register_onlost(void *id, lslboost::condition_variable *cond) {
lslboost::lock_guard<lslboost::mutex> lock(client_status_mut_);
onlost_[id] = cond;
}
/// Unregister a condition variable
void inlet_connection::unregister_onlost(void *id) {
lslboost::lock_guard<lslboost::mutex> lock(client_status_mut_);
onlost_.erase(id);
}
/// Register a callback function that shall be called when a recovery has been performed
void inlet_connection::register_onrecover(void *id, const lslboost::function<void()> &func) {
lslboost::lock_guard<lslboost::mutex> lock(onrecover_mut_);
onrecover_[id] = func;
}
/// Unregister a recovery callback function
void inlet_connection::unregister_onrecover(void *id) {
lslboost::lock_guard<lslboost::mutex> lock(onrecover_mut_);
onrecover_.erase(id);
}
| 44.457478 | 198 | 0.709235 | [
"object",
"vector"
] |
d2de462cc377babbe5f8848025058154428da665 | 247 | hpp | C++ | cpp/dc.hpp | jieyaren/hello-world | 9fbc7d117b9aee98d748669646dd200c25a4122f | [
"WTFPL"
] | 3 | 2021-11-12T09:20:21.000Z | 2022-02-18T11:34:33.000Z | cpp/dc.hpp | jieyaren/hello-world | 9fbc7d117b9aee98d748669646dd200c25a4122f | [
"WTFPL"
] | 1 | 2021-03-08T03:23:04.000Z | 2021-03-08T03:23:04.000Z | cpp/dc.hpp | jieyaren/hello-world | 9fbc7d117b9aee98d748669646dd200c25a4122f | [
"WTFPL"
] | null | null | null | #include <vector>
#include <unordered_set>
#include <algorithm>
class Solution {
public:
int dc(std::vector<int>& candies) {
return std::min(std::unordered_set<int>(candies.begin(), candies.end()).size(), candies.size() / 2);
}
}; | 24.7 | 108 | 0.651822 | [
"vector"
] |
d2e219e23644c3a552d33dc13916a41b3dc29a61 | 3,009 | cpp | C++ | facelib/faceobject.cpp | artintexo/facedemo | d1bf8d7c758736a588e20ff264b76f7c1558a183 | [
"MIT"
] | 1 | 2019-06-17T07:24:07.000Z | 2019-06-17T07:24:07.000Z | facelib/faceobject.cpp | artintexo/facedemo | d1bf8d7c758736a588e20ff264b76f7c1558a183 | [
"MIT"
] | null | null | null | facelib/faceobject.cpp | artintexo/facedemo | d1bf8d7c758736a588e20ff264b76f7c1558a183 | [
"MIT"
] | null | null | null | #include "facelib/faceobject.h"
#include "facelib/nodedata.h"
#include "facelib/nodeitem.h"
#include "facelib/nodemodel.h"
#include "facelib/worker.h"
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
namespace facelib {
FaceObject::FaceObject(QObject *parent)
: QObject(parent), token_(""), model_(nullptr)
{
}
FaceObject::~FaceObject()
{
delete model_;
}
void FaceObject::setToken(const QString &token)
{
token_ = token;
}
QAbstractItemModel *FaceObject::model() const
{
return model_;
}
void FaceObject::createModel(const QStringList &paths)
{
if (model_ != nullptr)
delete model_;
model_ = new NodeModel(paths, this);
}
void FaceObject::startDetect()
{
QThread *thread_ = new QThread();
Worker *worker_ = new Worker(token_, model_->getSortedPaths());
worker_->moveToThread(thread_);
connect(this, &FaceObject::cancelled, worker_, &Worker::slotCancelled);
connect(worker_, &Worker::detected, this, &FaceObject::slotDetected);
connect(worker_, &Worker::progress, this, &FaceObject::slotProgress);
connect(worker_, &Worker::finished, this, &FaceObject::slotFinished);
connect(thread_, &QThread::started, worker_, &Worker::slotStarted);
connect(worker_, &Worker::finished, thread_, &QThread::quit);
connect(worker_, &Worker::finished, worker_, &Worker::deleteLater);
connect(thread_, &QThread::finished, thread_, &QThread::deleteLater);
thread_->start();
}
void FaceObject::cancelDetect()
{
emit cancelled();
}
void FaceObject::slotDetected(const QString &path, const QByteArray &json)
{
if (json.count() > 0) {
QJsonDocument doc = QJsonDocument::fromJson(json);
int statusCode = doc.object().value("status_code").toInt(-1);
if (statusCode == 200) {
QList<FaceData> list;
QJsonArray array = doc.object().value("data").toArray();
for (const QJsonValue value : array) {
QJsonValue bbox = value.toObject().value("bbox");
QJsonValue demographics = value.toObject().value("demographics");
FaceData faceData;
faceData.age = static_cast<int>(demographics.toObject().value("age").toObject().value("mean").toDouble());
faceData.gender = demographics.toObject().value("gender").toString();
faceData.rect = QRect(bbox.toObject().value("x").toInt(),
bbox.toObject().value("y").toInt(),
bbox.toObject().value("width").toInt(),
bbox.toObject().value("height").toInt());
list.append(faceData);
}
if (list.empty() == false)
model_->updateItem(path, list);
}
}
emit detected(path, json);
}
void FaceObject::slotProgress(int value)
{
emit progress(value);
}
void FaceObject::slotFinished()
{
emit finished();
}
}
| 27.861111 | 122 | 0.626122 | [
"object",
"model"
] |
5e4eace72799d5431080f5cbbfef4a84cbb0d743 | 4,746 | cpp | C++ | sqlserver/src/v20180328/model/CreatePublishSubscribeRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | sqlserver/src/v20180328/model/CreatePublishSubscribeRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | sqlserver/src/v20180328/model/CreatePublishSubscribeRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"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/sqlserver/v20180328/model/CreatePublishSubscribeRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Sqlserver::V20180328::Model;
using namespace std;
CreatePublishSubscribeRequest::CreatePublishSubscribeRequest() :
m_publishInstanceIdHasBeenSet(false),
m_subscribeInstanceIdHasBeenSet(false),
m_databaseTupleSetHasBeenSet(false),
m_publishSubscribeNameHasBeenSet(false)
{
}
string CreatePublishSubscribeRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_publishInstanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PublishInstanceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_publishInstanceId.c_str(), allocator).Move(), allocator);
}
if (m_subscribeInstanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SubscribeInstanceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_subscribeInstanceId.c_str(), allocator).Move(), allocator);
}
if (m_databaseTupleSetHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DatabaseTupleSet";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_databaseTupleSet.begin(); itr != m_databaseTupleSet.end(); ++itr, ++i)
{
d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(d[key.c_str()][i], allocator);
}
}
if (m_publishSubscribeNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PublishSubscribeName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_publishSubscribeName.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreatePublishSubscribeRequest::GetPublishInstanceId() const
{
return m_publishInstanceId;
}
void CreatePublishSubscribeRequest::SetPublishInstanceId(const string& _publishInstanceId)
{
m_publishInstanceId = _publishInstanceId;
m_publishInstanceIdHasBeenSet = true;
}
bool CreatePublishSubscribeRequest::PublishInstanceIdHasBeenSet() const
{
return m_publishInstanceIdHasBeenSet;
}
string CreatePublishSubscribeRequest::GetSubscribeInstanceId() const
{
return m_subscribeInstanceId;
}
void CreatePublishSubscribeRequest::SetSubscribeInstanceId(const string& _subscribeInstanceId)
{
m_subscribeInstanceId = _subscribeInstanceId;
m_subscribeInstanceIdHasBeenSet = true;
}
bool CreatePublishSubscribeRequest::SubscribeInstanceIdHasBeenSet() const
{
return m_subscribeInstanceIdHasBeenSet;
}
vector<DatabaseTuple> CreatePublishSubscribeRequest::GetDatabaseTupleSet() const
{
return m_databaseTupleSet;
}
void CreatePublishSubscribeRequest::SetDatabaseTupleSet(const vector<DatabaseTuple>& _databaseTupleSet)
{
m_databaseTupleSet = _databaseTupleSet;
m_databaseTupleSetHasBeenSet = true;
}
bool CreatePublishSubscribeRequest::DatabaseTupleSetHasBeenSet() const
{
return m_databaseTupleSetHasBeenSet;
}
string CreatePublishSubscribeRequest::GetPublishSubscribeName() const
{
return m_publishSubscribeName;
}
void CreatePublishSubscribeRequest::SetPublishSubscribeName(const string& _publishSubscribeName)
{
m_publishSubscribeName = _publishSubscribeName;
m_publishSubscribeNameHasBeenSet = true;
}
bool CreatePublishSubscribeRequest::PublishSubscribeNameHasBeenSet() const
{
return m_publishSubscribeNameHasBeenSet;
}
| 31.223684 | 105 | 0.751159 | [
"vector",
"model"
] |
5e57f6d24b6b6d35a3c51e0b030959a1f1e26842 | 1,984 | cc | C++ | cdn/src/model/SetUserGreenManagerConfigRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | cdn/src/model/SetUserGreenManagerConfigRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | cdn/src/model/SetUserGreenManagerConfigRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cdn/model/SetUserGreenManagerConfigRequest.h>
using AlibabaCloud::Cdn::Model::SetUserGreenManagerConfigRequest;
SetUserGreenManagerConfigRequest::SetUserGreenManagerConfigRequest() :
RpcServiceRequest("cdn", "2018-05-10", "SetUserGreenManagerConfig")
{
setMethod(HttpRequest::Method::Post);
}
SetUserGreenManagerConfigRequest::~SetUserGreenManagerConfigRequest()
{}
long SetUserGreenManagerConfigRequest::getOwnerId()const
{
return ownerId_;
}
void SetUserGreenManagerConfigRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string SetUserGreenManagerConfigRequest::getSecurityToken()const
{
return securityToken_;
}
void SetUserGreenManagerConfigRequest::setSecurityToken(const std::string& securityToken)
{
securityToken_ = securityToken;
setParameter("SecurityToken", securityToken);
}
std::string SetUserGreenManagerConfigRequest::getQuota()const
{
return quota_;
}
void SetUserGreenManagerConfigRequest::setQuota(const std::string& quota)
{
quota_ = quota;
setParameter("Quota", quota);
}
std::string SetUserGreenManagerConfigRequest::getRatio()const
{
return ratio_;
}
void SetUserGreenManagerConfigRequest::setRatio(const std::string& ratio)
{
ratio_ = ratio;
setParameter("Ratio", ratio);
}
| 26.810811 | 90 | 0.763609 | [
"model"
] |
5e6442faad6835b84b19a50b329324ac45f42d85 | 34,093 | cpp | C++ | tests/variable/variable.cpp | 0u812/libcellml | 8e4c73dcb8e8c6e40a9d75067a361ac1807aa83e | [
"Apache-2.0"
] | null | null | null | tests/variable/variable.cpp | 0u812/libcellml | 8e4c73dcb8e8c6e40a9d75067a361ac1807aa83e | [
"Apache-2.0"
] | null | null | null | tests/variable/variable.cpp | 0u812/libcellml | 8e4c73dcb8e8c6e40a9d75067a361ac1807aa83e | [
"Apache-2.0"
] | null | null | null | /*
Copyright libCellML Contributors
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 "test_utils.h"
#include "gtest/gtest.h"
#include <libcellml>
TEST(Variable, setValidVariableName)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable name=\"valid_name\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInvalidVariableName)
{
const std::string in = "invalid name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable name=\"invalid name\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, getValidVariableName)
{
const std::string in = "valid_name";
const std::string e = in;
libcellml::Variable v;
v.setName(in);
const std::string a = v.name();
EXPECT_EQ(e, a);
}
TEST(Variable, getInvalidVariableName)
{
const std::string in = "invalid name";
const std::string e = in;
libcellml::Variable v;
v.setName(in);
const std::string a = v.name();
EXPECT_EQ(e, a);
}
TEST(Variable, setUnits)
{
const std::string in = "dimensionless";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable units=\"dimensionless\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
u->setName(in);
v->setUnits(u);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setUnitsAndName)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable name=\"valid_name\" units=\"dimensionless\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
u->setName("dimensionless");
v->setUnits(u);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInitialValueByString)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable initial_value=\"0.0\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setInitialValue("0.0");
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInitialValueByDouble)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable initial_value=\"0\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
double value = 0.0;
v->setInitialValue(value);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInitialValueByReference)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable initial_value=\"referencedVariable\"/>\n"
" </component>\n"
"</model>\n";
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("referencedVariable");
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setInitialValue(v1);
c->addVariable(v2);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, getUnsetInitialValue)
{
libcellml::Variable v;
EXPECT_EQ(v.initialValue(), "");
}
TEST(Variable, getSetInitialValue)
{
libcellml::Variable v;
const std::string e = "0.0";
v.setInitialValue(e);
const std::string a = v.initialValue();
EXPECT_EQ(e, a);
}
TEST(Variable, setInterfaceTypeByInvalidString)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable interface=\"invalid\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setInterfaceType("invalid");
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInterfaceTypeNoneByValidString)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable interface=\"none\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setInterfaceType("none");
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInterfaceTypeNoneByEnum)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable interface=\"none\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setInterfaceType(libcellml::Variable::InterfaceType::NONE);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInterfaceTypePrivate)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable interface=\"private\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setInterfaceType(libcellml::Variable::InterfaceType::PRIVATE);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInterfaceTypePublic)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable interface=\"public\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setInterfaceType(libcellml::Variable::InterfaceType::PUBLIC);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setInterfaceTypePublicAndPrivate)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable interface=\"public_and_private\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setInterfaceType(libcellml::Variable::InterfaceType::PUBLIC_AND_PRIVATE);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, setGetInterfaceType)
{
libcellml::Variable v1;
libcellml::Variable v2;
libcellml::Variable v3;
libcellml::Variable v4;
libcellml::Variable::InterfaceType interfaceType1 = libcellml::Variable::InterfaceType::NONE;
libcellml::Variable::InterfaceType interfaceType2 = libcellml::Variable::InterfaceType::PRIVATE;
libcellml::Variable::InterfaceType interfaceType3 = libcellml::Variable::InterfaceType::PUBLIC;
libcellml::Variable::InterfaceType interfaceType4 = libcellml::Variable::InterfaceType::PUBLIC_AND_PRIVATE;
v1.setInterfaceType(interfaceType1);
v2.setInterfaceType(interfaceType2);
v3.setInterfaceType(interfaceType3);
v4.setInterfaceType(interfaceType4);
const std::string interfaceTypeString1 = "none";
const std::string interfaceTypeString2 = "private";
const std::string interfaceTypeString3 = "public";
const std::string interfaceTypeString4 = "public_and_private";
EXPECT_EQ(interfaceTypeString1, v1.interfaceType());
EXPECT_EQ(interfaceTypeString2, v2.interfaceType());
EXPECT_EQ(interfaceTypeString3, v3.interfaceType());
EXPECT_EQ(interfaceTypeString4, v4.interfaceType());
}
TEST(Variable, addVariable)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"valid_name\" units=\"dimensionless\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
c->setName(in);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
c->addVariable(v);
libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
u->setName("dimensionless");
v->setUnits(u);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, getParentComponent)
{
libcellml::Component c;
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
c.addVariable(v);
EXPECT_EQ(&c, v->parent());
}
TEST(Variable, getNullParentComponent)
{
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
EXPECT_EQ(nullptr, v->parent());
}
TEST(Variable, addVariableToUnnamedComponent)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable name=\"valid_name\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
c->addVariable(v);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, addTwoVariables)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable1\"/>\n"
" <variable name=\"variable2\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
c->setName(in);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
c->addVariable(v2);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, addVariablesWithAndWithoutNameAndUnits)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component>\n"
" <variable name=\"var1\" units=\"dimensionless\"/>\n"
" <variable name=\"var2\"/>\n"
" <variable units=\"dimensionless\"/>\n"
" <variable/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("var1");
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("var2");
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
c->addVariable(v1);
c->addVariable(v2);
c->addVariable(v3);
c->addVariable(v4);
libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
u->setName("dimensionless");
v1->setUnits(u);
v3->setUnits(u);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, componentWithTwoVariablesWithInitialValues)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable initial_value=\"1\"/>\n"
" <variable initial_value=\"-1\"/>\n"
" </component>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
c->setName(in);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setInitialValue(1.0);
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setInitialValue(-1.0);
c->addVariable(v2);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, removeVariableMethods)
{
const std::string in = "valid_name";
const std::string e1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable2\"/>\n"
" </component>\n"
"</model>\n";
const std::string e2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\"/>\n"
"</model>\n";
libcellml::ModelPtr m = createModelWithComponent();
libcellml::ComponentPtr c = m->component(0);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v5 = std::make_shared<libcellml::Variable>();
c->setName(in);
v1->setName("variable1");
v2->setName("variable2");
v3->setName("variable3");
v4->setName("variable4");
c->addVariable(v1);
c->addVariable(v2);
c->addVariable(v3);
EXPECT_TRUE(c->removeVariable("variable1"));
EXPECT_TRUE(c->removeVariable(v3));
libcellml::Printer printer;
std::string a = printer.printModel(m);
EXPECT_EQ(e1, a);
EXPECT_FALSE(c->removeVariable("BAD_NAME"));
c->addVariable(v4);
c->removeAllVariables();
a = printer.printModel(m);
EXPECT_EQ(e2, a);
EXPECT_FALSE(c->removeVariable(v5));
c->addVariable(v1);
c->addVariable(v2);
c->addVariable(v3);
EXPECT_TRUE(c->removeVariable(0)); // v1
EXPECT_TRUE(c->removeVariable(1)); // new index of v3
a = printer.printModel(m);
EXPECT_EQ(e1, a);
EXPECT_FALSE(c->removeVariable(1));
}
TEST(Variable, getVariableMethods)
{
const std::string in = "valid_name";
libcellml::Component c;
c.setName(in);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
c.addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
c.addVariable(v2);
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
v3->setName("variable3");
c.addVariable(v3);
libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
v4->setName("variable4");
c.addVariable(v4);
// Get by string
libcellml::VariablePtr vMethod1 = c.variable("variable1");
const std::string a1 = vMethod1->name();
EXPECT_EQ("variable1", a1);
// Get by index
libcellml::VariablePtr vMethod2 = c.variable(1);
const std::string a2 = vMethod2->name();
EXPECT_EQ("variable2", a2);
// Get const by string
const libcellml::VariablePtr vMethod3 = static_cast<const libcellml::Component>(c).variable("variable3");
const std::string a3 = vMethod3->name();
EXPECT_EQ("variable3", a3);
// Get const by index
const libcellml::VariablePtr vMethod4 = static_cast<const libcellml::Component>(c).variable(3);
const std::string a4 = vMethod4->name();
EXPECT_EQ("variable4", a4);
// Get invalid index
EXPECT_EQ(nullptr, static_cast<const libcellml::Component>(c).variable(42));
EXPECT_EQ(nullptr, c.variable(7));
// Get non-existent variable by string
EXPECT_EQ(nullptr, c.variable("notreal"));
EXPECT_EQ(nullptr, static_cast<const libcellml::Component>(c).variable("doesntexist"));
}
TEST(Variable, takeVariableMethods)
{
const std::string in = "valid_name";
libcellml::Component c;
c.setName(in);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
c.addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
c.addVariable(v2);
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
v3->setName("variable3");
c.addVariable(v3);
libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
v4->setName("variable4");
c.addVariable(v4);
// Take by index
libcellml::VariablePtr tv = c.takeVariable(0);
std::string tvn = tv->name();
EXPECT_EQ("variable1", tvn);
libcellml::VariablePtr gv = c.variable(0);
std::string gvn = gv->name();
EXPECT_EQ("variable2", gvn);
tv = c.takeVariable(0);
tvn = tv->name();
EXPECT_EQ("variable2", tvn);
gv = c.variable(0);
gvn = gv->name();
EXPECT_EQ("variable3", gvn);
// Take by string
libcellml::VariablePtr tv3 = c.takeVariable("variable3");
const std::string tvn3 = tv3->name();
EXPECT_EQ("variable3", tvn3);
// Get invalid index
EXPECT_EQ(nullptr, c.takeVariable(737));
// Get non-existent variable by string
EXPECT_EQ(nullptr, c.takeVariable("notreal"));
EXPECT_EQ(nullptr, c.takeVariable("doesntexist"));
}
TEST(Variable, modelWithComponentWithVariableWithValidName)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"valid_name\" units=\"dimensionless\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName(in);
m.addComponent(c);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
c->addVariable(v);
libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
u->setName("dimensionless");
v->setUnits(u);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
EXPECT_EQ("valid_name", v->name());
}
TEST(Variable, modelWithComponentWithVariableWithInvalidName)
{
const std::string in = "invalid name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"invalid name\">\n"
" <variable name=\"invalid name\" units=\"dimensionless\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName(in);
m.addComponent(c);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
c->addVariable(v);
libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
u->setName("dimensionless");
v->setUnits(u);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
EXPECT_EQ("invalid name", v->name());
}
TEST(Variable, modelWithComponentWithVariableWithInvalidUnitsNameAndParse)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"valid_name\" units=\"invalid name\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName(in);
m.addComponent(c);
libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
v->setName(in);
c->addVariable(v);
libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
u->setName("invalid name");
v->setUnits(u);
libcellml::Printer printer;
std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
EXPECT_EQ("invalid name", u->name());
// Parse
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Variable, modelWithComponentWithTwoNamedVariablesWithInitialValues)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable1\" initial_value=\"1.0\"/>\n"
" <variable name=\"variable2\" initial_value=\"-1.0\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName(in);
m.addComponent(c);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
v1->setInitialValue("1.0");
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
v2->setInitialValue("-1.0");
c->addVariable(v2);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, modelWithComponentWithTwoNamedVariablesWithInitialValuesOneReferenced)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable1\" initial_value=\"1\"/>\n"
" <variable name=\"variable2\" initial_value=\"variable1\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName(in);
m.addComponent(c);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
v1->setInitialValue(1.0);
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
v2->setInitialValue(v1);
c->addVariable(v2);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, modelWithComponentWithTwoNamedVariablesWithInitialValuesAndParse)
{
const std::string in = "valid_name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable1\" initial_value=\"1.0\"/>\n"
" <variable name=\"variable2\" initial_value=\"-1.0\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName(in);
m.addComponent(c);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
v1->setInitialValue("1.0");
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
v2->setInitialValue("-1.0");
c->addVariable(v2);
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Variable, modelWithComponentWithFourNamedVariablesWithInterfaces)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable1\" interface=\"none\"/>\n"
" <variable name=\"variable2\" interface=\"public\"/>\n"
" <variable name=\"variable3\" interface=\"private\"/>\n"
" <variable name=\"variable4\" interface=\"public_and_private\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName("valid_name");
m.addComponent(c);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
v1->setInterfaceType(libcellml::Variable::InterfaceType::NONE);
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
v2->setInterfaceType(libcellml::Variable::InterfaceType::PUBLIC);
c->addVariable(v2);
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
v3->setName("variable3");
v3->setInterfaceType(libcellml::Variable::InterfaceType::PRIVATE);
c->addVariable(v3);
libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
v4->setName("variable4");
v4->setInterfaceType(libcellml::Variable::InterfaceType::PUBLIC_AND_PRIVATE);
c->addVariable(v4);
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
}
TEST(Variable, modelWithComponentWithFourNamedVariablesWithInterfacesAndParse)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable1\" interface=\"none\"/>\n"
" <variable name=\"variable2\" interface=\"public\"/>\n"
" <variable name=\"variable3\" interface=\"private\"/>\n"
" <variable name=\"variable4\" interface=\"public_and_private\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName("valid_name");
m.addComponent(c);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
v1->setInterfaceType(libcellml::Variable::InterfaceType::NONE);
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
v2->setInterfaceType("public");
c->addVariable(v2);
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
v3->setName("variable3");
v3->setInterfaceType(libcellml::Variable::InterfaceType::PRIVATE);
c->addVariable(v3);
libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
v4->setName("variable4");
v4->setInterfaceType(libcellml::Variable::InterfaceType::PUBLIC_AND_PRIVATE);
c->addVariable(v4);
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Variable, modelWithComponentWithFiveNamedVariablesWithInterfacesAndParse)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable name=\"variable1\" interface=\"none\"/>\n"
" <variable name=\"variable2\" interface=\"public\"/>\n"
" <variable name=\"variable3\" interface=\"private\"/>\n"
" <variable name=\"variable4\" interface=\"public_and_private\"/>\n"
" <variable name=\"variable5\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
c->setName("valid_name");
m.addComponent(c);
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
v1->setName("variable1");
v1->setInterfaceType(libcellml::Variable::InterfaceType::NONE);
c->addVariable(v1);
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
v2->setName("variable2");
v2->setInterfaceType("public");
c->addVariable(v2);
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
v3->setName("variable3");
v3->setInterfaceType(libcellml::Variable::InterfaceType::PRIVATE);
c->addVariable(v3);
libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
v4->setName("variable4");
v4->setInterfaceType(libcellml::Variable::InterfaceType::PUBLIC_AND_PRIVATE);
c->addVariable(v4);
libcellml::VariablePtr v5 = std::make_shared<libcellml::Variable>();
v5->setName("variable4");
v5->setInterfaceType("other");
c->addVariable(v5);
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Variable, modelUnitsAttributeBeforeNameAttribute)
{
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
" <component name=\"valid_name\">\n"
" <variable units=\"dimensionless\" name=\"variable1\" interface=\"none\"/>\n"
" <variable id=\"sin\" units=\"dimensionless\" name=\"sin1\" interface=\"public_and_private\"/>\n"
" <variable id=\"deriv_approx_initial_value\" units=\"dimensionless\" initial_value=\"0\" name=\"deriv_approx_initial_value\" interface=\"public_and_private\"/>\n"
" </component>\n"
"</model>\n";
libcellml::Model m;
libcellml::Parser parser;
parser.parseModel(e);
EXPECT_EQ(size_t(0), parser.errorCount());
}
| 33.391773 | 174 | 0.630452 | [
"model"
] |
5e64860373de8d1095176f070c52add405ecafdd | 15,761 | cpp | C++ | test/test_concepts.cpp | cjdb/NanoRange | 16d33c66c7869e57dd82ff8673eb5172eff1343d | [
"BSL-1.0"
] | 323 | 2017-10-09T19:46:26.000Z | 2022-03-29T10:44:07.000Z | test/test_concepts.cpp | cjdb/NanoRange | 16d33c66c7869e57dd82ff8673eb5172eff1343d | [
"BSL-1.0"
] | 66 | 2018-05-30T23:54:56.000Z | 2021-03-26T00:20:57.000Z | test/test_concepts.cpp | cjdb/NanoRange | 16d33c66c7869e57dd82ff8673eb5172eff1343d | [
"BSL-1.0"
] | 26 | 2018-06-08T14:01:20.000Z | 2022-02-17T13:31:47.000Z |
#include <nanorange/iterator.hpp>
#include <nanorange/ranges.hpp>
//#include <nanorange-old.hpp>
#include <bitset>
#include <functional>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <array>
namespace rng = nano::ranges;
struct incomplete;
struct base {};
struct derived : base {};
class private_derived : base {};
struct from_int_only {
from_int_only(int);
template <typename T>
from_int_only(T) = delete;
};
struct to_int {
operator int() const;
};
// same_as concept tests
static_assert(rng::same_as<int, int>, "");
static_assert(!rng::same_as<float, double>, "");
static_assert(rng::same_as<void, void>, "");
static_assert(rng::same_as<incomplete, incomplete>, "");
static_assert(!rng::same_as<int, void>, "");
// derived_from tests
static_assert(!rng::derived_from<int, int>, "");
static_assert(!rng::derived_from<int&, int&>, "");
static_assert(!rng::derived_from<void, incomplete>, "");
static_assert(!rng::derived_from<int, float>, "");
static_assert(rng::derived_from<derived, base>, "");
static_assert(!rng::derived_from<base, derived>, "");
static_assert(!rng::derived_from<private_derived, base>, "");
// ConvertibleTo tests
static_assert(rng::convertible_to<void, void>, "");
static_assert(!rng::convertible_to<int, void>, "");
static_assert(!rng::convertible_to<void, int>, "");
static_assert(rng::convertible_to<int, int>, "");
static_assert(rng::convertible_to<int, const int>, "");
static_assert(rng::convertible_to<const int, int>, "");
static_assert(rng::convertible_to<int&, const volatile int>, "");
static_assert(rng::convertible_to<int&, int const&>, "");
static_assert(!rng::convertible_to<const int&, int&>, "");
static_assert(rng::convertible_to<int&&, int const&>, "");
static_assert(!rng::convertible_to<int&, int&&>, "");
// Hmmm, is this correct?
static_assert(!rng::convertible_to<int[], int[]>, "");
static_assert(rng::convertible_to<int, bool>, "");
static_assert(rng::convertible_to<float, int>, "");
static_assert(rng::convertible_to<derived&, base&>, "");
static_assert(!rng::convertible_to<base&, derived&>, "");
static_assert(!rng::convertible_to<private_derived&, base&>, "");
static_assert(rng::convertible_to<int&, from_int_only>, "");
static_assert(!rng::convertible_to<long, from_int_only>, "");
static_assert(rng::convertible_to<to_int, int>, "");
static_assert(rng::convertible_to<to_int, long>, "");
static_assert(rng::convertible_to<int*, void*>, "");
static_assert(!rng::convertible_to<void*, int*>, "");
static_assert(rng::convertible_to<const char*, std::string>, "");
static_assert(!rng::convertible_to<std::string, const char*>, "");
// CommonReference tests
static_assert(rng::common_reference_with<int&, int&>, "");
static_assert(!rng::common_reference_with<void, int>, "");
using void_cr = rng::common_reference_t<void, void>;
static_assert(rng::same_as<void_cr, void>, "");
static_assert(rng::convertible_to<void, void>, "");
static_assert(rng::common_reference_with<void, void>, "");
// Common tests
static_assert(rng::common_with<int, int>, "");
// Integal tests
static_assert(rng::integral<char>, "");
static_assert(rng::integral<signed char>, "");
static_assert(rng::integral<unsigned char>, "");
static_assert(rng::integral<bool>, "");
static_assert(!rng::integral<float>, "");
static_assert(!rng::integral<int&>, "");
static_assert(rng::integral<const int>, "");
static_assert(!rng::integral<float>, "");
static_assert(!rng::integral<std::string>, "");
static_assert(!rng::integral<void>, "");
// SignedIntegral tests
static_assert(rng::signed_integral<signed char>, "");
static_assert(!rng::signed_integral<unsigned char>, "");
static_assert(!rng::signed_integral<bool>, "");
static_assert(!rng::signed_integral<std::string>, "");
// UnsignedIntegral tests
static_assert(rng::unsigned_integral<unsigned char>, "");
static_assert(!rng::unsigned_integral<signed char>, "");
static_assert(!rng::unsigned_integral<signed>, "");
static_assert(!rng::unsigned_integral<void>, "");
static_assert(!rng::unsigned_integral<std::string>, "");
// Assignable tests
struct weird_assign {
int operator=(const weird_assign&);
};
static_assert(rng::assignable_from<int&, int&>, "");
static_assert(rng::assignable_from<int&, int>, "");
static_assert(rng::assignable_from<int&, int&&>, "");
static_assert(!rng::assignable_from<int, int&>, "");
static_assert(!rng::assignable_from<int const&, int&>, "");
static_assert(rng::assignable_from<std::string&, const char*>, "");
static_assert(!rng::assignable_from<weird_assign&, weird_assign&>, "");
static_assert(!rng::assignable_from<void, int>, "");
// Swappable tests
static_assert(rng::swappable<int>, "");
static_assert(!rng::swappable<void>, "");
static_assert(rng::swappable<std::string>, "");
static_assert(rng::swappable<base>, "");
static_assert(!rng::swappable_with<int, long>, "");
static_assert(!rng::swappable_with<int, const int>, "");
static_assert(!rng::swappable_with<int[], int[]>, "");
static_assert(!rng::swappable_with<int*, void*>, "");
static_assert(!rng::swappable_with<base, derived>, "");
// Destructible tests
struct throwing_dtor {
~throwing_dtor() noexcept(false) {}
};
class private_dtor {
~private_dtor() = default;
};
static_assert(rng::destructible<int>, "");
static_assert(rng::destructible<std::string>, "");
static_assert(!rng::destructible<void>, "");
static_assert(!rng::destructible<throwing_dtor>, "");
static_assert(!rng::destructible<private_dtor>, "");
// Constructible tests
static_assert(rng::constructible_from<int, long&>, "");
static_assert(rng::constructible_from<base&, derived&>, "");
static_assert(rng::constructible_from<std::string, const char(&)[6]>, "");
static_assert(rng::constructible_from<std::string, char, int, std::allocator<char>>, "");
static_assert(!rng::constructible_from<throwing_dtor>, "");
// DefaultConstructible tests
struct agg {
int i; float f;
};
static_assert(!rng::default_initializable<void>, "");
static_assert(rng::default_initializable<int>, "");
static_assert(rng::default_initializable<agg>, "");
static_assert(rng::default_initializable<std::string>, "");
static_assert(!rng::default_initializable<from_int_only>, "");
// FIXME (MSVC): MSVC incorrectly allows ::new const int;
// We'll leave the inverse test here so we can notice when it gets changed
#ifndef _MSC_VER
static_assert(!rng::default_initializable<const int>);
#else
static_assert(rng::default_initializable<const int>);
#endif
static_assert(rng::default_initializable<int[2]>);
// MoveConstructible tests
struct no_copy_or_move {
no_copy_or_move(const no_copy_or_move&) = delete;
no_copy_or_move& operator=(const no_copy_or_move&) = delete;
};
static_assert(!rng::move_constructible<void>, "");
static_assert(rng::move_constructible<int>, "");
static_assert(rng::move_constructible<std::string>, "");
static_assert(rng::move_constructible<std::unique_ptr<int>>, "");
static_assert(!rng::move_constructible<no_copy_or_move>, "");
// CopyConstructible tests
struct odd_copy_ctor {
odd_copy_ctor(odd_copy_ctor&);
};
static_assert(!rng::copy_constructible<void>, "");
static_assert(rng::copy_constructible<int>, "");
static_assert(rng::copy_constructible<std::string>, "");
static_assert(!rng::copy_constructible<std::unique_ptr<int>>, "");
static_assert(!rng::copy_constructible<no_copy_or_move>, "");
static_assert(!rng::copy_constructible<odd_copy_ctor>, "");
// Boolean tests
struct explicitly_convertible_to_bool {
explicit operator bool();
};
static_assert(!rng::detail::boolean_testable<void>, "");
static_assert(rng::detail::boolean_testable<bool>, "");
static_assert(rng::detail::boolean_testable<int>, "");
static_assert(rng::detail::boolean_testable<std::true_type>, "");
static_assert(rng::detail::boolean_testable<std::bitset<1>::reference>, "");
static_assert(rng::detail::boolean_testable<std::vector<bool>::reference>, "");
static_assert(rng::detail::boolean_testable<int*>, "");
static_assert(!rng::detail::boolean_testable<std::unique_ptr<int>>, "");
static_assert(!rng::detail::boolean_testable<explicitly_convertible_to_bool>, "");
// EqualityComparable tests
static_assert(rng::equality_comparable<int>, "");
static_assert(rng::equality_comparable<int&>, "");
static_assert(!rng::equality_comparable<void>, "");
static_assert(!rng::equality_comparable<std::thread>, "");
// equality_comparable_with tests
static_assert(rng::equality_comparable_with<double, double>, "");
static_assert(rng::equality_comparable_with<std::string, const char*>, "");
static_assert(!rng::equality_comparable_with<int, void>, "");
static_assert(!rng::equality_comparable_with<int, std::string>, "");
// totally_ordered tests
static_assert(!rng::totally_ordered<void>, "");
static_assert(rng::totally_ordered<int>, "");
static_assert(rng::totally_ordered<float>, "");
static_assert(rng::totally_ordered<std::string>, "");
static_assert(!rng::totally_ordered<std::thread>, "");
// StrictTotallyOrderedWith tests
static_assert(!rng::totally_ordered_with<void, void>, "");
static_assert(rng::totally_ordered_with<int, int>, "");
//static_assert(rng::StrictTotallyOrderedWith<int, float>, "");
static_assert(rng::totally_ordered_with<std::string, const char*>, "");
static_assert(rng::totally_ordered_with<int, double>, "");
// Copyable tests
struct odd_assign {
odd_assign(const odd_assign&) = default;
odd_assign& operator=(odd_assign&);
};
static_assert(!rng::copyable<void>, "");
static_assert(rng::copyable<int>, "");
static_assert(!rng::copyable<int&>, "");
static_assert(rng::copyable<std::string>, "");
static_assert(!rng::copyable<std::unique_ptr<int>>, "");
static_assert(!rng::copyable<odd_assign>, "");
// Semiregular tests
static_assert(!rng::semiregular<void>, "");
static_assert(rng::semiregular<int>, "");
static_assert(rng::semiregular<std::string>, "");
static_assert(rng::semiregular<int*>, "");
static_assert(!rng::semiregular<int&>, "");
// regular tests
static_assert(!rng::regular<void>, "");
static_assert(rng::regular<int>, "");
static_assert(rng::regular<std::string>, "");
static_assert(rng::regular<int*>, "");
static_assert(!rng::regular<int&>, "");
// [regular]Invocable tests
// FIXME: Add these
static_assert(!rng::invocable<void>, "");
// Predicate tests
int int_cmp(int, int);
static_assert(!rng::predicate<void>, "");
static_assert(rng::predicate<decltype(int_cmp), int, int>, "");
static_assert(rng::predicate<std::equal_to<>, int, int>, "");
const auto cmp = [] (auto const& lhs, auto const& rhs) { return lhs < rhs; };
static_assert(rng::predicate<decltype(cmp), int, float>, "");
// Relation tests
static_assert(!rng::relation<void, void, void>, "");
static_assert(rng::relation<std::equal_to<>, int, int>, "");
// Readable tests
static_assert(!rng::readable<void>, "");
static_assert(!rng::readable<int>, "");
static_assert(rng::readable<int*>, "");
static_assert(rng::readable<std::unique_ptr<int>>, "");
static_assert(rng::readable<std::vector<int>::const_iterator>, "");
struct MoveOnlyReadable {
using value_type = std::unique_ptr<int>;
value_type operator*() const;
};
static_assert(rng::readable<MoveOnlyReadable>, "");
// Writable tests
static_assert(!rng::writable<void, void>, "");
static_assert(rng::writable<int*, int>, "");
static_assert(!rng::writable<int const*, int>, "");
static_assert(rng::writable<std::unique_ptr<int>, int>, "");
static_assert(rng::writable<std::vector<int>::iterator, int>, "");
static_assert(!rng::writable<std::vector<int>::const_iterator, int>, "");
// weakly_incrementable tests
static_assert(!rng::weakly_incrementable<void>, "");
static_assert(rng::weakly_incrementable<int>, "");
static_assert(rng::weakly_incrementable<int*>, "");
static_assert(rng::weakly_incrementable<std::vector<int>::iterator>, "");
// Incrementable tests
static_assert(!rng::incrementable<void>, "");
static_assert(rng::incrementable<int>, "");
static_assert(rng::incrementable<int*>, "");
// Iterator tests
static_assert(!rng::input_or_output_iterator<void>, "");
static_assert(!rng::input_or_output_iterator<int>, "");
static_assert(rng::input_or_output_iterator<int*>, "");
static_assert(rng::input_or_output_iterator<int const*>, "");
static_assert(!rng::input_or_output_iterator<std::unique_ptr<int>>, "");
static_assert(rng::input_or_output_iterator<std::vector<int>::iterator>, "");
static_assert(rng::input_or_output_iterator<std::vector<bool>::const_iterator>, "");
// Sentinel tests
static_assert(!rng::sentinel_for<void, void>, "");
static_assert(!rng::sentinel_for<void, int*>, "");
static_assert(rng::sentinel_for<int*, int*>, "");
// InputIterator tests
static_assert(!rng::input_iterator<void>, "");
static_assert(!rng::input_iterator<float>, "");
static_assert(rng::input_iterator<int*>, "");
static_assert(rng::input_iterator<int const*>, "");
static_assert(!rng::input_iterator<std::unique_ptr<int>>, "");
static_assert(rng::input_iterator<std::vector<int>::iterator>, "");
static_assert(rng::input_iterator<std::vector<bool>::const_iterator>, "");
// OutputIterator tests
static_assert(!rng::output_iterator<void, void>, "");
static_assert(!rng::output_iterator<int&, int>, "");
static_assert(rng::output_iterator<int*, int>, "");
static_assert(!rng::output_iterator<int const*, int>, "");
static_assert(rng::output_iterator<std::vector<int>::iterator, int>, "");
static_assert(!rng::output_iterator<std::vector<int>::const_iterator, int>, "");
// Hmmm....
//static_assert(rng::OutputIterator<std::vector<bool>::iterator, bool>, "");
static_assert(!rng::output_iterator<std::vector<bool>::const_iterator, bool>, "");
// ForwardIterator tests
static_assert(!rng::forward_iterator<void>, "");
static_assert(rng::forward_iterator<int*>, "");
static_assert(rng::forward_iterator<std::vector<int>::iterator>, "");
// BidirectionalIterator tests
static_assert(!rng::bidirectional_iterator<void>, "");
static_assert(rng::bidirectional_iterator<int*>, "");
static_assert(rng::bidirectional_iterator<std::vector<int>::iterator>, "");
// RandomAccessIterator tests
static_assert(!rng::random_access_iterator<void>, "");
static_assert(rng::random_access_iterator<int*>, "");
static_assert(rng::random_access_iterator<std::vector<int>::iterator>, "");
// ContiguousIterator tests
static_assert(!rng::contiguous_iterator<void>, "");
static_assert(!rng::contiguous_iterator<void*>, "");
static_assert(rng::contiguous_iterator<int*>, "");
static_assert(rng::contiguous_iterator<const int*>, "");
// IndirectUnaryInvocable tests
static_assert(!rng::indirect_unary_invocable<void, void>, "");
// Range tests
static_assert(!rng::range<void>, "");
static_assert(rng::range<std::vector<int>>, "");
// SizedRange tests
static_assert(!rng::sized_range<void>, "");
static_assert(rng::sized_range<std::vector<int>>, "");
// ContiguousRange tests
static_assert(!rng::contiguous_range<void>, "");
static_assert(!rng::contiguous_range<void*>, "");
static_assert(rng::contiguous_range<std::vector<int>>, "");
// View tests
static_assert(!rng::view<void>, "");
static_assert(!rng::view<std::vector<int>&>, "");
// common_iterator
using I = rng::common_iterator<int*, rng::unreachable_sentinel_t>;
static_assert(rng::input_or_output_iterator<rng::common_iterator<int*, rng::unreachable_sentinel_t>>, "");
static_assert(rng::input_iterator<rng::common_iterator<int*, rng::unreachable_sentinel_t>>, "");
static_assert(rng::forward_iterator<rng::common_iterator<int*, rng::unreachable_sentinel_t>>, "");
static_assert(rng::equality_comparable<I>, "");
using eq = decltype(std::declval<I const&>() == std::declval<I const&>());
// Regression test for #24
struct value_type_and_element_type {
using value_type = int;
using element_type = int;
};
static_assert(!rng::readable<value_type_and_element_type>, ""); | 37.52619 | 106 | 0.72838 | [
"vector"
] |
5e65d8bc15b574fc4febaece5a5681de716b46e0 | 8,290 | hpp | C++ | WICWIU_src/Dataset.hpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 119 | 2018-05-30T01:16:36.000Z | 2021-11-08T13:01:07.000Z | WICWIU_src/Dataset.hpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 24 | 2018-08-05T16:50:42.000Z | 2020-10-28T00:38:48.000Z | WICWIU_src/Dataset.hpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 35 | 2018-06-29T17:10:13.000Z | 2021-06-05T04:07:48.000Z | #ifndef _DATASET_H_
#define _DATASET_H_
#include <stdio.h>
#include <vector>
#include <queue>
#include "Tensor.hpp"
template<typename DTYPE> class WData {
public:
DTYPE *m_aData;
int m_capacity;
WData(DTYPE *data, int capacity) {
m_aData = data;
m_capacity = capacity;
}
virtual ~WData() {
delete[] m_aData;
}
virtual DTYPE* GetData() {
return m_aData;
}
virtual int GetCapacity() {
return m_capacity;
}
DTYPE& operator[](int idx) {
return m_aData[idx];
}
};
template<typename DTYPE> class Dataset { // [] operator override
private:
/* data */
char m_dataPath[256];
std::vector<char *> imageName;
std::vector<int> label;
std::vector<int> m_vPosIndex;
std::vector<int> m_vNegIndex;
public:
Dataset();
virtual ~Dataset();
virtual void Alloc();
virtual void Dealloc();
virtual std::vector<Tensor<DTYPE> *>* GetData(int idx);
virtual std::vector<Tensor<DTYPE> *>* GetDataOfPositiveLabel(int anchorIdx, int *pPosIdx = NULL);
virtual std::vector<Tensor<DTYPE> *>* GetDataOfNegativeLabel(int anchorIdx, int *pNegIdx = NULL);
void SetLabel(const int *pLabel, int noLabel);
void SetLabel(const unsigned char *pLabel, int noLabel);
virtual int GetLabel(int idx) {
if(idx < 0 || idx >= label.size()){
printf("idx = %d is out of range (label.size() = %lu) in %s (%s %d)\n", idx, label.size(), __FUNCTION__, __FILE__, __LINE__);
// MyPause(__FUNCTION__);
return -1;
}
return label[idx];
}
virtual int GetLength() { return label.size(); }
int GetNumOfDatasetMember();
virtual void CopyData(int idx, DTYPE *pDest) { // copy i-th iamge into pDest. (designed for k-NN)
printf("This functions should be overriden by derived class");
printf("Press Enter to continue... (%s)", __FUNCTION__);
getchar();
}
virtual void SetPosNegIndices(std::vector<int> *pvPosIndex, std::vector<int> *pvNegIndex){ // registers indices fo positive and negative samples for each sample
if(pvPosIndex && pvPosIndex->size() > 0){
m_vPosIndex.resize(pvPosIndex->size());
memcpy(&m_vPosIndex[0], &(*pvPosIndex)[0], pvPosIndex->size() * sizeof(m_vPosIndex[0]));
}
if(pvNegIndex && pvNegIndex->size() > 0){
m_vNegIndex.resize(pvNegIndex->size());
memcpy(&m_vNegIndex[0], &(*pvNegIndex)[0], pvNegIndex->size() * sizeof(m_vNegIndex[0]));
}
}
std::vector<int> & GetPositiveIndices() { return m_vPosIndex; }
std::vector<int> & GetNegativeIndices() { return m_vNegIndex; }
virtual int GetPositiveIndex(int idx){ // for triplet loss
if(rand() % 2 != 0) // for stochasticity
return -1;
return (idx < m_vPosIndex.size() ? m_vPosIndex[idx] : -1);
}
virtual int GetNegativeIndex(int idx){ // for triplet loss
if(rand() % 2 != 0) // for stochasticity
return -1;
return (idx < m_vNegIndex.size() ? m_vNegIndex[idx] : -1);
}
};
template<typename DTYPE> Dataset<DTYPE>::Dataset() {
#ifdef __DEBUG___
std::cout << __FUNCTION__ << '\n';
std::cout << __FILE__ << '\n';
#endif // ifdef __DEBUG___
}
template<typename DTYPE> Dataset<DTYPE>::~Dataset() {
#ifdef __DEBUG___
std::cout << __FUNCTION__ << '\n';
std::cout << __FILE__ << '\n';
#endif // ifdef __DEBUG___
}
template<typename DTYPE> void Dataset<DTYPE>::Alloc() {
#ifdef __DEBUG___
std::cout << __FUNCTION__ << '\n';
std::cout << __FILE__ << '\n';
#endif // ifdef __DEBUG___
}
template<typename DTYPE> void Dataset<DTYPE>::Dealloc() {
#ifdef __DEBUG___
std::cout << __FUNCTION__ << '\n';
std::cout << __FILE__ << '\n';
#endif // ifdef __DEBUG___
}
template<typename DTYPE> std::vector<Tensor<DTYPE> *> *Dataset<DTYPE>::GetData(int idx) {
// virtual
// we need to implement default function
std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(1, NULL);
int capacity = 1;
Tensor<DTYPE> *data = Tensor<DTYPE>::Zeros(1, 1, 1, 1, capacity);
(*data)[0] = (DTYPE)idx;
(*result)[0] = data;
return result;
}
template<typename DTYPE> int Dataset<DTYPE>::GetNumOfDatasetMember() {
// # of data columns
// e.g. (X, Y) : returns 2
// e.g. (X, Y, Z): returns 3
// virtual
// we need to implement default function
int numOfDatasetMember = 0;
std::vector<Tensor<DTYPE> *> *temp = this->GetData(0);
if (temp) {
numOfDatasetMember = temp->size();
for (int i = 0; i < numOfDatasetMember; i++) {
if ((*temp)[i]) {
delete (*temp)[i];
(*temp)[i] = NULL;
}
}
delete temp;
temp = NULL;
}
return numOfDatasetMember;
}
template<typename DTYPE> void Dataset<DTYPE>::SetLabel(const int *pLabel, int noLabel)
{
try {
label.resize(noLabel);
} catch(...){
printf("Failed to allocate memory (noLabel = %d) in %s (%s %d)\n", noLabel, __FUNCTION__, __FILE__, __LINE__);
return;
}
// memcpy_s(&label[0], noLabel * sizeof(int), pLabel, noLabel * sizeof(int))
for(int i = 0; i < noLabel; i++)
label[i] = pLabel[i];
#ifdef __DEBUG__
printf("SetLabel() read %d labels of int type\n", noLabel);
// printf("Press Enter to continue...");
// getchar();
#endif // __DEBUG__
}
template<typename DTYPE> void Dataset<DTYPE>::SetLabel(const unsigned char *pLabel, int noLabel)
{
try {
label.resize(noLabel);
} catch(...){
printf("Failed to allocate memory (noLabel = %d) in %s (%s %d)\n", noLabel, __FUNCTION__, __FILE__, __LINE__);
return;
}
for(int i = 0; i < noLabel; i++)
label[i] = (int)pLabel[i];
#ifdef __DEBUG__
// for test
// FILE *fp = fopen("label.txt", "w");
// for(int j = 0; j < noLabel; j++){
// fprintf(fp, "%d\t%d\n", j, label[j]);
// }
// fclose(fp);
printf("SetLabel() read %d labels of unsigned char type\n", noLabel);
// printf("Press Enter to continue...");
// getchar();
#endif // __DEBUG__
}
template<typename DTYPE> std::vector<Tensor<DTYPE>*> *Dataset<DTYPE>::GetDataOfPositiveLabel(int anchorIdx, int *pPosIdx)
{
std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(0, NULL);
int anchorLabel = this->GetLabel(anchorIdx);
if(anchorLabel < 0){
printf("Error! The label of anchor sample (idx = %d) is %d in %s (%s %d)\n", anchorIdx, anchorLabel, __FUNCTION__, __FILE__, __LINE__);
return NULL;
}
// printf("anchorIdx = %d, anchorLabel = %d\n", anchorIdx, anchorLabel);
int posIdx = this->GetPositiveIndex(anchorIdx);
if(posIdx < 0){
int noSamples = GetLength();
posIdx = rand() % noSamples;
for(int i = 0; i < noSamples; i++){
if(this->GetLabel(posIdx) == anchorLabel && posIdx != anchorIdx)
break;
posIdx++;
if(posIdx >= noSamples)
posIdx = 0;
}
}
//printf("posIdx = %d, posLabel = %d\n", m_curImg, this->GetLabel(m_curImg));
//getchar();
if(pPosIdx)
*pPosIdx = posIdx;
return GetData(posIdx);
}
template<typename DTYPE> std::vector<Tensor<DTYPE>*> *Dataset<DTYPE>::GetDataOfNegativeLabel(int anchorIdx, int *pNegIdx)
{
std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(0, NULL);
int anchorLabel = this->GetLabel(anchorIdx);
if(anchorLabel < 0){
printf("Error! The label of anchor sample (idx = %d) is %d in %s (%s %d)\n", anchorIdx, anchorLabel, __FUNCTION__, __FILE__, __LINE__);
return NULL;
}
int negIdx = this->GetNegativeIndex(anchorIdx);
if(negIdx < 0){
int noSamples = GetLength();
negIdx = rand() % noSamples;
for(int i = 0; i < noSamples; i++){
if(this->GetLabel(negIdx) != anchorLabel)
break;
negIdx++;
if(negIdx >= noSamples)
negIdx = 0;
}
}
if(pNegIdx)
*pNegIdx = negIdx;
return GetData(negIdx);
}
#endif // ifndef _DATASET_H_
| 28.986014 | 168 | 0.587455 | [
"vector"
] |
5e7343c0635602e64df21416f48814879b8b58a0 | 35,843 | cpp | C++ | src/mrt/maplert/src/mrt_classloader.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 5 | 2019-09-02T04:44:52.000Z | 2021-11-08T12:23:51.000Z | src/mrt/maplert/src/mrt_classloader.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 2 | 2020-07-21T01:22:01.000Z | 2021-12-06T08:07:16.000Z | src/mrt/maplert/src/mrt_classloader.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 4 | 2019-09-02T04:46:52.000Z | 2020-09-10T11:30:03.000Z | /*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "mrt_classloader.h"
#include <cassert>
#include <cstdio>
#include <dlfcn.h>
#include "cpphelper.h"
#include "mrt_well_known.h"
#include "exception/mrt_exception.h"
#include "loader/object_locator.h"
#include "yieldpoint.h"
#include "interp_support.h"
#include "mrt_primitive_class.def"
#include "base/systrace.h"
#include "chosen.h"
namespace maplert {
LoaderAPI *LoaderAPI::pInstance = nullptr;
LoaderAPI &LoaderAPI::Instance() {
if (pInstance == nullptr) {
pInstance = new (std::nothrow) ClassLoaderImpl();
if (pInstance == nullptr) {
CL_LOG(FATAL) << "new ClassLoaderImpl failed" << maple::endl;
}
}
return *pInstance;
}
ClassLoaderImpl::ClassLoaderImpl() {
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Flang_2FObject_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Flang_2FString_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Flang_2FClass_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Futil_2FFormatter_24Flags_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Futil_2FHashMap_24Node_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Futil_2FFormatter_24FormatString_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Flang_2FCharSequence_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(
&MRT_CLASSINFO(ALjava_2Flang_2FThreadLocal_24ThreadLocalMap_24Entry_3B)));
#ifdef __OPENJDK__
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Futil_2FHashtable_24Entry_3B)));
#else // libcore
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALjava_2Futil_2FHashtable_24HashtableEntry_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALlibcore_2Freflect_2FAnnotationMember_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALsun_2Fsecurity_2Futil_2FDerValue_3B)));
primitiveClasses.push_back(reinterpret_cast<MClass*>(&MRT_CLASSINFO(ALsun_2Fsecurity_2Fx509_2FAVA_3B)));
#endif // __OPENJDK__
}
ClassLoaderImpl::~ClassLoaderImpl() {
mMappedClassLoader.clear();
}
void ClassLoaderImpl::UnInit() {
std::set<jobject> reqMplClsLoaders;
mMplFilesOther.GetObjLoaders(reqMplClsLoaders);
mMplFilesBoot.GetObjLoaders(reqMplClsLoaders);
for (auto it = reqMplClsLoaders.begin(); it != reqMplClsLoaders.end(); ++it) {
UnloadClasses(reinterpret_cast<const MObject*>(*it));
}
std::vector<const ObjFile*> regMplFiles;
mMplFilesOther.GetObjFiles(regMplFiles);
mMplFilesBoot.GetObjFiles(regMplFiles);
for (auto it = regMplFiles.begin(); it != regMplFiles.end(); ++it) {
delete *it;
*it = nullptr;
}
ObjectLoader::UnInit();
}
void ClassLoaderImpl::ResetCLCache() {
CLCache::instance.ResetCache();
}
jclass ClassLoaderImpl::GetCache(const jclass contextClass, const std::string &className,
uint32_t &index, bool &lockFail) {
return CLCache::instance.GetCache(contextClass, className, index, lockFail);
}
void ClassLoaderImpl::WriteCache(const jclass klass, const jclass contextClass, uint32_t index) {
CLCache::instance.WriteCache(klass, contextClass, index);
}
// API Interfaces Begin
void ClassLoaderImpl::RegisterMplFile(const ObjFile &objFile) {
const ObjFile *pmf = mMplFilesOther.Get(objFile.GetName());
if (pmf == nullptr) {
mMplFilesOther.Put(objFile.GetName(), objFile);
}
}
bool ClassLoaderImpl::UnRegisterMplFile(const ObjFile &objFile) {
if (GetMplFileRegistered(objFile.GetName()) == nullptr) {
RemoveMappedClassLoader(objFile.GetName());
delete &objFile;
return true;
}
return false;
}
bool ClassLoaderImpl::RegisterJniClass(IEnv env, jclass javaClass, const std::string &mFileName,
const std::string &jniClassName, INativeMethod methods, int32_t methodCount, bool fake) {
if (mFileName.empty()) {
return mMplFilesOther.Register(env, javaClass, jniClassName, methods, methodCount, fake);
}
const ObjFile *mf = mMplFilesBoot.Get(mFileName);
if (mf == nullptr) {
mf = mMplFilesOther.Get(mFileName);
}
ObjFile *objFile = const_cast<ObjFile*>(mf);
if (mf != nullptr && objFile->CanRegisterNativeMethods(jniClassName) && (objFile->RegisterNativeMethods(env,
javaClass, jniClassName, methods, methodCount, fake) == true)) {
return true;
}
return false;
}
size_t ClassLoaderImpl::GetListSize(AdapterFileList type) {
if (type == kMplFileBootList) {
return mMplFilesBoot.GetRegisterSize();
} else {
return mMplFilesOther.GetRegisterSize();
}
}
const ObjFile *ClassLoaderImpl::GetMplFileRegistered(const std::string &name) {
const ObjFile *pmf = mMplFilesBoot.Get(name);
if (pmf != nullptr) {
return pmf;
}
return mMplFilesOther.Get(name);
}
const ObjFile *ClassLoaderImpl::GetAppMplFileRegistered(const std::string &packageApk) {
std::vector<const ObjFile*> files;
mMplFilesOther.GetObjFiles(files);
std::string package;
std::string apkName;
std::string::size_type index = packageApk.find("/");
if (index == std::string::npos) {
CL_LOG(ERROR) << "packageApk must $package_name/xx.apk " << packageApk.c_str() << maple::endl;
return nullptr;
} else {
package = packageApk.substr(0, index);
apkName = packageApk.substr(index + 1);
}
for (auto it = files.begin(); it != files.end(); ++it) {
std::string soName = (*it)->GetName();
// different installation, different so name
// adb push: /system/priv-app/Calendar/Calendar.apk!/maple/arm64/mapleclasses.so
// adb install: /data/app/com.android.calendar-C5VubFGVWn3V4prwdHIuHQ==/base.apk!/maple/arm64/mapleclasses.so
if ((soName.find(kAppSoPostfix) != std::string::npos || soName.find(kAppPartialSoPostfix) != std::string::npos) &&
(soName.find(package) != std::string::npos || soName.find(apkName) != std::string::npos)) {
return *it;
}
}
return nullptr;
}
bool ClassLoaderImpl::LoadMplFileInBootClassPath(const std::string &pathString) {
maple::ScopedTrace trace("LoadMplFileInBootClassPath, %p", pathString.c_str());
if (pathString.length() < 1) {
return false;
}
// split class_pathString to arraylist;
std::vector<std::string> classPaths = stringutils::Split(pathString, ':');
// store the boot class path
jobject classLoader = nullptr;
// loop to process boot classpath
std::vector<ObjFile*> objList;
pLinker->SetLoadState(kLoadStateBoot);
for (std::string &path : classPaths) {
std::string jarName = path;
size_t pos = path.rfind("/");
if (pos != std::string::npos && pos < path.length()) {
jarName = path.substr(pos + 1);
}
if (kIgnoreJarList.find(jarName) != std::string::npos) {
continue;
}
FileAdapter adapter(path, pAdapterEx);
ObjFile *objFile = adapter.OpenObjectFile(classLoader);
if (objFile == nullptr) {
std::string message = "Failed to dlopen " + path;
(void)(pAdapterEx->EnableMygote(false, message));
return false;
}
if (objFile->GetFileType() == FileType::kMFile) {
if (!pLinker->Add(*objFile, classLoader)) {
CL_LOG(ERROR) << "invalid maple file" << path << ", lazy=" << objFile->IsLazyBinding() << objFile->GetName() <<
maple::endl;
delete objFile;
continue;
}
mMplFilesBoot.Put(objFile->GetName(), *objFile);
objFile->Load();
objList.push_back(objFile);
} else {
CL_LOG(ERROR) << "open Non maple file: " << path << ", " << objFile->GetName() << maple::endl;
delete objFile;
objFile = nullptr;
}
}
if (!LoadClasses(reinterpret_cast<MObject*>(classLoader), objList)) {
(void)pAdapterEx->EnableMygote(false, "Failed to load classes.");
return false;
}
// For boot class loader, we just link when load so.
(void)(pLinker->Link());
SetLinked(classLoader, false);
return true;
}
bool ClassLoaderImpl::LoadMplFileInAppClassPath(jobject clLoader, FileAdapter &adapter) {
maple::ScopedTrace trace("LoadMplFileInAppClassPath, %p", adapter.GetConvertPath().c_str());
MObject *classLoader = reinterpret_cast<MObject*>(clLoader);
bool isFallBack = false;
do {
std::vector<std::string> pathList;
adapter.GetObjFileList(pathList, isFallBack);
// Load classes in all MplFiles and add LinkerMFileInfo
std::vector<LinkerMFileInfo*> mplInfoList;
for (auto path : pathList) {
// 1. check mpl file if registered
const ObjFile *pmfCookie = GetMplFileRegistered(path);
if (LIKELY(pmfCookie == nullptr)) {
// 2. open mpl file
ObjFile *pmf = adapter.OpenObjectFile(clLoader, isFallBack, path);
if (pmf == nullptr) {
CL_LOG(ERROR) << "failed to open maple file " << path << ", classloader:" << classLoader << maple::endl;
if (isFallBack) {
MRT_ThrowNewException("java/io/IOException", path.c_str());
}
continue;
}
if (!pLinker->IsFrontPatchMode(path) && classLoader != nullptr) {
// 3. load mpl file's classes to classloader
if (!LoadClassesFromMplFile(classLoader, *pmf, mplInfoList, adapter.HasSiblings())) {
delete pmf;
CL_LOG(ERROR) << "failed to load maple file " << path << ", classloader:" << classLoader << maple::endl;
MRT_ThrowNewException("java/io/IOException", path.c_str());
continue;
}
}
RegisterMplFile(*pmf);
pmfCookie = pmf;
} else if (pmfCookie->GetClassLoader() != clLoader) {
std::string message = "Attempt to load the same maple file " + path + " in with multiple class loaders";
CL_LOG(ERROR) << message << maple::endl;
if (!SetMappedClassLoader(path, classLoader, reinterpret_cast<MObject*>(pmfCookie->GetClassLoader()))) {
MRT_ThrowNewException("java/lang/InternalError", message.c_str());
continue;
} else if (VLOG_IS_ON(classloader)) {
adapter.DumpMethodName();
}
}
if (pmfCookie != nullptr) {
adapter.Put(adapter.GetOriginPath(), *pmfCookie);
}
}
// A workaround for class's muid failed to resolve issue when multi-so loading
if (!isFallBack && adapter.HasSiblings()) {
LinkStartUpAndMultiSo(mplInfoList, adapter.HasStartUp());
}
isFallBack = !isFallBack && (adapter.GetSize() == 0 || adapter.IsPartialAot());
} while (isFallBack);
return (adapter.GetSize() > 0) ? true : false;
}
#ifndef __ANDROID__
// Only for QEMU mplsh test.
bool ClassLoaderImpl::LoadMplFileInUserClassPath(const std::string &paths) {
maple::ScopedTrace trace("LoadMplFileInUserClassPath, %p", paths.c_str());
CL_VLOG(classloader) << paths << maple::endl;
if (paths.length() < 1) {
CL_LOG(ERROR) << "class path is null for SystemClassLoader!!" << maple::endl;
return true;
}
// split class path string (paths) to arraylist;
std::vector<std::string> clsPaths = stringutils::Split(paths, ':');
MObject *classLoader = mSystemClassLoader;
std::vector<ObjFile*> objList;
for (auto path : clsPaths) {
FileAdapter adapter(path, pAdapterEx);
ObjFile *objFile = adapter.OpenObjectFile(reinterpret_cast<jobject>(classLoader)); // check for MFile first
if (objFile != nullptr && objFile->GetFileType() == FileType::kMFile) {
// MFile open OK. continue the linking process
if (!pLinker->Add(*objFile, reinterpret_cast<jobject>(classLoader))) {
CL_LOG(ERROR) << "invalid maple file or multiple loading:" << path << ", " << objFile->GetName() << maple::endl;
delete objFile;
continue;
}
mMplFilesOther.Put(path, *objFile);
objFile->Load();
objList.push_back(objFile);
} else {
objFile = adapter.OpenObjectFile(reinterpret_cast<jobject>(classLoader), true);
// try MFile failed, then check for DFile
if (objFile == nullptr) { // try DFile also failed, stop loading.
CL_LOG(ERROR) << "open " << path << "failed!" << maple::endl;
return false;
}
// DFile open OK. continue the linking process
// Note: objFile should be of type FileType::kDFile
std::vector<LinkerMFileInfo*> infoList;
if (!LoadClassesFromMplFile(classLoader, *objFile, infoList)) {
// loading the classes list in this dexFile failed
CL_LOG(ERROR) << "open " << path << "failed! size=" << infoList.size() << maple::endl;
delete objFile;
continue;
}
mMplFilesOther.Put(path, *objFile);
}
}
(void)(pLinker->Link());
SetLinked(reinterpret_cast<jobject>(classLoader), false);
if (!LoadClasses(classLoader, objList)) {
CL_LOG(ERROR) << "load class failed!!" << maple::endl;
return false;
}
return true;
}
#endif
jclass ClassLoaderImpl::FindClass(const std::string &className, const SearchFilter &constFilter) {
std::string javaDescriptor; // Like Ljava/lang/Object;
MClass *klass = nullptr;
jobject systemClassLoader = reinterpret_cast<jobject>(mSystemClassLoader);
SearchFilter &filter = const_cast<SearchFilter&>(constFilter);
// Like Ljava/lang/Object;
javaDescriptor = filter.isInternalName ? GetClassNametoDescriptor(className) : className;
if (UNLIKELY(javaDescriptor.empty())) {
CL_LOG(ERROR) << "javaDescriptor is nullptr" << maple::endl;
}
filter.contextCL = IsBootClassLoader(filter.specificCL) ? nullptr : filter.specificCL;
if (filter.isLowerDelegate && filter.contextCL != nullptr) {
// For delegate last class loader, the search order is as below:
// . boot class loader
// . current class loader
// . parent class loader
// Otherwise, the order is as below:
// . parent class loader (Includes boot class loader)
// . current class loader
if (filter.isDelegateLast) {
klass = LocateInCurrentClassLoader(javaDescriptor, filter.Reset());
} else {
klass = LocateInParentClassLoader(javaDescriptor, filter.Reset());
}
if (klass == nullptr && !filter.IsNullOrSystem(systemClassLoader)) {
filter.currentCL = systemClassLoader;
klass = reinterpret_cast<MClass*>(LocateClass(javaDescriptor, filter.ResetFile()));
}
if (klass == nullptr && !filter.IsBootOrSystem(systemClassLoader)) {
klass = reinterpret_cast<MClass*>(
LinkerAPI::Instance().InvokeClassLoaderLoadClass(filter.contextCL, javaDescriptor));
}
} else {
klass = FindClassInSingleClassLoader(javaDescriptor, filter.Reset());
}
// It could be normal here. We are searching class by parent-delegation-model, so we may not find class in parent
// classLoader temporarily.
if (UNLIKELY(klass == nullptr)) {
CL_DLOG(classloader) << "failed, classloader=" << filter.contextCL << ", cl name=" <<
(filter.contextCL == nullptr ? "BootCL(null)" : reinterpret_cast<MObject*>(
filter.contextCL)->GetClass()->GetName()) << ", class name=" << className << maple::endl;
return nullptr;
}
MObject *pendingClassLoader = GetClassCL(klass);
if (pendingClassLoader == nullptr && klass->IsLazyBinding()) {
CL_VLOG(classloader) << className << ", from boot, and lazy" << maple::endl;
SetClassCL(reinterpret_cast<jclass>(klass), filter.contextCL);
}
return reinterpret_cast<jclass>(klass);
}
void ClassLoaderImpl::DumpUnregisterNativeFunc(std::ostream &os) {
if (VLOG_IS_ON(binding)) {
CL_VLOG(classloader) << "boot class:" << maple::endl;
mMplFilesBoot.DumpUnregisterNativeFunc(os);
CL_VLOG(classloader) << "application class:" << maple::endl;
mMplFilesOther.DumpUnregisterNativeFunc(os);
}
}
void ClassLoaderImpl::VisitClasses(maple::rootObjectFunc &func) {
std::vector<const ObjFile*> files;
std::vector<const ObjFile*> files2;
mMplFilesOther.GetObjFiles(files);
mMplFilesBoot.GetObjFiles(files2);
std::unordered_set<const MObject*> loaders;
for (auto it = files.begin(); it != files.end(); ++it) {
(void)(loaders.insert(reinterpret_cast<const MObject*>((*it)->GetClassLoader()))); // de-duplicate
}
for (auto it = files2.begin(); it != files2.end(); ++it) {
(void)(loaders.insert(reinterpret_cast<const MObject*>((*it)->GetClassLoader()))); // de-duplicate
}
(void)(loaders.insert(nullptr)); // bootstrap class loader
for (auto it = loaders.begin(); it != loaders.end(); ++it) {
VisitClassesByLoader(*it, func);
}
}
// Get all mapped {classLoader, mpl_file_handle} by latter classloader.
bool ClassLoaderImpl::GetMappedClassLoaders(const jobject classLoader,
std::vector<std::pair<jobject, const ObjFile*>> &mappedPairs) {
bool ret = false;
for (auto it = mMappedClassLoader.begin(); it != mMappedClassLoader.end(); ++it) {
std::string fileName = it->first;
jobject latterClassLoader = reinterpret_cast<jobject>(it->second.first);
jobject mappedClassLoader = reinterpret_cast<jobject>(it->second.second);
if (classLoader == latterClassLoader) {
const ObjFile *pmfCookies = GetMplFileRegistered(fileName);
mappedPairs.push_back(std::make_pair(mappedClassLoader, pmfCookies));
ret = true;
CL_LOG(INFO) << classLoader << "->{" << mappedClassLoader << "," << fileName << "}" << maple::endl;
}
}
return ret;
}
bool ClassLoaderImpl::GetMappedClassLoader(const std::string &fileName, jobject classLoader, jobject &realClassLoader) {
auto range = mMappedClassLoader.equal_range(fileName);
for (auto val = range.first; val != range.second; ++val) {
if (classLoader == reinterpret_cast<jobject>(val->second.first)) {
realClassLoader = reinterpret_cast<jobject>(val->second.second);
CL_LOG(INFO) << "get mapped classLoader from " << classLoader << ":" << realClassLoader << " for " << fileName <<
maple::endl;
return true;
}
}
CL_LOG(ERROR) << "failed, get mapped classLoader from " << classLoader << " for " << fileName << maple::endl;
return false;
}
bool ClassLoaderImpl::RegisterNativeMethods(ObjFile &objFile,
jclass klass, INativeMethod methods, int32_t methodCount) {
return MClassLocatorManagerInterpEx::RegisterNativeMethods(*this, objFile,
klass, methods.As<const JNINativeMethod*>(), methodCount);
}
// -----------------------MRT_EXPORT Split--------------------------------------
jclass ClassLoaderImpl::LocateClass(const std::string &className, const SearchFilter &constFilter) {
SearchFilter &filter = const_cast<SearchFilter&>(constFilter);
ClassLocator *classLocator = GetCLClassTable(filter.currentCL).As<ClassLocator*>();
if (classLocator == nullptr) {
return nullptr;
}
MClass *klass = classLocator->InquireClass(className, filter);
if (klass == nullptr) {
return nullptr;
}
if (klass->GetClIndex() == kClIndexUnInit) { // For lazy binding.
SetClassCL(reinterpret_cast<jclass>(klass), filter.currentCL);
}
return reinterpret_cast<jclass>(klass);
}
// API Interfaces End
bool ClassLoaderImpl::SetMappedClassLoader(const std::string &fileName,
MObject *classLoader, MObject *realClassLoader) {
auto range = mMappedClassLoader.equal_range(fileName);
for (auto val = range.first; val != range.second; ++val) {
if (classLoader == val->second.first) {
CL_LOG(ERROR) << "failed, shouldn't double map " << classLoader << " to " << realClassLoader << " for " <<
fileName << maple::endl;
return true;
}
}
(void)(mMappedClassLoader.emplace(fileName, std::make_pair(classLoader, realClassLoader)));
CL_LOG(INFO) << "mapped " << classLoader << " to " << realClassLoader << " for " << fileName << maple::endl;
return true;
}
void ClassLoaderImpl::RemoveMappedClassLoader(const std::string &fileName) {
(void)(mMappedClassLoader.erase(fileName));
}
// For delegate last class loader, the search order is as below:
// . boot class loader
// . current class loader
// . parent class loader
MClass *ClassLoaderImpl::LocateInCurrentClassLoader(const std::string &className, SearchFilter &filter) {
MClass *klass = nullptr;
if (IsBootClassLoader(filter.contextCL)) { // Boot class loder
klass = reinterpret_cast<MClass*>(LocateClass(className, filter.Clear()));
return klass;
}
// Current class loader
klass = reinterpret_cast<MClass*>(LocateClass(className, filter.ResetClear()));
if (klass != nullptr) {
return klass;
}
// To traverse in parents.
filter.currentCL = GetCLParent(filter.contextCL);
filter.ignoreBootSystem = true;
klass = LocateInParentClassLoader(className, filter.ResetFile());
return klass;
}
MClass *ClassLoaderImpl::LocateInParentClassLoader(const std::string &className, SearchFilter &filter) {
MClass *klass = nullptr;
if (IsBootClassLoader(filter.currentCL)) { // Boot class loder
if (filter.ignoreBootSystem) { // Not to search in BootClassLoader and SystemClassLoader
return nullptr;
}
klass = reinterpret_cast<MClass*>(LocateClass(className, filter.ClearFile()));
return klass;
}
jobject classLoader = filter.currentCL;
filter.currentCL = GetCLParent(classLoader);
if ((klass = LocateInParentClassLoader(className, filter)) == nullptr) {
filter.currentCL = classLoader;
klass = reinterpret_cast<MClass*>(LocateClass(className, filter.ResetFile()));
}
return klass;
}
// Reduce cyclomatic complexity of FindClass().
// Before find the class in current classloader, check the boot firstly.
MClass *ClassLoaderImpl::FindClassInSingleClassLoader(const std::string &javaDescriptor, SearchFilter &filter) {
MClass *klass = nullptr;
jobject systemClassLoader = reinterpret_cast<jobject>(mSystemClassLoader);
// If current is boot classloader, or not boot but its parent is null, we check the boot classLoader firsly.
if (filter.contextCL == nullptr || GetCLParent(filter.contextCL) == nullptr) {
klass = reinterpret_cast<MClass*>(LocateClass(javaDescriptor, filter.Clear()));
}
// check the current classloader, if it's not boot or system classloader
if (klass == nullptr && !filter.IsBootOrSystem(systemClassLoader)) {
// Find in current classloader.
klass = reinterpret_cast<MClass*>(LocateClass(javaDescriptor, filter.Reset()));
}
// at last for the shared libraries, we check system classloader
if (klass == nullptr && filter.contextCL != nullptr && systemClassLoader != nullptr) {
// Find in systemclassloader.
filter.currentCL = systemClassLoader;
klass = reinterpret_cast<MClass*>(LocateClass(javaDescriptor, filter.ClearFile()));
}
return klass;
}
void ClassLoaderImpl::LinkStartUpAndMultiSo(std::vector<LinkerMFileInfo*> &mplInfoList, bool hasStartup) {
if (mplInfoList.size() > 0) { // We always load the first one, no matter is startup or not.
(void)(pLinker->Link(*(mplInfoList[0]), false));
}
for (size_t i = 1; i < mplInfoList.size(); ++i) {
auto mplInfo = mplInfoList[i];
void *param[] = { reinterpret_cast<void*>(pLinker), reinterpret_cast<void*>(mplInfo) };
if (hasStartup) {
pAdapterEx->CreateThreadAndLoadFollowingClasses([](void *data)->void* {
void **p = reinterpret_cast<void**>(data);
LinkerAPI *linker = reinterpret_cast<LinkerAPI*>(p[0]);
LinkerMFileInfo *info = reinterpret_cast<LinkerMFileInfo*>(p[1]);
(void)(linker->Link(*info, false));
return nullptr;
}, param);
} else {
(void)(pLinker->Link(*mplInfo, false));
}
}
#ifdef LINKER_DECOUPLE
(void)pLinker->HandleDecouple(mplInfoList);
#endif
}
MClass *ClassLoaderImpl::GetPrimitiveClass(const std::string &mplClassName) {
MClass *classInfo = nullptr;
// check the dimension of the type
size_t dim = 0;
while (mplClassName[dim] == '[') {
++dim;
}
// predefined primitive types has a dimension <= 3
if (dim > 3) {
return nullptr;
}
char typeChar = mplClassName[0];
if (dim > 0) {
typeChar = mplClassName[dim];
}
switch (typeChar) {
case 'Z':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_Z[dim]); // boolean
break;
case 'B':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_B[dim]); // byte
break;
case 'S':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_S[dim]); // short
break;
case 'C':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_C[dim]); // char
break;
case 'I':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_I[dim]); // int
break;
case 'F':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_F[dim]); // float
break;
case 'D':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_D[dim]); // double
break;
case 'J':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_J[dim]); // long
break;
case 'V':
classInfo = reinterpret_cast<MClass*>(__mrt_pclasses_V[dim]); // void
break;
default:
break;
}
if (classInfo != nullptr) {
JSAN_ADD_CLASS_METADATA(classInfo); // Need move this func to init func.
classInfo->SetClIndex(static_cast<uint16_t>(kClIndexFlag | 0)); // Initialize each class cl index as boot cl.
}
return classInfo;
}
void ClassLoaderImpl::VisitPrimitiveClass(const maple::rootObjectFunc &func) {
// primitive and primitive array classes
func((maple::address_t)__mrt_pclasses_V[0]); // void
// predefined primitive types has a dimension <= 3
for (int dim = 0; dim <= 3; ++dim) {
func((maple::address_t)__mrt_pclasses_Z[dim]); // boolean
func((maple::address_t)__mrt_pclasses_B[dim]); // byte
func((maple::address_t)__mrt_pclasses_S[dim]); // short
func((maple::address_t)__mrt_pclasses_C[dim]); // char
func((maple::address_t)__mrt_pclasses_I[dim]); // int
func((maple::address_t)__mrt_pclasses_F[dim]); // float
func((maple::address_t)__mrt_pclasses_D[dim]); // double
func((maple::address_t)__mrt_pclasses_J[dim]); // long
}
}
MClass *ClassLoaderImpl::DoCreateArrayClass(MClass &klass, MClass &componentClass, const std::string &name) {
MRTSetMetadataShadow(reinterpret_cast<ClassMetadata*>(&klass), WellKnown::GetMClassClass());
klass.SetMonitor(0);
klass.SetClIndex(componentClass.GetClIndex());
klass.SetObjectSize(sizeof(reffield_t)); // here should all be object classes
#ifdef USE_32BIT_REF
klass.SetFlag(FLAG_CLASS_ARRAY);
klass.SetNumOfSuperClasses(0);
#endif // USE_32BIT_REF
ClassMetadataRO *classMetadataRo = reinterpret_cast<ClassMetadataRO*>(
reinterpret_cast<uintptr_t>(&klass) + sizeof(ClassMetadata));
klass.SetClassMetaRoData(reinterpret_cast<uintptr_t>(classMetadataRo));
klass.SetItable(0);
klass.SetVtable(VTAB_OBJECT);
klass.SetGctib(reinterpret_cast<uintptr_t>(GCTIB_OBJECT_ARRAY));
classMetadataRo->className.SetRef(name.c_str());
classMetadataRo->fields.SetDataRef(nullptr);
classMetadataRo->methods.SetDataRef(nullptr);
classMetadataRo->componentClass.SetDataRef(&componentClass);
uint32_t modifiers = componentClass.GetArrayModifiers();
classMetadataRo->numOfFields = 0;
classMetadataRo->numOfMethods = 0;
#ifndef USE_32BIT_REF
classMetadataRo->flag = FLAG_CLASS_ARRAY;
classMetadataRo->numOfSuperclasses = 0;
classMetadataRo->padding = 0;
#endif // !USE_32BIT_REF
classMetadataRo->mod = modifiers;
classMetadataRo->annotation.SetDataRef(nullptr);
classMetadataRo->clinitAddr.SetDataRef(nullptr);
// set this class as initialized with a readable address *klass*
klass.SetInitStateRawValue(reinterpret_cast<uintptr_t>(&klass));
return &klass;
}
// Only create this array class, don't recursively create missing ones
MClass *ClassLoaderImpl::CreateArrayClass(const std::string &mplClassName, MClass &componentClass) {
if (mplClassName.empty()) {
CL_LOG(ERROR) << "failed, mplClassName is null." << maple::endl;
return nullptr;
}
MClass *klass = reinterpret_cast<MClass*>(MRT_AllocFromMeta(sizeof(ClassMetadata) + sizeof(ClassMetadataRO),
kClassMetaData));
const std::string *allocName;
// must alloc head obj, otherwise mplClassName will be free in advance
allocName = new (std::nothrow) std::string(mplClassName);
if (allocName == nullptr) {
LOG(FATAL) << "ClassLoaderImpl::CreateArrayClass: new string failed" << maple::endl;
}
return DoCreateArrayClass(*klass, componentClass, *allocName);
}
#ifdef __cplusplus
extern "C" {
#endif
// MRT API Interfaces Begin
bool MRT_IsClassInitialized(jclass klass) {
return reinterpret_cast<MClass*>(klass)->GetClIndex() != static_cast<uint16_t>(-1);
}
jobject MRT_GetNativeContexClassLoader() {
jclass contextCls = MRT_GetNativeContexClass();
if (contextCls != nullptr) {
return MRT_GetClassLoader(contextCls);
}
return nullptr;
}
jclass MRT_GetNativeContexClass() {
UnwindContext context;
UnwindContext &lastContext = maplert::TLMutator().GetLastJavaContext();
(void)MapleStack::GetLastJavaContext(context, lastContext, 0);
jclass clazz = nullptr;
if (!TryGetNativeContexClassLoaderForInterp(context, clazz)) {
if (context.IsCompiledContext()) {
clazz = context.frame.GetDeclaringClass();
}
}
return clazz;
}
jobject MRT_GetClassLoader(jclass klass) {
if (klass == nullptr) {
CL_LOG(ERROR) << "failed, class object is null!" << maple::endl;
return nullptr;
}
MObject *classLoader = LoaderAPI::As<ClassLoaderImpl&>().GetClassCL(reinterpret_cast<MClass*>(klass));
if (classLoader == nullptr) {
CL_DLOG(classloader) << "failed, classLoader returns null" << maple::endl;
}
return reinterpret_cast<jobject>(classLoader);
}
jobject MRT_ReflectGetClassLoader(jobject jobj)
__attribute__ ((alias ("MCC_GetCurrentClassLoader")));
jobject MCC_GetCurrentClassLoader(jobject caller) {
MClass *callerObj = reinterpret_cast<MClass*>(caller);
MClass *callerClass = callerObj->GetClass();
// when the caller function is a static method, the caller itself is the classInfo
if (callerClass == WellKnown::GetMClassClass()) {
callerClass = callerObj;
}
jobject classLoader = MRT_GetClassLoader(reinterpret_cast<jclass>(callerClass));
if (classLoader != nullptr) {
RC_LOCAL_INC_REF(classLoader);
}
return classLoader;
}
jobject MRT_GetBootClassLoader() {
// nullptr represents BootClassLoader in lower implementation.
// For upper layer, always return BootClassLoader instance, but not nullptr.
return LoaderAPI::As<ClassLoaderImpl&>().GetBootClassLoaderInstance();
}
// Get class in specific classloader.
// If classLoader is null, it means finding class in bootclassloader.
jclass MRT_GetClassByClassLoader(jobject classLoader, const std::string className) {
bool isDelegateLast = false;
MObject *mapleCl = reinterpret_cast<MObject*>(classLoader);
if (classLoader != nullptr) {
MClass *classLoaderClass = mapleCl->GetClass();
isDelegateLast = classLoaderClass == WellKnown::GetMClassDelegateLastClassLoader();
if (isDelegateLast) {
CL_VLOG(classloader) << "name:" << className << ", clname:" << classLoaderClass->GetName() << maple::endl;
}
}
jclass klass = LoaderAPI::Instance().FindClass(className, SearchFilter(classLoader, false, true, isDelegateLast));
if (klass != nullptr) {
(void)LinkerAPI::Instance().LinkClassLazily(klass);
}
return klass;
}
// Get class by reference to class in context.
// If context class is null, it means finding class in bootclassloader.
jclass MRT_GetClassByContextClass(jclass contextClass, const std::string className) {
bool isInternalName = true;
size_t len = className.size();
if (len == 0) {
return nullptr;
}
// try cache first
uint32_t index = 0;
bool lockFail(false);
jclass cacheResult = CLCache::instance.GetCache(contextClass, className, index, lockFail);
if (cacheResult) {
return cacheResult;
}
if (className[len - 1] == ';') {
isInternalName = false;
}
jclass klass = nullptr;
if (contextClass == nullptr) {
klass = LoaderAPI::Instance().FindClass(className, SearchFilter(nullptr, isInternalName, true, false));
} else {
klass = LoaderAPI::Instance().FindClass(className,
SearchFilter(MRT_GetClassLoader(contextClass), isInternalName, true, false));
}
if (klass != nullptr) {
(void)LinkerAPI::Instance().LinkClassLazily(klass);
}
if (!lockFail) {
CLCache::instance.WriteCache(klass, contextClass, index);
}
return klass;
}
// Get class by reference to class in context.
// If context object is null, it means finding class in bootclassloader.
jclass MRT_GetClassByContextObject(jobject obj, const std::string className) {
if (obj == nullptr) {
return MRT_GetClassByContextClass(nullptr, className);;
}
MObject *clsObj = reinterpret_cast<MObject*>(obj);
return MRT_GetClassByContextClass(reinterpret_cast<jclass>(clsObj->GetClass()), className);
}
CLCache CLCache::instance;
jclass MRT_GetClass(jclass caller, const std::string className) {
uint32_t index = 0;
bool lockFail(false);
jclass cacheResult = CLCache::instance.GetCache(caller, className, index, lockFail);
if (cacheResult != nullptr) {
return cacheResult;
}
MClass *callerCls = reinterpret_cast<MClass*>(caller);
MClass *callerClass = callerCls->GetClass();
// When the caller function is a static method, the caller itself is the classInfo
if (callerClass == WellKnown::GetMClassClass()) {
callerClass = callerCls;
}
jobject classLoader = MRT_GetClassLoader(reinterpret_cast<jclass>(callerClass));
jclass klass = LoaderAPI::Instance().FindClass(className, SearchFilter(classLoader, false, true, false));
if (klass != nullptr) {
(void)LinkerAPI::Instance().LinkClassLazily(klass);
} else {
CL_LOG(ERROR) << "callerClass=" << callerClass->GetName() << ", lazy=" << callerClass->IsLazyBinding() <<
", classLoader=" << classLoader << ", className=" << className << maple::endl;
}
if (!lockFail) {
CLCache::instance.WriteCache(klass, caller, index);
}
return klass;
}
// Notice: It's invoked by compiler generating routine.
jclass MCC_GetClass(jclass caller, const char *className) {
constexpr int eightBit = 256;
jclass klass = MRT_GetClass(caller, className);
if (UNLIKELY(klass == nullptr)) {
char msg[eightBit] = { 0 };
MClass *callerClass = reinterpret_cast<MClass*>(caller)->GetClass();
// When the caller function is a static method, the caller itself is the classInfo
if (callerClass == WellKnown::GetMClassClass()) {
callerClass = reinterpret_cast<MClass*>(caller);
}
if (sprintf_s(msg, sizeof(msg), "No class found for %s, by %s", className, callerClass->GetName()) < 0) {
CL_LOG(ERROR) << "sprintf_s failed" << maple::endl;
}
MRT_ThrowNoClassDefFoundErrorUnw(msg);
return nullptr;
}
return klass;
}
void MRT_RegisterDynamicClass(jobject classLoader, jclass klass) {
LoaderAPI::As<ClassLoaderImpl&>().RegisterDynamicClass(
reinterpret_cast<const MObject*>(classLoader), reinterpret_cast<const MClass*>(klass));
}
void MRT_UnregisterDynamicClass(jobject classLoader, jclass klass) {
LoaderAPI::As<ClassLoaderImpl&>().UnregisterDynamicClass(
reinterpret_cast<const MObject*>(classLoader), reinterpret_cast<const MClass*>(klass));
}
#ifdef __cplusplus
}
#endif
}
| 39.087241 | 120 | 0.699969 | [
"object",
"vector",
"model"
] |
5e7381917e6fd98a2ff0195e6dc247eb2cfa9f26 | 6,724 | cpp | C++ | src/renderer/Camera.cpp | kondrak/vk_playground | 9cadf4ec445fd607728026653a8092b8e78efb1b | [
"MIT"
] | null | null | null | src/renderer/Camera.cpp | kondrak/vk_playground | 9cadf4ec445fd607728026653a8092b8e78efb1b | [
"MIT"
] | null | null | null | src/renderer/Camera.cpp | kondrak/vk_playground | 9cadf4ec445fd607728026653a8092b8e78efb1b | [
"MIT"
] | null | null | null | #include "renderer/Camera.hpp"
#include "renderer/RenderContext.hpp"
#include "Math.hpp"
extern RenderContext g_renderContext;
static const float MouseSensitivity = 800.f;
Camera::Camera(float x, float y, float z) : m_position(x, y, z),
m_yLimit(1.f),
m_viewVector(0.0f, 0.0f, -1.0f),
m_rightVector(1.0f, 0.0f, 0.0f),
m_upVector(0.0f, 1.0f, 0.0f),
m_rotation(0.0f, 0.0f, 0.0f)
{
SetMode(CAM_DOF6);
}
Camera::Camera(const Math::Vector3f &position,
const Math::Vector3f &up,
const Math::Vector3f &right,
const Math::Vector3f &view ) : m_position(position),
m_yLimit(1.f),
m_viewVector(view),
m_rightVector(right),
m_upVector(up),
m_rotation(0.0f, 0.0f, 0.0f)
{
SetMode(CAM_DOF6);
}
void Camera::UpdateView()
{
// view matrix
Math::MakeView(m_viewMatrix, m_position, m_viewVector, m_upVector);
}
void Camera::RotateCamera(float angle, float x, float y, float z)
{
// create quaternion from axis-angle
RotateCamera(Math::Quaternion(Math::Vector3f(x, y, z), angle));
}
void Camera::RotateCamera(const Math::Quaternion &q)
{
Math::Quaternion result;
Math::Quaternion viewQuat(m_viewVector.m_x,
m_viewVector.m_y,
m_viewVector.m_z,
0);
result = ((q * viewQuat) * q.GetConjugate());
m_viewVector.m_x = result.m_x;
m_viewVector.m_y = result.m_y;
m_viewVector.m_z = result.m_z;
}
void Camera::Move(const Math::Vector3f &Direction)
{
m_position = m_position + Direction;
}
void Camera::MoveForward(float Distance)
{
m_position = m_position + (m_viewVector * -Distance);
}
void Camera::MoveUpward(float Distance)
{
m_position = m_position + (m_upVector * Distance);
}
void Camera::Strafe(float Distance)
{
m_position = m_position + (m_rightVector * Distance);
}
void Camera::SetMode(CameraMode cm)
{
if (m_mode != cm)
{
m_mode = cm;
UpdateProjection();
}
}
void Camera::rotateX(float angle)
{
m_rotation.m_x += angle;
RotateCamera(angle, m_rightVector.m_x, m_rightVector.m_y, m_rightVector.m_z);
m_upVector = m_rightVector.CrossProduct(m_viewVector);
}
void Camera::rotateY(float angle)
{
m_rotation.m_y += angle;
RotateCamera(angle, m_upVector.m_x, m_upVector.m_y, m_upVector.m_z);
m_rightVector = m_viewVector.CrossProduct(m_upVector);
}
void Camera::rotateZ(float angle)
{
m_rotation.m_z += angle;
Math::Vector3f axis = m_viewVector;
axis.QuickNormalize();
Math::Quaternion rotQuat(axis, angle);
Math::Quaternion viewQuat(m_upVector.m_x, m_upVector.m_y, m_upVector.m_z, 0);
Math::Quaternion result = ((rotQuat * viewQuat) * rotQuat.GetConjugate());
m_upVector.m_x = result.m_x;
m_upVector.m_y = result.m_y;
m_upVector.m_z = result.m_z;
m_rightVector = m_upVector.CrossProduct(m_viewVector) * -1;
}
void Camera::OnMouseMove(int x, int y)
{
// vector that describes mouseposition - center
Math::Vector3f MouseDirection(0, 0, 0);
// skip if cursor didn't move
if ((x == g_renderContext.halfWidth) && (y == g_renderContext.halfHeight))
return;
// keep the cursor at screen center
SDL_WarpMouseInWindow(g_renderContext.window, g_renderContext.halfWidth, g_renderContext.halfHeight);
MouseDirection.m_x = (float)(g_renderContext.halfWidth - x) / MouseSensitivity;
MouseDirection.m_y = (float)(g_renderContext.halfHeight - y) / MouseSensitivity;
m_rotation.m_x += MouseDirection.m_y;
m_rotation.m_y += MouseDirection.m_x;
// camera up-down movement limit
if (m_mode == CAM_FPS)
{
if (m_rotation.m_x > m_yLimit)
{
MouseDirection.m_y = m_yLimit + MouseDirection.m_y - m_rotation.m_x;
m_rotation.m_x = m_yLimit;
}
if (m_rotation.m_x < -m_yLimit)
{
MouseDirection.m_y = -m_yLimit + MouseDirection.m_y - m_rotation.m_x;
m_rotation.m_x = -m_yLimit;
}
}
// get the axis to rotate around the x-axis.
Math::Vector3f Axis = m_viewVector.CrossProduct(m_upVector);
// normalize to properly use the conjugate
Axis.QuickNormalize();
RotateCamera(MouseDirection.m_y, Axis.m_x, Axis.m_y, Axis.m_z);
if (m_mode == CAM_DOF6)
m_upVector = m_rightVector.CrossProduct(m_viewVector);
if (m_mode == CAM_FPS)
RotateCamera(MouseDirection.m_x, m_upVector.m_x, m_upVector.m_y, m_upVector.m_z);
else
{
// Rotate in horizontal plane
Math::Vector3f Axis2(m_viewVector.CrossProduct(m_rightVector));
Axis2.QuickNormalize();
RotateCamera(-MouseDirection.m_x, Axis2.m_x, Axis2.m_y, Axis2.m_z);
}
m_rightVector = m_viewVector.CrossProduct(m_upVector);
m_rightVector.QuickNormalize();
}
void Camera::UpdateProjection()
{
switch (m_mode)
{
case CAM_DOF6:
case CAM_FPS:
if (g_renderContext.width > g_renderContext.height)
{
Math::MakePerspective(m_projectionMatrix,
g_renderContext.fov,
g_renderContext.scrRatio,
g_renderContext.nearPlane,
g_renderContext.farPlane);
}
else
{
Math::MakePerspective(m_projectionMatrix,
g_renderContext.fov / g_renderContext.scrRatio,
g_renderContext.scrRatio,
g_renderContext.nearPlane,
g_renderContext.farPlane);
}
break;
case CAM_ORTHO:
Math::MakeOrthogonal(m_projectionMatrix, g_renderContext.left, g_renderContext.right, g_renderContext.bottom, g_renderContext.top, 0.1f, 5.f);
break;
}
// Convert projection matrix to Vulkan coordinate system (https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/)
Math::Matrix4f vulkanCorrection;
vulkanCorrection.Zero();
vulkanCorrection[0] = 1.f;
vulkanCorrection[5] = -1.f;
vulkanCorrection[10] = 0.5f;
vulkanCorrection[14] = 0.5f;
vulkanCorrection[15] = 1.f;
m_projectionMatrix = m_projectionMatrix * vulkanCorrection;
}
| 30.017857 | 150 | 0.600833 | [
"vector"
] |
5e74e75953f771dd65e0a988e7479b34165ee4bb | 5,514 | cpp | C++ | raytracing/diffuse_reflection/Main.cpp | abcdjdj/OpenGL-playground | 5f6f4de948b86d1b06bc493d7a0d5efb3ba03536 | [
"MIT"
] | null | null | null | raytracing/diffuse_reflection/Main.cpp | abcdjdj/OpenGL-playground | 5f6f4de948b86d1b06bc493d7a0d5efb3ba03536 | [
"MIT"
] | null | null | null | raytracing/diffuse_reflection/Main.cpp | abcdjdj/OpenGL-playground | 5f6f4de948b86d1b06bc493d7a0d5efb3ba03536 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include "Parameters.h"
constexpr float inf = std::numeric_limits<float>::infinity();
std::vector<float> background_color {BACKGROUND_R, BACKGROUND_G, BACKGROUND_B};
class Point
{
public:
float x, y, z;
Point() {}
Point(float x, float y, float z):x(x), y(y), z(z) {}
Point CanvasToViewport();
float dot(Point &p);
float norm();
Point operator +(Point &p);
Point operator -(Point &p);
Point operator *(float c);
void operator =(Point p);
};
using Vector = Point;
float Point::dot(Point &p)
{
return x * p.x + y * p.y + z * p.z;
}
float Point::norm()
{
return sqrt(this->dot(*this));
}
Point Point::operator +(Point &p)
{
return Point {x + p.x, y + p.y, z + p.z};
}
Point Point::operator -(Point &p)
{
return Point {x - p.x, y - p.y, z - p.z};
}
Point Point::operator *(float c)
{
return Point{c * x, c * y, c * z};
}
void Point::operator =(Point p)
{
x = p.x;
y = p.y;
z = p.z;
}
Point Point::CanvasToViewport()
{
return Point {x * V_W/C_W, y * V_H/C_H, V_D};
}
enum
{
LIGHT_AMBIENT,
LIGHT_POINT,
LIGHT_DIRECTIONAL
};
class Light
{
public:
int type;
float intensity;
Point position, direction;
Light(int t, float i, Point p);
};
Light::Light(int t, float i, Point p = Point{0.0f, 0.0f, 0.0f})
{
type = t;
intensity = i;
if(t == LIGHT_POINT)
position = p;
else if(t == LIGHT_DIRECTIONAL)
direction = p;
}
float ComputeLighting(Point p, Vector normal, std::vector<Light> &light_sources)
{
float i = 0.0f;
for(int k = 0; k < light_sources.size(); ++k) {
if(light_sources[k].type == LIGHT_AMBIENT)
i += light_sources[k].intensity;
else {
Vector light;
if(light_sources[k].type == LIGHT_POINT)
light = light_sources[k].position - p;
else
light = light_sources[k].direction;
float n_dot_l = light.dot(normal);
if(n_dot_l > 0)
i += light_sources[k].intensity * n_dot_l/(normal.norm() * light.norm());
}
}
return i;
}
class Sphere
{
public:
Point center;
std::vector<float> color;
float radius;
Sphere(Point c, std::vector<float> clr, float r):center(c), color(clr), radius(r) {}
std::pair<float, float> IntersectRaySphere(Point &origin, Point &direction);
};
std::pair<float, float> Sphere::IntersectRaySphere(Point &origin, Point &direction)
{
Vector oc = origin - center;
float k1 = direction.dot(direction);
float k2 = 2 * oc.dot(direction);
float k3 = oc.dot(oc) - radius * radius;
float discriminant = k2 * k2 - 4 * k1 * k3;
if(discriminant < 0)
return std::pair<float, float>(inf, inf);
float t1 = (-k2 + sqrt(discriminant)) / (2 * k1);
float t2 = (-k2 - sqrt(discriminant)) / (2 * k1);
return std::pair<float, float>(t1, t2);
}
std::vector<float> TraceRay(Point &origin, Point &direction, float t_min, float t_max,
std::vector<Sphere> &sphere_list, std::vector<Light> &light_sources)
{
float closest_t = inf;
Sphere *closest_sphere = nullptr;
for(int i = 0; i < sphere_list.size(); ++i) {
std::pair<float, float> t_pair = sphere_list[i].IntersectRaySphere(origin, direction);
float t1 = t_pair.first;
float t2 = t_pair.second;
if(t1 >= t_min && t1 <= t_max && t1 < closest_t) {
closest_t = t1;
closest_sphere = &sphere_list[i];
}
if(t2 >= t_min && t2 <= t_max && t2 < closest_t) {
closest_t = t2;
closest_sphere = &sphere_list[i];
}
}
if(closest_sphere == nullptr)
return background_color;
// Compute point of intersection, normal
direction = direction * closest_t;
Point p = origin + direction;
Vector n = p - closest_sphere->center;
float norm_n = n.norm();
n.x /= norm_n;
n.y /= norm_n;
n.z /= norm_n;
std::vector<float> final_color = closest_sphere->color;
float intensity = ComputeLighting(p, n, light_sources);
final_color[0] = round(final_color[0] * intensity);
final_color[1] = round(final_color[1] * intensity);
final_color[2] = round(final_color[2] * intensity);
return final_color;
}
int main(int argc, char **argv)
{
// Create the scene
std::vector<Sphere> sphere_list;
sphere_list.push_back(Sphere(Point(0, -1, 3), std::vector<float>{255, 0, 0}, 1));
sphere_list.push_back(Sphere(Point(2, 0, 4), std::vector<float>{0, 0, 255}, 1));
sphere_list.push_back(Sphere(Point(-2, 0, 4), std::vector<float>{0, 255, 0}, 1));
sphere_list.push_back(Sphere(Point(0, -5001, 0), std::vector<float>{255, 255, 0}, 5000));
// Light Sources
std::vector<Light> light_sources;
light_sources.push_back(Light(LIGHT_AMBIENT, 0.2f));
light_sources.push_back(Light(LIGHT_POINT, 0.6f, Point{2, 1, 0}));
light_sources.push_back(Light(LIGHT_DIRECTIONAL, 0.2f, Vector{1, 4, 4}));
Point origin{O_X, O_Y, O_Z};
for(int y = C_H/2 - 1; y >= -C_H/2; --y) {
for(int x = -C_W/2; x <= C_W/2 - 1; ++x) {
Point converted = Point{x, y, 0}.CanvasToViewport();
std::vector<float> color = TraceRay(origin, converted, 1, inf, sphere_list, light_sources);
std::cout << color[0] << " " << color[1] << " " << color[2] << std::endl;
}
}
}
| 26.382775 | 103 | 0.589227 | [
"vector"
] |
5e8ff7356b54a76d277fe15e3318616d93e5fb42 | 1,443 | cpp | C++ | core/src/cpp/tests/UUID/uuidBoostTest.cpp | OpenKGC/hypergraphdb | 05073f5082df60577e48af283311172dd3f2f847 | [
"Apache-2.0"
] | 186 | 2015-07-09T06:00:54.000Z | 2022-03-16T01:14:40.000Z | core/src/cpp/tests/UUID/uuidBoostTest.cpp | OpenKGC/hypergraphdb | 05073f5082df60577e48af283311172dd3f2f847 | [
"Apache-2.0"
] | 27 | 2015-08-01T20:33:10.000Z | 2022-03-08T21:11:23.000Z | core/src/cpp/tests/UUID/uuidBoostTest.cpp | OpenKGC/hypergraphdb | 05073f5082df60577e48af283311172dd3f2f847 | [
"Apache-2.0"
] | 56 | 2015-10-15T10:00:14.000Z | 2022-03-12T20:56:14.000Z | // example of tagging an object with a uuid
// see boost/libs/uuid/test/test_tagging.cpp
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <vector>
#include <iomanip>
using namespace std;
void print( vector<char> v )
{
std::cout.fill( '0' );
for( int i=0 ; i<v.size( ) ; i++ )
{
std::cout << setw(8) << std::hex << (int)v[i];
std::cout<< "-" ;
}
cout << endl;
}
class object
{
public:
object()
: tag(boost::uuids::random_generator()())
, state(0)
{}
explicit object(int state)
: tag(boost::uuids::random_generator()())
, state(state)
{}
object(object const& rhs)
: tag(rhs.tag)
, state(rhs.state)
{}
bool operator==(object const& rhs) const {
return tag == rhs.tag;
}
object& operator=(object const& rhs) {
tag = rhs.tag;
state = rhs.state;
}
void printMe( )
{
std::vector<char> v(tag.size());
std::copy(tag.begin(), tag.end(), v.begin());
print( v );
}
int get_state() const { return state; }
void set_state(int new_state) { state = new_state; }
private:
boost::uuids::uuid tag;
int state;
};
int main( )
{
object o1(1);
o1.printMe();
object o2 = o1;
o2.set_state(2);
assert(o1 == o2);
object o3(3);
// assert(o1 != o3);
// assert(o2 != o3);
}
| 18.0375 | 62 | 0.527374 | [
"object",
"vector"
] |
5e93c9e10d07ebfcac2a2ec5770f35cfce3f1ce3 | 51,476 | cpp | C++ | src/visualizer/Visualizer3D.cpp | omarosamahu/Kimera-VIO | a652739af937200a2b82da86c217fec28334f146 | [
"BSD-2-Clause"
] | 1 | 2020-06-04T20:12:58.000Z | 2020-06-04T20:12:58.000Z | src/visualizer/Visualizer3D.cpp | omarosamahu/Kimera-VIO | a652739af937200a2b82da86c217fec28334f146 | [
"BSD-2-Clause"
] | null | null | null | src/visualizer/Visualizer3D.cpp | omarosamahu/Kimera-VIO | a652739af937200a2b82da86c217fec28334f146 | [
"BSD-2-Clause"
] | null | null | null | /* ----------------------------------------------------------------------------
* Copyright 2017, Massachusetts Institute of Technology,
* Cambridge, MA 02139
* All Rights Reserved
* Authors: Luca Carlone, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file Visualizer.cpp
* @brief Build and visualize 2D mesh from Frame
* @author Antoni Rosinol, AJ Haeffner, Luca Carlone
*/
#include "kimera-vio/visualizer/Visualizer3D.h"
#include <algorithm> // for min
#include <memory> // for shared_ptr<>
#include <string> // for string
#include <unordered_map> // for unordered_map<>
#include <utility> // for pair<>
#include <vector> // for vector<>
#include <gflags/gflags.h>
#include "kimera-vio/backend/VioBackEnd-definitions.h"
#include "kimera-vio/common/FilesystemUtils.h"
#include "kimera-vio/utils/Statistics.h"
#include "kimera-vio/utils/Timer.h"
#include "kimera-vio/utils/UtilsGTSAM.h"
#include "kimera-vio/utils/UtilsOpenCV.h"
#include "kimera-vio/factors/PointPlaneFactor.h" // For visualization of constraints.
DEFINE_bool(visualize_mesh, false, "Enable 3D mesh visualization.");
DEFINE_bool(visualize_mesh_2d, false, "Visualize mesh 2D.");
DEFINE_bool(visualize_semantic_mesh, false,
"Color the 3d mesh according to their semantic labels.");
DEFINE_bool(visualize_mesh_with_colored_polygon_clusters, false,
"Color the polygon clusters according to their cluster id.");
DEFINE_bool(visualize_point_cloud, true, "Enable point cloud visualization.");
DEFINE_bool(visualize_convex_hull, false, "Enable convex hull visualization.");
DEFINE_bool(visualize_plane_constraints, false,
"Enable plane constraints"
" visualization.");
DEFINE_bool(visualize_planes, false, "Enable plane visualization.");
DEFINE_bool(visualize_plane_label, false, "Enable plane label visualization.");
DEFINE_bool(visualize_mesh_in_frustum, false,
"Enable mesh visualization in "
"camera frustum.");
DEFINE_string(
visualize_load_mesh_filename, "",
"Load a mesh in the visualization, i.e. to visualize ground-truth "
"point cloud from Euroc's Vicon dataset.");
// 3D Mesh related flags.
DEFINE_int32(mesh_shading, 0, "Mesh shading:\n 0: Flat, 1: Gouraud, 2: Phong");
DEFINE_int32(mesh_representation, 1,
"Mesh representation:\n 0: Points, 1: Surface, 2: Wireframe");
DEFINE_bool(texturize_3d_mesh, false,
"Whether you want to add texture to the 3d"
"mesh. The texture is taken from the image"
" frame.");
DEFINE_bool(set_mesh_ambient,
false,
"Whether to use ambient light for the "
"mesh.");
DEFINE_bool(set_mesh_lighting, true, "Whether to use lighting for the mesh.");
DEFINE_bool(log_mesh, false, "Log the mesh at time horizon.");
DEFINE_bool(log_accumulated_mesh, false, "Accumulate the mesh when logging.");
DEFINE_int32(displayed_trajectory_length, 50,
"Set length of plotted trajectory."
"If -1 then all the trajectory is plotted.");
namespace VIO {
// Contains internal data for Visualizer3D window.
Visualizer3D::WindowData::WindowData()
: window_(cv::viz::Viz3d("3D Visualizer")),
cloud_color_(cv::viz::Color::white()),
background_color_(cv::viz::Color::black()),
mesh_representation_(FLAGS_mesh_representation),
mesh_shading_(FLAGS_mesh_shading),
mesh_ambient_(FLAGS_set_mesh_ambient),
mesh_lighting_(FLAGS_set_mesh_lighting) {}
/* -------------------------------------------------------------------------- */
Visualizer3D::Visualizer3D(const VisualizationType& viz_type,
const BackendType& backend_type)
: visualization_type_(viz_type),
backend_type_(backend_type),
logger_(nullptr) {
if (FLAGS_log_mesh) {
logger_ = VIO::make_unique<VisualizerLogger>();
}
if (VLOG_IS_ON(2)) {
window_data_.window_.setGlobalWarnings(true);
} else {
window_data_.window_.setGlobalWarnings(false);
}
window_data_.window_.registerKeyboardCallback(keyboardCallback,
&window_data_);
window_data_.window_.setBackgroundColor(window_data_.background_color_);
window_data_.window_.showWidget("Coordinate Widget",
cv::viz::WCoordinateSystem());
}
/* -------------------------------------------------------------------------- */
// Returns true if visualization is ready, false otherwise.
// TODO(Toni): Put all flags inside spinOnce into Visualizer3DParams!
VisualizerOutput::UniquePtr Visualizer3D::spinOnce(
const VisualizerInput& input) {
DCHECK(input.frontend_output_);
DCHECK(input.mesher_output_);
DCHECK(input.backend_output_);
VisualizerOutput::UniquePtr output = VIO::make_unique<VisualizerOutput>();
output->visualization_type_ = visualization_type_;
cv::Mat mesh_2d_img; // Only for visualization.
const Frame& left_stereo_keyframe =
input.frontend_output_->stereo_frame_lkf_.getLeftFrame();
switch (visualization_type_) {
// Computes and visualizes 3D mesh from 2D triangulation.
// vertices: all leftframe kps with right-VALID (3D), lmkId != -1 and
// inside the image triangles: all the ones with edges inside images as
// produced by cv::subdiv, which have uniform gradient (updateMesh3D also
// filters out geometrically) Sparsity comes from filtering out triangles
// corresponding to non planar obstacles which are assumed to have
// non-uniform gradient.
case VisualizationType::kMesh2dTo3dSparse: {
// Visualize 2d mesh.
if (FLAGS_visualize_mesh_2d || FLAGS_visualize_mesh_in_frustum) {
const ImageToDisplay& mesh_display = ImageToDisplay(
"Mesh 2D",
visualizeMesh2DStereo(input.mesher_output_->mesh_2d_for_viz_,
left_stereo_keyframe));
if (FLAGS_visualize_mesh_2d) {
output->images_to_display_.push_back(mesh_display);
}
if (FLAGS_visualize_mesh_in_frustum) {
mesh_2d_img = mesh_display.image_;
}
}
// 3D mesh visualization
VLOG(10) << "Starting 3D mesh visualization...";
static std::vector<Plane> planes_prev;
static PointsWithIdMap points_with_id_VIO_prev;
static LmkIdToLmkTypeMap lmk_id_to_lmk_type_map_prev;
static cv::Mat vertices_mesh_prev;
static cv::Mat polygons_mesh_prev;
static Mesh3DVizProperties mesh_3d_viz_props_prev;
if (FLAGS_visualize_mesh) {
VLOG(10) << "Visualize mesh.";
if (FLAGS_visualize_semantic_mesh) {
VLOG(10) << "Visualize Semantic mesh.";
LOG_IF(WARNING, FLAGS_visualize_mesh_with_colored_polygon_clusters)
<< "Both gflags visualize_semantic_mesh and "
"visualize_mesh_with_colored_polygon_cluster are set to True,"
" but visualization of the semantic mesh has priority over "
"visualization of the polygon clusters.";
visualizeMesh3D(vertices_mesh_prev,
mesh_3d_viz_props_prev.colors_,
polygons_mesh_prev,
mesh_3d_viz_props_prev.tcoords_,
mesh_3d_viz_props_prev.texture_);
} else {
VLOG(10) << "Visualize mesh with colored clusters.";
LOG_IF(ERROR, mesh_3d_viz_props_prev.colors_.rows > 0u)
<< "The 3D mesh is being colored with semantic information, but"
" gflag visualize_semantic_mesh is set to false...";
visualizeMesh3DWithColoredClusters(
planes_prev,
vertices_mesh_prev,
polygons_mesh_prev,
FLAGS_visualize_mesh_with_colored_polygon_clusters,
input.timestamp_);
}
}
if (FLAGS_visualize_point_cloud) {
visualizePoints3D(points_with_id_VIO_prev, lmk_id_to_lmk_type_map_prev);
}
if (!FLAGS_visualize_load_mesh_filename.empty()) {
static bool visualize_ply_mesh_once = true;
if (visualize_ply_mesh_once) {
visualizePlyMesh(FLAGS_visualize_load_mesh_filename.c_str());
visualize_ply_mesh_once = false;
}
}
if (FLAGS_visualize_convex_hull) {
if (planes_prev.size() != 0) {
visualizeConvexHull(planes_prev.at(0).triangle_cluster_,
vertices_mesh_prev, polygons_mesh_prev);
}
}
if (backend_type_ == BackendType::kStructuralRegularities &&
FLAGS_visualize_plane_constraints) {
LandmarkIds lmk_ids_in_current_pp_factors;
for (const auto& g : input.backend_output_->graph_) {
const auto& ppf =
boost::dynamic_pointer_cast<gtsam::PointPlaneFactor>(g);
if (ppf) {
// We found a PointPlaneFactor.
// Get point key.
Key point_key = ppf->getPointKey();
LandmarkId lmk_id = gtsam::Symbol(point_key).index();
lmk_ids_in_current_pp_factors.push_back(lmk_id);
// Get point estimate.
gtsam::Point3 point;
// This call makes visualizer unable to perform this
// in parallel. But you can just copy the state_
CHECK(getEstimateOfKey(
input.backend_output_->state_, point_key, &point));
// Visualize.
const Key& ppf_plane_key = ppf->getPlaneKey();
// not sure, we are having some w planes_prev
// others with planes...
for (const Plane& plane : input.mesher_output_->planes_) {
if (ppf_plane_key == plane.getPlaneSymbol().key()) {
gtsam::OrientedPlane3 current_plane_estimate;
CHECK(getEstimateOfKey( // This call makes visualizer
// unable to perform this in
// parallel.
input.backend_output_->state_,
ppf_plane_key,
¤t_plane_estimate));
// WARNING assumes the backend updates normal and distance
// of plane and that no one modifies it afterwards...
visualizePlaneConstraints(
plane.getPlaneSymbol().key(),
current_plane_estimate.normal().point3(),
current_plane_estimate.distance(), lmk_id, point);
// Stop since there are not multiple planes for one
// ppf.
break;
}
}
}
}
// Remove lines that are not representing a point plane factor
// in the current graph.
removeOldLines(lmk_ids_in_current_pp_factors);
}
// Must go after visualize plane constraints.
if (FLAGS_visualize_planes || FLAGS_visualize_plane_constraints) {
for (const Plane& plane : input.mesher_output_->planes_) {
const gtsam::Symbol& plane_symbol = plane.getPlaneSymbol();
const std::uint64_t& plane_index = plane_symbol.index();
gtsam::OrientedPlane3 current_plane_estimate;
if (getEstimateOfKey<gtsam::OrientedPlane3>(
input.backend_output_->state_,
plane_symbol.key(),
¤t_plane_estimate)) {
const cv::Point3d& plane_normal_estimate =
UtilsOpenCV::unit3ToPoint3d(current_plane_estimate.normal());
CHECK(plane.normal_ == plane_normal_estimate);
// We have the plane in the optimization.
// Visualize plane.
visualizePlane(plane_index, plane_normal_estimate.x,
plane_normal_estimate.y, plane_normal_estimate.z,
current_plane_estimate.distance(),
FLAGS_visualize_plane_label,
plane.triangle_cluster_.cluster_id_);
} else {
// We could not find the plane in the optimization...
// Careful cause we might enter here because there are new
// segmented planes.
// Delete the plane.
LOG(ERROR) << "Remove plane viz for id:" << plane_index;
if (FLAGS_visualize_plane_constraints) {
removePlaneConstraintsViz(plane_index);
}
removePlane(plane_index);
}
}
// Also remove planes that were deleted by the backend...
for (const Plane& plane : planes_prev) {
const gtsam::Symbol& plane_symbol = plane.getPlaneSymbol();
const std::uint64_t& plane_index = plane_symbol.index();
gtsam::OrientedPlane3 current_plane_estimate;
if (!getEstimateOfKey(input.backend_output_->state_,
plane_symbol.key(),
¤t_plane_estimate)) {
// We could not find the plane in the optimization...
// Delete the plane.
if (FLAGS_visualize_plane_constraints) {
removePlaneConstraintsViz(plane_index);
}
removePlane(plane_index);
}
}
}
planes_prev = input.mesher_output_->planes_;
vertices_mesh_prev = input.mesher_output_->vertices_mesh_;
polygons_mesh_prev = input.mesher_output_->polygons_mesh_;
points_with_id_VIO_prev = input.backend_output_->landmarks_with_id_map_;
lmk_id_to_lmk_type_map_prev =
input.backend_output_->lmk_id_to_lmk_type_map_;
LOG_IF(WARNING, mesh3d_viz_properties_callback_)
<< "Coloring the mesh using semantic segmentation colors.";
mesh_3d_viz_props_prev =
// Call semantic mesh segmentation if someone registered a callback.
mesh3d_viz_properties_callback_
? mesh3d_viz_properties_callback_(left_stereo_keyframe.timestamp_,
left_stereo_keyframe.img_,
input.mesher_output_->mesh_2d_,
input.mesher_output_->mesh_3d_)
: (FLAGS_texturize_3d_mesh ? Visualizer3D::texturizeMesh3D(
left_stereo_keyframe.timestamp_,
left_stereo_keyframe.img_,
input.mesher_output_->mesh_2d_,
input.mesher_output_->mesh_3d_)
: Mesh3DVizProperties()),
VLOG(10) << "Finished mesh visualization.";
break;
}
// Computes and visualizes a 3D point cloud with VIO points in current time
// horizon of the optimization.
case VisualizationType::kPointcloud: {
// Do not color the cloud, send empty lmk id to lmk type map
visualizePoints3D(input.backend_output_->landmarks_with_id_map_,
input.backend_output_->lmk_id_to_lmk_type_map_);
break;
}
case VisualizationType::kNone: {
break;
}
}
// Visualize trajectory.
VLOG(10) << "Starting trajectory visualization...";
addPoseToTrajectory(input.backend_output_->W_State_Blkf_.pose_.compose(
input.frontend_output_->stereo_frame_lkf_.getBPoseCamLRect()));
visualizeTrajectory3D(FLAGS_visualize_mesh_in_frustum
? mesh_2d_img
: left_stereo_keyframe.img_);
VLOG(10) << "Finished trajectory visualization.";
// TODO avoid copying and use a std::unique_ptr! You need to pass window_data_
// as a parameter to all the functions and set them as const.
output->window_ = window_data_.window_;
return output;
}
/* -------------------------------------------------------------------------- */
// Create a 2D mesh from 2D corners in an image
cv::Mat Visualizer3D::visualizeMesh2D(
const std::vector<cv::Vec6f>& triangulation2D,
const cv::Mat& img,
const KeypointsCV& extra_keypoints) {
static const cv::Scalar kDelaunayColor(0u, 255u, 0u);
static const cv::Scalar kPointsColor(255u, 0u, 0u);
// Duplicate image for annotation and visualization.
cv::Mat img_clone = img.clone();
cv::cvtColor(img_clone, img_clone, cv::COLOR_GRAY2BGR);
cv::Size size = img_clone.size();
cv::Rect rect(0, 0, size.width, size.height);
std::vector<cv::Point> pt(3);
for (size_t i = 0; i < triangulation2D.size(); i++) {
const cv::Vec6f& t = triangulation2D[i];
// Visualize mesh vertices.
pt[0] = cv::Point(cvRound(t[0]), cvRound(t[1]));
pt[1] = cv::Point(cvRound(t[2]), cvRound(t[3]));
pt[2] = cv::Point(cvRound(t[4]), cvRound(t[5]));
// Visualize mesh edges.
cv::line(img_clone, pt[0], pt[1], kDelaunayColor, 1, CV_AA, 0);
cv::line(img_clone, pt[1], pt[2], kDelaunayColor, 1, CV_AA, 0);
cv::line(img_clone, pt[2], pt[0], kDelaunayColor, 1, CV_AA, 0);
}
// Visualize extra vertices.
for (const auto& keypoint : extra_keypoints) {
cv::circle(img_clone, keypoint, 2, kPointsColor, CV_FILLED, CV_AA, 0);
}
return img_clone;
}
/* -------------------------------------------------------------------------- */
// Visualize 2d mesh.
cv::Mat Visualizer3D::visualizeMesh2DStereo(
const std::vector<cv::Vec6f>& triangulation_2D,
const Frame& ref_frame) {
static const cv::Scalar kDelaunayColor(0, 255, 0); // Green
static const cv::Scalar kMeshVertexColor(255, 0, 0); // Blue
static const cv::Scalar kInvalidKeypointsColor(0, 0, 255); // Red
// Sanity check.
DCHECK(ref_frame.landmarks_.size() == ref_frame.keypoints_.size())
<< "Frame: wrong dimension for the landmarks.";
// Duplicate image for annotation and visualization.
cv::Mat img_clone = ref_frame.img_.clone();
cv::cvtColor(img_clone, img_clone, cv::COLOR_GRAY2BGR);
// Visualize extra vertices.
for (size_t i = 0; i < ref_frame.keypoints_.size(); i++) {
// Only for valid keypoints, but possibly without a right pixel.
// Kpts that are both valid and have a right pixel are currently the ones
// passed to the mesh.
if (ref_frame.landmarks_[i] != -1) {
cv::circle(img_clone,
ref_frame.keypoints_[i],
2,
kInvalidKeypointsColor,
CV_FILLED,
CV_AA,
0);
}
}
std::vector<cv::Point> pt(3);
for (const cv::Vec6f& triangle : triangulation_2D) {
// Visualize mesh vertices.
pt[0] = cv::Point(cvRound(triangle[0]), cvRound(triangle[1]));
pt[1] = cv::Point(cvRound(triangle[2]), cvRound(triangle[3]));
pt[2] = cv::Point(cvRound(triangle[4]), cvRound(triangle[5]));
cv::circle(img_clone, pt[0], 2, kMeshVertexColor, CV_FILLED, CV_AA, 0);
cv::circle(img_clone, pt[1], 2, kMeshVertexColor, CV_FILLED, CV_AA, 0);
cv::circle(img_clone, pt[2], 2, kMeshVertexColor, CV_FILLED, CV_AA, 0);
// Visualize mesh edges.
cv::line(img_clone, pt[0], pt[1], kDelaunayColor, 1, CV_AA, 0);
cv::line(img_clone, pt[1], pt[2], kDelaunayColor, 1, CV_AA, 0);
cv::line(img_clone, pt[2], pt[0], kDelaunayColor, 1, CV_AA, 0);
}
return img_clone;
}
/* -------------------------------------------------------------------------- */
// Visualize a 3D point cloud of unique 3D landmarks.
void Visualizer3D::visualizePoints3D(
const PointsWithIdMap& points_with_id,
const LmkIdToLmkTypeMap& lmk_id_to_lmk_type_map) {
bool color_the_cloud = false;
if (lmk_id_to_lmk_type_map.size() != 0) {
color_the_cloud = true;
CHECK_EQ(points_with_id.size(), lmk_id_to_lmk_type_map.size());
}
// Sanity check dimension.
if (points_with_id.size() == 0) {
// No points to visualize.
LOG(WARNING) << "No landmark information for Visualizer. "
"Not displaying 3D points.";
return;
}
// Populate cloud structure with 3D points.
cv::Mat point_cloud(1, points_with_id.size(), CV_32FC3);
cv::Mat point_cloud_color(1, lmk_id_to_lmk_type_map.size(), CV_8UC3,
window_data_.cloud_color_);
cv::Point3f* data = point_cloud.ptr<cv::Point3f>();
size_t i = 0;
for (const std::pair<LandmarkId, gtsam::Point3>& id_point : points_with_id) {
const gtsam::Point3& point_3d = id_point.second;
data[i].x = static_cast<float>(point_3d.x());
data[i].y = static_cast<float>(point_3d.y());
data[i].z = static_cast<float>(point_3d.z());
if (color_the_cloud) {
DCHECK(lmk_id_to_lmk_type_map.find(id_point.first) !=
lmk_id_to_lmk_type_map.end());
switch (lmk_id_to_lmk_type_map.at(id_point.first)) {
case LandmarkType::SMART: {
point_cloud_color.col(i) = cv::viz::Color::white();
break;
}
case LandmarkType::PROJECTION: {
point_cloud_color.col(i) = cv::viz::Color::green();
break;
}
default: {
point_cloud_color.col(i) = cv::viz::Color::white();
break;
}
}
}
i++;
}
// Create a cloud widget.
cv::viz::WCloud cloud_widget(point_cloud, window_data_.cloud_color_);
if (color_the_cloud) {
cloud_widget = cv::viz::WCloud(point_cloud, point_cloud_color);
}
cloud_widget.setRenderingProperty(cv::viz::POINT_SIZE, 1);
window_data_.window_.showWidget("Point cloud.", cloud_widget);
}
/* -------------------------------------------------------------------------- */
// Visualize a 3D point cloud of unique 3D landmarks with its connectivity.
void Visualizer3D::visualizePlane(const PlaneId& plane_index, const double& n_x,
const double& n_y, const double& n_z,
const double& d,
const bool& visualize_plane_label,
const int& cluster_id) {
const std::string& plane_id_for_viz = "Plane " + std::to_string(plane_index);
// Create a plane widget.
const cv::Vec3d normal(n_x, n_y, n_z);
const cv::Point3d center(d * n_x, d * n_y, d * n_z);
static const cv::Vec3d new_yaxis(0, 1, 0);
static const cv::Size2d size(1.0, 1.0);
cv::viz::Color plane_color;
getColorById(cluster_id, &plane_color);
cv::viz::WPlane plane_widget(center, normal, new_yaxis, size, plane_color);
if (visualize_plane_label) {
static double increase = 0.0;
const cv::Point3d text_position(d * n_x, d * n_y,
d * n_z + std::fmod(increase, 1));
increase += 0.1;
window_data_.window_.showWidget(
plane_id_for_viz + "_label",
cv::viz::WText3D(plane_id_for_viz, text_position, 0.07, true));
}
window_data_.window_.showWidget(plane_id_for_viz, plane_widget);
is_plane_id_in_window_[plane_index] = true;
}
/* -------------------------------------------------------------------------- */
// Draw a line in opencv.
void Visualizer3D::drawLine(const std::string& line_id, const double& from_x,
const double& from_y, const double& from_z,
const double& to_x, const double& to_y,
const double& to_z) {
cv::Point3d pt1(from_x, from_y, from_z);
cv::Point3d pt2(to_x, to_y, to_z);
drawLine(line_id, pt1, pt2);
}
/* -------------------------------------------------------------------------- */
void Visualizer3D::drawLine(const std::string& line_id, const cv::Point3d& pt1,
const cv::Point3d& pt2) {
cv::viz::WLine line_widget(pt1, pt2);
window_data_.window_.showWidget(line_id, line_widget);
}
/* -------------------------------------------------------------------------- */
// Visualize a 3D point cloud of unique 3D landmarks with its connectivity.
void Visualizer3D::visualizeMesh3D(const cv::Mat& map_points_3d,
const cv::Mat& polygons_mesh) {
cv::Mat colors(0, 1, CV_8UC3, cv::viz::Color::gray()); // Do not color mesh.
visualizeMesh3D(map_points_3d, colors, polygons_mesh);
}
/* -------------------------------------------------------------------------- */
// Visualize a 3D point cloud of unique 3D landmarks with its connectivity,
// and provide color for each polygon.
void Visualizer3D::visualizeMesh3D(const cv::Mat& map_points_3d,
const cv::Mat& colors,
const cv::Mat& polygons_mesh,
const cv::Mat& tcoords,
const cv::Mat& texture) {
// Check data
bool color_mesh = false;
if (colors.rows != 0) {
CHECK_EQ(map_points_3d.rows, colors.rows)
<< "Map points and Colors should have same number of rows. One"
" color per map point.";
LOG(ERROR) << "Coloring mesh!";
color_mesh = true;
}
if (tcoords.rows != 0) {
CHECK_EQ(map_points_3d.rows, tcoords.rows)
<< "Map points and tcoords should have same number of rows. One"
"tcoord per map point.";
CHECK(!texture.empty());
}
// No points/mesh to visualize.
if (map_points_3d.rows == 0 || polygons_mesh.rows == 0) {
return;
}
cv::viz::Mesh cv_mesh;
cv_mesh.cloud = map_points_3d.t();
cv_mesh.polygons = polygons_mesh;
cv_mesh.colors = color_mesh ? colors.t() : cv::Mat();
cv_mesh.tcoords = tcoords.t();
cv_mesh.texture = texture;
// Create a mesh widget.
cv::viz::WMesh mesh(cv_mesh);
// Decide mesh shading style.
switch (window_data_.mesh_shading_) {
case 0: {
mesh.setRenderingProperty(cv::viz::SHADING, cv::viz::SHADING_FLAT);
break;
}
case 1: {
mesh.setRenderingProperty(cv::viz::SHADING, cv::viz::SHADING_GOURAUD);
break;
}
case 2: {
mesh.setRenderingProperty(cv::viz::SHADING, cv::viz::SHADING_PHONG);
break;
}
default: {
break;
}
}
// Decide mesh representation style.
switch (window_data_.mesh_representation_) {
case 0: {
mesh.setRenderingProperty(cv::viz::REPRESENTATION,
cv::viz::REPRESENTATION_POINTS);
mesh.setRenderingProperty(cv::viz::POINT_SIZE, 1);
break;
}
case 1: {
mesh.setRenderingProperty(cv::viz::REPRESENTATION,
cv::viz::REPRESENTATION_SURFACE);
break;
}
case 2: {
mesh.setRenderingProperty(cv::viz::REPRESENTATION,
cv::viz::REPRESENTATION_WIREFRAME);
break;
}
default: {
break;
}
}
mesh.setRenderingProperty(cv::viz::AMBIENT, window_data_.mesh_ambient_);
mesh.setRenderingProperty(cv::viz::LIGHTING, window_data_.mesh_lighting_);
// Plot mesh.
window_data_.window_.showWidget("Mesh", mesh);
}
/* -------------------------------------------------------------------------- */
// Visualize a PLY from filename (absolute path).
void Visualizer3D::visualizePlyMesh(const std::string& filename) {
LOG(INFO) << "Showing ground truth mesh: " << filename;
// The ply file must have in the header a "element vertex" and
// a "element face" primitives, otherwise you'll get a
// "Cannot read geometry" error.
cv::viz::Mesh mesh(cv::viz::Mesh::load(filename));
if (mesh.polygons.size[1] == 0) {
LOG(WARNING) << "No polygons available for mesh, showing point cloud only.";
// If there are no polygons, convert to point cloud, otw there will be
// nothing displayed...
cv::viz::WCloud cloud(mesh.cloud, cv::viz::Color::lime());
cloud.setRenderingProperty(cv::viz::REPRESENTATION,
cv::viz::REPRESENTATION_POINTS);
cloud.setRenderingProperty(cv::viz::POINT_SIZE, 2);
cloud.setRenderingProperty(cv::viz::OPACITY, 0.1);
// Plot point cloud.
window_data_.window_.showWidget("Mesh from ply", cloud);
} else {
// Plot mesh.
window_data_.window_.showWidget("Mesh from ply", cv::viz::WMesh(mesh));
}
}
/* -------------------------------------------------------------------------- */
// Visualize a 3D point cloud of unique 3D landmarks with its connectivity.
/// Each triangle is colored depending on the cluster it is in, or gray if it
/// is in no cluster.
/// [in] clusters: a set of triangle clusters. The ids of the triangles must
/// match the order in polygons_mesh.
/// [in] map_points_3d: set of 3d points in the mesh, format is n rows, with
/// three columns (x, y, z).
/// [in] polygons_mesh: mesh faces, format is n rows, 1 column,
/// with [n id_a id_b id_c, ..., n /id_x id_y id_z], where n = polygon size
/// n=3 for triangles.
/// [in] color_mesh whether to color the mesh or not
/// [in] timestamp to store the timestamp of the mesh when logging the mesh.
void Visualizer3D::visualizeMesh3DWithColoredClusters(
const std::vector<Plane>& planes, const cv::Mat& map_points_3d,
const cv::Mat& polygons_mesh,
const bool visualize_mesh_with_colored_polygon_clusters,
const Timestamp& timestamp) {
if (visualize_mesh_with_colored_polygon_clusters) {
// Color the mesh.
cv::Mat colors;
colorMeshByClusters(planes, map_points_3d, polygons_mesh, &colors);
// Visualize the colored mesh.
visualizeMesh3D(map_points_3d, colors, polygons_mesh);
// Log the mesh.
if (FLAGS_log_mesh) {
logMesh(map_points_3d, colors, polygons_mesh, timestamp,
FLAGS_log_accumulated_mesh);
}
} else {
// Visualize the mesh with same colour.
visualizeMesh3D(map_points_3d, polygons_mesh);
}
}
/* -------------------------------------------------------------------------- */
// Visualize convex hull in 2D for set of points in triangle cluster,
// projected along the normal of the cluster.
void Visualizer3D::visualizeConvexHull(const TriangleCluster& cluster,
const cv::Mat& map_points_3d,
const cv::Mat& polygons_mesh) {
// Create a new coord system, which has as z the normal.
const cv::Point3f& normal = cluster.cluster_direction_;
// Find first axis of the coord system.
// Pick random x and y
static constexpr float random_x = 0.1;
static constexpr float random_y = 0.0;
// Find z, such that dot product with the normal is 0.
float z = -(normal.x * random_x + normal.y * random_y) / normal.z;
// Create new first axis:
cv::Point3f x_axis(random_x, random_y, z);
// Normalize new first axis:
x_axis /= cv::norm(x_axis);
// Create new second axis, by cross product normal to x_axis;
cv::Point3f y_axis = normal.cross(x_axis);
// Normalize just in case?
y_axis /= cv::norm(y_axis);
// Construct new cartesian coord system:
cv::Mat new_coordinates(3, 3, CV_32FC1);
new_coordinates.at<float>(0, 0) = x_axis.x;
new_coordinates.at<float>(0, 1) = x_axis.y;
new_coordinates.at<float>(0, 2) = x_axis.z;
new_coordinates.at<float>(1, 0) = y_axis.x;
new_coordinates.at<float>(1, 1) = y_axis.y;
new_coordinates.at<float>(1, 2) = y_axis.z;
new_coordinates.at<float>(2, 0) = normal.x;
new_coordinates.at<float>(2, 1) = normal.y;
new_coordinates.at<float>(2, 2) = normal.z;
std::vector<cv::Point2f> points_2d;
std::vector<float> z_s;
for (const size_t& triangle_id : cluster.triangle_ids_) {
size_t triangle_idx = std::round(triangle_id * 4);
if (triangle_idx + 3 >= polygons_mesh.rows) {
throw std::runtime_error(
"Visualizer3D: an id in triangle_ids_ is"
" too large.");
}
int32_t idx_1 = polygons_mesh.at<int32_t>(triangle_idx + 1);
int32_t idx_2 = polygons_mesh.at<int32_t>(triangle_idx + 2);
int32_t idx_3 = polygons_mesh.at<int32_t>(triangle_idx + 3);
// Project points to new coord system
cv::Point3f new_map_point_1 = // new_coordinates *
// map_points_3d.row(idx_1).t();
map_points_3d.at<cv::Point3f>(idx_1);
cv::Point3f new_map_point_2 = // new_coordinates *
// map_points_3d.row(idx_2).t();
map_points_3d.at<cv::Point3f>(idx_2);
cv::Point3f new_map_point_3 = // new_coordinates *
// map_points_3d.row(idx_3).t();
map_points_3d.at<cv::Point3f>(idx_3);
// Keep only 1st and 2nd component, aka the projection of the point on the
// plane.
points_2d.push_back(cv::Point2f(new_map_point_1.x, new_map_point_1.y));
z_s.push_back(new_map_point_1.z);
points_2d.push_back(cv::Point2f(new_map_point_2.x, new_map_point_2.y));
z_s.push_back(new_map_point_2.z);
points_2d.push_back(cv::Point2f(new_map_point_3.x, new_map_point_3.y));
z_s.push_back(new_map_point_3.z);
}
// Create convex hull.
if (points_2d.size() != 0) {
std::vector<int> hull_idx;
convexHull(cv::Mat(points_2d), hull_idx, false);
// Add the z component.
std::vector<cv::Point3f> hull_3d;
for (const int& idx : hull_idx) {
hull_3d.push_back(
cv::Point3f(points_2d.at(idx).x, points_2d.at(idx).y, z_s.at(idx)));
}
static constexpr bool visualize_hull_as_polyline = false;
if (visualize_hull_as_polyline) {
// Close the hull.
CHECK_NE(hull_idx.size(), 0);
hull_3d.push_back(cv::Point3f(points_2d.at(hull_idx.at(0)).x,
points_2d.at(hull_idx.at(0)).y,
z_s.at(hull_idx.at(0))));
// Visualize convex hull.
cv::viz::WPolyLine convex_hull(hull_3d);
window_data_.window_.showWidget("Convex hull", convex_hull);
} else {
// Visualize convex hull as a mesh of one polygon with multiple points.
if (hull_3d.size() > 2) {
cv::Mat polygon_hull = cv::Mat(4 * (hull_3d.size() - 2), 1, CV_32SC1);
size_t i = 1;
for (size_t k = 0; k + 3 < polygon_hull.rows; k += 4) {
polygon_hull.row(k) = 3;
polygon_hull.row(k + 1) = 0;
polygon_hull.row(k + 2) = static_cast<int>(i);
polygon_hull.row(k + 3) = static_cast<int>(i) + 1;
i++;
}
cv::viz::Color mesh_color;
getColorById(cluster.cluster_id_, &mesh_color);
cv::Mat normals = cv::Mat(0, 1, CV_32FC3);
for (size_t k = 0; k < hull_3d.size(); k++) {
normals.push_back(normal);
}
cv::Mat colors(hull_3d.size(), 1, CV_8UC3, mesh_color);
cv::viz::WMesh mesh(hull_3d, polygon_hull, colors.t(), normals.t());
window_data_.window_.showWidget("Convex hull", mesh);
}
}
}
}
/* -------------------------------------------------------------------------- */
// Visualize trajectory. Adds an image to the frustum if cv::Mat is not empty.
void Visualizer3D::visualizeTrajectory3D(const cv::Mat& frustum_image) {
if (trajectory_poses_3d_.size() == 0) { // no points to visualize
return;
}
// Show current camera pose.
static const cv::Matx33d K(458, 0.0, 360, 0.0, 458, 240, 0.0, 0.0, 1.0);
cv::viz::WCameraPosition cam_widget_ptr;
if (frustum_image.empty()) {
cam_widget_ptr = cv::viz::WCameraPosition(K, 1.0, cv::viz::Color::white());
} else {
cam_widget_ptr = cv::viz::WCameraPosition(K, frustum_image, 1.0,
cv::viz::Color::white());
}
window_data_.window_.showWidget(
"Camera Pose with Frustum", cam_widget_ptr, trajectory_poses_3d_.back());
window_data_.window_.setWidgetPose("Camera Pose with Frustum",
trajectory_poses_3d_.back());
// Option A: This does not work very well.
// window_data_.window_.resetCameraViewpoint("Camera Pose with Frustum");
// Viewer is our viewpoint, camera the pose estimate (frustum).
static constexpr bool follow_camera = false;
if (follow_camera) {
cv::Affine3f camera_in_world_coord = trajectory_poses_3d_.back();
// Option B: specify viewer wrt camera. Works, but motion is non-smooth.
// cv::Affine3f viewer_in_camera_coord (Vec3f(
// -0.3422019, -0.3422019, 1.5435732),
// Vec3f(3.0, 0.0, -4.5));
// cv::Affine3f viewer_in_world_coord =
// viewer_in_camera_coord.concatenate(camera_in_world_coord);
// Option C: use "look-at" camera parametrization.
// Works, but motion is non-smooth as well.
cv::Vec3d cam_pos(-6.0, 0.0, 6.0);
cv::Vec3d cam_focal_point(camera_in_world_coord.translation());
cv::Vec3d cam_y_dir(0.0, 0.0, -1.0);
cv::Affine3f cam_pose =
cv::viz::makeCameraPose(cam_pos, cam_focal_point, cam_y_dir);
window_data_.window_.setViewerPose(cam_pose);
// window_data_.window_.setViewerPose(viewer_in_world_coord);
}
// Create a Trajectory frustums widget.
std::vector<cv::Affine3f> trajectory_frustums(
trajectory_poses_3d_.end() -
std::min(trajectory_poses_3d_.size(), size_t(10u)),
trajectory_poses_3d_.end());
cv::viz::WTrajectoryFrustums trajectory_frustums_widget(
trajectory_frustums, K, 0.2, cv::viz::Color::red());
window_data_.window_.showWidget("Trajectory Frustums",
trajectory_frustums_widget);
// Create a Trajectory widget. (argument can be PATH, FRAMES, BOTH).
std::vector<cv::Affine3f> trajectory(trajectory_poses_3d_.begin(),
trajectory_poses_3d_.end());
cv::viz::WTrajectory trajectory_widget(trajectory, cv::viz::WTrajectory::PATH,
1.0, cv::viz::Color::red());
window_data_.window_.showWidget("Trajectory", trajectory_widget);
}
/* -------------------------------------------------------------------------- */
// Remove widget. True if successful, false if not.
bool Visualizer3D::removeWidget(const std::string& widget_id) {
try {
window_data_.window_.removeWidget(widget_id);
return true;
} catch (const cv::Exception& e) {
VLOG(20) << e.what();
LOG(ERROR) << "Widget with id: " << widget_id.c_str()
<< " is not in window.";
} catch (...) {
LOG(ERROR) << "Unrecognized exception when using "
"window_data_.window_.removeWidget() "
<< "with widget with id: " << widget_id.c_str();
}
return false;
}
/* -------------------------------------------------------------------------- */
// Visualize line widgets from plane to lmks.
// Point key is required to avoid duplicated lines!
void Visualizer3D::visualizePlaneConstraints(const PlaneId& plane_id,
const gtsam::Point3& normal,
const double& distance,
const LandmarkId& lmk_id,
const gtsam::Point3& point) {
PlaneIdMap::iterator plane_id_it = plane_id_map_.find(plane_id);
LmkIdToLineIdMap* lmk_id_to_line_id_map_ptr = nullptr;
LineNr* line_nr_ptr = nullptr;
if (plane_id_it != plane_id_map_.end()) {
// We already have this plane id stored.
lmk_id_to_line_id_map_ptr = &(plane_id_it->second);
// Ensure we also have the line nr stored.
const auto& line_nr_it = plane_to_line_nr_map_.find(plane_id);
CHECK(line_nr_it != plane_to_line_nr_map_.end());
line_nr_ptr = &(line_nr_it->second);
} else {
// We have not this plane id stored.
// Create it by calling default ctor.
lmk_id_to_line_id_map_ptr = &(plane_id_map_[plane_id]);
plane_id_it = plane_id_map_.find(plane_id);
DCHECK(plane_id_it != plane_id_map_.end());
// Also start line nr to 0.
plane_to_line_nr_map_[plane_id] = 0;
DCHECK(plane_to_line_nr_map_.find(plane_id) != plane_to_line_nr_map_.end());
line_nr_ptr = &(plane_to_line_nr_map_[plane_id]);
}
CHECK_NOTNULL(lmk_id_to_line_id_map_ptr);
CHECK_NOTNULL(line_nr_ptr);
// TODO should use map from line_id_to_lmk_id as well,
// to remove the line_ids which are not having a lmk_id...
const auto& lmk_id_to_line_id = lmk_id_to_line_id_map_ptr->find(lmk_id);
if (lmk_id_to_line_id == lmk_id_to_line_id_map_ptr->end()) {
// We have never drawn this line.
// Store line nr (as line id).
(*lmk_id_to_line_id_map_ptr)[lmk_id] = *line_nr_ptr;
std::string line_id = "Line " + std::to_string((int)plane_id_it->first) +
std::to_string((int)(*line_nr_ptr));
// Draw it.
drawLineFromPlaneToPoint(line_id, normal.x(), normal.y(), normal.z(),
distance, point.x(), point.y(), point.z());
// Augment line_nr for next line_id.
(*line_nr_ptr)++;
} else {
// We have drawn this line before.
// Update line.
std::string line_id = "Line " + std::to_string((int)plane_id_it->first) +
std::to_string((int)lmk_id_to_line_id->second);
updateLineFromPlaneToPoint(line_id, normal.x(), normal.y(), normal.z(),
distance, point.x(), point.y(), point.z());
}
}
/* -------------------------------------------------------------------------- */
// Remove line widgets from plane to lmks, for lines that are not pointing
// to any lmk_id in lmk_ids.
void Visualizer3D::removeOldLines(const LandmarkIds& lmk_ids) {
for (PlaneIdMap::value_type& plane_id_pair : plane_id_map_) {
LmkIdToLineIdMap& lmk_id_to_line_id_map = plane_id_pair.second;
for (LmkIdToLineIdMap::iterator lmk_id_to_line_id_it =
lmk_id_to_line_id_map.begin();
lmk_id_to_line_id_it != lmk_id_to_line_id_map.end();) {
if (std::find(lmk_ids.begin(), lmk_ids.end(),
lmk_id_to_line_id_it->first) == lmk_ids.end()) {
// We did not find the lmk_id of the current line in the list
// of lmk_ids...
// Delete the corresponding line.
std::string line_id = "Line " +
std::to_string((int)plane_id_pair.first) +
std::to_string((int)lmk_id_to_line_id_it->second);
removeWidget(line_id);
// Delete the corresponding entry in the map from lmk id to line id.
lmk_id_to_line_id_it =
lmk_id_to_line_id_map.erase(lmk_id_to_line_id_it);
} else {
lmk_id_to_line_id_it++;
}
}
}
}
/* -------------------------------------------------------------------------- */
// Remove line widgets from plane to lmks.
void Visualizer3D::removePlaneConstraintsViz(const PlaneId& plane_id) {
PlaneIdMap::iterator plane_id_it = plane_id_map_.find(plane_id);
if (plane_id_it != plane_id_map_.end()) {
VLOG(0) << "Removing line constraints for plane with id: " << plane_id;
for (const auto& lmk_id_to_line_id : plane_id_it->second) {
std::string line_id = "Line " + std::to_string((int)plane_id_it->first) +
std::to_string((int)lmk_id_to_line_id.second);
removeWidget(line_id);
}
// Delete the corresponding entry in the map for this plane.
plane_id_map_.erase(plane_id_it);
// Same for the map holding the line nr.
auto line_nr_it = plane_to_line_nr_map_.find(plane_id);
CHECK(line_nr_it != plane_to_line_nr_map_.end());
plane_to_line_nr_map_.erase(line_nr_it);
} else {
// Careful if we did not find, might be because it is a newly segmented
// plane.
LOG(WARNING) << "Could not find plane with id: " << plane_id
<< " from plane_id_map_...";
}
}
/* -------------------------------------------------------------------------- */
// Remove plane widget.
void Visualizer3D::removePlane(const PlaneId& plane_index,
const bool& remove_plane_label) {
const std::string& plane_id_for_viz = "Plane " + std::to_string(plane_index);
if (is_plane_id_in_window_.find(plane_index) !=
is_plane_id_in_window_.end() &&
is_plane_id_in_window_[plane_index]) {
if (removeWidget(plane_id_for_viz)) {
if (remove_plane_label) {
if (!removeWidget(plane_id_for_viz + "_label")) {
LOG(WARNING) << "Did you disable labels of planes?, then also"
"disable label removal. Otherwise, did you change "
"the id of the label? then change it here as well.";
}
}
is_plane_id_in_window_[plane_index] = false;
} else {
is_plane_id_in_window_[plane_index] = true;
}
}
}
/* -------------------------------------------------------------------------- */
// Add pose to the previous trajectory.
void Visualizer3D::addPoseToTrajectory(const gtsam::Pose3& current_pose_gtsam) {
trajectory_poses_3d_.push_back(
UtilsOpenCV::gtsamPose3ToCvAffine3d(current_pose_gtsam));
if (FLAGS_displayed_trajectory_length > 0) {
while (trajectory_poses_3d_.size() > FLAGS_displayed_trajectory_length) {
trajectory_poses_3d_.pop_front();
}
}
}
/* -------------------------------------------------------------------------- */
/** Render window with drawn objects/widgets.
* @param wait_time Amount of time in milliseconds for the event loop to keep
* running.
* @param force_redraw If true, window renders.
*/
void Visualizer3D::renderWindow(int wait_time, bool force_redraw) {
window_data_.window_.spinOnce(wait_time, force_redraw);
}
/* -------------------------------------------------------------------------- */
// Get a screenshot of the window.
void Visualizer3D::getScreenshot(const std::string& filename) {
LOG(WARNING) << "Taking a screenshot of the window, saved in: " + filename;
window_data_.window_.saveScreenshot(filename);
}
/* -------------------------------------------------------------------------- */
void Visualizer3D::setOffScreenRendering() {
window_data_.window_.setOffScreenRendering();
}
/* -------------------------------------------------------------------------- */
// Log mesh to ply file.
void Visualizer3D::logMesh(const cv::Mat& map_points_3d, const cv::Mat& colors,
const cv::Mat& polygons_mesh,
const Timestamp& timestamp,
bool log_accumulated_mesh) {
/// Log the mesh in a ply file.
static Timestamp last_timestamp = timestamp;
static const Timestamp first_timestamp = timestamp;
if ((timestamp - last_timestamp) >
6500000000) { // Log every 6 seconds approx. (a little bit more than
// time-horizon)
LOG(WARNING) << "Logging mesh every (ns) = " << timestamp - last_timestamp;
CHECK(logger_);
logger_->logMesh(
map_points_3d, colors, polygons_mesh, timestamp, log_accumulated_mesh);
last_timestamp = timestamp;
}
}
/* -------------------------------------------------------------------------- */
// Input the mesh points and triangle clusters, and
// output colors matrix for mesh visualizer.
// This will color the point with the color of the last plane having it.
void Visualizer3D::colorMeshByClusters(const std::vector<Plane>& planes,
const cv::Mat& map_points_3d,
const cv::Mat& polygons_mesh,
cv::Mat* colors) const {
CHECK_NOTNULL(colors);
*colors = cv::Mat(map_points_3d.rows, 1, CV_8UC3, cv::viz::Color::gray());
// The code below assumes triangles as polygons.
static constexpr bool log_landmarks = false;
for (const Plane& plane : planes) {
const TriangleCluster& cluster = plane.triangle_cluster_;
// Decide color for cluster.
cv::viz::Color cluster_color = cv::viz::Color::gray();
getColorById(cluster.cluster_id_, &cluster_color);
for (const size_t& triangle_id : cluster.triangle_ids_) {
size_t triangle_idx = std::round(triangle_id * 4);
DCHECK_LE(triangle_idx + 3, polygons_mesh.rows)
<< "Visualizer3D: an id in triangle_ids_ is too large.";
int32_t idx_1 = polygons_mesh.at<int32_t>(triangle_idx + 1);
int32_t idx_2 = polygons_mesh.at<int32_t>(triangle_idx + 2);
int32_t idx_3 = polygons_mesh.at<int32_t>(triangle_idx + 3);
// Overrides potential previous color.
colors->row(idx_1) = cluster_color;
colors->row(idx_2) = cluster_color;
colors->row(idx_3) = cluster_color;
}
}
}
/* -------------------------------------------------------------------------- */
// Decide color of the cluster depending on its id.
void Visualizer3D::getColorById(const size_t& id, cv::viz::Color* color) const {
CHECK_NOTNULL(color);
switch (id) {
case 0: {
*color = cv::viz::Color::red();
break;
}
case 1: {
*color = cv::viz::Color::green();
break;
}
case 2: {
*color = cv::viz::Color::blue();
break;
}
default: {
*color = cv::viz::Color::gray();
break;
}
}
}
/* -------------------------------------------------------------------------- */
// Draw a line from lmk to plane center.
void Visualizer3D::drawLineFromPlaneToPoint(
const std::string& line_id, const double& plane_n_x,
const double& plane_n_y, const double& plane_n_z, const double& plane_d,
const double& point_x, const double& point_y, const double& point_z) {
const cv::Point3d center(plane_d * plane_n_x, plane_d * plane_n_y,
plane_d * plane_n_z);
const cv::Point3d point(point_x, point_y, point_z);
drawLine(line_id, center, point);
}
/* -------------------------------------------------------------------------- */
// Update line from lmk to plane center.
void Visualizer3D::updateLineFromPlaneToPoint(
const std::string& line_id, const double& plane_n_x,
const double& plane_n_y, const double& plane_n_z, const double& plane_d,
const double& point_x, const double& point_y, const double& point_z) {
removeWidget(line_id);
drawLineFromPlaneToPoint(line_id, plane_n_x, plane_n_y, plane_n_z, plane_d,
point_x, point_y, point_z);
}
/* -------------------------------------------------------------------------- */
void Visualizer3D::keyboardCallback(const cv::viz::KeyboardEvent& event,
void* t) {
WindowData* window_data = (Visualizer3D::WindowData*)t;
if (event.action == cv::viz::KeyboardEvent::Action::KEY_DOWN) {
toggleFreezeScreenKeyboardCallback(event.code, *window_data);
setMeshRepresentation(event.code, *window_data);
setMeshShadingCallback(event.code, *window_data);
setMeshAmbientCallback(event.code, *window_data);
setMeshLightingCallback(event.code, *window_data);
getViewerPoseKeyboardCallback(event.code, *window_data);
getCurrentWindowSizeKeyboardCallback(event.code, *window_data);
getScreenshotCallback(event.code, *window_data);
}
}
/* -------------------------------------------------------------------------- */
void Visualizer3D::recordVideo() {
static int i = 0u;
static const std::string dir_path = ".";
static const std::string dir_name = "3d_viz_video";
static const std::string dir_full_path =
common::pathAppend(dir_path, dir_name);
if (i == 0u) CHECK(common::createDirectory(dir_path, dir_name));
std::string screenshot_path =
common::pathAppend(dir_full_path, std::to_string(i));
i++;
LOG(WARNING) << "Recording video sequence for 3d Viz, "
<< "current frame saved in: " + screenshot_path;
window_data_.window_.saveScreenshot(screenshot_path);
LOG(ERROR) << "WTF";
}
} // namespace VIO
| 42.124386 | 86 | 0.608147 | [
"mesh",
"geometry",
"render",
"vector",
"3d"
] |
5ea47bac7f846b301edba658f36033d95ec7894d | 5,985 | cc | C++ | tensorflow/cc/framework/gradients_test.cc | yxiong/tensorflow | f71cc62282bf2e066f9ebd08cf3f605fc98c6e41 | [
"Apache-2.0"
] | 6 | 2016-09-07T18:38:41.000Z | 2020-01-12T23:01:03.000Z | tensorflow/cc/framework/gradients_test.cc | yxiong/tensorflow | f71cc62282bf2e066f9ebd08cf3f605fc98c6e41 | [
"Apache-2.0"
] | null | null | null | tensorflow/cc/framework/gradients_test.cc | yxiong/tensorflow | f71cc62282bf2e066f9ebd08cf3f605fc98c6e41 | [
"Apache-2.0"
] | 8 | 2017-06-08T09:46:06.000Z | 2021-06-20T14:03:19.000Z | /* Copyright 2016 The TensorFlow 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 "tensorflow/cc/framework/gradients.h"
#include "tensorflow/cc/framework/grad_op_registry.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/graph/equal_graph_def.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
using namespace ops; // NOLINT(build/namespaces)
namespace {
// TODO(andydavis) Add more unit tests once more gradient functions are ported.
// TODO(andydavis) Add unit test that adds gradients to compute two Outputs,
// where the gradient w.r.t. one Output depends on the other.
class GradientsTest : public ::testing::Test {
protected:
GradientsTest()
: scope_expected_(Scope::NewRootScope()),
scope_test_(Scope::NewRootScope()) {}
void CompareTestAndExpectedGraphs() {
GraphDef gdef_test;
TF_EXPECT_OK(scope_test_.ToGraphDef(&gdef_test));
GraphDef gdef_exp;
TF_EXPECT_OK(scope_expected_.ToGraphDef(&gdef_exp));
TF_EXPECT_GRAPH_EQ(gdef_test, gdef_exp);
}
Scope scope_expected_;
Scope scope_test_;
};
// EX.
// ^ ^
// dy| dx| // MatMul Gradient Graph
// | |
// MatMul_1 MatMul_2
// ^ ^ ^ ^
// | |----------| |
// | ^ |
// | dz| |
// | | |
// | Const_3 |
// | |
// | ^ |
// | z| | // MatMul Forward Graph
// | | |
// | MatMul_0 |
// | / \ |
// | ^ ^ |
// | | | |
// |---x| y|---|
// | |
// | |
// Const_0 Const_1
//
TEST_F(GradientsTest, OneMatMul) {
bool expected = false;
for (Scope scope : {scope_test_, scope_expected_}) {
// Construct forward graph.
auto x = Const(scope, {{1.0, 2.0}, {3.0, 4.0}});
auto y = Const(scope, {{1.0, 0.0}, {0.0, 1.0}});
auto z = MatMul(scope, x, y);
TF_EXPECT_OK(scope.status());
CHECK_NOTNULL(z.node());
if (expected) {
// Construct backward graph.
auto dz = Const(scope, {{1.0, 1.0}, {1.0, 1.0}});
auto dx = MatMul(scope, dz, y, MatMul::TransposeB(true));
auto dy = MatMul(scope, x, dz, MatMul::TransposeA(true));
} else {
// Call AddSymbolicGradients.
auto dz = Const(scope, {{1.0, 1.0}, {1.0, 1.0}});
std::vector<ops::Output> grad_outputs;
TF_EXPECT_OK(
AddSymbolicGradients(scope, {z}, {x, y}, {dz}, &grad_outputs));
}
expected = true;
}
CompareTestAndExpectedGraphs();
}
TEST_F(GradientsTest, TwoMatMuls_Chained) {
bool expected = false;
for (Scope scope : {scope_test_, scope_expected_}) {
// Construct forward graph.
auto u = Const(scope, {{1.0, 2.0}, {3.0, 4.0}});
auto v = Const(scope, {{1.0, 0.0}, {0.0, 1.0}});
auto x = MatMul(scope, u, v);
auto y = Const(scope, {{1.0, 0.0}, {0.0, 1.0}});
auto z = MatMul(scope, x, y);
TF_EXPECT_OK(scope.status());
CHECK_NOTNULL(z.node());
if (expected) {
// Construct backward graph.
auto dz = Const(scope, {{1.0, 1.0}, {1.0, 1.0}});
auto dx = MatMul(scope, dz, y, MatMul::TransposeB(true));
auto dy = MatMul(scope, x, dz, MatMul::TransposeA(true));
auto du = MatMul(scope, dx, v, MatMul::TransposeB(true));
auto dv = MatMul(scope, u, dx, MatMul::TransposeA(true));
} else {
// Call AddSymbolicGradients.
auto dz = Const(scope, {{1.0, 1.0}, {1.0, 1.0}});
std::vector<ops::Output> grad_outputs;
TF_EXPECT_OK(
AddSymbolicGradients(scope, {z}, {u, v}, {dz}, &grad_outputs));
}
expected = true;
}
CompareTestAndExpectedGraphs();
}
TEST_F(GradientsTest, TwoMatMuls_Independent) {
bool expected = false;
for (Scope scope : {scope_test_, scope_expected_}) {
// Construct forward graph.
auto t = Const(scope, {{1.0, 2.0}, {3.0, 4.0}});
auto u = Const(scope, {{1.0, 0.0}, {0.0, 1.0}});
auto v = MatMul(scope, t, u);
TF_EXPECT_OK(scope.status());
CHECK_NOTNULL(v.node());
auto x = Const(scope, {{5.0, 6.0}, {7.0, 8.0}});
auto y = Const(scope, {{1.0, 0.0}, {0.0, 1.0}});
auto z = MatMul(scope, x, y);
TF_EXPECT_OK(scope.status());
CHECK_NOTNULL(z.node());
if (expected) {
// Construct backward graph.
auto dv = Const(scope, {{1.0, 1.0}, {1.0, 1.0}});
auto dt = MatMul(scope, dv, u, MatMul::TransposeB(true));
auto du = MatMul(scope, t, dv, MatMul::TransposeA(true));
auto dz = Const(scope, {{1.0, 1.0}, {1.0, 1.0}});
auto dx = MatMul(scope, dz, y, MatMul::TransposeB(true));
auto dy = MatMul(scope, x, dz, MatMul::TransposeA(true));
} else {
// Call AddSymbolicGradients.
auto dv = Const(scope_test_, {{1.0, 1.0}, {1.0, 1.0}});
auto dz = Const(scope_test_, {{1.0, 1.0}, {1.0, 1.0}});
std::vector<ops::Output> grad_outputs;
TF_EXPECT_OK(AddSymbolicGradients(scope, {v, z}, {t, u, x, y}, {dv, dz},
&grad_outputs));
}
expected = true;
}
CompareTestAndExpectedGraphs();
}
} // namespace
} // namespace tensorflow
| 33.813559 | 80 | 0.576274 | [
"vector"
] |
5ea62f402c0e3b8258fd46d4d80b31a16477836b | 1,066 | cpp | C++ | ConStorm/src/files/load.cpp | drake200120xx/ConStorm | bfc47b6424154e8258d375d0a5eaff687d0cad27 | [
"Apache-2.0"
] | null | null | null | ConStorm/src/files/load.cpp | drake200120xx/ConStorm | bfc47b6424154e8258d375d0a5eaff687d0cad27 | [
"Apache-2.0"
] | null | null | null | ConStorm/src/files/load.cpp | drake200120xx/ConStorm | bfc47b6424154e8258d375d0a5eaff687d0cad27 | [
"Apache-2.0"
] | null | null | null | /*
Code by Drake Johnson
*/
#include "../../include/cons/files/load.hpp"
namespace fs = std::filesystem;
static std::mutex s_files_mutex;
static void load_file(
cons::FilesLoad::file_vec* output_vec,
const fs::path path,
const cons::File::openmode om)
{
std::lock_guard<std::mutex> lock(s_files_mutex);
output_vec->emplace_back(path, om);
}
namespace cons
{
FilesLoad::FilesLoad(
const std::vector<fs::path>& file_paths,
File::openmode open_mode)
{
m_files.reserve(file_paths.size());
m_futures.reserve(file_paths.size());
for (const auto& file : file_paths)
m_futures.push_back(
std::async(
std::launch::async,
load_file, &m_files, file, open_mode)
);
}
FilesLoad::FilesLoad(
const std::vector<std::string>& file_paths,
File::openmode open_mode)
{
m_files.reserve(file_paths.size());
m_futures.reserve(file_paths.size());
for (const auto& file_str : file_paths)
m_futures.push_back(
std::async(
std::launch::async,
load_file, &m_files, file_str, open_mode)
);
}
} // namespace cons
| 21.755102 | 49 | 0.688555 | [
"vector"
] |
5ea671e2a0a7ac4c8783728841cdebb708bb4913 | 3,894 | cpp | C++ | 03 Software/examples/pixels/pixelFunLoop.cpp | lloydrichards/mimirOpen | 95a42fb99cd2f9e0d041d7cbb975bc6adb6646b4 | [
"MIT"
] | null | null | null | 03 Software/examples/pixels/pixelFunLoop.cpp | lloydrichards/mimirOpen | 95a42fb99cd2f9e0d041d7cbb975bc6adb6646b4 | [
"MIT"
] | 7 | 2020-07-30T10:29:34.000Z | 2020-11-11T18:02:58.000Z | 03 Software/examples/pixels/pixelFunLoop.cpp | lloydrichards/mimirOpen | 95a42fb99cd2f9e0d041d7cbb975bc6adb6646b4 | [
"MIT"
] | null | null | null | // NeoPixelFunFadeInOut
// This example will randomly pick a color and fade all pixels to that color, then
// it will fade them to black and restart over
//
// This example demonstrates the use of a single animation channel to animate all
// the pixels at once.
//
#include <NeoPixelBus.h>
#include <NeoPixelAnimator.h>
const uint16_t PixelCount = 5; // make sure to set this to the number of pixels in your strip
const uint8_t PixelPin = 33; // make sure to set this to the correct pin, ignored for Esp8266
const uint8_t AnimationChannels = 1; // we only need one as all the pixels are animated at once
NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);
// For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use.
// There are other Esp8266 alternative methods that provide more pin options, but also have
// other side effects.
// for details see wiki linked here https://github.com/Makuna/NeoPixelBus/wiki/ESP8266-NeoMethods
NeoPixelAnimator animations(AnimationChannels); // NeoPixel animation management object
boolean fadeToColor = true; // general purpose variable used to store effect state
// what is stored for state is specific to the need, in this case, the colors.
// basically what ever you need inside the animation update function
struct MyAnimationState
{
RgbColor StartingColor;
RgbColor EndingColor;
};
// one entry per pixel to match the animation timing manager
MyAnimationState animationState[AnimationChannels];
void SetRandomSeed()
{
uint32_t seed;
// random works best with a seed that can use 31 bits
// analogRead on a unconnected pin tends toward less than four bits
seed = analogRead(0);
delay(1);
for (int shifts = 3; shifts < 31; shifts += 3)
{
seed ^= analogRead(0) << shifts;
delay(1);
}
randomSeed(seed);
}
// simple blend function
void BlendAnimUpdate(const AnimationParam& param)
{
// this gets called for each animation on every time step
// progress will start at 0.0 and end at 1.0
// we use the blend function on the RgbColor to mix
// color based on the progress given to us in the animation
RgbColor updatedColor = RgbColor::LinearBlend(
animationState[param.index].StartingColor,
animationState[param.index].EndingColor,
param.progress);
// apply the color to the strip
for (uint16_t pixel = 0; pixel < PixelCount; pixel++)
{
strip.SetPixelColor(pixel, updatedColor);
}
}
void FadeInFadeOutRinseRepeat(float luminance)
{
if (fadeToColor)
{
// Fade upto a random color
// we use HslColor object as it allows us to easily pick a hue
// with the same saturation and luminance so the colors picked
// will have similiar overall brightness
RgbColor target = HslColor(random(360) / 360.0f, 1.0f, luminance);
uint16_t time = random(800, 2000);
animationState[0].StartingColor = strip.GetPixelColor(0);
animationState[0].EndingColor = target;
animations.StartAnimation(0, time, BlendAnimUpdate);
}
else
{
// fade to black
uint16_t time = random(600, 700);
animationState[0].StartingColor = strip.GetPixelColor(0);
animationState[0].EndingColor = RgbColor(0);
animations.StartAnimation(0, time, BlendAnimUpdate);
}
// toggle to the next effect state
fadeToColor = !fadeToColor;
}
void setup()
{
strip.Begin();
strip.Show();
SetRandomSeed();
}
void loop()
{
if (animations.IsAnimating())
{
// the normal loop just needs these two to run the active animations
animations.UpdateAnimations();
strip.Show();
}
else
{
// no animation runnning, start some
//
FadeInFadeOutRinseRepeat(0.2f); // 0.0 = black, 0.25 is normal, 0.5 is bright
}
} | 30.661417 | 98 | 0.687982 | [
"object"
] |
5ea7fe15db6b0d7593b24dc7a90a815d1c2ade7a | 11,096 | hpp | C++ | src/underscore.hpp | Nachooking/underscore_cpp | 71ec1ae6c62f5e9609a7d316f2e58ce5b45559ce | [
"MIT"
] | 7 | 2018-08-26T15:25:49.000Z | 2019-01-28T11:57:24.000Z | src/underscore.hpp | mohitanand001/underscore_cpp | e214da7f97ee492e226a27f6773c7dbf191b3ce9 | [
"MIT"
] | 67 | 2018-08-26T14:16:27.000Z | 2019-12-13T21:05:50.000Z | src/underscore.hpp | mohitanand001/underscore_cpp | e214da7f97ee492e226a27f6773c7dbf191b3ce9 | [
"MIT"
] | 38 | 2018-08-26T15:25:53.000Z | 2019-12-12T15:46:22.000Z | #pragma once
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <map>
#include <set>
#include <vector>
namespace _
{
template <typename Iterator, typename Predicate>
bool any(Iterator begin, const Iterator end, Predicate predicate)
{
while (begin != end)
{
if (predicate(*begin)) return true;
begin++;
}
return false;
}
template <typename Container, typename Predicate>
bool any(const Container &container, Predicate predicate)
{
return any(container.begin(), container.end(), predicate);
}
template <typename Iterator, typename Data>
bool contains(Iterator begin, const Iterator end, const Data &data)
{
while (begin != end)
{
if (*begin == data) return true;
begin++;
}
return false;
}
template <typename Container, typename Data>
bool contains(const Container &container, const Data &data)
{
return contains(container.begin(), container.end(), data);
}
template <typename Iterator, typename X, typename Y>
bool contains(Iterator begin, Iterator end, const std::pair<X, Y> &p)
{
while (begin != end)
{
if ((*begin).first == p.first and (*begin).second == p.second) return true;
begin++;
}
return false;
}
template <typename Container, typename X, typename Y>
bool contains(const Container &container, const std::pair<X, Y> &p)
{
return contains(container.begin(), container.end(), p);
}
template <typename Iterator, typename Predicate>
size_t count_by(Iterator begin, Iterator end, Predicate predicate)
{
size_t count = 0;
while (begin != end)
{
if (predicate(*begin))
{
count++;
}
begin++;
}
return count;
}
template <typename Container, typename Predicate>
size_t count_by(const Container &container, Predicate predicate)
{
return count_by(container.begin(), container.end(), predicate);
}
// forward declaration out of alphabetical order b/c count_by uses group_by
template <typename Container, typename Function>
auto group_by(Container &container, Function function)
-> std::map<decltype(function(*container.begin())),
std::vector<typename Container::value_type>>;
template <typename Container, typename Function>
auto count_by(Container &container, Function function)
-> std::map<decltype(function(*container.begin())), size_t>
{
std::map<decltype(function(*container.begin())), size_t> result;
std::map<decltype(function(*container.begin())),
std::vector<typename Container::value_type>>
grouped_by = group_by(container, function);
for (auto &kv : grouped_by)
{
result[kv.first] = kv.second.size();
}
return result;
}
template <typename Iterator, typename Function>
void each(Iterator begin, const Iterator end, Function function)
{
while (begin != end)
{
function(*begin);
begin++;
}
}
template <typename Container, typename Function>
void each(const Container &container, Function function)
{
each(container.begin(), container.end(), function);
}
template <typename Iterator, typename Predicate>
bool every(Iterator begin, const Iterator end, Predicate predicate)
{
while (begin != end)
{
if (predicate(*begin) == false) return false;
begin++;
}
return true;
}
template <typename Container, typename Predicate>
bool every(const Container &container, Predicate predicate)
{
return every(container.begin(), container.end(), predicate);
}
template <typename Container, typename Function>
Container filter_accept(const Container &container, Function function)
{
Container result;
typename Container::iterator first_begin, result_begin = result.begin();
for (first_begin = container.begin(); first_begin != container.end(); ++first_begin)
{
if (function(*first_begin))
{
result.insert(result.end(), *first_begin);
}
}
return result;
}
template <typename Container, typename Function>
Container filter_reject(const Container &container, Function function)
{
Container result;
typename Container::iterator first_begin, result_begin = result.begin();
for (first_begin = container.begin(); first_begin != container.end(); ++first_begin)
{
if (!function(*first_begin))
{
result.insert(result.end(), *first_begin);
}
}
return result;
}
template <typename Iterator, typename Predicate>
Iterator find_if(Iterator begin, Iterator end, Predicate predicate)
{
while (begin != end)
{
if (predicate(*begin))
{
return begin;
}
begin++;
}
return end;
}
template <typename Iterator, typename Container, typename Predicate>
Iterator find_if(const Container &container, Predicate predicate)
{
return find_if(container.begin(), container.end(), predicate);
}
template <typename Iterator, typename Predicate>
Iterator find_if_not(Iterator begin, Iterator end, Predicate predicate)
{
while (begin != end)
{
if (!predicate(*begin))
{
return begin;
}
begin++;
}
return end;
}
template <typename Iterator, typename Container, typename Predicate>
Iterator find_if_not(const Container &container, Predicate predicate)
{
return find_if_not(container.begin(), container.end(), predicate);
}
template <typename Container, typename Function>
auto group_by(Container &container, Function function)
-> std::map<decltype(function(*container.begin())),
std::vector<typename Container::value_type>>
{
std::map<decltype(function(*container.begin())),
std::vector<typename Container::value_type>>
result;
typename Container::iterator begin = container.begin();
typename Container::iterator end = container.end();
while (begin != end)
{
result[function(*begin)].push_back(*begin);
begin++;
}
return result;
}
template <typename Container>
Container intersect(const Container &container)
{
return container;
}
template <typename Container>
Container intersect(const Container &container1, const Container &container2)
{
Container result, c1, c2;
c1 = container1;
c2 = container2;
sort(c1.begin(), c1.end());
sort(c2.begin(), c2.end());
typename Container::const_iterator first_begin = c1.begin(),
second_begin = c2.begin();
while (first_begin != c1.end() && second_begin != c2.end())
{
if (*first_begin == *second_begin)
{
result.insert(result.end(), *first_begin);
first_begin++;
second_begin++;
}
else if (*first_begin > *second_begin)
{
second_begin++;
}
else
{
first_begin++;
}
}
return result;
}
template <typename Container, typename... Containers>
Container intersect(const Container &container1, const Container &container2, Containers ... others)
{
return intersect(intersect(container1, container2), intersect(others...));
}
template <typename Container>
typename Container::const_iterator max(const Container &container)
{
if (container.begin() == container.end()) return container.end();
typename Container::const_iterator max = container.begin();
for (typename Container::const_iterator it = ++container.begin(); it != container.end();
++it)
{
if ((*max) < (*it)) max = it;
}
return max;
}
template <typename Container>
typename Container::const_iterator min(const Container &container)
{
if (container.begin() == container.end()) return container.end();
typename Container::const_iterator min = container.begin();
for (typename Container::const_iterator it = ++container.begin(); it != container.end();
++it)
{
if ((*min) > (*it)) min = it;
}
return min;
}
template <typename Container, typename Operator, typename Operand>
Operand reduce(const Container &container, Operator operate, Operand base)
{
Operand result = base;
for (typename Container::const_iterator it = container.begin(); it != container.end(); ++it)
result = operate(result, *it);
return result;
}
template <typename Container>
Container set_union(const Container &container1)
{
return container1;
}
template <typename Container>
Container set_union(const Container &container1, const Container &container2)
{
if (container1.size() > 0 && container2.size() == 0)
{
return container1;
}
if (container2.size() > 0 && container1.size() == 0)
{
return container2;
}
if (container1 == container2)
{
return container1;
}
Container result;
std::set<typename Container::value_type> uniques;
for (auto elem : container1)
{
uniques.emplace(elem);
}
for (auto elem : container2)
{
uniques.emplace(elem);
}
for (auto elem : uniques)
{
result.push_back(elem);
}
return result;
}
// TODO: Do the above algorithm with all containers provided at once - instead
// of recursively calling
template <typename Container, typename... Containers>
Container set_union(const Container &container1, const Container &container2, Containers... others)
{
return set_union(set_union(container1, container2), others...);
}
template <typename Container>
int size(const Container &container)
{
return (container.end() - container.begin());
}
template <typename Iterator, typename Function>
void transform(Iterator first_begin, Iterator first_end, Iterator second_begin,
Function function)
{
while (first_begin != first_end)
{
(*second_begin) = function(*first_begin);
first_begin++;
second_begin++;
}
}
}
| 29.510638 | 104 | 0.583904 | [
"vector",
"transform"
] |
5ea94d06dc8f078bd85ef0e6cdc28d19646a1da0 | 1,677 | hpp | C++ | src/Domain/Model.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | src/Domain/Model.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | src/Domain/Model.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | #if !defined MODEL
#define MODEL
#include <GL/gl.h>
#include <string>
#include "Shape.hpp"
#include "../Third-Party-Libs/glm/glm.hpp"
struct Model{
std::string nome;
Shape *shape = nullptr;
Shape *hitbox = nullptr;
glm::vec2 hitbox_offset = {0.0f, 0.0f};
glm::vec2 shape_offset = {0.0f, 0.0f};
glm::vec3 color = {1.0f, 1.0f, 1.0f};
virtual std::string getNome() { return nome; };
virtual void setNome(std::string nome) { this->nome = nome; };
virtual glm::vec3 getColor() { return color; };
virtual void setColor(glm::vec3 color){ this->color = color; };
virtual Shape *getShape() { return shape; };
virtual void setShape(Shape *shape, glm::vec2 shape_offset = {0.0f, 0.0f}){ this->shape_offset = shape_offset ;this->shape = shape; };
virtual Shape *getHitbox() { return hitbox; };
virtual void setHitbox(Shape *hitbox, glm::vec2 hitbox_offset = {0.0f, 0.0f}) { this->hitbox = hitbox; this->hitbox_offset = hitbox_offset; };
virtual glm::vec2 getHitboxOffset(){ return hitbox_offset; };
~Model(){
#if defined TEST
std::cout << "Deletando " << this->nome << std::endl;
#endif
if (shape) delete shape;
if (hitbox && shape != hitbox) delete hitbox;
shape = hitbox = nullptr;
}
virtual void draw(){
glColor3f(color.x, color.y, color.z);
glTranslatef(shape_offset.x, shape_offset.y, 0.0f);
if (shape) shape->draw();
#if defined TEST
//glColor3f(1.0f, 1.0f, 1.0f);
//glTranslatef(hitbox_offset.x, hitbox_offset.y, 0.0f);
//if (hitbox) hitbox->draw();
#endif
}
};
#endif | 32.25 | 146 | 0.604055 | [
"shape",
"model"
] |
5eae472eef46d139a48837b644712a9878bef456 | 1,410 | cpp | C++ | Cpp/UVa/WIP/11709.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | Cpp/UVa/WIP/11709.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | Cpp/UVa/WIP/11709.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long l;
typedef vector<l> vl;
void dfsSCC(l &a, vl *adj, stack<l> &st, l *onStack, l *ids, l *low, l &id,
l &counter) {
st.push(a);
onStack[a] = true;
ids[a] = low[a] = id++;
for (auto &b : adj[a]) {
if (ids[b] == -1) dfsSCC(b, adj, st, onStack, ids, low, id, counter);
if (onStack[b]) low[a] = min(low[a], low[b]);
}
if (ids[a] == low[a]) {
l c;
do {
c = st.top();
st.pop();
onStack[c] = false;
low[c] = ids[a];
} while (c != a);
counter++;
}
}
// main - low -> uninit array[n]
l SCC(vl *adj, l n, l *low) {
l id = 0, counter = 0;
l ids[n], onStack[n];
stack<l> st;
for (l i = 0; i < n; i++) {
ids[i] = -1;
onStack[i] = false;
}
for (l i = 0; i < n; i++)
if (ids[i] == -1) dfsSCC(i, adj, st, onStack, ids, low, id, counter);
return counter;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
while (true) {
l n, m;
cin >> n >> m;
if (n == 0 && m == 0) break;
map<string, l> mp;
l index = 0;
for (l i = 0; i < n; i++) {
string a, b;
cin >> a >> b;
mp[a + b] = index++;
}
vl adj[n];
l low[n];
for (l i = 0; i < m; i++) {
string a, b, c, d;
cin >> a >> b >> c >> d;
adj[mp[a + b]].emplace_back(mp[c + d]);
}
cout << SCC(adj, n, low) << "\n";
}
} | 22.03125 | 75 | 0.453191 | [
"vector"
] |
5eb32a4e776411730ce98d0618a95801418bf86f | 490 | cpp | C++ | rotate-matrix.cpp | babu-thomas/interviewbit-solutions | 21125bf30b2d94b6f03310a4917679f216f55af3 | [
"MIT"
] | 16 | 2018-12-04T16:23:07.000Z | 2021-09-21T06:32:04.000Z | rotate-matrix.cpp | babu-thomas/interviewbit-solutions | 21125bf30b2d94b6f03310a4917679f216f55af3 | [
"MIT"
] | 1 | 2019-08-21T16:20:03.000Z | 2019-08-21T16:21:41.000Z | rotate-matrix.cpp | babu-thomas/interviewbit-solutions | 21125bf30b2d94b6f03310a4917679f216f55af3 | [
"MIT"
] | 23 | 2019-06-21T12:09:57.000Z | 2021-09-22T18:03:28.000Z | // Time - O(N), Space - O(1)
void Solution::rotate(vector<vector<int> > &A) {
int rows = A.size();
if(rows == 0) {
return;
}
int cols = A[0].size();
// Transpose
for(int i = 0; i < rows; i++) {
for(int j = i; j < cols; j++) {
swap(A[i][j], A[j][i]);
}
}
// Reverse rows
for(int i = 0; i < rows; i++) {
for(int j = 0, k = cols - 1; j < k; j++, k--) {
swap(A[i][j], A[i][k]);
}
}
}
| 21.304348 | 55 | 0.377551 | [
"vector"
] |
5eb7e7206745ebaa57bf2edd21b737c18bd87c01 | 8,404 | cpp | C++ | main.cpp | andrewgonzalez/quicksort | eba6589b9cdbc9b8a1887a891fd7cc0da90261dc | [
"MIT"
] | null | null | null | main.cpp | andrewgonzalez/quicksort | eba6589b9cdbc9b8a1887a891fd7cc0da90261dc | [
"MIT"
] | null | null | null | main.cpp | andrewgonzalez/quicksort | eba6589b9cdbc9b8a1887a891fd7cc0da90261dc | [
"MIT"
] | null | null | null | // Andrew Gonzalez
// CS 350
// The intent of this project is to measure runtime performance for
// the Quicksort algorithm using various pivot choosing strategies.
#include <iostream>
#include <fstream>
#include <chrono>
#include <algorithm>
#include "quicksort.h"
using namespace std::chrono;
typedef int (*partFunc)(int*,int,int,int);
typedef int (*pivotFunc)(int*,int,int);
typedef void (*fillArr)(int*,int);
// prototypes
partFunc determinePartition(char*, char*);
pivotFunc determinePivot(char*, char*);
fillArr determineArrayOrder(char*, char*);
void randomOrder(int *sourceArray, int arrSize);
void partialOrder(int *sourceArray, int arrSize);
void sortedOrder(int *sourceArray, int arrSize);
void reverseOrder(int *sourceArray, int arrSize);
bool checkCorrectness(int *checkArray, int arrSize);
void printArr(int *pInt, int arrSize);
int main(int argc, char *argv[]) {
int (*partitionFunc)(int*,int,int,int);
int (*pivotFunc)(int*,int,int);
void (*fillArray)(int*,int);
int * sourceArray;
// beginning array size of 100 and max of 1 million
int arrSize = 100;
int maxSize = 10000;
int loopCount = 10;
char filename[35];
bool verifySort = false;
high_resolution_clock clock;
high_resolution_clock::time_point start;
high_resolution_clock::time_point end;
// chrono::duration class template using microseconds
microseconds timeTaken;
std::ofstream fout;
// Use command line arguments to determine which functions to use
if (4 == argc) {
partitionFunc = determinePartition(argv[1], filename);
pivotFunc = determinePivot(argv[2], filename);
fillArray = determineArrayOrder(argv[3], filename);
}
else if (5 == argc) {
partitionFunc = determinePartition(argv[1], filename);
pivotFunc = determinePivot(argv[2], filename);
fillArray = determineArrayOrder(argv[3], filename);
if (strcmp("verify", argv[4]) == 0) {
verifySort = true;
}
}
else {
// default arguments
partitionFunc = lomutoPartition;
pivotFunc = basicPivot;
fillArray = randomOrder;
strcat(filename, "lomuto");
strcat(filename, "basic");
strcat(filename, "Random");
}
// open a file to print output to
strcat(filename, ".csv");
fout.open(filename, std::ofstream::out);
fout << "Array Size, Time (microseconds)" << "\n";
// If we're going to verify that the sort works correctly then we don't need
// to sort a bunch of huge arrays, just one array will do.
if (verifySort) {
maxSize = 100;
loopCount = 1;
}
while (arrSize <= maxSize) {
sourceArray = new int[arrSize];
timeTaken = microseconds::zero();
for (int i = 0; i < loopCount; ++i) {
fillArray(sourceArray, arrSize);
start = clock.now();
quicksort(sourceArray, 0, arrSize - 1, partitionFunc, pivotFunc);
end = clock.now();
timeTaken += duration_cast<microseconds>(end - start);
}
timeTaken /= loopCount; // average the runs of quicksort
fout << arrSize << ", " << timeTaken.count() << "\n";
if (verifySort) {
if (checkCorrectness(sourceArray, arrSize))
std::cout << argv[1] << " " << argv[2] << " " << argv[3] << " sorts correctly" << std::endl;
else
std::cout << argv[1] << " " << argv[2] << " " << argv[3] << " does not sort correctly" << std::endl;
}
delete[] sourceArray;
arrSize += 100;
}
fout.close();
return 0;
}
// Determine which partition algorithm the user entered at the command line.
// Input: two c-style strings (char array), one for the partition to use for quicksort,
// and a string to use for the filename respectively.
// Output: a function pointer to the partition function to use.
partFunc determinePartition(char * partition, char * filename) {
if (strcmp("lomuto", partition) == 0) {
strcat(filename, "lomuto");
return lomutoPartition;
}
// default to hoare partition if no match
strcat(filename, "hoare");
return hoarePartition;
}
// Determine which pivot algorithm the user entered at the command line.
// Input: two c-style strings (char array), one for the pivot to use for quicksort,
// and a string to use for the filename respectively.
// Output: a function pointer to the pivot function to use.
pivotFunc determinePivot(char * pivot, char * filename) {
if (strcmp("random", pivot) == 0) {
strcat(filename, "random");
return randomPivot;
}
else if (strcmp("m3", pivot) == 0) {
strcat(filename, "m3");
return medianOfThree;
}
else if (strcmp("mM", pivot) == 0) {
strcat(filename, "mM");
return medianOfMedians;
}
// default to basic pivot if no match
strcat(filename, "basic");
return basicPivot;
}
// Determine which array filling algorithm the user entered at the command line.
// Input: two c-style strings (char array), one for the array fill to use for quicksort,
// and a string to use for the filename respectively.
// Output: a function pointer to the array filling function to use.
fillArr determineArrayOrder(char * fillOrder, char * filename) {
if (strcmp("sorted", fillOrder) == 0) {
strcat(filename, "Sorted");
return sortedOrder;
}
else if (strcmp("partsort", fillOrder) == 0) {
strcat(filename, "Partial");
return partialOrder;
}
else if (strcmp("reverse", fillOrder) == 0) {
strcat(filename, "Reverse");
return reverseOrder;
}
// default to randomly filled array
strcat(filename, "Random");
return randomOrder;
}
// Fill the passed in int array with random integers.
// Input: an int array and an int for the array size.
// Output: void
void randomOrder(int *sourceArray, int arrSize) {
// Using a Mersenne twister as the engine to generate random numbers.
// This will generate uints, and I need ints, so I'm using the
// uniform_int_distribution engine to transform the uints
// into ints within the range 0...INT32_MAX.
std::random_device seed;
std::mt19937 randGen(seed());
std::uniform_int_distribution<int> dist(0, INT32_MAX);
// Fill source array with random numbers
for (int i = 0; i < arrSize; ++i) {
sourceArray[i] = dist(randGen);
}
}
// Fill the passed in array with mostly sorted integers. Every 10th element
// will have a random integer.
// Input: an int array and an int for the array size.
// Output: void
void partialOrder(int *sourceArray, int arrSize) {
int insertRandom = 7;
std::random_device seed;
std::mt19937 randGen(seed());
std::uniform_int_distribution<int> dist(0, INT32_MAX);
for (int i = 0; i < arrSize; ++i) {
if ((i % insertRandom) == 0)
sourceArray[i] = dist(randGen);
else
sourceArray[i] = i;
}
}
// Fill the passed in array with sorted integers (ascending order).
// Input: an int array and an int for the array size.
// Output: void
void sortedOrder(int *sourceArray, int arrSize) {
// Fill source array with sorted data
for (int i = 0; i < arrSize; ++i) {
sourceArray[i] = i;
}
}
// Fill the passed in array with reverse sorted integers (descending order).
// Input: an int array and an int for the array size.
// Output: void
void reverseOrder(int *sourceArray, int arrSize) {
int j;
for (int i = 0; i < arrSize; ++i) {
j = arrSize - i;
sourceArray[i] = j;
}
}
// Checks if an array is sorted by comparing each element to the next. If the
// current element is greater than the next, then the array is not sorted.
// Input: an int array and an int for the array size.
// Output: true if the array is sorted, false otherwise.
bool checkCorrectness(int *checkArray, int arrSize) {
bool isCorrect = true;
for (int i = 0; isCorrect && i < arrSize - 1; ++i) {
if (checkArray[i] > checkArray[i+1])
isCorrect = false;
}
return isCorrect;
}
// Print the contents of an array to the standard output.
// Input: an int array and an int for the array size.
// Output: void
void printArr(int *pInt, int arrSize) {
for (int i = 0; i < arrSize; ++i)
std::cout << pInt[i] << std::endl;
}
| 32.956863 | 116 | 0.638981 | [
"transform"
] |
5ebb51017480f37a3a086ea8edb1baac668daee3 | 2,174 | cpp | C++ | src/streams/file.cpp | thgcode/synthizer | 50ff649e0651441bf67f986983e71c5ce6de239c | [
"Unlicense"
] | 1 | 2021-02-06T07:29:35.000Z | 2021-02-06T07:29:35.000Z | src/streams/file.cpp | thgcode/synthizer | 50ff649e0651441bf67f986983e71c5ce6de239c | [
"Unlicense"
] | null | null | null | src/streams/file.cpp | thgcode/synthizer | 50ff649e0651441bf67f986983e71c5ce6de239c | [
"Unlicense"
] | null | null | null | #include <filesystem>
#include <fstream>
#include <utility>
#include <vector>
#include <tuple>
#include <memory>
#include "synthizer/byte_stream.hpp"
namespace synthizer {
class FileByteStream: public ByteStream {
public:
FileByteStream(std::fstream &&f);
std::string getName() override;
std::size_t read(std::size_t count, char *destination) override;
bool supportsSeek() override;
std::size_t getPosition() override;
void seek(std::size_t position) override;
std::size_t getLength() override;
private:
std::fstream stream;
std::size_t length = 0;
};
FileByteStream::FileByteStream(std::fstream &&s): stream(std::move(s)) {
this->stream.seekg(0, std::ios_base::end);
this->length = this->stream.tellg();
this->stream.seekg(0, std::ios_base::beg);
}
std::string FileByteStream::getName() {
return "file";
}
std::size_t FileByteStream::read(std::size_t count, char *destination) {
std::size_t read = 0;
int retries = 5;
if (count == 0)
return 0;
do {
this->stream.read(destination+read, count-read);
read += this->stream.gcount();
if (read == count || this->stream.eof())
break;
retries --;
} while(retries > 0);
return read;
}
bool FileByteStream::supportsSeek() {
return true;
}
std::size_t FileByteStream::getPosition() {
auto pos = this->stream.tellg();
if (pos < 0)
throw EByteStream("Unable to get file position. This should probably never happen.");
return pos;
}
void FileByteStream::seek(std::size_t position) {
this->stream.clear();
this->stream.seekg(position);
if (this->stream.good() != true)
throw EByteStream("Unable to seek.");
}
std::size_t FileByteStream::getLength() {
return this->length;
}
std::shared_ptr<ByteStream> fileStream(const std::string &path, const std::vector<std::tuple<std::string, std::string>> &options) {
(void) options;
auto p = std::filesystem::u8path(path);
if (std::filesystem::exists(p) == false)
throw EByteStreamNotFound();
std::fstream stream;
stream.open(p, std::ios::in|std::ios::binary);
if (stream.is_open() == false)
throw EByteStream("File path existed, but we were unable to open.");
return std::make_shared<FileByteStream>(std::move(stream));
}
}
| 23.89011 | 131 | 0.699172 | [
"vector"
] |
5ebd8541060e52bfb826a39ca26b6a0ba3b86a9b | 1,041 | cpp | C++ | cpp_code/STCPlan.cpp | Tesla2fox/ComplexSystemIntelligentControl | 9fd73a4b315177a6241d366fd86dacf7348b4ee6 | [
"MIT"
] | 3 | 2018-07-04T02:45:00.000Z | 2019-10-23T08:30:03.000Z | cpp_code/STCPlan.cpp | Tesla2fox/ComplexSystemIntelligentControl | 9fd73a4b315177a6241d366fd86dacf7348b4ee6 | [
"MIT"
] | null | null | null | cpp_code/STCPlan.cpp | Tesla2fox/ComplexSystemIntelligentControl | 9fd73a4b315177a6241d366fd86dacf7348b4ee6 | [
"MIT"
] | 1 | 2018-09-13T12:47:52.000Z | 2018-09-13T12:47:52.000Z | #include "STCPlan.h"
namespace pl
{
pl::STCPlan::~STCPlan()
{
}
void pl::STCPlan::setRange(vector<size_t> const & vVertInd)
{
_vVertInd.clear();
_vGridInd.clear();
_vVertInd = vVertInd;
for (auto &it : _vVertInd)
_vGridInd.push_back(this->_mainMap.tgraph2map[it]);
}
void STCPlan::setRange(vector<GridIndex> const & vInd) {
_vVertInd.clear();
_vGridInd.clear();
_vGridInd = vInd;
for (auto &it : _vGridInd)
_vVertInd.push_back(this->_mainMap.tmap2graph[it]);
}
void pl::STCPlan::setStartPnt(size_t const & startRow, size_t const & startCol)
{
_startPntInd.first = startRow;
_startPntInd.second = startCol;
}
void pl::STCPlan::plan()
{
constructGraph();
}
void pl::STCPlan::constructGraph()
{
if (!_mainMap.allConnected(_vVertInd))
return;
vector<size_t> rangeRow, rangeCol;
for (auto &it : this->_vGridInd)
{
rangeRow.push_back(it.first);
rangeCol.push_back(it.second);
}
writeDebug(c_deg, "rangRow", rangeRow);
writeDebug(c_deg, "rangeCol", rangeCol);
}
}
| 19.277778 | 80 | 0.677233 | [
"vector"
] |
5ec08681ee1e23c5cd6162077b788cfcc28df545 | 1,774 | cpp | C++ | src/pywinrt/strings/runtime.cpp | pywinrt/pywinrt | b86e80fc497cb405c79b85d542a889057c3aa084 | [
"MIT"
] | 3 | 2022-02-12T19:40:06.000Z | 2022-03-29T20:39:26.000Z | src/pywinrt/strings/runtime.cpp | pywinrt/pywinrt | b86e80fc497cb405c79b85d542a889057c3aa084 | [
"MIT"
] | 8 | 2022-01-27T19:11:26.000Z | 2022-03-24T01:25:12.000Z | src/pywinrt/strings/runtime.cpp | pywinrt/pywinrt | b86e80fc497cb405c79b85d542a889057c3aa084 | [
"MIT"
] | null | null | null |
#include <Python.h>
#include "pybase.h"
/**
* Adds a Python type to a Python module.
*
* @param module The module to add the type to.
* @param type_name A valid Python identifier.
* @param type_spec The Python type spec.
* @param base_type The base type, a tuple of base types or nullptr to use the base
* slot.
* @returns A borrowed reference to the type object or nullptr on error.
*/
PyTypeObject* py::register_python_type(
PyObject* module,
const char* const type_name,
PyType_Spec* type_spec,
PyObject* base_type) noexcept
{
py::pyobj_handle type_object{PyType_FromSpecWithBases(type_spec, base_type)};
if (!type_object)
{
return nullptr;
}
// steals ref to type_object on success!
if (PyModule_AddObject(module, type_name, type_object.get()) == -1)
{
return nullptr;
}
return reinterpret_cast<PyTypeObject*>(type_object.detach());
}
/**
* Wraps a WinRT KeyValuePair iterator in a Python type that iterates the
* keys only to be consistent with the Python mapping protocol.
* @param iter The mapping iterator returned from the First() method.
* @return A new reference to a new object that wraps @p iter.
*/
PyObject* py::wrap_mapping_iter(PyObject* iter) noexcept
{
auto mapping_iter_type = py::get_python_type<py::MappingIter>();
if (!mapping_iter_type)
{
return nullptr;
}
#if PY_VERSION_HEX >= 0x03090000
py::pyobj_handle wrapper{
PyObject_CallOneArg(reinterpret_cast<PyObject*>(mapping_iter_type), iter)};
#else
py::pyobj_handle wrapper{PyObject_CallFunctionObjArgs(
reinterpret_cast<PyObject*>(mapping_iter_type), iter, nullptr)};
#endif
if (!wrapper)
{
return nullptr;
}
return wrapper.detach();
}
| 26.477612 | 83 | 0.696167 | [
"object"
] |
5ec3360d627431860f4e3228b840a3142a5d68a4 | 9,138 | cc | C++ | sas/src/model/DescribeImageVulListRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | sas/src/model/DescribeImageVulListRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | sas/src/model/DescribeImageVulListRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/sas/model/DescribeImageVulListRequest.h>
using AlibabaCloud::Sas::Model::DescribeImageVulListRequest;
DescribeImageVulListRequest::DescribeImageVulListRequest() :
RpcServiceRequest("sas", "2018-12-03", "DescribeImageVulList")
{
setMethod(HttpRequest::Method::Post);
}
DescribeImageVulListRequest::~DescribeImageVulListRequest()
{}
std::string DescribeImageVulListRequest::getType()const
{
return type_;
}
void DescribeImageVulListRequest::setType(const std::string& type)
{
type_ = type;
setParameter("Type", type);
}
long DescribeImageVulListRequest::getCreateTsStart()const
{
return createTsStart_;
}
void DescribeImageVulListRequest::setCreateTsStart(long createTsStart)
{
createTsStart_ = createTsStart;
setParameter("CreateTsStart", std::to_string(createTsStart));
}
std::string DescribeImageVulListRequest::getContainerFieldName()const
{
return containerFieldName_;
}
void DescribeImageVulListRequest::setContainerFieldName(const std::string& containerFieldName)
{
containerFieldName_ = containerFieldName;
setParameter("ContainerFieldName", containerFieldName);
}
std::string DescribeImageVulListRequest::getSourceIp()const
{
return sourceIp_;
}
void DescribeImageVulListRequest::setSourceIp(const std::string& sourceIp)
{
sourceIp_ = sourceIp;
setParameter("SourceIp", sourceIp);
}
std::string DescribeImageVulListRequest::getTag()const
{
return tag_;
}
void DescribeImageVulListRequest::setTag(const std::string& tag)
{
tag_ = tag;
setParameter("Tag", tag);
}
long DescribeImageVulListRequest::getModifyTsEnd()const
{
return modifyTsEnd_;
}
void DescribeImageVulListRequest::setModifyTsEnd(long modifyTsEnd)
{
modifyTsEnd_ = modifyTsEnd;
setParameter("ModifyTsEnd", std::to_string(modifyTsEnd));
}
std::string DescribeImageVulListRequest::getLevel()const
{
return level_;
}
void DescribeImageVulListRequest::setLevel(const std::string& level)
{
level_ = level;
setParameter("Level", level);
}
std::string DescribeImageVulListRequest::getResource()const
{
return resource_;
}
void DescribeImageVulListRequest::setResource(const std::string& resource)
{
resource_ = resource;
setParameter("Resource", resource);
}
std::string DescribeImageVulListRequest::getGroupId()const
{
return groupId_;
}
void DescribeImageVulListRequest::setGroupId(const std::string& groupId)
{
groupId_ = groupId;
setParameter("GroupId", groupId);
}
std::string DescribeImageVulListRequest::getAliasName()const
{
return aliasName_;
}
void DescribeImageVulListRequest::setAliasName(const std::string& aliasName)
{
aliasName_ = aliasName;
setParameter("AliasName", aliasName);
}
std::string DescribeImageVulListRequest::getInstanceId()const
{
return instanceId_;
}
void DescribeImageVulListRequest::setInstanceId(const std::string& instanceId)
{
instanceId_ = instanceId;
setParameter("InstanceId", instanceId);
}
std::string DescribeImageVulListRequest::getName()const
{
return name_;
}
void DescribeImageVulListRequest::setName(const std::string& name)
{
name_ = name;
setParameter("Name", name);
}
std::string DescribeImageVulListRequest::getIds()const
{
return ids_;
}
void DescribeImageVulListRequest::setIds(const std::string& ids)
{
ids_ = ids;
setParameter("Ids", ids);
}
long DescribeImageVulListRequest::getCreateTsEnd()const
{
return createTsEnd_;
}
void DescribeImageVulListRequest::setCreateTsEnd(long createTsEnd)
{
createTsEnd_ = createTsEnd;
setParameter("CreateTsEnd", std::to_string(createTsEnd));
}
std::string DescribeImageVulListRequest::getNecessity()const
{
return necessity_;
}
void DescribeImageVulListRequest::setNecessity(const std::string& necessity)
{
necessity_ = necessity;
setParameter("Necessity", necessity);
}
std::string DescribeImageVulListRequest::getUuids()const
{
return uuids_;
}
void DescribeImageVulListRequest::setUuids(const std::string& uuids)
{
uuids_ = uuids;
setParameter("Uuids", uuids);
}
std::string DescribeImageVulListRequest::getRepoId()const
{
return repoId_;
}
void DescribeImageVulListRequest::setRepoId(const std::string& repoId)
{
repoId_ = repoId;
setParameter("RepoId", repoId);
}
std::string DescribeImageVulListRequest::getStatusList()const
{
return statusList_;
}
void DescribeImageVulListRequest::setStatusList(const std::string& statusList)
{
statusList_ = statusList;
setParameter("StatusList", statusList);
}
std::string DescribeImageVulListRequest::getTargetType()const
{
return targetType_;
}
void DescribeImageVulListRequest::setTargetType(const std::string& targetType)
{
targetType_ = targetType;
setParameter("TargetType", targetType);
}
std::string DescribeImageVulListRequest::getCveId()const
{
return cveId_;
}
void DescribeImageVulListRequest::setCveId(const std::string& cveId)
{
cveId_ = cveId;
setParameter("CveId", cveId);
}
std::string DescribeImageVulListRequest::getRemark()const
{
return remark_;
}
void DescribeImageVulListRequest::setRemark(const std::string& remark)
{
remark_ = remark;
setParameter("Remark", remark);
}
std::string DescribeImageVulListRequest::getRepoNamespace()const
{
return repoNamespace_;
}
void DescribeImageVulListRequest::setRepoNamespace(const std::string& repoNamespace)
{
repoNamespace_ = repoNamespace;
setParameter("RepoNamespace", repoNamespace);
}
std::string DescribeImageVulListRequest::getRegionId()const
{
return regionId_;
}
void DescribeImageVulListRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
std::string DescribeImageVulListRequest::getContainerFieldValue()const
{
return containerFieldValue_;
}
void DescribeImageVulListRequest::setContainerFieldValue(const std::string& containerFieldValue)
{
containerFieldValue_ = containerFieldValue;
setParameter("ContainerFieldValue", containerFieldValue);
}
int DescribeImageVulListRequest::getPageSize()const
{
return pageSize_;
}
void DescribeImageVulListRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::string DescribeImageVulListRequest::getDigest()const
{
return digest_;
}
void DescribeImageVulListRequest::setDigest(const std::string& digest)
{
digest_ = digest;
setParameter("Digest", digest);
}
long DescribeImageVulListRequest::getModifyTsStart()const
{
return modifyTsStart_;
}
void DescribeImageVulListRequest::setModifyTsStart(long modifyTsStart)
{
modifyTsStart_ = modifyTsStart;
setParameter("ModifyTsStart", std::to_string(modifyTsStart));
}
std::string DescribeImageVulListRequest::getLang()const
{
return lang_;
}
void DescribeImageVulListRequest::setLang(const std::string& lang)
{
lang_ = lang;
setParameter("Lang", lang);
}
std::string DescribeImageVulListRequest::getDealed()const
{
return dealed_;
}
void DescribeImageVulListRequest::setDealed(const std::string& dealed)
{
dealed_ = dealed;
setParameter("Dealed", dealed);
}
int DescribeImageVulListRequest::getCurrentPage()const
{
return currentPage_;
}
void DescribeImageVulListRequest::setCurrentPage(int currentPage)
{
currentPage_ = currentPage;
setParameter("CurrentPage", std::to_string(currentPage));
}
std::string DescribeImageVulListRequest::getBatchName()const
{
return batchName_;
}
void DescribeImageVulListRequest::setBatchName(const std::string& batchName)
{
batchName_ = batchName;
setParameter("BatchName", batchName);
}
std::string DescribeImageVulListRequest::getRepoName()const
{
return repoName_;
}
void DescribeImageVulListRequest::setRepoName(const std::string& repoName)
{
repoName_ = repoName;
setParameter("RepoName", repoName);
}
std::string DescribeImageVulListRequest::getRepoInstanceId()const
{
return repoInstanceId_;
}
void DescribeImageVulListRequest::setRepoInstanceId(const std::string& repoInstanceId)
{
repoInstanceId_ = repoInstanceId;
setParameter("RepoInstanceId", repoInstanceId);
}
std::string DescribeImageVulListRequest::getRepoRegionId()const
{
return repoRegionId_;
}
void DescribeImageVulListRequest::setRepoRegionId(const std::string& repoRegionId)
{
repoRegionId_ = repoRegionId;
setParameter("RepoRegionId", repoRegionId);
}
| 22.618812 | 97 | 0.756074 | [
"model"
] |
5ec5ced1fdff962b9edc7ff96a44cdc47e4cf072 | 16,616 | cpp | C++ | third_party/angle/src/libANGLE/renderer/gl/egl/android/DisplayAndroid.cpp | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/angle/src/libANGLE/renderer/gl/egl/android/DisplayAndroid.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/angle/src/libANGLE/renderer/gl/egl/android/DisplayAndroid.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | //
// Copyright (c) 2016 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.
//
// DisplayAndroid.cpp: Android implementation of egl::Display
#include <android/native_window.h>
#include "common/debug.h"
#include "libANGLE/Display.h"
#include "libANGLE/Surface.h"
#include "libANGLE/renderer/gl/egl/FunctionsEGLDL.h"
#include "libANGLE/renderer/gl/egl/PbufferSurfaceEGL.h"
#include "libANGLE/renderer/gl/egl/WindowSurfaceEGL.h"
#include "libANGLE/renderer/gl/egl/android/DisplayAndroid.h"
#include "libANGLE/renderer/gl/renderergl_utils.h"
namespace
{
const char *GetEGLPath()
{
#if defined(__LP64__)
return "/system/lib64/libEGL.so";
#else
return "/system/lib/libEGL.so";
#endif
}
} // namespace
namespace rx
{
DisplayAndroid::DisplayAndroid(const egl::DisplayState &state)
: DisplayEGL(state), mDummyPbuffer(EGL_NO_SURFACE), mCurrentSurface(EGL_NO_SURFACE)
{
}
DisplayAndroid::~DisplayAndroid()
{
}
egl::Error DisplayAndroid::initialize(egl::Display *display)
{
FunctionsEGLDL *egl = new FunctionsEGLDL();
mEGL = egl;
void *eglHandle = reinterpret_cast<void *>(display->getAttributeMap().get(
EGL_PLATFORM_ANGLE_EGL_HANDLE_ANGLE, 0));
ANGLE_TRY(egl->initialize(display->getNativeDisplayId(), GetEGLPath(), eglHandle));
gl::Version eglVersion(mEGL->majorVersion, mEGL->minorVersion);
ASSERT(eglVersion >= gl::Version(1, 4));
static_assert(EGL_OPENGL_ES3_BIT == EGL_OPENGL_ES3_BIT_KHR, "Extension define must match core");
EGLint esBit = (eglVersion >= gl::Version(1, 5) || mEGL->hasExtension("EGL_KHR_create_context"))
? EGL_OPENGL_ES3_BIT
: EGL_OPENGL_ES2_BIT;
// clang-format off
std::vector<EGLint> configAttribListBase =
{
EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER,
// Android doesn't support pixmaps
EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
EGL_CONFIG_CAVEAT, EGL_NONE,
EGL_CONFORMANT, esBit,
EGL_RENDERABLE_TYPE, esBit,
};
// clang-format on
if (mEGL->hasExtension("EGL_EXT_pixel_format_float"))
{
// Don't request floating point configs
configAttribListBase.push_back(EGL_COLOR_COMPONENT_TYPE_EXT);
configAttribListBase.push_back(EGL_COLOR_COMPONENT_TYPE_FIXED_EXT);
}
std::vector<EGLint> configAttribListWithFormat = configAttribListBase;
// EGL1.5 spec Section 2.2 says that depth, multisample and stencil buffer depths
// must match for contexts to be compatible.
// Choose RGBA8888
configAttribListWithFormat.push_back(EGL_RED_SIZE);
configAttribListWithFormat.push_back(8);
configAttribListWithFormat.push_back(EGL_GREEN_SIZE);
configAttribListWithFormat.push_back(8);
configAttribListWithFormat.push_back(EGL_BLUE_SIZE);
configAttribListWithFormat.push_back(8);
configAttribListWithFormat.push_back(EGL_ALPHA_SIZE);
configAttribListWithFormat.push_back(8);
// Choose DEPTH24_STENCIL8
configAttribListWithFormat.push_back(EGL_DEPTH_SIZE);
configAttribListWithFormat.push_back(24);
configAttribListWithFormat.push_back(EGL_STENCIL_SIZE);
configAttribListWithFormat.push_back(8);
// Choose no multisampling
configAttribListWithFormat.push_back(EGL_SAMPLE_BUFFERS);
configAttribListWithFormat.push_back(0);
// Complete the attrib lists
configAttribListBase.push_back(EGL_NONE);
configAttribListWithFormat.push_back(EGL_NONE);
EGLint numConfig;
EGLConfig configWithFormat;
EGLBoolean success =
mEGL->chooseConfig(configAttribListWithFormat.data(), &configWithFormat, 1, &numConfig);
if (success == EGL_FALSE)
{
return egl::EglNotInitialized()
<< "eglChooseConfig failed with " << egl::Error(mEGL->getError());
}
int dummyPbufferAttribs[] = {
EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE,
};
mDummyPbuffer = mEGL->createPbufferSurface(configWithFormat, dummyPbufferAttribs);
if (mDummyPbuffer == EGL_NO_SURFACE)
{
return egl::EglNotInitialized()
<< "eglCreatePbufferSurface failed with " << egl::Error(mEGL->getError());
}
// Create mDummyPbuffer with a normal config, but create a no_config mContext, if possible
if (mEGL->hasExtension("EGL_KHR_no_config_context"))
{
mConfigAttribList = configAttribListBase;
mConfig = EGL_NO_CONFIG_KHR;
}
else
{
mConfigAttribList = configAttribListWithFormat;
mConfig = configWithFormat;
}
ANGLE_TRY(initializeContext(display->getAttributeMap()));
success = mEGL->makeCurrent(mDummyPbuffer, mContext);
if (success == EGL_FALSE)
{
return egl::EglNotInitialized()
<< "eglMakeCurrent failed with " << egl::Error(mEGL->getError());
}
mCurrentSurface = mDummyPbuffer;
mFunctionsGL = mEGL->makeFunctionsGL();
mFunctionsGL->initialize(display->getAttributeMap());
return DisplayGL::initialize(display);
}
void DisplayAndroid::terminate()
{
DisplayGL::terminate();
EGLBoolean success = mEGL->makeCurrent(EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (success == EGL_FALSE)
{
ERR() << "eglMakeCurrent error " << egl::Error(mEGL->getError());
}
mCurrentSurface = EGL_NO_SURFACE;
if (mDummyPbuffer != EGL_NO_SURFACE)
{
success = mEGL->destroySurface(mDummyPbuffer);
mDummyPbuffer = EGL_NO_SURFACE;
if (success == EGL_FALSE)
{
ERR() << "eglDestroySurface error " << egl::Error(mEGL->getError());
}
}
if (mContext != EGL_NO_CONTEXT)
{
success = mEGL->destroyContext(mContext);
mContext = EGL_NO_CONTEXT;
if (success == EGL_FALSE)
{
ERR() << "eglDestroyContext error " << egl::Error(mEGL->getError());
}
}
egl::Error result = mEGL->terminate();
if (result.isError())
{
ERR() << "eglTerminate error " << result;
}
SafeDelete(mEGL);
SafeDelete(mFunctionsGL);
}
SurfaceImpl *DisplayAndroid::createWindowSurface(const egl::SurfaceState &state,
EGLNativeWindowType window,
const egl::AttributeMap &attribs)
{
EGLConfig config;
EGLint numConfig;
EGLBoolean success;
const EGLint configAttribList[] = {EGL_CONFIG_ID, mConfigIds[state.config->configID], EGL_NONE};
success = mEGL->chooseConfig(configAttribList, &config, 1, &numConfig);
ASSERT(success && numConfig == 1);
return new WindowSurfaceEGL(state, mEGL, config, window);
}
SurfaceImpl *DisplayAndroid::createPbufferSurface(const egl::SurfaceState &state,
const egl::AttributeMap &attribs)
{
EGLConfig config;
EGLint numConfig;
EGLBoolean success;
const EGLint configAttribList[] = {EGL_CONFIG_ID, mConfigIds[state.config->configID], EGL_NONE};
success = mEGL->chooseConfig(configAttribList, &config, 1, &numConfig);
ASSERT(success && numConfig == 1);
return new PbufferSurfaceEGL(state, mEGL, config);
}
SurfaceImpl *DisplayAndroid::createPbufferFromClientBuffer(const egl::SurfaceState &state,
EGLenum buftype,
EGLClientBuffer clientBuffer,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
SurfaceImpl *DisplayAndroid::createPixmapSurface(const egl::SurfaceState &state,
NativePixmapType nativePixmap,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
ImageImpl *DisplayAndroid::createImage(const egl::ImageState &state,
EGLenum target,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return DisplayGL::createImage(state, target, attribs);
}
template <typename T>
void DisplayAndroid::getConfigAttrib(EGLConfig config, EGLint attribute, T *value) const
{
EGLint tmp;
EGLBoolean success = mEGL->getConfigAttrib(config, attribute, &tmp);
ASSERT(success == EGL_TRUE);
*value = tmp;
}
template <typename T, typename U>
void DisplayAndroid::getConfigAttribIfExtension(EGLConfig config,
EGLint attribute,
T *value,
const char *extension,
const U &defaultValue) const
{
if (mEGL->hasExtension(extension))
{
getConfigAttrib(config, attribute, value);
}
else
{
*value = static_cast<T>(defaultValue);
}
}
egl::ConfigSet DisplayAndroid::generateConfigs()
{
egl::ConfigSet configSet;
mConfigIds.clear();
EGLint numConfigs;
EGLBoolean success = mEGL->chooseConfig(mConfigAttribList.data(), nullptr, 0, &numConfigs);
ASSERT(success == EGL_TRUE && numConfigs > 0);
std::vector<EGLConfig> configs(numConfigs);
EGLint numConfigs2;
success =
mEGL->chooseConfig(mConfigAttribList.data(), configs.data(), numConfigs, &numConfigs2);
ASSERT(success == EGL_TRUE && numConfigs2 == numConfigs);
for (int i = 0; i < numConfigs; i++)
{
egl::Config config;
getConfigAttrib(configs[i], EGL_BUFFER_SIZE, &config.bufferSize);
getConfigAttrib(configs[i], EGL_RED_SIZE, &config.redSize);
getConfigAttrib(configs[i], EGL_GREEN_SIZE, &config.greenSize);
getConfigAttrib(configs[i], EGL_BLUE_SIZE, &config.blueSize);
getConfigAttrib(configs[i], EGL_LUMINANCE_SIZE, &config.luminanceSize);
getConfigAttrib(configs[i], EGL_ALPHA_SIZE, &config.alphaSize);
getConfigAttrib(configs[i], EGL_ALPHA_MASK_SIZE, &config.alphaMaskSize);
getConfigAttrib(configs[i], EGL_BIND_TO_TEXTURE_RGB, &config.bindToTextureRGB);
getConfigAttrib(configs[i], EGL_BIND_TO_TEXTURE_RGBA, &config.bindToTextureRGBA);
getConfigAttrib(configs[i], EGL_COLOR_BUFFER_TYPE, &config.colorBufferType);
getConfigAttrib(configs[i], EGL_CONFIG_CAVEAT, &config.configCaveat);
getConfigAttrib(configs[i], EGL_CONFIG_ID, &config.configID);
getConfigAttrib(configs[i], EGL_CONFORMANT, &config.conformant);
getConfigAttrib(configs[i], EGL_DEPTH_SIZE, &config.depthSize);
getConfigAttrib(configs[i], EGL_LEVEL, &config.level);
getConfigAttrib(configs[i], EGL_MAX_PBUFFER_WIDTH, &config.maxPBufferWidth);
getConfigAttrib(configs[i], EGL_MAX_PBUFFER_HEIGHT, &config.maxPBufferHeight);
getConfigAttrib(configs[i], EGL_MAX_PBUFFER_PIXELS, &config.maxPBufferPixels);
getConfigAttrib(configs[i], EGL_MAX_SWAP_INTERVAL, &config.maxSwapInterval);
getConfigAttrib(configs[i], EGL_MIN_SWAP_INTERVAL, &config.minSwapInterval);
getConfigAttrib(configs[i], EGL_NATIVE_RENDERABLE, &config.nativeRenderable);
getConfigAttrib(configs[i], EGL_NATIVE_VISUAL_ID, &config.nativeVisualID);
getConfigAttrib(configs[i], EGL_NATIVE_VISUAL_TYPE, &config.nativeVisualType);
getConfigAttrib(configs[i], EGL_RENDERABLE_TYPE, &config.renderableType);
getConfigAttrib(configs[i], EGL_SAMPLE_BUFFERS, &config.sampleBuffers);
getConfigAttrib(configs[i], EGL_SAMPLES, &config.samples);
getConfigAttrib(configs[i], EGL_STENCIL_SIZE, &config.stencilSize);
getConfigAttrib(configs[i], EGL_SURFACE_TYPE, &config.surfaceType);
getConfigAttrib(configs[i], EGL_TRANSPARENT_TYPE, &config.transparentType);
getConfigAttrib(configs[i], EGL_TRANSPARENT_RED_VALUE, &config.transparentRedValue);
getConfigAttrib(configs[i], EGL_TRANSPARENT_GREEN_VALUE, &config.transparentGreenValue);
getConfigAttrib(configs[i], EGL_TRANSPARENT_BLUE_VALUE, &config.transparentBlueValue);
getConfigAttribIfExtension(configs[i], EGL_COLOR_COMPONENT_TYPE_EXT,
&config.colorComponentType, "EGL_EXT_pixel_format_float",
EGL_COLOR_COMPONENT_TYPE_FIXED_EXT);
if (config.colorBufferType == EGL_RGB_BUFFER)
{
ASSERT(config.colorComponentType == EGL_COLOR_COMPONENT_TYPE_FIXED_EXT);
if (config.redSize == 8 && config.greenSize == 8 && config.blueSize == 8 &&
config.alphaSize == 8)
{
config.renderTargetFormat = GL_RGBA8;
}
else if (config.redSize == 8 && config.greenSize == 8 && config.blueSize == 8 &&
config.alphaSize == 0)
{
config.renderTargetFormat = GL_RGB8;
}
else if (config.redSize == 5 && config.greenSize == 6 && config.blueSize == 5 &&
config.alphaSize == 0)
{
config.renderTargetFormat = GL_RGB565;
}
else if (config.redSize == 5 && config.greenSize == 5 && config.blueSize == 5 &&
config.alphaSize == 1)
{
config.renderTargetFormat = GL_RGB5_A1;
}
else if (config.redSize == 4 && config.greenSize == 4 && config.blueSize == 4 &&
config.alphaSize == 4)
{
config.renderTargetFormat = GL_RGBA4;
}
else
{
ERR() << "RGBA(" << config.redSize << "," << config.greenSize << ","
<< config.blueSize << "," << config.alphaSize << ") not handled";
UNREACHABLE();
}
}
else
{
UNREACHABLE();
}
if (config.depthSize == 0 && config.stencilSize == 0)
{
config.depthStencilFormat = GL_ZERO;
}
else if (config.depthSize == 16 && config.stencilSize == 0)
{
config.depthStencilFormat = GL_DEPTH_COMPONENT16;
}
else if (config.depthSize == 24 && config.stencilSize == 0)
{
config.depthStencilFormat = GL_DEPTH_COMPONENT24;
}
else if (config.depthSize == 24 && config.stencilSize == 8)
{
config.depthStencilFormat = GL_DEPTH24_STENCIL8;
}
else if (config.depthSize == 0 && config.stencilSize == 8)
{
config.depthStencilFormat = GL_STENCIL_INDEX8;
}
else
{
UNREACHABLE();
}
config.matchNativePixmap = EGL_NONE;
config.optimalOrientation = 0;
int internalId = configSet.add(config);
mConfigIds[internalId] = config.configID;
}
return configSet;
}
bool DisplayAndroid::testDeviceLost()
{
return false;
}
egl::Error DisplayAndroid::restoreLostDevice(const egl::Display *display)
{
UNIMPLEMENTED();
return egl::NoError();
}
bool DisplayAndroid::isValidNativeWindow(EGLNativeWindowType window) const
{
return ANativeWindow_getFormat(window) >= 0;
}
DeviceImpl *DisplayAndroid::createDevice()
{
UNIMPLEMENTED();
return nullptr;
}
egl::Error DisplayAndroid::waitClient(const gl::Context *context) const
{
UNIMPLEMENTED();
return egl::NoError();
}
egl::Error DisplayAndroid::waitNative(const gl::Context *context, EGLint engine) const
{
UNIMPLEMENTED();
return egl::NoError();
}
egl::Error DisplayAndroid::makeCurrent(egl::Surface *drawSurface,
egl::Surface *readSurface,
gl::Context *context)
{
if (drawSurface)
{
SurfaceEGL *drawSurfaceEGL = GetImplAs<SurfaceEGL>(drawSurface);
EGLSurface surface = drawSurfaceEGL->getSurface();
if (surface != mCurrentSurface)
{
if (mEGL->makeCurrent(surface, mContext) == EGL_FALSE)
{
return egl::Error(mEGL->getError(), "eglMakeCurrent failed");
}
mCurrentSurface = surface;
}
}
return DisplayGL::makeCurrent(drawSurface, readSurface, context);
}
egl::Error DisplayAndroid::makeCurrentSurfaceless(gl::Context *context)
{
// Nothing to do because EGL always uses the same context and the previous surface can be left
// current.
return egl::NoError();
}
} // namespace rx
| 35.656652 | 100 | 0.639444 | [
"vector"
] |
5ec695b79f57ad6aa2761492040d908379c392ca | 776 | hpp | C++ | 2016/Day18/LightMap.hpp | marcuskrahl/AdventOfCode | 0148d9a01a565aac1a6104a6001478fab3b6d4f8 | [
"MIT"
] | null | null | null | 2016/Day18/LightMap.hpp | marcuskrahl/AdventOfCode | 0148d9a01a565aac1a6104a6001478fab3b6d4f8 | [
"MIT"
] | null | null | null | 2016/Day18/LightMap.hpp | marcuskrahl/AdventOfCode | 0148d9a01a565aac1a6104a6001478fab3b6d4f8 | [
"MIT"
] | null | null | null | #ifndef LIGHT_MAP_HPP
#define LIGHT_MAP_HPP
#include <vector>
class LightMap {
public:
LightMap(unsigned int max_x, unsigned int max_y);
bool is_on(unsigned int x, unsigned int y) const;
void turn_on(unsigned int x, unsigned int y);
void turn_off(unsigned int x, unsigned int y);
unsigned int get_active_lights() const;
LightMap evolve();
LightMap corner_evolve();
private:
std::vector<std::vector<unsigned char>> map;
unsigned int max_x;
unsigned int max_y;
bool should_be_turned_off(unsigned int x, unsigned int y);
bool should_be_turned_on(unsigned int x, unsigned int y);
unsigned int get_number_of_on_neighbors(unsigned int x, unsigned int y);
};
#endif
| 29.846154 | 80 | 0.670103 | [
"vector"
] |
5ec8f34e5b0f0a17b0f3677111f10f0fade8f841 | 17,489 | cpp | C++ | src/footstep_planner/src/test/footstep_planner_test.cpp | vinitha910/homotopy_guided_footstep_planner | d7706292ab264134e949d1bb0b860a5608597623 | [
"BSD-3-Clause"
] | 6 | 2019-01-13T07:34:15.000Z | 2021-12-18T19:48:49.000Z | src/footstep_planner/src/test/footstep_planner_test.cpp | vinitha910/homotopy_guided_footstep_planner | d7706292ab264134e949d1bb0b860a5608597623 | [
"BSD-3-Clause"
] | null | null | null | src/footstep_planner/src/test/footstep_planner_test.cpp | vinitha910/homotopy_guided_footstep_planner | d7706292ab264134e949d1bb0b860a5608597623 | [
"BSD-3-Clause"
] | 4 | 2019-01-13T07:37:27.000Z | 2021-01-26T22:13:18.000Z | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Vinitha Ranganeni & Sahit Chintalapudi
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <footstep_planner/graphs/homotopy_information.h>
#include <footstep_planner/graphs/nav_lattice_2D.h>
#include <footstep_planner/graphs/nav_lattice_8D.h>
#include <footstep_planner/planners/hbsp.h>
#include <footstep_planner/planners/dijkstra.h>
#include <footstep_planner/planners/mha.h>
#include <footstep_planner/heuristics/homotopy_based_heuristic.h>
#include <footstep_planner/heuristics/backward_dijkstra_heuristic.h>
#include <footstep_planner/rviz/visualize.h>
#include <fcntl.h>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <ros/ros.h>
#include <ros/package.h>
#include <std_msgs/String.h>
#include <fstream>
using namespace footstep_planner;
int get_closest_stepping_cell(
const int x, const int y, const int surf,
const std::shared_ptr<environment::proto::EnvironmentProjections>
environment) {
const int num_cells_x = environment->cols();
const int num_cells_y = environment->rows();
const int index_2d = (y * num_cells_x) + x;
const int surf_z =
environment->projections(surf).workspace_2d_to_surface_3d(index_2d);
const int index_3d = surf_z * num_cells_y * num_cells_x + index_2d;
return environment->surface_3d_to_stepping_cells(index_3d);
}
bool read_signature_array(
XmlRpc::XmlRpcValue& signatures_xml,
std::vector<std::vector<int>>* signatures) {
if (signatures_xml.size() > 0) {
for (int i = 0; i < signatures_xml.size(); ++i) {
XmlRpc::XmlRpcValue& signature_xml = signatures_xml[i];
if (signature_xml.getType() != XmlRpc::XmlRpcValue::TypeArray) {
ROS_ERROR("Signature must be represented as an array");
return false;
}
std::vector<int> signature;
for (int j = 0; j < signature_xml.size(); ++j) {
XmlRpc::XmlRpcValue& beam = signature_xml[j];
if (beam.getType() != XmlRpc::XmlRpcValue::TypeInt) {
ROS_ERROR("Signature must be an array of integers");
return false;
}
signature.push_back(std::move((static_cast<int>(beam))));
}
signatures->push_back(signature);
}
}
}
bool read_signatures(
std::vector<std::vector<int>>* signatures,
std::vector<std::vector<int>>* h_signatures,
const ros::NodeHandle& nh) {
XmlRpc::XmlRpcValue signatures_xml;
nh.getParam("signatures", signatures_xml);
if (signatures_xml.getType() != XmlRpc::XmlRpcValue::TypeArray) {
ROS_ERROR("signatures parameter must be an array");
return false;
}
signatures->reserve(signatures_xml.size());
read_signature_array(signatures_xml, signatures);
XmlRpc::XmlRpcValue h_signatures_xml;
nh.getParam("h_signatures", h_signatures_xml);
if (h_signatures_xml.getType() != XmlRpc::XmlRpcValue::TypeArray) {
ROS_ERROR("h_signatures parameter must be an array");
return false;
}
h_signatures->reserve(h_signatures_xml.size());
read_signature_array(h_signatures_xml, h_signatures);
return true;
}
int main(int argc, char* argv[]) {
ROS_INFO("footstep_planner_test");
ros::init(argc, argv, "footstep_local_planner_test");
ros::NodeHandle nh;
ros::NodeHandle ph("~");
const char *stats_filepath = nullptr;
const char *test_num = nullptr;
if (argc > 1) {
stats_filepath = argv[1];
ROS_INFO("Append statistics to %s", stats_filepath);
test_num = argv[2];
ROS_INFO("Test #%s", test_num);
}
ros::Publisher obstacles_vis_pub =
nh.advertise<visualization_msgs::Marker>("obstacles_marker", 1);
ros::Publisher platforms_vis_pub =
nh.advertise<visualization_msgs::Marker>("platforms_marker", 1);
ros::Publisher h_vals_pub =
nh.advertise<visualization_msgs::MarkerArray>("heuristic_vals", 1);
ros::Publisher goal_pub =
nh.advertise<visualization_msgs::Marker>("goal_region", 1);
ros::Publisher start_pub =
nh.advertise<visualization_msgs::Marker>("start_region", 1);
ros::Publisher path_pub =
nh.advertise<visualization_msgs::Marker>("path", 1);
std::string global_frame_id = "world";
visualize::publish_child_frame(nh, global_frame_id, "obstacles_marker");
visualize::publish_child_frame(nh, global_frame_id, "platforms_marker");
visualize::publish_child_frame(nh, global_frame_id, "heuristic_vals");
visualize::publish_child_frame(nh, global_frame_id, "goal_region");
visualize::publish_child_frame(nh, global_frame_id, "start_region");
visualize::publish_child_frame(nh, global_frame_id, "path");
// Read in parameters giving stl paths
std::string platforms;
std::string obstacles;
std::string query_type;
std::vector<std::string> surfaces;
std::vector<std::string> stepping_surfaces;
nh.getParam("surfaces", surfaces);
nh.getParam("platforms", platforms);
nh.getParam("query_type", query_type);
nh.getParam("obstacles", obstacles);
nh.getParam("stepping_surfaces", stepping_surfaces);
std::map<std::string, std::string> proto_msgs;
nh.getParam("proto_msgs", proto_msgs);
const std::string footstep_planner_path =
ros::package::getPath(proto_msgs["package"]);
// Parses robot parameters proto message
std::string robot_details_path =
footstep_planner_path + proto_msgs["robot_parameters"];
int robot_details_file = open(robot_details_path.c_str(), O_RDONLY);
google::protobuf::io::FileInputStream file_input(robot_details_file);
proto::RobotParameters robot_details;
google::protobuf::TextFormat::Parse(&file_input, &robot_details);
std::map<std::string, double> map_params;
nh.getParam("map_params", map_params);
const auto environment_interpreter =
std::make_shared<environment::EnvironmentInterpreter>(
platforms,
obstacles,
surfaces,
stepping_surfaces,
map_params,
robot_details);
// Project and save environment
const std::string projections_file =
footstep_planner_path + proto_msgs["projections"];
const std::string stepping_cells_file =
footstep_planner_path + proto_msgs["stepping_cells"];
bool load_proto_msgs;
nh.getParam("load_proto_msgs", load_proto_msgs);
if (!load_proto_msgs) {
if (!environment_interpreter->project_and_save_environment(
projections_file.c_str(),
stepping_cells_file.c_str())) return 1;
} else {
ROS_INFO("Parsing Environment Projections...");
if (!environment_interpreter->read_projection(
projections_file.c_str(),
stepping_cells_file.c_str())) return 1;
}
// Initialize and save homotopy information for the projected environment
const std::string beams_outfile =
footstep_planner_path + proto_msgs["beams"];
const std::string gates_outfile =
footstep_planner_path + proto_msgs["gates"];
const auto homotopy_information =
std::make_shared<graphs::HomotopyInformation>(
environment_interpreter->get_environment_projections());
if (!load_proto_msgs) {
if (!homotopy_information->find_and_save_beams_and_gates(
beams_outfile,
gates_outfile)) return 1;
} else {
ROS_INFO("Parsing Beams and Gates...");
if (!homotopy_information->read_beams_and_gates(
beams_outfile,
gates_outfile)) return 1;
}
// Initialize graph for the projected environment
const auto nav_lattice_2d = std::make_shared<graphs::NavLattice2D>(
environment_interpreter->get_environment_projections());
std::map<std::string, double> goal;
nh.getParam("goal_pose", goal);
// The robot goal state is the start state for the heuristic
const int projected_start_id =
nav_lattice_2d->set_start_state(goal["x"], goal["y"], goal["workspace"]);
if (projected_start_id == -1) {
ROS_ERROR("Error: Invalid Start Pose!");
return 1;
}
// Get start and goal IDs for heuristics
std::map<std::string, double> start;
nh.getParam("start_pose", start);
// The robot start state is the goal state for the heuristic
const int projected_goal_id =
nav_lattice_2d->set_goal_state(
start["x"], start["y"], start["workspace"]);
if (projected_goal_id == -1) {
ROS_ERROR("Error: Invalid Goal Pose!");
return 1;
}
// Read the signatures from the scenario file
std::vector<std::vector<int>> signatures;
std::vector<std::vector<int>> h_signatures;
read_signatures(&signatures, &h_signatures, nh);
ROS_INFO("Generating anchor heuristic...");
double start_time =
static_cast<double>(clock()) / static_cast<double>(CLOCKS_PER_SEC);
// Run planner for the 2D Backwards Dijkstra Heuristic
const auto dijkstra_planner =
std::make_shared<planners::Dijkstra>(
nav_lattice_2d,
projected_start_id);
double end_time =
static_cast<double>(clock()) / static_cast<double>(CLOCKS_PER_SEC);
const double anchor_heuristic_gen_time = end_time - start_time;
// Create the 2D Backwards Dijkstra Heuristic
const auto dijkstra_heur =
std::make_shared<heuristics::BackwardDijkstraHeuristic>(
dijkstra_planner,
environment_interpreter->get_environment_projections());
ROS_INFO("Generating homotopy-based heuristics...");
start_time =
static_cast<double>(clock()) / static_cast<double>(CLOCKS_PER_SEC);
// Run planner for hbsp heuristic
const auto hbsp_planner =
std::make_shared<planners::HBSP>(
homotopy_information,
nav_lattice_2d,
projected_goal_id,
projected_start_id,
signatures,
h_signatures);
end_time =
static_cast<double>(clock()) / static_cast<double>(CLOCKS_PER_SEC);
const double hbsp_heuristic_gen_time =
signatures.size() > 0 ? end_time - start_time : 0.0;
// Create the HBSP Heuristics
const auto hbsp_heur =
std::make_shared<heuristics::HomotopyBasedHeuristic>(
hbsp_planner,
environment_interpreter->get_environment_projections());
const auto nav_lattice_4d = std::make_shared<graphs::NavLattice8D>(
environment_interpreter->get_distance_map(),
robot_details,
homotopy_information,
environment_interpreter->get_valid_stepping_cells());
const int start_z =
get_closest_stepping_cell(
start["x"],
start["y"],
start["workspace"],
environment_interpreter->get_environment_projections());
const int start_state_id =
nav_lattice_4d->set_start_state(
start["x"],
start["y"],
start_z,
start["theta"]);
if (start_state_id == -1) {
ROS_ERROR("Error: Invalid Robot Start Pose.");
return 1;
}
const int goal_z =
get_closest_stepping_cell(
goal["x"],
goal["y"],
goal["workspace"],
environment_interpreter->get_environment_projections());
const int goal_state_id =
nav_lattice_4d->set_goal_state(
goal["x"],
goal["y"],
goal_z,
goal["theta"]);
if (goal_state_id == -1) {
ROS_ERROR("Error: Invalid Robot Goal Pose.");
return 1;
}
const auto mha_planner =
std::make_shared<planners::MHAPlanner>(
nav_lattice_4d,
dijkstra_heur,
hbsp_heur,
signatures.size(),
nh,
global_frame_id);
if (mha_planner->set_start(start_state_id) == 0) {
return 1;
}
if (mha_planner->set_goal(goal_state_id) == 0) {
return 1;
}
std::map<std::string, bool> visualize;
nh.getParam("visualize", visualize);
if (visualize["robot_model"]) {
double x_m, y_m, z_m;
environment_interpreter->get_distance_map()->gridToWorld(
start["x"], start["y"], start_z, x_m, y_m, z_m);
visualize::visualize_robot_model(
nh, global_frame_id, x_m, y_m, z_m, start["theta"]);
environment_interpreter->get_distance_map()->gridToWorld(
goal["x"], goal["y"], goal_z, x_m, y_m, z_m);
visualize::visualize_goal_region(
nh, global_frame_id, goal_pub, x_m, y_m, z_m);
}
if (visualize["world"]) {
visualize::visualize_obstacles(
obstacles, global_frame_id, obstacles_vis_pub);
visualize::visualize_platforms(
platforms, global_frame_id, platforms_vis_pub);
}
if (visualize["homotopic_heuristic"]) {
visualize::visualize_hbsp_heuristic_values(
nh,
global_frame_id,
environment_interpreter->get_distance_map(),
environment_interpreter,
nav_lattice_2d,
hbsp_planner,
h_vals_pub);
}
if (visualize["anchor_heuristic"]) {
visualize::visualize_dijkstra_heuristic_values(
nh,
global_frame_id,
environment_interpreter->get_distance_map(),
environment_interpreter,
nav_lattice_2d,
dijkstra_planner,
h_vals_pub);
}
std::vector<int> solution_stateIDs_V;
int solcost;
ROS_INFO("Planning...");
const int sol = mha_planner->replan(60.0, &solution_stateIDs_V, &solcost);
const double total_planning_time =
hbsp_heuristic_gen_time + \
anchor_heuristic_gen_time + \
mha_planner->get_final_eps_planning_time();
// log statistics if stats file given on command line
if (stats_filepath != nullptr) {
FILE* file = fopen(stats_filepath, "a");
if (file) {
fprintf(file, "\n");
fprintf(file, "test_%s:\n", test_num);
fprintf(file, " solution_found: %d\n", sol);
fprintf(file, " hbsp_heuristic_time: %f\n", hbsp_heuristic_gen_time);
fprintf(file, " anchor_heuristic_time: %f\n", anchor_heuristic_gen_time);
fprintf(file, " planning_time: %f\n", mha_planner->get_final_eps_planning_time());
fprintf(file, " total_planning_time: %f\n", total_planning_time);
fprintf(file, " path length: %d\n", static_cast<int>(solution_stateIDs_V.size()));
fprintf(file, " query_type: \"%s\"\n\n", query_type.c_str());
fclose(file);
} else {
ROS_WARN("Failed to append stats to %s", stats_filepath);
}
}
// print statistics
ROS_INFO("Statistics:");
ROS_INFO(" Solution Cost: %d", solcost);
ROS_INFO(" hbsp_heuristic_time: %f", hbsp_heuristic_gen_time);
ROS_INFO(" anchor_heuristic_time: %f", anchor_heuristic_gen_time);
ROS_INFO(" planning time: %f", mha_planner->get_final_eps_planning_time());
ROS_INFO(" total_planning_time: %f", total_planning_time);
ROS_INFO(" path length: %d", static_cast<int>(solution_stateIDs_V.size()));
if (visualize["path"]) {
visualize::visualize_path(
solution_stateIDs_V,
nav_lattice_4d,
global_frame_id,
path_pub);
}
// Uncomment if visualizing
// ros::spin();
return 0;
}
| 38.35307 | 107 | 0.649494 | [
"vector"
] |
5ec980bc4325c0cefb3134111518340ed9decdda | 10,075 | cpp | C++ | automator.cpp | authoff-swordpointstudios/testable | 63580c98752da80aface0152554f4d609fc172bf | [
"Apache-2.0"
] | null | null | null | automator.cpp | authoff-swordpointstudios/testable | 63580c98752da80aface0152554f4d609fc172bf | [
"Apache-2.0"
] | null | null | null | automator.cpp | authoff-swordpointstudios/testable | 63580c98752da80aface0152554f4d609fc172bf | [
"Apache-2.0"
] | null | null | null | #include <QQuickWindow>
#include <QEventLoop>
#include <QTimer>
#include <QQuickItem>
#include <QTime>
#include <QTest>
#include <QSignalSpy>
#include "automator.h"
#include "priv/objectutils.h"
#include "testablefunctions.h"
using namespace Testable;
static bool hasMethod(QObject* object, QString method) {
const QMetaObject* meta = object->metaObject();
int index = -1;
for (int i = 0 ; i < meta->methodCount(); i++) {
if (method == meta->method(i).name()) {
index = i;
break;
}
}
return index >= 0;
}
static bool hasMethods(QObject* object, QStringList filters) {
const QMetaObject* meta = object->metaObject();
bool res = false;
for (int i = 0 ; i < meta->methodCount(); i++) {
if (filters.indexOf(meta->method(i).name()) >= 0) {
res = true;
break;
}
}
return res;
}
static void invokeMethod(QObject*object, QString method, QJSValue jsObject) {
QJSValue func = jsObject.property(method);
QJSValue result = func.call();
if (result.isError()) {
QStringList stack = result.property("stack").toString().split("\n");
QStringList pair = stack[0].split("@");
QString source = pair[1];
if (source.indexOf(QRegExp("qrc:/*Testable/TestableCase.qml")) == 0) {
pair = stack[1].split("@");
source = pair[1];
}
QString message = result.property("message").toString();
qWarning().noquote() << source + ":" << "Error:" << message;
object->setProperty("hasError", true);
}
}
static void invokeMethodIfPresent(QObject* object, QString method, QJSValue jsObject) {
if (hasMethod(object, method)) {
invokeMethod(object,method, jsObject);
}
}
static void invokeTestableCase(QQmlEngine* engine, QObject* object, QStringList filters) {
const QMetaObject* meta = object->metaObject();
QJSValue jsObject = engine->newQObject(object);
invokeMethodIfPresent(object,"initTestCase", jsObject);
for (int j = 0 ; j < meta->methodCount();j++) {
const QMetaMethod method = meta->method(j);
QString methodName = method.name();
if (methodName.indexOf("test_") == 0 &&
(filters.size() == 0 || filters.indexOf(methodName) >= 0)) {
invokeMethodIfPresent(object, "init", jsObject);
invokeMethod(object,methodName,jsObject);
invokeMethodIfPresent(object, "cleanup", jsObject);
}
}
invokeMethodIfPresent(object,"cleanupTestCase", jsObject);
}
Automator::Automator(QQmlApplicationEngine* engine) : QObject()
{
setEngine(engine);
m_anyError = false;
}
QQmlApplicationEngine *Automator::engine() const
{
return m_engine;
}
void Automator::setEngine(QQmlApplicationEngine *engine)
{
m_engine = engine;
connect(engine,SIGNAL(warnings(QList<QQmlError>)),
this,SLOT(onWarnings(QList<QQmlError>)));
}
void Automator::wait(int timeout) {
QEventLoop loop;
QTimer timer;
QObject::connect(&timer,SIGNAL(timeout()),
&loop,SLOT(quit()));
timer.start(timeout);
loop.exec();
}
QObject *Automator::findObject(QString objectName)
{
QObjectList list = findObjects(objectName);
QObject* res = 0;
if (list.size() > 0) {
res = list.first();
}
return res;
}
QObjectList Automator::findObjects(QString objectName)
{
QObjectList result;
foreach (QObject* object, m_engine->rootObjects()) {
QObjectList subResult = findObjects(object, objectName);
if (subResult.size() > 0) {
result << subResult;
}
}
return ObjectUtils::uniq(result);
}
bool Automator::waitExists(QString objectName, int timeout)
{
QTime time;
time.start();
while (true) {
QObject* object = findObject(objectName);
if (object) {
break;
}
wait(100);
if (time.elapsed() > timeout) {
qWarning() << "waitExists() : Time out";
return false;
}
}
return true;
}
bool Automator::waitUntil(QObject *object, QString property, QVariant value, int timeout)
{
QVariant objectValue = object->property(property.toLocal8Bit().constData());
QTime time;
time.start();
while (objectValue != value) {
wait(100);
objectValue = object->property(property.toLocal8Bit().constData());
if (time.elapsed() > timeout) {
qWarning() << "waitUntil() : Time out";
return false;
}
}
return true;
}
bool Automator::waitUntilSignal(QObject *object, const char *signal, int timeout)
{
QTimer timer;
QSignalSpy spy(&timer,SIGNAL(timeout()));
QEventLoop loop;
if (timeout > 0) {
// Avoid using lambda function with QTimer::timeout to keep travis happy
timer.setInterval(timeout);
timer.setSingleShot(true);
connect(&timer,SIGNAL(timeout()), &loop,SLOT(quit()));
timer.start();
}
connect(object,signal,&loop,SLOT(quit()));
loop.exec();
timer.stop();
return spy.count() == 0;
}
bool Automator::waitUntil(QString objectName, QString property, QVariant value, int timeout)
{
QTime time;
time.start();
QObject* object = findObject(objectName);
if (!object) {
qWarning() << "Object not found" << objectName;
return false;
}
return waitUntil(object, property, value, timeout);
}
bool Automator::click(QQuickItem *item, int delay, QPointF pt)
{
QQuickWindow* win = window();
if (!win) {
qWarning() << "click: No window object";
return false;
}
QPointF hit;
if (pt.isNull()) {
int w = item->width();
int h = item->height();
int cx = w /2;
int cy = h / 2;
hit = item->mapToScene(QPointF(cx,cy));
} else {
hit = item->mapToScene(pt);
}
QTest::mouseClick(win, Qt::LeftButton,
Qt::NoModifier,
hit.toPoint(),
delay);
return true;
}
bool Automator::click(QQuickItem *item, QString childObjectName)
{
QObjectList list = findObjects(item, childObjectName);
QQuickItem* child = 0;
if (list.size() == 0) {
return false;
}
child = qobject_cast<QQuickItem*>(list.first());
if (!child) {
return false;
}
return click(child);
}
bool Automator::click(QString objectName, int delay, QPointF point)
{
QQuickItem* item = qobject_cast<QQuickItem*>(findObject(objectName));
if (!item) {
qWarning() << "Object not found" << objectName;
return false;
}
return click(item, delay, point);
}
QObjectList Automator::findObjects(QObject *object, QString objectName)
{
QObjectList result;
if (!object) {
return result;
}
if (object->objectName() == objectName) {
result << object;
}
if (inherited(object,"QQuickRepeater")) {
int count = object->property("count").toInt();
for (int i = 0 ; i < count ;i++) {
QQuickItem* item;
QMetaObject::invokeMethod(object,"itemAt",Qt::DirectConnection,
Q_RETURN_ARG(QQuickItem*,item),
Q_ARG(int,i));
QObjectList subResult = findObjects(item, objectName);
if (subResult.size() > 0) {
result.append(subResult);
}
}
} else if (inherited(object, "QQuickFlickable") || inherited(object, "QQuickWindow")) {
QQuickItem* contentItem = object->property("contentItem").value<QQuickItem*>();
if (contentItem) {
QList<QQuickItem *>items = contentItem->childItems() ;
for (int i = 0 ; i < items.size() ; i++) {
QObjectList subResult = findObjects(items.at(i),objectName);
if (subResult.size() > 0) {
result.append(subResult);
}
}
QObjectList subResult = findObjects(contentItem, objectName);
if (subResult.size() > 0) {
result.append(subResult);
}
}
}
QObjectList children = object->children();
for (int i = 0 ; i < children.size();i++) {
QObjectList subResult = findObjects(children.at(i), objectName);
if (subResult.size() > 0) {
result.append(subResult);
}
}
return ObjectUtils::uniq(result);
}
QQuickWindow *Automator::window()
{
QObject *firstObject = m_engine->rootObjects().first();
QQuickWindow *window = qobject_cast<QQuickWindow*>(firstObject);
return window;
}
bool Automator::anyError() const
{
return m_anyError;
}
void Automator::setAnyError(bool anyError)
{
m_anyError = anyError;
}
QObject* Automator::obtainSingletonObject(QString package, int versionMajor, int versionMinor, QString typeName)
{
/// Modified from QFAppDispatcher::singletonObject() in QuickFlux project
QString pattern = "import QtQuick 2.0\nimport %1 %2.%3;QtObject { property var object : %4 }";
QString qml = pattern.arg(package).arg(versionMajor).arg(versionMinor).arg(typeName);
QObject* holder = 0;
QQmlComponent comp (m_engine.data());
comp.setData(qml.toUtf8(),QUrl());
holder = comp.create();
if (!holder) {
qWarning() << QString("Testable: Failed to gain singleton object: %1").arg(typeName);
qWarning() << QString("Error: ") << comp.errorString();
return 0;
}
QObject* object = holder->property("object").value<QObject*>();
holder->deleteLater();
if (!object) {
qWarning() << QString("Testable: Failed to gain singleton object: %1").arg(typeName);
qWarning() << QString("Error: Unknown");
}
return object;
}
void Automator::onWarnings(QList<QQmlError> warnings)
{
for (int i = 0 ; i < warnings.size();i++){
if (warnings.at(i).toString().indexOf("Error") != -1) {
setAnyError(true);
}
}
}
| 25.1875 | 112 | 0.594541 | [
"object"
] |
5ec9d4946c67de5fbb5535ac094d98f148c2f8f6 | 2,064 | hpp | C++ | src/material/material.hpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | 1 | 2021-09-13T20:22:29.000Z | 2021-09-13T20:22:29.000Z | src/material/material.hpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | null | null | null | src/material/material.hpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | 1 | 2021-09-13T20:22:31.000Z | 2021-09-13T20:22:31.000Z | #pragma once
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <memory>
#include <vector>
enum class Side { FRONT, BACK, BOTH };
class Light;
class Material {
public:
Material(glm::vec3 color = glm::vec3(1.0f, 0.0f, 0.0), float specularCoefficient = 0.5f, float shininess = 32.0f);
virtual ~Material();
Material(Material&& other) = default;
Material(const Material& other) = default;
Material& operator=(const Material& other) = default;
Material& operator=(Material&& other) = default;
virtual void create();
virtual void setColor(glm::vec3 color);
virtual void setShininess(float shininess);
virtual void setLights(const std::vector<std::shared_ptr<Light>>& lights);
virtual void setEmissiveColorAndStrength(glm::vec3 color, float strength);
virtual void setEmissiveColor(glm::vec3 color);
virtual void setEmissiveStrength(float strength);
virtual void setModelMatrix(const glm::mat4& modelMatrix);
virtual void setProjectionAndViewMatrices(
const glm::mat4& projectionMatrix,
const glm::mat4& viewMatrix
);
virtual void setMatrices(
const glm::mat4& projectionMatrix,
const glm::mat4& viewMatrix,
const glm::mat4& modelMatrix
);
virtual void setUniforms() {}
bool compile(std::string vertexShader, std::string fragmentShader);
GLuint getProgram() {
return program;
}
void setSide(Side s) {
side = s;
}
Side getSide() {
return side;
}
glm::vec3 getColor() {
return color;
}
float getSpecularCoefficient() {
return specularCoefficient;
}
float getShininess() {
return shininess;
}
private:
GLuint program = 0;
glm::vec3 color;
float specularCoefficient;
float shininess;
Side side = Side::FRONT;
};
| 24.282353 | 122 | 0.591085 | [
"vector"
] |
5ed3d29673deb9cf89576c56a801e78a37d9dcad | 3,196 | cpp | C++ | gnc/matlab/code_generation/sharedutils/biecdbieglngohlf_pinv.cpp | Robo0603179/astrobee | 19e58806c63cddd9046342c7fa2ac7808f40ad3c | [
"Apache-2.0"
] | 629 | 2017-08-31T23:09:00.000Z | 2022-03-30T11:55:40.000Z | gnc/matlab/code_generation/sharedutils/biecdbieglngohlf_pinv.cpp | Robo0603179/astrobee | 19e58806c63cddd9046342c7fa2ac7808f40ad3c | [
"Apache-2.0"
] | 269 | 2018-05-05T12:31:16.000Z | 2022-03-30T22:04:11.000Z | gnc/matlab/code_generation/sharedutils/biecdbieglngohlf_pinv.cpp | Robo0603179/astrobee | 19e58806c63cddd9046342c7fa2ac7808f40ad3c | [
"Apache-2.0"
] | 248 | 2017-08-31T23:20:56.000Z | 2022-03-30T22:29:16.000Z | //
// File: biecdbieglngohlf_pinv.cpp
//
// Code generated for Simulink model 'est_estimator'.
//
// Model version : 1.1142
// Simulink Coder version : 8.11 (R2016b) 25-Aug-2016
// C/C++ source code generated on : Tue Oct 16 10:06:07 2018
//
#include "rtwtypes.h"
#include "rtGetNaN.h"
#include "rt_nonfinite.h"
#include "gdjmjekfdjecpppp_svd.h"
#include "biecdbieglngohlf_pinv.h"
// Function for MATLAB Function: '<S24>/compute_of_global_points'
void biecdbieglngohlf_pinv(const real32_T A[16], real32_T X[16])
{
real32_T V[16];
int32_T vcol;
real32_T tol;
int32_T j;
real32_T U[16];
real32_T S[16];
boolean_T b_p;
int32_T ar;
int32_T ia;
int32_T b_ic;
int32_T r;
b_p = true;
for (r = 0; r < 16; r++) {
X[r] = 0.0F;
if (b_p && ((!rtIsInfF(A[r])) && (!rtIsNaNF(A[r])))) {
} else {
b_p = false;
}
}
if (b_p) {
gdjmjekfdjecpppp_svd(A, U, S, V);
} else {
for (r = 0; r < 16; r++) {
U[r] = (rtNaNF);
S[r] = 0.0F;
V[r] = (rtNaNF);
}
S[0] = (rtNaNF);
S[5] = (rtNaNF);
S[10] = (rtNaNF);
S[15] = (rtNaNF);
}
tol = 4.0F * S[0] * 1.1920929E-7F;
r = 0;
vcol = 0;
while (((int32_T)(vcol + 1) < 5) && (S[(int32_T)((int32_T)(vcol << 2) + vcol)]
> tol)) {
r++;
vcol++;
}
if (r > 0) {
vcol = 0;
for (j = 0; (int32_T)(j + 1) <= r; j++) {
tol = 1.0F / S[(int32_T)((int32_T)(j << 2) + j)];
for (ar = vcol; (int32_T)(ar + 1) <= (int32_T)(vcol + 4); ar++) {
V[ar] *= tol;
}
vcol += 4;
}
for (j = 0; (int32_T)(j + 1) < 5; j++) {
X[j] = 0.0F;
}
for (j = 4; (int32_T)(j + 1) < 9; j++) {
X[j] = 0.0F;
}
for (j = 8; (int32_T)(j + 1) < 13; j++) {
X[j] = 0.0F;
}
for (j = 12; (int32_T)(j + 1) < 17; j++) {
X[j] = 0.0F;
}
ar = -1;
vcol = (int32_T)((int32_T)((int32_T)(r - 1) << 2) + 1);
for (j = 0; (int32_T)(j + 1) <= vcol; j += 4) {
if (U[j] != 0.0F) {
ia = ar;
for (b_ic = 0; (int32_T)(b_ic + 1) < 5; b_ic++) {
ia++;
X[b_ic] += U[j] * V[ia];
}
}
ar += 4;
}
ar = -1;
vcol = (int32_T)((int32_T)((int32_T)(r - 1) << 2) + 2);
for (j = 1; (int32_T)(j + 1) <= vcol; j += 4) {
if (U[j] != 0.0F) {
ia = ar;
for (b_ic = 4; (int32_T)(b_ic + 1) < 9; b_ic++) {
ia++;
X[b_ic] += U[j] * V[ia];
}
}
ar += 4;
}
ar = -1;
vcol = (int32_T)((int32_T)((int32_T)(r - 1) << 2) + 3);
for (j = 2; (int32_T)(j + 1) <= vcol; j += 4) {
if (U[j] != 0.0F) {
ia = ar;
for (b_ic = 8; (int32_T)(b_ic + 1) < 13; b_ic++) {
ia++;
X[b_ic] += U[j] * V[ia];
}
}
ar += 4;
}
ar = -1;
vcol = (int32_T)((int32_T)((int32_T)(r - 1) << 2) + 4);
for (j = 3; (int32_T)(j + 1) <= vcol; j += 4) {
if (U[j] != 0.0F) {
ia = ar;
for (b_ic = 12; (int32_T)(b_ic + 1) < 17; b_ic++) {
ia++;
X[b_ic] += U[j] * V[ia];
}
}
ar += 4;
}
}
}
//
// File trailer for generated code.
//
// [EOF]
//
| 20.888889 | 80 | 0.421464 | [
"model"
] |
5ed3d69f76debc2425525f6a43e7c0810fe2c480 | 10,381 | cc | C++ | tensorflow/compiler/plugin/poplar/driver/tools/replica_identical_dataflow_analysis.cc | pierricklee/tensorflow | c6a61d7b19a9242b06f40120ab42f0fdb0b5c462 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/plugin/poplar/driver/tools/replica_identical_dataflow_analysis.cc | pierricklee/tensorflow | c6a61d7b19a9242b06f40120ab42f0fdb0b5c462 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/plugin/poplar/driver/tools/replica_identical_dataflow_analysis.cc | pierricklee/tensorflow | c6a61d7b19a9242b06f40120ab42f0fdb0b5c462 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 The TensorFlow 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 "tensorflow/compiler/plugin/poplar/driver/tools/replica_identical_dataflow_analysis.h"
#include <utility>
#include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/all_gather.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/matcher_predicates.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/util.h"
#include "tensorflow/compiler/xla/service/call_graph.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/core/lib/core/errors.h"
namespace xla {
namespace poplarplugin {
std::ostream& operator<<(std::ostream& stream,
const ValueReplicaCategory& category) {
stream << "ValueReplicaCategory::";
switch (category) {
case ValueReplicaCategory::Identical:
stream << "Identical";
break;
case ValueReplicaCategory::Differing:
stream << "Differing";
break;
case ValueReplicaCategory::Unknown:
stream << "Unknown";
break;
default:
CHECK(false);
break;
}
return stream;
}
ValuesIdenticalAcrossReplicasVisitor::ValuesIdenticalAcrossReplicasVisitor(
const absl::flat_hash_map<const HloInstruction*, ValueCategoryTree>&
category_overrides)
: value_category_mapping_(category_overrides) {
// We don't want to visit instructions with an overide since that will negate
// the effect of having an override
MarkOverridesAsVisited(category_overrides);
}
StatusOr<ValueReplicaCategory>
ValuesIdenticalAcrossReplicasVisitor::ValueCategory(
const HloInstruction* inst, const ShapeIndex& value_index) const {
auto inst_it = value_category_mapping_.find(inst);
if (inst_it != value_category_mapping_.end()) {
const auto category = inst_it->second.element(value_index);
CHECK_NE(category, ValueReplicaCategory::Unknown);
return category;
}
return InternalErrorStrCat(
"Value category for instruction '", inst->name(),
"' not found. Run the visitor on its computation to find its value "
"category.");
}
Status ValuesIdenticalAcrossReplicasVisitor::DefaultAction(
const HloInstruction* inst) {
return SetAllInstructionValuesToIdenticalOrDiffering(
inst, AllOperandsIdentical(inst));
}
Status ValuesIdenticalAcrossReplicasVisitor::HandleCall(
const HloInstruction* inst) {
auto* comp = inst->to_apply();
if (IsFunction(inst)) {
return SetAllInstructionValuesToMatchComputationRoot(inst, comp);
}
return SetAllInstructionValuesToDiffering(inst);
}
Status ValuesIdenticalAcrossReplicasVisitor::HandleCustomCall(
const HloInstruction* inst) {
if (IsPoplarInstruction(PoplarOp::AllGather, inst)) {
const auto* all_gather = Cast<HloPoplarAllGatherInstruction>(inst);
// A default constructed PoplarReplicaGroups refers to a single group
// containing all replicas
const auto gather_all_replicas =
all_gather->GetPoplarReplicaGroups() == PoplarReplicaGroups();
return SetAllInstructionValuesToIdenticalOrDiffering(all_gather,
gather_all_replicas);
}
return SetAllInstructionValuesToDiffering(inst);
}
Status ValuesIdenticalAcrossReplicasVisitor::HandleAllReduce(
const HloInstruction* inst) {
const bool reduce_all_replicas = inst->replica_groups().empty();
return SetAllInstructionValuesToIdenticalOrDiffering(inst,
reduce_all_replicas);
}
Status ValuesIdenticalAcrossReplicasVisitor::HandleFusion(
const HloInstruction* inst) {
return SetAllInstructionValuesToIdenticalOrDiffering(
inst, IsPopOpsFusion(inst, "wide_const"));
}
Status ValuesIdenticalAcrossReplicasVisitor::HandleGetTupleElement(
const HloInstruction* inst) {
auto* tuple = inst->operand(0);
auto tuple_index = inst->tuple_index();
auto value_categories = ValueCategoryTree(inst->shape());
value_categories.CopySubtreeFrom(value_category_mapping_.at(tuple),
{tuple_index}, RootShapeIndex());
value_category_mapping_[inst] = std::move(value_categories);
return Status::OK();
}
Status ValuesIdenticalAcrossReplicasVisitor::HandleTuple(
const HloInstruction* inst) {
auto value_categories = ValueCategoryTree(inst->shape());
// Setup the child nodes of the shape tree.
for (auto i = 0l; i < inst->operand_count(); ++i) {
value_categories.CopySubtreeFrom(
value_category_mapping_.at(inst->operand(i)), RootShapeIndex(), {i});
}
value_category_mapping_[inst] = std::move(value_categories);
// Setup the root node of the shape tree.
SetInstrucionValueToIdenticalOrDiffering(inst, RootShapeIndex(),
AllOperandsIdentical(inst));
return Status::OK();
}
bool ValuesIdenticalAcrossReplicasVisitor::AllOperandsIdentical(
const HloInstruction* inst) const {
bool all_operands_identical = true;
for (auto* operand : inst->operands()) {
const auto root_category =
value_category_mapping_.at(operand).element(RootShapeIndex());
all_operands_identical &= root_category == ValueReplicaCategory::Identical;
}
return all_operands_identical;
}
Status ValuesIdenticalAcrossReplicasVisitor::
SetAllInstructionValuesToMatchComputationRoot(const HloInstruction* caller,
const HloComputation* comp) {
// To determine the value categories of a particular call we run the visitor
// with a set of overrides so that the categories of the computations
// parameters are the same as the callers operands. This should produce the
// same result as if the computations parameters were replaced with the
// callers operands but without the overhead of creating a new
// module/computation etc.
absl::flat_hash_map<const HloInstruction*, ValueCategoryTree>
parameter_overrides;
auto& params = comp->parameter_instructions();
CHECK_EQ(params.size(), caller->operand_count());
for (auto i = 0u; i < params.size(); ++i) {
parameter_overrides[params[i]] =
value_category_mapping_.at(caller->operand(i));
}
ValuesIdenticalAcrossReplicasVisitor comp_visitor(parameter_overrides);
comp->Accept(&comp_visitor);
// Note that even though comp->root_instruction is already in
// value_category_mapping_ we can't assign it from that since
// absl::flat_hash_map does not have reference stability, so the reference we
// try to copy from gets invalidated if value_category_mapping_ has to be
// reallocated.
value_category_mapping_[caller] =
comp_visitor.value_category_mapping_.at(comp->root_instruction());
// Since the caller is part of a flattened module we get a unique computation
// per caller, so we can just move across the sub visitor instructions without
// worrying about collisions.
value_category_mapping_.insert(
std::make_move_iterator(comp_visitor.value_category_mapping_.begin()),
std::make_move_iterator(comp_visitor.value_category_mapping_.end()));
return Status::OK();
}
Status ValuesIdenticalAcrossReplicasVisitor::SetAllInstructionValuesToIdentical(
const HloInstruction* inst) {
return SetAllInstructionValuesToIdenticalOrDiffering(inst,
/*identical*/ true);
}
Status ValuesIdenticalAcrossReplicasVisitor::SetAllInstructionValuesToDiffering(
const HloInstruction* inst) {
return SetAllInstructionValuesToIdenticalOrDiffering(inst,
/*identical*/ false);
}
Status ValuesIdenticalAcrossReplicasVisitor::
SetAllInstructionValuesToIdenticalOrDiffering(const HloInstruction* inst,
bool identical) {
const auto category = identical ? ValueReplicaCategory::Identical
: ValueReplicaCategory::Differing;
value_category_mapping_[inst] = ValueCategoryTree(inst->shape(), category);
return Status::OK();
}
void ValuesIdenticalAcrossReplicasVisitor::
SetInstrucionValueToIdenticalOrDiffering(const HloInstruction* inst,
const ShapeIndex& value_index,
bool identical) {
const auto category = identical ? ValueReplicaCategory::Identical
: ValueReplicaCategory::Differing;
*value_category_mapping_[inst].mutable_element(value_index) = category;
}
void ValuesIdenticalAcrossReplicasVisitor::MarkOverridesAsVisited(
const absl::flat_hash_map<const HloInstruction*, ValueCategoryTree>&
category_overrides) {
for (auto& item : category_overrides) {
auto* inst = item.first;
SetVisitState(inst->unique_id(), kVisited);
}
}
Status ReplicaIdenticalDataflowAnalysis::Run(const HloModule* module) {
auto module_call_graph = CallGraph::Build(module);
if (module_call_graph->IsFlattened()) {
auto* entry_computation = module->entry_computation();
return entry_computation->Accept(&value_category_visitor_);
}
return FailedPrecondition(
"Expected the call graph of the module to be flat.");
}
StatusOr<ValueReplicaCategory> ReplicaIdenticalDataflowAnalysis::ValueCategory(
const HloInstruction* inst, const ShapeIndex& value_index) {
return value_category_visitor_.ValueCategory(inst, value_index);
}
StatusOr<bool> ReplicaIdenticalDataflowAnalysis::IsValueIdenticalAcrossReplicas(
const HloInstruction* inst, const ShapeIndex& value_index) {
TF_ASSIGN_OR_RETURN(ValueReplicaCategory category,
ValueCategory(inst, value_index));
return category == ValueReplicaCategory::Identical;
}
} // namespace poplarplugin
} // namespace xla
| 38.735075 | 95 | 0.72257 | [
"shape"
] |
5edb62352b4f61d5a406b66a0219dbda9d940bce | 3,998 | cpp | C++ | src/xray/editor/dialog/sources/dialog_text_editor.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/editor/dialog/sources/dialog_text_editor.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/editor/dialog/sources/dialog_text_editor.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | //-------------------------------------------------------------------------------------------
// Created : 04.02.2010
// Author : Sergey Pryshchepa
// Copyright (C) GSC Game World - 2010
//-------------------------------------------------------------------------------------------
#include "pch.h"
#include "dialog_text_editor.h"
#include "dialog_graph_node.h"
#include "dialog_editor.h"
#include "dialog_text_editor_sorter.h"
#include "string_table_ids_storage.h"
#include "string_table_id.h"
using xray::dialog_editor::dialog_text_editor;
using xray::dialog_editor::string_tables::string_table_ids_storage;
using xray::dialog_editor::dialog_graph_node;
using xray::dialog_editor::dialog_editor_impl;
using xray::dialog_editor::AlphanumComparator;
using namespace System;
using namespace System::Collections;
using namespace xray::dialog_editor::string_tables;
void dialog_text_editor::assign_string_table_ids()
{
combo_box->Items->Clear();
Generic::List<String^ >^ lst = gcnew Generic::List<String^ >();
const string_table_ids_storage::string_table_ids_type* str_tbl = string_tables::get_string_tables()->string_table_ids();
string_table_ids_storage::string_table_ids_type::const_iterator b = str_tbl->begin();
for(; b!=str_tbl->end(); ++b)
lst->Add(gcnew String(b->first));
lst->Sort(gcnew AlphanumComparator());
for each(String^ v in lst)
combo_box->Items->Add(v);
lst->Clear();
if(m_editing_node!=nullptr)
text_box->Text = m_editor->get_text_by_id(m_editing_node->string_table);
}
void dialog_text_editor::update_selected_node(dialog_graph_node^ n)
{
if(n->is_dialog())
{
m_editing_node = nullptr;
Hide();
return;
}
if(!Visible)
return;
combo_box->SelectedItem = n->string_table;
text_box->Text = m_editor->get_text_by_id(n->string_table);
m_editing_node = n;
ActiveControl = text_box;
changed = false;
}
void dialog_text_editor::on_editor_closing(System::Object^ , System::Windows::Forms::FormClosingEventArgs^ e)
{
changed = false;
m_editing_node = nullptr;
Hide();
e->Cancel = true;
}
void dialog_text_editor::combo_box_selection_changed(System::Object^ , System::EventArgs^ )
{
text_box->Text = m_editor->get_text_by_id((String^)combo_box->SelectedItem);
changed = true;
}
void dialog_text_editor::on_key_down(System::Object^ , System::Windows::Forms::KeyEventArgs^ e)
{
changed = true;
if(e->KeyCode==Keys::Return)
{
update_editing_node_text();
m_editing_node = nullptr;
Hide();
changed = false;
}
else if(e->KeyCode==Keys::Escape)
{
m_editing_node = nullptr;
Hide();
changed = false;
}
}
void dialog_text_editor::on_key_press(System::Object^ , System::Windows::Forms::KeyPressEventArgs^ e)
{
if(e->KeyChar==(char)Keys::Return || e->KeyChar==(char)Keys::LineFeed)
e->Handled = true;
}
void dialog_text_editor::update_editing_node_text()
{
if(m_editing_node!=nullptr && combo_box->Text!="")
{
if(combo_box->SelectedItem==nullptr)
{
combo_box->Items->Insert(find_new_str_id_cb_pos(combo_box->Text), combo_box->Text);
m_editor->add_new_id(combo_box->Text, text_box->Text);
}
//else
//{
// System::String^ txt1 = text_box->Text;
// System::String^ txt2 = m_editor->get_text_by_id((String^)combo_box->SelectedItem);
// int a = 0;
//}
m_editor->update_node_text(m_editing_node, combo_box->Text, text_box->Text);
}
}
void dialog_text_editor::on_ok_clicked(System::Object^ , System::EventArgs^ )
{
update_editing_node_text();
changed = false;
}
void dialog_text_editor::on_cancel_clicked(System::Object^ , System::EventArgs^ )
{
m_editing_node = nullptr;
Hide();
changed = false;
}
u32 dialog_text_editor::find_new_str_id_cb_pos(System::String^ new_str_id)
{
u32 index = 0;
AlphanumComparator^ comparer = gcnew AlphanumComparator();
while(comparer->Compare(new_str_id, (String^)combo_box->Items[index])>=0)
++index;
return index;
}
| 28.15493 | 122 | 0.678339 | [
"object"
] |
5ede4823b93cb518c86e35e93318938ab1362b3e | 2,144 | cpp | C++ | src/scene/scene.cpp | miuho/Fast-Subdivision | d9e2ba1b46cadfb1570ce0a25d80141f71659f9d | [
"MIT"
] | null | null | null | src/scene/scene.cpp | miuho/Fast-Subdivision | d9e2ba1b46cadfb1570ce0a25d80141f71659f9d | [
"MIT"
] | 1 | 2018-08-08T00:28:27.000Z | 2018-08-08T00:28:27.000Z | src/scene/scene.cpp | miuho/Fast-Subdivision | d9e2ba1b46cadfb1570ce0a25d80141f71659f9d | [
"MIT"
] | null | null | null | /**
* @file scene.cpp
* @brief Function definitions for scenes.
*
*/
#include "scene/scene.hpp"
#include <ctime>
namespace _462 {
Geometry::Geometry():
position( Vector3::Zero ),
orientation( Quaternion::Identity ),
scale( Vector3::Ones )
{
}
Geometry::~Geometry() { }
PointLight::PointLight():
position( Vector3::Zero ),
color( Color3::White )
{
attenuation.constant = 1;
attenuation.linear = 0;
attenuation.quadratic = 0;
}
Scene::Scene()
{
reset();
}
Scene::~Scene()
{
reset();
}
bool Scene::subdivide_geometries()
{
bool success = true;
int n = geometries.size();
std::clock_t start;
start = std::clock();
for (int i = 0; i < n; i++)
{
success &= geometries[i]->subdivide();
}
double duration = (std::clock() - start)/double(CLOCKS_PER_SEC);
std::cout << "Subdivision took " << duration << " seconds." << std::endl;
return success;
}
const Scene::GeometryList& Scene::get_geometries() const
{
return geometries;
}
const Scene::PointLightList& Scene::get_lights() const
{
return point_lights;
}
const Scene::MaterialList& Scene::get_materials() const
{
return materials;
}
const Scene::MeshList& Scene::get_meshes() const
{
return meshes;
}
void Scene::reset()
{
for ( GeometryList::iterator i = geometries.begin(); i != geometries.end(); ++i ) {
delete *i;
}
for ( MaterialList::iterator i = materials.begin(); i != materials.end(); ++i ) {
delete *i;
}
for ( MeshList::iterator i = meshes.begin(); i != meshes.end(); ++i ) {
delete *i;
}
geometries.clear();
materials.clear();
meshes.clear();
point_lights.clear();
camera = Camera();
background_color = Color3::Black;
ambient_light = Color3::Black;
refractive_index = 1.0;
}
void Scene::add_geometry( Geometry* g )
{
geometries.push_back( g );
}
void Scene::add_material( Material* m )
{
materials.push_back( m );
}
void Scene::add_mesh( Mesh* m )
{
meshes.push_back( m );
}
void Scene::add_light( const PointLight& l )
{
point_lights.push_back( l );
}
} /* _462 */
| 17.152 | 87 | 0.612873 | [
"mesh",
"geometry"
] |
5ee72c4c488c48befb160c62206f54285e647552 | 22,525 | cpp | C++ | frameworks/src/core/modules/test/unittest/common/dfx_tdd_test.cpp | jaspercloud/ace_engine_lite | ba29e09ccb4b017d1f18fbecd313a89bc9557d12 | [
"Apache-2.0"
] | null | null | null | frameworks/src/core/modules/test/unittest/common/dfx_tdd_test.cpp | jaspercloud/ace_engine_lite | ba29e09ccb4b017d1f18fbecd313a89bc9557d12 | [
"Apache-2.0"
] | null | null | null | frameworks/src/core/modules/test/unittest/common/dfx_tdd_test.cpp | jaspercloud/ace_engine_lite | ba29e09ccb4b017d1f18fbecd313a89bc9557d12 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Huawei Device 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 "dfx_tdd_test.h"
#include <unistd.h>
#include "js_fwk_common.h"
#include "wrapper/js.h"
namespace OHOS {
namespace ACELite {
const char * const DfxTddTest::BUNDLE1
= "(function () {"
" return new ViewModel({"
" render: function (vm) {"
" var _vm = vm || this;"
" return _c('swiper', {"
" attrs : {index : 0,duration : 75},"
" staticClass : ['container'], "
" on : {'change' : _vm.swiperChange}} , ["
" _c('stack', {"
" staticClass : ['container']} , ["
" _c('text', {"
" attrs : {value : function() {return _vm.textValue}},"
" staticClass : ['pm25-name'],"
" staticStyle : {color : 16711680},"
" on : {'click' : _vm.click1}"
" })"
" ])"
" ]);"
" },"
" styleSheet: {"
" classSelectors: {"
" 'pm25-value': {"
" textAlign: 'center',"
" fontSize: 38,"
" color: 15794175,"
" height: 454,"
" width: 454,"
" top: 235"
" },"
" 'pm25-name': {"
" textAlign: 'center',"
" color: 10667170,"
" width: 454,"
" height: 50,"
" top: 285"
" }"
" }"
" },"
" data: {textValue: 'Hello World'},"
" onInit: function onInit() {},"
" onShow: function onShow() {},"
" openDetail: function openDetail() {},"
" click3: function click3() {"
" var sum = num + 1;"
" this.textValue = 'Hello Ace';"
" },"
" click2: function click2() {"
" this.click3();"
" },"
" click1: function click1() {"
" this.click2();"
" }"
" });"
"})();";
const char * const DfxTddTest::BUNDLE2
= "(function () {"
" return new ViewModel({"
" render: function (vm) {"
" var _vm = vm || this;"
" return _c('swiper', {"
" attrs : {index : 0,duration : 75},"
" staticClass : ['container'], "
" on : {'change' : _vm.swiperChange}} , ["
" _c('stack', {"
" staticClass : ['container']} , ["
" _c('text', {"
" attrs : {value : function() {return _vm.textValue}},"
" staticClass : ['pm25-name'],"
" staticStyle : {color : 16711680}"
" })"
" ])"
" ]);"
" },"
" styleSheet: {"
" classSelectors: {"
" 'pm25-value': {"
" textAlign: 'center',"
" fontSize: 38,"
" color: 15794175,"
" height: 454,"
" width: 454,"
" top: 235"
" },"
" 'pm25-name': {"
" textAlign: 'center',"
" color: 10667170,"
" width: 454,"
" height: 50,"
" top: 285"
" }"
" }"
" },"
" data: {textValue: 'Hello World'},"
" onInit: function onInit() {},"
" onShow: function onShow() {},"
" openDetail: function openDetail() {},"
" click3: function click3() {"
" this.click4();"
" this.textValue = 'Hello Ace';"
" },"
" click2: function click2() {"
" this.click3();"
" },"
" click1: function click1() {"
" this.click2();"
" }"
" });"
"})();";
const char * const DfxTddTest::BUNDLE3
= "(function () {"
" return new ViewModel({"
" render: function (vm) {"
" var _vm = vm || this;"
" return _c('swiper', {"
" attrs : {index : 0,duration : 75},"
" staticClass : ['container'], "
" on : {'change' : _vm.swiperChange}} , ["
" _c('stack', {"
" staticClass : ['container']} , ["
" _c('text', {"
" attrs : {value : function() {return _vm.textValue}},"
" staticClass : ['pm25-name'],"
" staticStyle : {color : 16711680}"
" })"
" ])"
" ]);"
" },"
" styleSheet: {"
" classSelectors: {"
" 'pm25-value': {"
" textAlign: 'center',"
" fontSize: 38,"
" color: 15794175,"
" height: 454,"
" width: 454,"
" top: 235"
" },"
" 'pm25-name': {"
" textAlign: 'center',"
" color: 10667170,"
" width: 454,"
" height: 50,"
" top: 285"
" }"
" }"
" },"
" data: {textValue: 'Hello World'},"
" onInit: function onInit() {},"
" onShow: function onShow() {},"
" openDetail: function openDetail() {},"
" click3: function click3() {"
" this.textValue = 'Hello Ace';"
" console.log('Hello Ace.');"
" },"
" click2: function click2() {"
" this.click3();"
" },"
" click1: function click1() {"
" this.click2();"
" }"
" });"
"})();";
const char * const DfxTddTest::BUNDLE4
= "(function () {"
" return new ViewModel({"
" render: function (vm) {"
" var _vm = vm || this;"
" return _c('swiper', {"
" attrs : {index : 0,duration : 75},"
" staticClass : ['container'], "
" on : {'change' : _vm.swiperChange}} , ["
" _c('stack', {"
" staticClass : ['container']} , ["
" _c('text', {"
" attrs : {value : function() {return _vm.textValue}},"
" staticClass : ['pm25-name'],"
" staticStyle : {color : 16711680}"
" })"
" ])"
" ]);"
" },"
" styleSheet: {"
" classSelectors: {"
" 'pm25-value': {"
" textAlign: 'center',"
" fontSize: 38,"
" color: 15794175,"
" height: 454,"
" width: 454,"
" top: 235"
" },"
" 'pm25-name': {"
" textAlign: 'center',"
" color: 10667170,"
" width: 454,"
" height: 50,"
" top: 285"
" }"
" }"
" },"
" data: {textValue: 'Hello World'},"
" onInit: function onInit() {},"
" onShow: function onShow() {},"
" openDetail: function openDetail() {},"
" click32: function click32() {"
" this,click33();"
" },"
" click31: function click31() {"
" this.click32();"
" },"
" click30: function click30() {"
" this.click31();"
" },"
" click29: function click29() {"
" this,click30();"
" },"
" click28: function click28() {"
" this.click29();"
" },"
" click27: function click27() {"
" this.click28();"
" },"
" click26: function click26() {"
" this,click27();"
" },"
" click25: function click25() {"
" this.click26();"
" },"
" click24: function click24() {"
" this,click25();"
" },"
" click23: function click23() {"
" this.click24();"
" },"
" click22: function click22() {"
" this.click23();"
" },"
" click21: function click21() {"
" this,click22();"
" },"
" click20: function click20() {"
" this.click21();"
" },"
" click19: function click19() {"
" this.click20();"
" },"
" click18: function click18() {"
" this,click19();"
" },"
" click17: function click17() {"
" this.click18();"
" },"
" click16: function click16() {"
" this.click17();"
" },"
" click15: function click15() {"
" this,click16();"
" },"
" click14: function click14() {"
" this.click15();"
" },"
" click13: function click13() {"
" this.click14();"
" },"
" click12: function click12() {"
" this,click13();"
" },"
" click11: function click11() {"
" this.click12();"
" },"
" click10: function click10() {"
" this.click11();"
" },"
" click9: function click9() {"
" this,click10();"
" },"
" click8: function click8() {"
" this.click9();"
" },"
" click7: function click7() {"
" this.click8();"
" },"
" click6: function click6() {"
" this,click7();"
" },"
" click5: function click5() {"
" this.click6();"
" },"
" click4: function click4() {"
" this.click5();"
" },"
" click3: function click3() {"
" this,click4();"
" },"
" click2: function click2() {"
" this.click3();"
" },"
" click1: function click1() {"
" this.click2();"
" }"
" });"
"})();";
const char * const DfxTddTest::FUNC_NAME = "click1";
void DfxTddTest::DfxTest001()
{
TDD_CASE_BEGIN();
JSValue page = CreatePage(BUNDLE1, strlen(BUNDLE1));
JSValue ret = JSObject::Call(page, FUNC_NAME);
if (!jerry_value_is_error(ret)) {
TDD_CASE_END();
DestroyPage(page);
return;
}
// trace out error information if the result contains error
jerry_value_t errValue = jerry_get_value_from_error(ret, false);
jerry_value_t errStrVal = jerry_value_to_string(errValue);
jerry_release_value(errValue);
jerry_size_t errStrSize = jerry_get_utf8_string_size(errStrVal);
jerry_char_t *errStrBuffer = static_cast<jerry_char_t *>(ace_malloc(sizeof(jerry_char_t) * (errStrSize + 1)));
if (errStrBuffer == nullptr) {
jerry_release_value(errStrVal);
TDD_CASE_END();
DestroyPage(page);
return;
}
jerry_size_t stringEnd = jerry_string_to_utf8_char_buffer(errStrVal, errStrBuffer, errStrSize);
errStrBuffer[stringEnd] = '\0';
EXPECT_STREQ(reinterpret_cast<char *>(errStrBuffer), "ReferenceError: num is not defined");
ace_free(errStrBuffer);
errStrBuffer = nullptr;
jerry_release_value(errStrVal);
JSValue value = JSObject::Get(page, "textValue");
char *valueStr = JSString::Value(value);
if (valueStr != nullptr) {
EXPECT_STREQ(valueStr, "Hello World");
ace_free(valueStr);
valueStr = nullptr;
}
jerry_release_value(value);
TDD_CASE_END();
DestroyPage(page);
}
void DfxTddTest::DfxTest002()
{
TDD_CASE_BEGIN();
JSValue page = CreatePage(BUNDLE2, strlen(BUNDLE2));
JSValue errorValue = JSObject::Call(page, FUNC_NAME);
if (!jerry_value_is_error(errorValue)) {
TDD_CASE_END();
DestroyPage(page);
return;
}
const uint16_t stackMsgMaxLength = 256;
const uint8_t exceptLength = 3;
const char *stack = "stack";
jerry_value_t stackStr = jerry_create_string((const jerry_char_t *) stack);
jerry_value_t errorVal = jerry_get_value_from_error(errorValue, false);
jerry_value_t backtraceVal = jerry_get_property(errorVal, stackStr);
ReleaseJerryValue(stackStr, errorVal, VA_ARG_END_FLAG);
if (jerry_value_is_error(backtraceVal) || !(jerry_value_is_array(backtraceVal))) {
TDD_CASE_END();
DestroyPage(page);
jerry_release_value(backtraceVal);
return;
}
uint32_t length = jerry_get_array_length(backtraceVal);
EXPECT_EQ(length, exceptLength);
jerry_char_t *errStrBuffer = static_cast<jerry_char_t *>(ace_malloc(sizeof(jerry_char_t) * (stackMsgMaxLength)));
if (errStrBuffer == nullptr) {
jerry_release_value(backtraceVal);
TDD_CASE_END();
DestroyPage(page);
return;
}
jerry_value_t itemVal = jerry_get_property_by_index(backtraceVal, 0);
jerry_size_t strSize = 0;
if (!jerry_value_is_error(itemVal) && jerry_value_is_string(itemVal)) {
strSize = jerry_get_utf8_string_size(itemVal);
}
jerry_size_t stringEnd = jerry_string_to_utf8_char_buffer(itemVal, errStrBuffer, strSize);
errStrBuffer[stringEnd] = '\0';
EXPECT_STREQ(reinterpret_cast<char *>(errStrBuffer), "click3(), ");
ace_free(errStrBuffer);
errStrBuffer = nullptr;
JSValue value = JSObject::Get(page, "textValue");
char *valueStr = JSString::Value(value);
if (valueStr != nullptr) {
EXPECT_STREQ(valueStr, "Hello World");
ace_free(valueStr);
valueStr = nullptr;
}
ReleaseJerryValue(itemVal, backtraceVal, value, VA_ARG_END_FLAG);
TDD_CASE_END();
DestroyPage(page);
}
void DfxTddTest::DfxTest003()
{
TDD_CASE_BEGIN();
JSValue page = CreatePage(BUNDLE3, strlen(BUNDLE3));
JSValue ret = JSObject::Call(page, FUNC_NAME);
if (jerry_value_is_error(ret)) {
TDD_CASE_END();
DestroyPage(page);
return;
}
JSValue value = JSObject::Get(page, "textValue");
char *valueStr = JSString::Value(value);
if (valueStr != nullptr) {
EXPECT_STREQ(valueStr, "Hello Ace");
ace_free(valueStr);
valueStr = nullptr;
}
jerry_release_value(value);
TDD_CASE_END();
DestroyPage(page);
}
void DfxTddTest::DfxTest004()
{
TDD_CASE_BEGIN();
JSValue page = CreatePage(BUNDLE4, strlen(BUNDLE4));
JSValue ret = JSObject::Call(page, FUNC_NAME);
if (jerry_value_is_error(ret)) {
TDD_CASE_END();
DestroyPage(page);
return;
}
const uint8_t exceptLength = 32;
const char *stack = "stack";
jerry_value_t stackStr = jerry_create_string((const jerry_char_t *) stack);
jerry_value_t errorVal = jerry_get_value_from_error(ret, false);
jerry_value_t backtraceVal = jerry_get_property(errorVal, stackStr);
jerry_release_value(stackStr);
jerry_release_value(errorVal);
if (jerry_value_is_error(backtraceVal) || !(jerry_value_is_array(backtraceVal))) {
TDD_CASE_END();
DestroyPage(page);
jerry_release_value(backtraceVal);
return;
}
uint32_t length = jerry_get_array_length(backtraceVal);
EXPECT_EQ(length, exceptLength);
TDD_CASE_END();
jerry_release_value(backtraceVal);
DestroyPage(page);
}
void DfxTddTest::RunTests()
{
DfxTest001();
DfxTest002();
DfxTest003();
DfxTest004();
}
#ifdef TDD_ASSERTIONS
/* *
* @tc.name: DfxTest001
* @tc.desc: Verify error code.
* @tc.require: AR000F3PDP
*/
HWTEST_F(DfxTddTest, DfxTest001, TestSize.Level0)
{
DfxTddTest::DfxTest001();
}
/* *
* @tc.name: DfxTest002
* @tc.desc: Verify error message.
* @tc.require: AR000F3PDP
*/
HWTEST_F(DfxTddTest, DfxTest002, TestSize.Level0)
{
DfxTddTest::DfxTest002();
}
/* *
* @tc.name: DfxTest003
* @tc.desc: Verify normal process.
* @tc.require: AR000F3PDP
*/
HWTEST_F(DfxTddTest, DfxTest003, TestSize.Level1)
{
DfxTddTest::DfxTest003();
}
/* *
* @tc.name: DfxTest004
* @tc.desc: Verify pressure test.
* @tc.require: AR000F3PDP
*/
HWTEST_F(DfxTddTest, DfxTest004, TestSize.Level1)
{
DfxTddTest::DfxTest004();
}
#endif // TDD_ASSERTIONS
}
} // namespace ACELite
| 42.102804 | 117 | 0.364395 | [
"render"
] |
5ee8837f7271f377569050f4a0af27c3c6e1b1df | 6,325 | hpp | C++ | rigid2d/include/rigid2d/diff_drive.hpp | YaelBenShalom/Turtlebot3-SLAM-from-scratch | 82c118f8598549c4824c43c33b0f85d51b17f465 | [
"MIT"
] | 5 | 2021-12-20T11:55:53.000Z | 2022-03-07T19:00:34.000Z | rigid2d/include/rigid2d/diff_drive.hpp | YaelBenShalom/Turtlebot3-SLAM-from-scratch | 82c118f8598549c4824c43c33b0f85d51b17f465 | [
"MIT"
] | null | null | null | rigid2d/include/rigid2d/diff_drive.hpp | YaelBenShalom/Turtlebot3-SLAM-from-scratch | 82c118f8598549c4824c43c33b0f85d51b17f465 | [
"MIT"
] | 1 | 2022-01-20T09:25:22.000Z | 2022-01-20T09:25:22.000Z | /// \file diff_drive.hpp
/// \brief Library for the kinematics of a differential drive robot with a given
/// wheel base and wheel radius.
#ifndef DIFFDRIVE_INCLUDE_GUARD_HPP
#define DIFFDRIVE_INCLUDE_GUARD_HPP
#include "rigid2d/rigid2d.hpp"
#include <cmath>
#include <iosfwd>
namespace rigid2d
{
/// \brief The configuration of the robot
struct Config2D
{
/// \param x - the x configuration of the robot
double x;
/// \param y - the y configuration of the robot
double y;
/// \param theta - the theta configuration of the robot
double theta;
/// \brief constructor for zero configuration
Config2D();
/// \brief constructor for non-zero configuration
/// \param x_ - the x configuration of the robot
/// \param y_ - the y configuration of the robot
/// \param theta_ - the theta configuration of the robot
Config2D(double x_, double y_, double theta_);
};
/// \brief The velocity of the robot's wheels
struct WheelVelocity
{
/// \param right_wheel_vel - the velocity of the right wheel
double right_wheel_vel;
/// \param left_wheel_vel - the velocity of the left wheel
double left_wheel_vel;
/// \brief constructor for zero wheel velocity
WheelVelocity();
/// \brief constructor for non-zero wheel velocity
/// \param right_wheel_vel_ - the velocity of the right wheel
/// \param left_wheel_vel_ - the velocity of the left wheel
WheelVelocity(double right_wheel_vel_, double left_wheel_vel_);
};
/// \brief The angle of the robot's wheels
struct WheelAngle
{
/// \param right_wheel_angle - the angle of the right wheel
double right_wheel_angle;
/// \param left_wheel_angle - the angle of the left wheel
double left_wheel_angle;
/// \brief constructor for zero wheel angle
WheelAngle();
/// \brief constructor for non-zero wheel angle
/// \param right_wheel_angle_ - the angle of the right wheel
/// \param left_wheel_angle_ - the angle of the left wheel
WheelAngle(double right_wheel_angle_, double left_wheel_angle_);
};
/// \brief The class models the kinematics of a differential drive robot with a
/// given wheel base and wheel radius. The class:
/// 1. Track the configuration of a differential-drive robot
/// 2. Convert a desired twist to the equivalent wheel velocities required to
/// achieve that twist
/// 3. Update the configuration of the robot, given updated wheel angles
/// (assuming constant wheel velocity in-between updates)
class DiffDrive
{
private:
/// \param wheel_base - the distance between the wheels
double wheel_base;
/// \param wheel_radius - the radius of the wheels
double wheel_radius;
/// \param config - the current configuration of the robot
Config2D config;
/// \param wheel_vel - the wheel velocities of the robot
WheelVelocity wheel_vel;
/// \param wheel_angle - the wheel angle of the robot
WheelAngle wheel_angle;
public:
/// \brief defines the robot configuration as (0,0,0)
DiffDrive();
/// \brief defines the robot configuration as (0,0,0)
/// \param wheel_base_ - the distance between the wheels
/// \param wheel_radius_ - the radius of the wheels
DiffDrive(double wheel_base_, double wheel_radius_);
/// \brief defines the robot configuration
/// \param config_ - the current configuration of the robot
/// \param wheel_base_ - the distance between the wheels
/// \param wheel_radius_ - the radius of the wheels
DiffDrive(const Config2D &config_, double wheel_base_, double wheel_radius_);
/// \brief returns the configuration of the robot
/// \return the configuration of the robot
Config2D get_config();
/// \brief reset the configuration of the robot
/// \param config_ - the current configuration of the robot
/// \return void
void set_config(const Config2D &config_);
/// \brief returns the transform of the robot
/// \return the transform of the robot
Transform2D get_transform();
/// \brief returns the wheel angle of the robot
/// \return the wheel angle of the robot
WheelAngle get_wheel_angle();
/// \brief returns the wheel velocity of the robot
/// \return the wheel velocity of the robot
WheelVelocity get_wheel_vel();
/// \brief convert a desired twist to the equivalent wheel velocities
/// required to achieve that twist
/// \param twist - the robot's twist
/// \return the wheel velocities of the robot
WheelVelocity twist2Wheels(const Twist2D &twist);
/// \brief convert a desired wheel velocities to the equivalent twist
/// required to achieve those wheel velocities
/// \param vel - the robot's wheel velocity
/// \return the twist of the robot
Twist2D wheels2Twist(const WheelVelocity &vel);
/// \brief convert a wheels angles to the equivalent wheel velocities
/// \param right_wheel_angle_ - the right wheel angle (phi1)
/// \param left_wheel_angle_ - the left wheel angle (phi2)
/// \return the wheel velocities of the robot
WheelVelocity wheelAngle2WheelVel(double right_wheel_angle_,
double left_wheel_angle_);
/// \brief convert wheel velocities to the equivalent wheel angles
/// \param vel - the wheel velocities of the robot
/// \return the wheel angles of the robot
WheelAngle wheelVel2WheelAngle(const WheelVelocity &vel);
/// \brief updates the odometry with wheel angles
/// \param right_wheel_angle_ - the right wheel angle (phi1)
/// \param left_wheel_angle_ - the left wheel angle (phi2)
/// \return the wheel velocities of the robot
WheelVelocity updateOdometryWithAngles(double right_wheel_angle_,
double left_wheel_angle_);
/// \brief updates the odometry with twist input
/// \param tw - the twist of the robot
/// \return the wheel angles of the robot
WheelAngle updateOdometryWithTwist(const Twist2D &tw);
/// \brief rotating the wheels with twist input (without updating the
/// odometry)
/// \param tw - the twist of the robot \return the wheel angles of
/// the robot
WheelAngle rotatingWheelsWithTwist(const Twist2D &tw);
};
} // namespace rigid2d
#endif
| 36.773256 | 81 | 0.693755 | [
"transform"
] |
5eec588b402acded55b91f28310069ffb687d8fa | 2,535 | hpp | C++ | include/cpl/number_theory/chinese_remainder_theorem.hpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 25 | 2016-05-03T02:08:58.000Z | 2022-01-11T03:49:28.000Z | include/cpl/number_theory/chinese_remainder_theorem.hpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 22 | 2016-04-26T04:46:17.000Z | 2016-12-06T03:53:32.000Z | include/cpl/number_theory/chinese_remainder_theorem.hpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 5 | 2017-04-04T16:10:42.000Z | 2019-12-05T08:22:30.000Z | // Copyright Diego Ramirez 2015
// 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 CPL_NUMBER_THEORY_CHINESE_REMAINDER_THEOREM_HPP
#define CPL_NUMBER_THEORY_CHINESE_REMAINDER_THEOREM_HPP
#include <cpl/number_theory/modular.hpp> // mod_mul, mod_inverse
#include <cassert> // assert
#include <cstddef> // size_t
#include <utility> // pair, make_pair
#include <vector> // vector
namespace cpl {
/// \brief Solves the system of simultaneous congruences stated by the chinese
/// remainder theorem.
///
/// Uses the method of successive substitution to find a valid solution on the
/// given system. Let <tt>(\b a, \b m)</tt> be a system of \c N congruences, it
/// finds an integer \c x such that:
///
/// <blockquote><tt>x ≅ a<sub>i</sub> mod m<sub>i</sub></tt>, for all
/// <tt>i</tt></blockquote>
///
/// A solution \c x exists if and only if:
/// <blockquote><tt>a<sub>i</sub> ≅ a<sub>j</sub> (mod gcd(m<sub>i</sub>,
/// m<sub>j</sub></tt>)), for all \c i and \c j</blockquote>
///
/// \param a The sequence of remainders.
/// \param m The sequence of modulos.
///
/// \pre <tt>a.size() >= 1</tt>
/// \pre <tt>a.size() == m.size()</tt>
/// \pre <tt>a[i] >= 0 && a[i] < m[i]</tt>, for all <tt>i</tt>.
/// \pre The product of the <tt>m<sub>i</sub></tt> will be representable as a
/// value of type <tt>T</tt>.
/// \pre All values of <tt>m<sub>i</sub></tt> will be pairwise coprime.
///
/// \returns The smallest non-negative solution for the given system. All
/// other solutions \c x are congruent modulo the product of the
/// <tt>m<sub>i</sub></tt>.
///
/// \par Complexity
/// Exactly <tt>N - 1</tt> applications of <tt>mod_inverse</tt>,
/// where <tt>N = a.size()</tt>.
///
template <typename T>
T chinese_remainder_theorem(const std::vector<T>& a, const std::vector<T>& m) {
auto solve2 = [](T a0, T m0, T a1, T m1) {
T t = mod_inverse(m0 % m1, m1);
assert(t != m1); // Otherwise no solution exists.
t = mod_mul(mod_sub(a1, a0 % m1, m1), t, m1);
return std::make_pair(a0 + m0 * t, m0 * m1);
};
std::pair<T, T> reduced{a[0], m[0]};
for (size_t i = 1; i < a.size(); ++i) {
reduced = solve2(reduced.first, reduced.second, a[i], m[i]);
assert(reduced.first >= 0 && reduced.first < reduced.second);
}
return reduced.first;
}
} // end namespace cpl
#endif // Header guard
| 37.279412 | 79 | 0.614596 | [
"vector"
] |
5eecf64a9256e68c0b98a57ec96c15065429d63f | 16,660 | cpp | C++ | examples/cvode/hip/cvAdvDiff_kry_hip.cpp | d5ch4k/sundials | c0097c0bfd56e8f94dbb588e0894fdceacf6f737 | [
"BSD-3-Clause"
] | 256 | 2017-10-06T04:11:32.000Z | 2022-03-25T07:15:53.000Z | examples/cvode/hip/cvAdvDiff_kry_hip.cpp | d5ch4k/sundials | c0097c0bfd56e8f94dbb588e0894fdceacf6f737 | [
"BSD-3-Clause"
] | 114 | 2018-03-24T20:38:31.000Z | 2022-03-30T16:59:05.000Z | examples/cvode/hip/cvAdvDiff_kry_hip.cpp | d5ch4k/sundials | c0097c0bfd56e8f94dbb588e0894fdceacf6f737 | [
"BSD-3-Clause"
] | 77 | 2017-11-16T08:32:31.000Z | 2022-01-25T15:22:17.000Z | /* -----------------------------------------------------------------
* Programmer(s): Cody Balos @ LLNL
* -----------------------------------------------------------------
* Acknowledgements: This example is based on cvAdvDiff_kry_cuda.cu.
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2021, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* -----------------------------------------------------------------
* Example problem:
*
* The following is a simple example problem with a banded Jacobian,
* with the program for its solution by CVODE.
* The problem is the semi-discrete form of the advection-diffusion
* equation in 2-D:
* du/dt = d^2 u / dx^2 + .5 du/dx + d^2 u / dy^2
* on the rectangle 0 <= x <= 2, 0 <= y <= 1, and the time
* interval 0 <= t <= 1. Homogeneous Dirichlet boundary conditions
* are posed, and the initial condition is
* u(x,y,t=0) = x(2-x)y(1-y)exp(5xy).
* The PDE is discretized on a uniform MX+2 by MY+2 grid with
* central differencing, and with boundary values eliminated,
* leaving an ODE system of size NEQ = MX*MY.
* This program solves the problem with the BDF method, Newton
* iteration with the GMRES linear solver, and a user-supplied
* Jacobian routine.
* It uses scalar relative and absolute tolerances.
* Output is printed at t = .1, .2, ..., 1.
* Run statistics (optional outputs) are printed at the end.
* -----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <hip/hip_runtime.h>
#include <cvode/cvode.h> /* prototypes for CVODE fcts., consts. */
#include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */
#include <sundials/sundials_types.h> /* definition of type realtype */
#include <sundials/sundials_math.h> /* definition of ABS and EXP */
#include <nvector/nvector_hip.h>
/* Real Constants */
#define ATOL RCONST(1.0e-5) /* scalar absolute tolerance */
#define T0 RCONST(0.0) /* initial time */
#define T1 RCONST(0.1) /* first output time */
#define DTOUT RCONST(0.1) /* output time increment */
#define NOUT 10 /* number of output times */
#define ZERO RCONST(0.0)
#define HALF RCONST(0.5)
#define ONE RCONST(1.0)
#define TWO RCONST(2.0)
#define FIVE RCONST(5.0)
#if defined(SUNDIALS_EXTENDED_PRECISION)
#define GSYM "Lg"
#define ESYM "Le"
#define FSYM "Lf"
#else
#define GSYM "g"
#define ESYM "e"
#define FSYM "f"
#endif
#if defined(SUNDIALS_INT64_T)
#define DSYM "ld"
#else
#define DSYM "d"
#endif
/*
* HIP kernels
*/
__global__ void fKernel(const realtype *u, realtype *udot,
sunindextype MX, sunindextype MY,
realtype hordc, realtype horac, realtype verdc)
{
realtype uij, udn, uup, ult, urt, hdiff, hadv, vdiff;
sunindextype i, j, tid;
/* Loop over all grid points. */
tid = blockDim.x * blockIdx.x + threadIdx.x;
if (tid < MX*MY) {
i = tid/MY;
j = tid%MY;
uij = u[tid];
udn = (j == 0) ? ZERO : u[tid - 1];
uup = (j == MY-1) ? ZERO : u[tid + 1];
ult = (i == 0) ? ZERO : u[tid - MY];
urt = (i == MX-1) ? ZERO : u[tid + MY];
/* Set diffusion and advection terms and load into udot */
hdiff = hordc*(ult - TWO*uij + urt);
hadv = horac*(urt - ult);
vdiff = verdc*(uup - TWO*uij + udn);
udot[tid] = hdiff + hadv + vdiff;
}
}
__global__ void jtvKernel(const realtype *vdata, realtype *Jvdata,
sunindextype MX, sunindextype MY,
realtype hordc, realtype horac, realtype verdc)
{
sunindextype i, j, tid;
/* Loop over all grid points. */
tid = blockDim.x * blockIdx.x + threadIdx.x;
if (tid < MX*MY) {
i = tid/MY;
j = tid%MY;
/* set the tid-th element of Jv */
Jvdata[tid] = -TWO*(verdc+hordc) * vdata[tid];
if (i != 0) Jvdata[tid] += (hordc - horac) * vdata[tid-MY];
if (i != MX-1) Jvdata[tid] += (hordc + horac) * vdata[tid+MY];
if (j != 0) Jvdata[tid] += verdc * vdata[tid-1];
if (j != MY-1) Jvdata[tid] += verdc * vdata[tid+1];
}
}
/* Type : _UserData (contains model and discretization parameters) */
struct _UserData {
sunindextype MX, MY, NEQ;
realtype dx, dy, XMAX, YMAX;
realtype hdcoef, hacoef, vdcoef;
};
typedef _UserData *UserData;
/* Problem setup and initialization functions */
static UserData SetUserData(int argc, char** argv);
static void SetIC(N_Vector u, UserData data);
/* Functions Called by the Solver */
static int f(realtype t, N_Vector u, N_Vector udot, void *user_data);
static int jtv(N_Vector v, N_Vector Jv, realtype t,
N_Vector u, N_Vector fu,
void *user_data, N_Vector tmp);
/* Private Helper Functions */
static void PrintHeader(realtype reltol, realtype abstol, realtype umax, UserData data);
static void PrintOutput(realtype t, realtype umax, long int nst);
static void PrintFinalStats(void *cvode_mem);
/* Private function to check function return values */
static int check_retval(void *returnvalue, const char *funcname, int opt);
/*
*-------------------------------
* Main Program
*-------------------------------
*/
int main(int argc, char** argv)
{
sundials::Context sunctx;
realtype reltol, abstol, t, tout, umax;
N_Vector u;
UserData data;
SUNLinearSolver LS;
void *cvode_mem;
int iout, retval;
long int nst;
hipStream_t stream;
hipError_t cuerr;
u = NULL;
data = NULL;
LS = NULL;
cvode_mem = NULL;
/* optional: create a hipStream to use with the HIP NVector
(otherwise the default stream is used) and creating kernel
execution policies */
cuerr = hipStreamCreate(&stream);
if (cuerr != hipSuccess) {
printf("Error in hipStreamCreate(): %s\n", hipGetErrorString(cuerr));
return(1);
}
SUNHipThreadDirectExecPolicy stream_exec_policy(256, stream);
SUNHipBlockReduceExecPolicy reduce_exec_policy(256, 0, stream);
/* Set model parameters */
data = SetUserData(argc, argv);
if(check_retval((void *)data, "malloc", 2)) return(1);
reltol = ZERO; /* Set the tolerances */
abstol = ATOL;
/* Create a HIP vector with initial values */
u = N_VNew_Hip(data->NEQ, sunctx); /* Allocate u vector */
if(check_retval((void*)u, "N_VNew_Hip", 0)) return(1);
/* Use a non-default hip stream for kernel execution */
retval = N_VSetKernelExecPolicy_Hip(u, &stream_exec_policy, &reduce_exec_policy);
if(check_retval(&retval, "N_VSetKernelExecPolicy_Hip", 0)) return(1);
SetIC(u, data); /* Initialize u vector */
/* Call CVodeCreate to create the solver memory and specify the
* Backward Differentiation Formula */
cvode_mem = CVodeCreate(CV_BDF, sunctx);
if(check_retval((void *)cvode_mem, "CVodeCreate", 0)) return(1);
/* Call CVodeInit to initialize the integrator memory and specify the
* user's right hand side function in u'=f(t,u), the initial time T0, and
* the initial dependent variable vector u. */
retval = CVodeInit(cvode_mem, f, T0, u);
if(check_retval(&retval, "CVodeInit", 1)) return(1);
/* Call CVodeSStolerances to specify the scalar relative tolerance
* and scalar absolute tolerance */
retval = CVodeSStolerances(cvode_mem, reltol, abstol);
if (check_retval(&retval, "CVodeSStolerances", 1)) return(1);
/* Set the pointer to user-defined data */
retval = CVodeSetUserData(cvode_mem, data);
if(check_retval(&retval, "CVodeSetUserData", 1)) return(1);
/* Create SPGMR solver structure without preconditioning
* and the maximum Krylov dimension maxl */
LS = SUNLinSol_SPGMR(u, SUN_PREC_NONE, 0, sunctx);
if(check_retval(&retval, "SUNLinSol_SPGMR", 1)) return(1);
/* Set CVode linear solver to LS */
retval = CVodeSetLinearSolver(cvode_mem, LS, NULL);
if(check_retval(&retval, "CVodeSetLinearSolver", 1)) return(1);
/* Set the Jacobian-times-vector function */
retval = CVodeSetJacTimes(cvode_mem, NULL, jtv);
if(check_retval(&retval, "CVodeSetJacTimesVecFn", 1)) return(1);
/* In loop over output points: call CVode, print results, test for errors */
umax = N_VMaxNorm(u);
PrintHeader(reltol, abstol, umax, data);
for(iout=1, tout=T1; iout <= NOUT; iout++, tout += DTOUT) {
retval = CVode(cvode_mem, tout, u, &t, CV_NORMAL);
if(check_retval(&retval, "CVode", 1)) break;
umax = N_VMaxNorm(u);
retval = CVodeGetNumSteps(cvode_mem, &nst);
check_retval(&retval, "CVodeGetNumSteps", 1);
PrintOutput(t, umax, nst);
}
PrintFinalStats(cvode_mem); /* Print some final statistics */
N_VDestroy(u); /* Free the u vector */
CVodeFree(&cvode_mem); /* Free the integrator memory */
SUNLinSolFree(LS); /* Free linear solver memory */
free(data); /* Free the user data */
cuerr = hipStreamDestroy(stream); /* Free and cleanup the HIP stream */
if(cuerr != hipSuccess) { printf("Error: hipStreamDestroy() failed\n"); return(1); }
return(0);
}
/*
*-------------------------------------------
* Problem setup and initialization functions
*-------------------------------------------
*/
/* Set model and discretization parameters */
UserData SetUserData(int argc, char *argv[])
{
const sunindextype MX = 10;
const sunindextype MY = 5;
const realtype XMAX = RCONST(2.0); /* domain boundaries */
const realtype YMAX = RCONST(1.0);
/* Allocate user data structure */
UserData ud = (UserData) malloc(sizeof *ud);
if(check_retval((void*) ud, "AllocUserData", 2)) return(NULL);
ud->MX = MX;
ud->MY = MY;
ud->NEQ = MX*MY;
ud->XMAX = XMAX;
ud->YMAX = YMAX;
ud->dx = XMAX/(MX+1); /* Set grid coefficients in data */
ud->dy = YMAX/(MY+1);
ud->hdcoef = ONE/(ud->dx*ud->dx);
ud->hacoef = HALF/(TWO*ud->dx);
ud->vdcoef = ONE/(ud->dy*ud->dy);
return ud;
}
/* Set initial conditions in u vector */
static void SetIC(N_Vector u, UserData data)
{
/* Extract needed constants from data */
const realtype dx = data->dx;
const realtype dy = data->dy;
const realtype xmax = data->XMAX;
const realtype ymax = data->YMAX;
const sunindextype MY = data->MY;
const sunindextype NEQ = data->NEQ;
/* Extract pointer to solution vector data on the host */
realtype *udata = N_VGetHostArrayPointer_Hip(u);
sunindextype i, j, tid;
realtype x, y;
/* Load initial profile into u vector */
for (tid=0; tid < NEQ; tid++) {
i = tid / MY;
j = tid % MY;
x = (i+1)*dx;
y = (j+1)*dy;
udata[tid] = x*(xmax - x)*y*(ymax - y)*SUNRexp(FIVE*x*y);
}
N_VCopyToDevice_Hip(u);
}
/*
*-------------------------------
* Functions called by the solver
*-------------------------------
*/
/* f routine. Compute f(t,u). */
static int f(realtype t, N_Vector u, N_Vector udot, void *user_data)
{
UserData data = (UserData) user_data;
/* Extract needed constants from data */
const sunindextype MX = data->MX;
const sunindextype MY = data->MY;
const realtype hordc = data->hdcoef;
const realtype horac = data->hacoef;
const realtype verdc = data->vdcoef;
/* Extract pointers to vector data */
const realtype *udata = N_VGetDeviceArrayPointer_Hip(u);
realtype *dudata = N_VGetDeviceArrayPointer_Hip(udot);
unsigned block = 256;
unsigned grid = (MX*MY + block - 1) / block;
fKernel<<<grid,block>>>(udata, dudata, MX, MY, hordc, horac, verdc);
return(0);
}
/* Jacobian-times-vector routine. */
static int jtv(N_Vector v, N_Vector Jv, realtype t,
N_Vector u, N_Vector fu,
void *user_data, N_Vector tmp)
{
UserData data = (UserData) user_data;
/* Extract needed constants from data */
const sunindextype MX = data->MX;
const sunindextype MY = data->MY;
const realtype hordc = data->hdcoef;
const realtype horac = data->hacoef;
const realtype verdc = data->vdcoef;
/* Extract pointers to vector data */
const realtype *vdata = N_VGetDeviceArrayPointer_Hip(v);
realtype *Jvdata = N_VGetDeviceArrayPointer_Hip(Jv);
unsigned block = 256;
unsigned grid = (MX*MY + block - 1) / block;
N_VConst(ZERO, Jv);
jtvKernel<<<grid,block>>>(vdata, Jvdata, MX, MY, hordc, horac, verdc);
return(0);
}
/*
*-------------------------------
* Private helper functions
*-------------------------------
*/
/* Print first lines of output (problem description) */
static void PrintHeader(realtype reltol, realtype abstol, realtype umax,
UserData data)
{
printf("\n2-D Advection-Diffusion Equation\n");
printf("Mesh dimensions = %" DSYM " X %" DSYM "\n", data->MX, data->MY);
printf("Total system size = %" DSYM "\n", data->NEQ);
printf("Tolerance parameters: reltol = %" GSYM " abstol = %" GSYM "\n\n",
reltol, abstol);
printf("At t = %" GSYM " max.norm(u) =%14.6" ESYM " \n", T0, umax);
return;
}
/* Print current value */
static void PrintOutput(realtype t, realtype umax, long int nst)
{
printf("At t = %4.2" FSYM " max.norm(u) =%14.6" ESYM " nst = %4ld\n", t, umax, nst);
return;
}
/* Get and print some final statistics */
static void PrintFinalStats(void *cvode_mem)
{
long lenrw, leniw ;
long lenrwLS, leniwLS;
long int nst, nfe, nsetups, nni, ncfn, netf;
long int nli, npe, nps, ncfl, nfeLS;
int retval;
retval = CVodeGetWorkSpace(cvode_mem, &lenrw, &leniw);
check_retval(&retval, "CVodeGetWorkSpace", 1);
retval = CVodeGetNumSteps(cvode_mem, &nst);
check_retval(&retval, "CVodeGetNumSteps", 1);
retval = CVodeGetNumRhsEvals(cvode_mem, &nfe);
check_retval(&retval, "CVodeGetNumRhsEvals", 1);
retval = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);
check_retval(&retval, "CVodeGetNumLinSolvSetups", 1);
retval = CVodeGetNumErrTestFails(cvode_mem, &netf);
check_retval(&retval, "CVodeGetNumErrTestFails", 1);
retval = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);
check_retval(&retval, "CVodeGetNumNonlinSolvIters", 1);
retval = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);
check_retval(&retval, "CVodeGetNumNonlinSolvConvFails", 1);
retval = CVodeGetLinWorkSpace(cvode_mem, &lenrwLS, &leniwLS);
check_retval(&retval, "CVodeGetLinWorkSpace", 1);
retval = CVodeGetNumLinIters(cvode_mem, &nli);
check_retval(&retval, "CVodeGetNumLinIters", 1);
retval = CVodeGetNumPrecEvals(cvode_mem, &npe);
check_retval(&retval, "CVodeGetNumPrecEvals", 1);
retval = CVodeGetNumPrecSolves(cvode_mem, &nps);
check_retval(&retval, "CVodeGetNumPrecSolves", 1);
retval = CVodeGetNumLinConvFails(cvode_mem, &ncfl);
check_retval(&retval, "CVodeGetNumLinConvFails", 1);
retval = CVodeGetNumLinRhsEvals(cvode_mem, &nfeLS);
check_retval(&retval, "CVodeGetNumLinRhsEvals", 1);
printf("\nFinal Statistics.. \n\n");
printf("lenrw = %5ld leniw = %5ld\n" , lenrw, leniw);
printf("lenrwLS = %5ld leniwLS = %5ld\n" , lenrwLS, leniwLS);
printf("nst = %5ld\n" , nst);
printf("nfe = %5ld nfeLS = %5ld\n" , nfe, nfeLS);
printf("nni = %5ld nli = %5ld\n" , nni, nli);
printf("nsetups = %5ld netf = %5ld\n" , nsetups, netf);
printf("npe = %5ld nps = %5ld\n" , npe, nps);
printf("ncfn = %5ld ncfl = %5ld\n\n", ncfn, ncfl);
return;
}
/* Check function return value...
opt == 0 means SUNDIALS function allocates memory so check if
returned NULL pointer
opt == 1 means SUNDIALS function returns an integer value so check if
retval >= 0
opt == 2 means function allocates memory so check if returned
NULL pointer */
static int check_retval(void *returnvalue, const char *funcname, int opt)
{
int *retval;
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
if (opt == 0 && returnvalue == NULL) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
/* Check if retval < 0 */
else if (opt == 1) {
retval = (int *) returnvalue;
if (*retval < 0) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n",
funcname, *retval);
return(1); }}
/* Check if function returned NULL pointer - no memory allocated */
else if (opt == 2 && returnvalue == NULL) {
fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
return(0);
}
| 31.55303 | 90 | 0.629772 | [
"mesh",
"vector",
"model"
] |
5eed970af5a0c28814d2469b15b7e2fa4957dbae | 18,708 | cpp | C++ | Source/ZipUtility/Private/ZipFileFunctionLibrary.cpp | VJien/ZipUtility-UE4-Extra | 501165dfdfa5d31bddcbd4e52f7767171235ed38 | [
"MIT"
] | null | null | null | Source/ZipUtility/Private/ZipFileFunctionLibrary.cpp | VJien/ZipUtility-UE4-Extra | 501165dfdfa5d31bddcbd4e52f7767171235ed38 | [
"MIT"
] | null | null | null | Source/ZipUtility/Private/ZipFileFunctionLibrary.cpp | VJien/ZipUtility-UE4-Extra | 501165dfdfa5d31bddcbd4e52f7767171235ed38 | [
"MIT"
] | null | null | null | #include "ZipFileFunctionLibrary.h"
#include "ZipUtilityPrivatePCH.h"
#include "ZipFileFunctionInternalCallback.h"
#include "ListCallback.h"
#include "ProgressCallback.h"
#include "Interfaces/IPluginManager.h"
#include "WFULambdaRunnable.h"
#include "ZULambdaDelegate.h"
#include "SevenZipCallbackHandler.h"
#include "WindowsFileUtilityFunctionLibrary.h"
#include "7zpp.h"
using namespace SevenZip;
//Private Namespace
namespace{
//Threaded Lambda convenience wrappers - Task graph is only suitable for short duration lambdas, but doesn't incur thread overhead
FGraphEventRef RunLambdaOnAnyThread(TFunction< void()> InFunction)
{
return FFunctionGraphTask::CreateAndDispatchWhenReady(InFunction, TStatId(), nullptr, ENamedThreads::AnyThread);
}
//Uses proper threading, for any task that may run longer than about 2 seconds.
void RunLongLambdaOnAnyThread(TFunction< void()> InFunction)
{
WFULambdaRunnable::RunLambdaOnBackGroundThread(InFunction);
}
// Run the lambda on the queued threadpool
IQueuedWork* RunLambdaOnThreadPool(TFunction< void()> InFunction)
{
return WFULambdaRunnable::AddLambdaToQueue(InFunction);
}
//Private static vars
SevenZipLibrary SZLib;
//Utility functions
FString PluginRootFolder()
{
return IPluginManager::Get().FindPlugin("ZipUtility")->GetBaseDir();
//return FPaths::ConvertRelativePathToFull(FPaths::GameDir());
}
FString DLLPath()
{
#if defined(_WIN64)
FString PlatformString = FString(TEXT("Win64"));
#else
FString PlatformString = FString(TEXT("Win32"));
#endif
//Swap these to change which license you wish to fall under for zip-utility
FString DLLString = FString("7z.dll"); //Using 7z.dll: GNU LGPL + unRAR restriction
//FString dllString = FString("7za.dll"); //Using 7za.dll: GNU LGPL license, crucially doesn't support .zip out of the box
return FPaths::ConvertRelativePathToFull(FPaths::Combine(*PluginRootFolder(), TEXT("ThirdParty/7zpp/dll"), *PlatformString, *DLLString));
}
FString ReversePathSlashes(FString forwardPath)
{
return forwardPath.Replace(TEXT("/"), TEXT("\\"));
}
bool IsValidDirectory(FString& Directory, FString& FileName, const FString& Path)
{
bool Found = Path.Split(TEXT("/"), &Directory, &FileName, ESearchCase::IgnoreCase, ESearchDir::FromEnd);
//try a back split
if (!Found)
{
Found = Path.Split(TEXT("\\"), &Directory, &FileName, ESearchCase::IgnoreCase, ESearchDir::FromEnd);
}
//No valid Directory found
if (!Found)
return false;
else
return true;
}
SevenZip::CompressionLevelEnum libZipLevelFromUELevel(ZipUtilityCompressionLevel ueLevel) {
switch (ueLevel)
{
case COMPRESSION_LEVEL_NONE:
return SevenZip::CompressionLevel::None;
case COMPRESSION_LEVEL_FAST:
return SevenZip::CompressionLevel::Fast;
case COMPRESSION_LEVEL_NORMAL:
return SevenZip::CompressionLevel::Normal;
default:
return SevenZip::CompressionLevel::None;
}
}
SevenZip::CompressionFormatEnum libZipFormatFromUEFormat(EZipUtilityCompressionFormat UeFormat) {
switch (UeFormat)
{
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_UNKNOWN:
return CompressionFormat::Unknown;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_SEVEN_ZIP:
return CompressionFormat::SevenZip;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_ZIP:
return CompressionFormat::Zip;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_GZIP:
return CompressionFormat::GZip;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_BZIP2:
return CompressionFormat::BZip2;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_RAR:
return CompressionFormat::Rar;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_TAR:
return CompressionFormat::Tar;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_ISO:
return CompressionFormat::Iso;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_CAB:
return CompressionFormat::Cab;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_LZMA:
return CompressionFormat::Lzma;
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_LZMA86:
return CompressionFormat::Lzma86;
default:
return CompressionFormat::Unknown;
}
}
FString defaultExtensionFromUEFormat(EZipUtilityCompressionFormat ueFormat)
{
switch (ueFormat)
{
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_UNKNOWN:
return FString(TEXT(".dat"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_SEVEN_ZIP:
return FString(TEXT(".7z"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_ZIP:
return FString(TEXT(".zip"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_GZIP:
return FString(TEXT(".gz"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_BZIP2:
return FString(TEXT(".bz2"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_RAR:
return FString(TEXT(".rar"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_TAR:
return FString(TEXT(".tar"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_ISO:
return FString(TEXT(".iso"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_CAB:
return FString(TEXT(".cab"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_LZMA:
return FString(TEXT(".lzma"));
case EZipUtilityCompressionFormat::COMPRESSION_FORMAT_LZMA86:
return FString(TEXT(".lzma86"));
default:
return FString(TEXT(".dat"));
}
}
using namespace std;
//Background Thread convenience functions
UZipOperation* UnzipFilesOnBGThreadWithFormat(const TArray<int32> FileIndices, const FString& ArchivePath, const FString& DestinationDirectory, const UObject* ProgressDelegate, EZipUtilityCompressionFormat Format)
{
UZipOperation* ZipOperation = NewObject<UZipOperation>();
IQueuedWork* Work = RunLambdaOnThreadPool([ProgressDelegate, FileIndices, ArchivePath, DestinationDirectory, Format, ZipOperation]
{
SevenZipCallbackHandler PrivateCallback;
PrivateCallback.ProgressDelegate = (UObject*)ProgressDelegate;
ZipOperation->SetCallbackHandler(&PrivateCallback);
//UE_LOG(LogClass, Log, TEXT("path is: %s"), *path);
SevenZipExtractor Extractor(SZLib, *ArchivePath);
if (Format == EZipUtilityCompressionFormat::COMPRESSION_FORMAT_UNKNOWN)
{
if (!Extractor.DetectCompressionFormat())
{
UE_LOG(LogTemp, Log, TEXT("auto-compression detection did not succeed, passing in unknown format to 7zip library."));
}
}
else
{
Extractor.SetCompressionFormat(libZipFormatFromUEFormat(Format));
}
// Extract indices
const int32 NumberFiles = FileIndices.Num();
unsigned int* Indices = new unsigned int[NumberFiles];
for (int32 idx = 0; idx < NumberFiles; idx++)
{
Indices[idx] = FileIndices[idx];
}
// Perform the extraction
Extractor.ExtractFilesFromArchive(Indices, NumberFiles, *DestinationDirectory, &PrivateCallback);
// Clean up the indices
delete Indices;
// Null out the callback handler now that we're exiting
ZipOperation->SetCallbackHandler(nullptr);
});
ZipOperation->SetThreadPoolWorker(Work);
return ZipOperation;
}
//Background Thread convenience functions
UZipOperation* UnzipOnBGThreadWithFormat(const FString& ArchivePath, const FString& DestinationDirectory, const UObject* ProgressDelegate, EZipUtilityCompressionFormat Format)
{
UZipOperation* ZipOperation = NewObject<UZipOperation>();
IQueuedWork* Work = RunLambdaOnThreadPool([ProgressDelegate, ArchivePath, DestinationDirectory, Format, ZipOperation]
{
SevenZipCallbackHandler PrivateCallback;
PrivateCallback.ProgressDelegate = (UObject*)ProgressDelegate;
ZipOperation->SetCallbackHandler(&PrivateCallback);
//UE_LOG(LogClass, Log, TEXT("path is: %s"), *path);
SevenZipExtractor Extractor(SZLib, *ArchivePath);
if (Format == EZipUtilityCompressionFormat::COMPRESSION_FORMAT_UNKNOWN)
{
if (!Extractor.DetectCompressionFormat())
{
UE_LOG(LogTemp, Log, TEXT("auto-compression detection did not succeed, passing in unknown format to 7zip library."));
}
}
else
{
Extractor.SetCompressionFormat(libZipFormatFromUEFormat(Format));
}
Extractor.ExtractArchive(*DestinationDirectory, &PrivateCallback);
// Null out the callback handler now that we're exiting
ZipOperation->SetCallbackHandler(nullptr);
});
ZipOperation->SetThreadPoolWorker(Work);
return ZipOperation;
}
void ListOnBGThread(const FString& Path, const FString& Directory, const UObject* ListDelegate, EZipUtilityCompressionFormat Format)
{
//RunLongLambdaOnAnyThread - this shouldn't take long, but if it lags, swap the lambda methods
RunLambdaOnAnyThread([ListDelegate, Path, Format, Directory] {
SevenZipCallbackHandler PrivateCallback;
PrivateCallback.ProgressDelegate = (UObject*)ListDelegate;
SevenZipLister Lister(SZLib, *Path);
if (Format == EZipUtilityCompressionFormat::COMPRESSION_FORMAT_UNKNOWN)
{
if (!Lister.DetectCompressionFormat())
{
UE_LOG(LogTemp, Log, TEXT("auto-compression detection did not succeed, passing in unknown format to 7zip library."));
}
}
else
{
Lister.SetCompressionFormat(libZipFormatFromUEFormat(Format));
}
if (!Lister.ListArchive(&PrivateCallback))
{
// If ListArchive returned false, it was most likely because the compression format was unsupported
// Call OnDone with a failure message, make sure to call this on the game thread.
if (IZipUtilityInterface* ZipInterface = Cast<IZipUtilityInterface>((UObject*)ListDelegate))
{
UE_LOG(LogClass, Warning, TEXT("ZipUtility: Unknown failure for list operation on %s"), *Path);
UZipFileFunctionLibrary::RunLambdaOnGameThread([ZipInterface, ListDelegate, Path]
{
ZipInterface->Execute_OnDone((UObject*)ListDelegate, *Path, EZipUtilityCompletionState::FAILURE_UNKNOWN);
});
}
}
});
}
UZipOperation* ZipOnBGThread(const FString& Path, const FString& FileName, const FString& Directory, const UObject* ProgressDelegate, EZipUtilityCompressionFormat UeCompressionformat, ZipUtilityCompressionLevel UeCompressionlevel)
{
UZipOperation* ZipOperation = NewObject<UZipOperation>();
IQueuedWork* Work = RunLambdaOnThreadPool([ProgressDelegate, FileName, Path, UeCompressionformat, UeCompressionlevel, Directory, ZipOperation]
{
SevenZipCallbackHandler PrivateCallback;
PrivateCallback.ProgressDelegate = (UObject*)ProgressDelegate;
ZipOperation->SetCallbackHandler(&PrivateCallback);
//Set the zip format
EZipUtilityCompressionFormat UeFormat = UeCompressionformat;
if (UeFormat == EZipUtilityCompressionFormat::COMPRESSION_FORMAT_UNKNOWN)
{
UeFormat = EZipUtilityCompressionFormat::COMPRESSION_FORMAT_ZIP;
}
//Disallow creating .rar archives as per unrar restriction, this won't work anyway so redirect to 7z
else if (UeFormat == EZipUtilityCompressionFormat::COMPRESSION_FORMAT_RAR)
{
UE_LOG(LogClass, Warning, TEXT("ZipUtility: Rar compression not supported for creating archives, re-targeting as 7z."));
UeFormat = EZipUtilityCompressionFormat::COMPRESSION_FORMAT_SEVEN_ZIP;
}
//concatenate the output filename
FString OutputFileName = FString::Printf(TEXT("%s/%s%s"), *Directory, *FileName, *defaultExtensionFromUEFormat(UeFormat));
//UE_LOG(LogClass, Log, TEXT("\noutputfile is: <%s>\n path is: <%s>"), *outputFileName, *path);
SevenZipCompressor compressor(SZLib, *ReversePathSlashes(OutputFileName));
compressor.SetCompressionFormat(libZipFormatFromUEFormat(UeFormat));
compressor.SetCompressionLevel(libZipLevelFromUELevel(UeCompressionlevel));
if (PathIsDirectory(*Path))
{
//UE_LOG(LogClass, Log, TEXT("Compressing Folder"));
compressor.CompressDirectory(*ReversePathSlashes(Path), &PrivateCallback);
}
else
{
//UE_LOG(LogClass, Log, TEXT("Compressing File"));
compressor.CompressFile(*ReversePathSlashes(Path), &PrivateCallback);
}
// Null out the callback handler
ZipOperation->SetCallbackHandler(nullptr);
//Todo: expand to support zipping up contents of current folder
//compressor.CompressFiles(*ReversePathSlashes(path), TEXT("*"), &PrivateCallback);
});
ZipOperation->SetThreadPoolWorker(Work);
return ZipOperation;
}
}//End private namespace
UZipFileFunctionLibrary::UZipFileFunctionLibrary(const class FObjectInitializer& PCIP)
: Super(PCIP)
{
UE_LOG(LogTemp, Log, TEXT("DLLPath is: %s"), *DLLPath());
SZLib.Load(*DLLPath());
}
UZipFileFunctionLibrary::~UZipFileFunctionLibrary()
{
SZLib.Free();
}
bool UZipFileFunctionLibrary::UnzipFileNamed(const FString& archivePath, const FString& Name, UObject* ZipUtilityInterfaceDelegate, EZipUtilityCompressionFormat format /*= COMPRESSION_FORMAT_UNKNOWN*/)
{
UZipFileFunctionInternalCallback* InternalCallback = NewObject<UZipFileFunctionInternalCallback>();
InternalCallback->SetFlags(RF_MarkAsRootSet);
InternalCallback->SetCallback(Name, ZipUtilityInterfaceDelegate, format);
ListFilesInArchive(archivePath, InternalCallback, format);
return true;
}
bool UZipFileFunctionLibrary::UnzipFileNamedTo(const FString& archivePath, const FString& Name, const FString& destinationPath, UObject* ZipUtilityInterfaceDelegate, EZipUtilityCompressionFormat format /*= COMPRESSION_FORMAT_UNKNOWN*/)
{
UZipFileFunctionInternalCallback* InternalCallback = NewObject<UZipFileFunctionInternalCallback>();
InternalCallback->SetFlags(RF_MarkAsRootSet);
InternalCallback->SetCallback(Name, destinationPath, ZipUtilityInterfaceDelegate, format);
ListFilesInArchive(archivePath, InternalCallback, format);
return true;
}
UZipOperation* UZipFileFunctionLibrary::UnzipFilesTo(const TArray<int32> fileIndices, const FString & archivePath, const FString & destinationPath, UObject * ZipUtilityInterfaceDelegate, EZipUtilityCompressionFormat format)
{
bool bObjectIsValid = ZipUtilityInterfaceDelegate->GetClass()->ImplementsInterface(UZipUtilityInterface::StaticClass());
if (!bObjectIsValid)
{
UE_LOG(LogTemp, Warning, TEXT("Object passed as Delegate does not respond to IZipUtilityInterface"));
return nullptr;
}
return UnzipFilesOnBGThreadWithFormat(fileIndices, archivePath, destinationPath, ZipUtilityInterfaceDelegate, format);
}
UZipOperation* UZipFileFunctionLibrary::UnzipFiles(const TArray<int32> fileIndices, const FString & ArchivePath, UObject * ZipUtilityInterfaceDelegate, EZipUtilityCompressionFormat format)
{
FString Directory;
FString FileName;
//Check Directory validity
if (!IsValidDirectory(Directory, FileName, ArchivePath))
{
return nullptr;
}
if (fileIndices.Num() == 0)
{
return nullptr;
}
return UnzipFilesTo(fileIndices, ArchivePath, Directory, ZipUtilityInterfaceDelegate, format);
}
UZipOperation* UZipFileFunctionLibrary::Unzip(const FString& ArchivePath, UObject* ZipUtilityInterfaceDelegate, EZipUtilityCompressionFormat Format /*= COMPRESSION_FORMAT_UNKNOWN*/)
{
FString Directory;
FString FileName;
//Check Directory validity
if (!IsValidDirectory(Directory, FileName, ArchivePath) || !UWindowsFileUtilityFunctionLibrary::DoesFileExist(ArchivePath))
{
bool bObjectIsValid = ZipUtilityInterfaceDelegate->GetClass()->ImplementsInterface(UZipUtilityInterface::StaticClass());
if (!bObjectIsValid)
{
UE_LOG(LogTemp, Warning, TEXT("Object passed as Delegate does not respond to IZipUtilityInterface"));
return nullptr;
}
((IZipUtilityInterface*)ZipUtilityInterfaceDelegate)->Execute_OnDone((UObject*)ZipUtilityInterfaceDelegate, ArchivePath, EZipUtilityCompletionState::FAILURE_NOT_FOUND);
return nullptr;
}
return UnzipTo(ArchivePath, Directory, ZipUtilityInterfaceDelegate, Format);
}
UZipOperation* UZipFileFunctionLibrary::UnzipWithLambda(const FString& ArchivePath, TFunction<void()> OnDoneCallback, TFunction<void(float)> OnProgressCallback, EZipUtilityCompressionFormat Format)
{
UZULambdaDelegate* LambdaDelegate = NewObject<UZULambdaDelegate>();
LambdaDelegate->AddToRoot();
LambdaDelegate->SetOnDoneCallback([LambdaDelegate, OnDoneCallback]()
{
OnDoneCallback();
LambdaDelegate->RemoveFromRoot();
});
LambdaDelegate->SetOnProgessCallback(OnProgressCallback);
return Unzip(ArchivePath, LambdaDelegate, Format);
}
UZipOperation* UZipFileFunctionLibrary::UnzipTo(const FString& ArchivePath, const FString& DestinationPath, UObject* ZipUtilityInterfaceDelegate, EZipUtilityCompressionFormat Format)
{
return UnzipOnBGThreadWithFormat(ArchivePath, DestinationPath, ZipUtilityInterfaceDelegate, Format);
}
UZipOperation* UZipFileFunctionLibrary::Zip(const FString& ArchivePath, UObject* ZipUtilityInterfaceDelegate, EZipUtilityCompressionFormat Format, TEnumAsByte<ZipUtilityCompressionLevel> Level)
{
FString Directory;
FString FileName;
bool bObjectIsValid = ZipUtilityInterfaceDelegate->GetClass()->ImplementsInterface(UZipUtilityInterface::StaticClass());
if (!bObjectIsValid)
{
UE_LOG(LogTemp, Warning, TEXT("Object passed as Delegate does not respond to IZipUtilityInterface"));
return nullptr;
}
//Check Directory and File validity
if (!IsValidDirectory(Directory, FileName, ArchivePath) || !UWindowsFileUtilityFunctionLibrary::DoesFileExist(ArchivePath))
{
((IZipUtilityInterface*)ZipUtilityInterfaceDelegate)->Execute_OnDone((UObject*)ZipUtilityInterfaceDelegate, ArchivePath, EZipUtilityCompletionState::FAILURE_NOT_FOUND);
return nullptr;
}
return ZipOnBGThread(ArchivePath, FileName, Directory, ZipUtilityInterfaceDelegate, Format, Level);
}
UZipOperation* UZipFileFunctionLibrary::ZipWithLambda(const FString& ArchivePath, TFunction<void()> OnDoneCallback, TFunction<void(float)> OnProgressCallback /*= nullptr*/, EZipUtilityCompressionFormat Format /*= COMPRESSION_FORMAT_UNKNOWN*/, TEnumAsByte<ZipUtilityCompressionLevel> Level /*=COMPRESSION_LEVEL_NORMAL*/)
{
UZULambdaDelegate* LambdaDelegate = NewObject<UZULambdaDelegate>();
LambdaDelegate->AddToRoot();
LambdaDelegate->SetOnDoneCallback([OnDoneCallback, LambdaDelegate]()
{
OnDoneCallback();
LambdaDelegate->RemoveFromRoot();
});
LambdaDelegate->SetOnProgessCallback(OnProgressCallback);
return Zip(ArchivePath, LambdaDelegate, Format);
}
bool UZipFileFunctionLibrary::ListFilesInArchive(const FString& path, UObject* ListDelegate, EZipUtilityCompressionFormat format)
{
FString Directory;
FString FileName;
//Check Directory validity
if (!IsValidDirectory(Directory, FileName, path))
{
return false;
}
ListOnBGThread(path, Directory, ListDelegate, format);
return true;
}
FGraphEventRef UZipFileFunctionLibrary::RunLambdaOnGameThread(TFunction< void()> InFunction)
{
return FFunctionGraphTask::CreateAndDispatchWhenReady(InFunction, TStatId(), nullptr, ENamedThreads::GameThread);
}
| 36.899408 | 319 | 0.783622 | [
"object"
] |
d672996db6035a3142869354927b2727d7bb8f37 | 1,270 | cpp | C++ | answers/harshpreet0508/day28/q1.cpp | vishaljha2121/30-DaysOfCode-March-2021 | 27922819b4e0a3c1072822f8df22b7a0873fe72c | [
"MIT"
] | 22 | 2021-03-16T14:07:47.000Z | 2021-08-13T08:52:50.000Z | answers/harshpreet0508/day28/q1.cpp | vishaljha2121/30-DaysOfCode-March-2021 | 27922819b4e0a3c1072822f8df22b7a0873fe72c | [
"MIT"
] | 174 | 2021-03-16T21:16:40.000Z | 2021-06-12T05:19:51.000Z | answers/harshpreet0508/day28/q1.cpp | vishaljha2121/30-DaysOfCode-March-2021 | 27922819b4e0a3c1072822f8df22b7a0873fe72c | [
"MIT"
] | 135 | 2021-03-16T16:47:12.000Z | 2021-06-27T14:22:38.000Z | // Divide numbers 1..n into two sets of equal sum
#include <bits/stdc++.h>
using namespace std;
void find(int n)
{
if (n <= 2)
{
cout << "NO";
return;
}
int v = (n*(n+1)) / 2;
if(v & 1)
{
cout<<"NO";
return;
}
vector<int> v1,v2;
if (!(n & 1))
{
int t = 1;
int st = 1;
int l = n;
while (st < l)
{
if (t)
{
v1.push_back(st);
v1.push_back(l);
t = 0;
}
else
{
v2.push_back(st);
v2.push_back(l);
t = 1;
}
st++;
l--;
}
}
else
{
int r = v / 2;
bool v3[n + 1];
for (int i=1;i<=n;i++)
v3[i] = false;
v3[0] = true;
for (int i=n;i>=1;i--)
{
if (r > i)
{
v1.push_back(i);
v3[i] = true;
r-=i;
}
else
{
v1.push_back(r);
v3[r] = true;
break;
}
}
for (int i=1; i<=n;i++) {
if (!v3[i])
v2.push_back(i);
}
}
cout<<"\nYes\n";
cout << "Size of subset 1 is: ";
cout << v1.size() << "\n";
cout << "Elements of the subset are: ";
for (auto c : v1)
cout << c << " ";
cout << endl;
cout << "Size of subset 2 is: ";
cout << v2.size() << "\n";
cout << "Elements of the subset are: ";
for (auto c : v2)
cout << c << " ";
}
int main()
{
int n;
cin>>n;
find(n);
return 0;
}
| 10.948276 | 49 | 0.431496 | [
"vector"
] |
d6739aa4da6b16e41cdd56095f4e0b2f17a55423 | 7,498 | cpp | C++ | dlib/test/cublas.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | null | null | null | dlib/test/cublas.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | 4 | 2018-02-27T15:44:25.000Z | 2018-02-28T01:26:03.000Z | dlib/test/cublas.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2015 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#include <dlib/matrix.h>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include "../dnn/tensor_tools.h"
#include "tester.h"
// We only do these tests if CUDA is available to test in the first place.
#ifdef DLIB_USE_CUDA
namespace
{
using namespace test;
using namespace dlib;
using namespace std;
logger dlog("test.cublas");
void test_inv()
{
tt::tensor_rand rnd;
dlib::tt::inv tinv;
dlib::cuda::inv cinv;
resizable_tensor minv1, minv2;
for (int n = 1; n < 20; ++n)
{
print_spinner();
resizable_tensor m(n,n);
rnd.fill_uniform(m);
tinv(m, minv1);
cinv(m, minv2);
matrix<float> mref = inv(mat(m));
DLIB_TEST_MSG(mean(abs(mref-mat(minv1)))/mean(abs(mref)) < 1e-5, mean(abs(mref-mat(minv1)))/mean(abs(mref)) <<" n: " << n);
DLIB_TEST_MSG(mean(abs(mref-mat(minv2)))/mean(abs(mref)) < 1e-5, mean(abs(mref-mat(minv2)))/mean(abs(mref)) <<" n: " << n);
}
}
class cublas_tester : public tester
{
public:
cublas_tester (
) :
tester ("test_cublas",
"Runs tests on the cuBLAS bindings.")
{}
void perform_test (
)
{
test_inv();
{
resizable_tensor a(4,3), b(3,4), c(3,3);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = 2*mat(c)+trans(mat(a))*trans(mat(b));
a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();
cuda::gemm(2, c, 1, a, true, b, true);
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(4,3), b(4,3), c(3,3);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = 2*mat(c)+trans(mat(a))*mat(b);
a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();
cuda::gemm(2, c, 1, a, true, b, false);
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(3,4), b(3,4), c(3,3);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = 2*mat(c)+mat(a)*trans(mat(b));
a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();
cuda::gemm(2, c, 1, a, false, b, true);
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(3,4), b(3,4), c(3,3);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = mat(c)+mat(a)*trans(mat(b));
a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();
cuda::gemm(1, c, 1, a, false, b, true);
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(3,4), b(4,3), c(3,3);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = 2*mat(c)+mat(a)*mat(b);
a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();
cuda::gemm(2, c, 1, a, false, b, false);
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(3,4), b(4,3), c(3,3);
c = std::numeric_limits<float>::infinity();
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();
matrix<float> truth = mat(a)*mat(b);
cuda::gemm(0, c, 1, a, false, b, false);
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(3,4), b(4,4), c(3,4);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = 2*mat(c)+mat(a)*mat(b);
cuda::gemm(2, c, 1, a, false, b, false);
DLIB_TEST(get_rect(truth) == get_rect(mat(c)));
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(4,3), b(4,4), c(3,4);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = 2*mat(c)+trans(mat(a))*mat(b);
cuda::gemm(2, c, 1, a, true, b, false);
DLIB_TEST(get_rect(truth) == get_rect(mat(c)));
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(4,3), b(4,5), c(3,5);
c = 1;
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = 2*mat(c)+trans(mat(a))*mat(b);
cuda::gemm(2, c, 1, a, true, b, false);
DLIB_TEST(get_rect(truth) == get_rect(mat(c)));
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
{
resizable_tensor a(4,3), b(4,5), c(3,5);
c = std::numeric_limits<float>::infinity();
a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));
b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));
matrix<float> truth = trans(mat(a))*mat(b);
cuda::gemm(0, c, 1, a, true, b, false);
DLIB_TEST(get_rect(truth) == get_rect(mat(c)));
DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);
}
}
} a;
}
#endif // DLIB_USE_CUDA
| 37.678392 | 137 | 0.493465 | [
"vector"
] |
d67754efb88ab67cf03fc758c4441f94e0917765 | 11,145 | cpp | C++ | third_party/WebKit/Source/modules/webdatabase/SQLStatementBackend.cpp | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | third_party/WebKit/Source/modules/webdatabase/SQLStatementBackend.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | third_party/WebKit/Source/modules/webdatabase/SQLStatementBackend.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | /*
* Copyright (C) 2007, 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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 "modules/webdatabase/SQLStatementBackend.h"
#include "modules/webdatabase/Database.h"
#include "modules/webdatabase/SQLError.h"
#include "modules/webdatabase/SQLStatement.h"
#include "modules/webdatabase/StorageLog.h"
#include "modules/webdatabase/sqlite/SQLiteDatabase.h"
#include "modules/webdatabase/sqlite/SQLiteStatement.h"
#include "wtf/text/CString.h"
// The Life-Cycle of a SQLStatement i.e. Who's keeping the SQLStatement alive?
// ==========================================================================
// The RefPtr chain goes something like this:
//
// At birth (in SQLTransactionBackend::executeSQL()):
// =================================================
// SQLTransactionBackend
// // HeapDeque<Member<SQLStatementBackend>> m_statementQueue
// // points to ...
// --> SQLStatementBackend
// // Member<SQLStatement> m_frontend points to ...
// --> SQLStatement
//
// After grabbing the statement for execution (in
// SQLTransactionBackend::getNextStatement()):
// ======================================================================
// SQLTransactionBackend
// // Member<SQLStatementBackend> m_currentStatementBackend
// // points to ...
// --> SQLStatementBackend
// // Member<SQLStatement> m_frontend points to ...
// --> SQLStatement
//
// Then we execute the statement in
// SQLTransactionBackend::runCurrentStatementAndGetNextState().
// And we callback to the script in
// SQLTransaction::deliverStatementCallback() if necessary.
// - Inside SQLTransaction::deliverStatementCallback(), we operate on a raw
// SQLStatement*. This pointer is valid because it is owned by
// SQLTransactionBackend's
// SQLTransactionBackend::m_currentStatementBackend.
//
// After we're done executing the statement (in
// SQLTransactionBackend::getNextStatement()):
// ======================================================================
// When we're done executing, we'll grab the next statement. But before we
// do that, getNextStatement() nullify
// SQLTransactionBackend::m_currentStatementBackend.
// This will trigger the deletion of the SQLStatementBackend and
// SQLStatement.
//
// Note: unlike with SQLTransaction, there is no JS representation of
// SQLStatement. Hence, there is no GC dependency at play here.
namespace blink {
SQLStatementBackend* SQLStatementBackend::create(
SQLStatement* frontend,
const String& statement,
const Vector<SQLValue>& arguments,
int permissions) {
return new SQLStatementBackend(frontend, statement, arguments, permissions);
}
SQLStatementBackend::SQLStatementBackend(SQLStatement* frontend,
const String& statement,
const Vector<SQLValue>& arguments,
int permissions)
: m_frontend(frontend),
m_statement(statement.isolatedCopy()),
m_arguments(arguments),
m_hasCallback(m_frontend->hasCallback()),
m_hasErrorCallback(m_frontend->hasErrorCallback()),
m_resultSet(SQLResultSet::create()),
m_permissions(permissions) {
DCHECK(isMainThread());
m_frontend->setBackend(this);
}
DEFINE_TRACE(SQLStatementBackend) {
visitor->trace(m_frontend);
visitor->trace(m_resultSet);
}
SQLStatement* SQLStatementBackend::frontend() {
return m_frontend.get();
}
SQLErrorData* SQLStatementBackend::sqlError() const {
return m_error.get();
}
SQLResultSet* SQLStatementBackend::sqlResultSet() const {
return m_resultSet->isValid() ? m_resultSet.get() : 0;
}
bool SQLStatementBackend::execute(Database* db) {
ASSERT(!m_resultSet->isValid());
// If we're re-running this statement after a quota violation, we need to
// clear that error now
clearFailureDueToQuota();
// This transaction might have been marked bad while it was being set up on
// the main thread, so if there is still an error, return false.
if (m_error)
return false;
db->setAuthorizerPermissions(m_permissions);
SQLiteDatabase* database = &db->sqliteDatabase();
SQLiteStatement statement(*database, m_statement);
int result = statement.prepare();
if (result != SQLResultOk) {
STORAGE_DVLOG(1) << "Unable to verify correctness of statement "
<< m_statement << " - error " << result << " ("
<< database->lastErrorMsg() << ")";
if (result == SQLResultInterrupt)
m_error = SQLErrorData::create(SQLError::kDatabaseErr,
"could not prepare statement", result,
"interrupted");
else
m_error = SQLErrorData::create(SQLError::kSyntaxErr,
"could not prepare statement", result,
database->lastErrorMsg());
db->reportExecuteStatementResult(1, m_error->code(), result);
return false;
}
// FIXME: If the statement uses the ?### syntax supported by sqlite, the bind
// parameter count is very likely off from the number of question marks. If
// this is the case, they might be trying to do something fishy or malicious
if (statement.bindParameterCount() != m_arguments.size()) {
STORAGE_DVLOG(1)
<< "Bind parameter count doesn't match number of question marks";
m_error = SQLErrorData::create(
SQLError::kSyntaxErr,
"number of '?'s in statement string does not match argument count");
db->reportExecuteStatementResult(2, m_error->code(), 0);
return false;
}
for (unsigned i = 0; i < m_arguments.size(); ++i) {
result = statement.bindValue(i + 1, m_arguments[i]);
if (result == SQLResultFull) {
setFailureDueToQuota(db);
return false;
}
if (result != SQLResultOk) {
STORAGE_DVLOG(1) << "Failed to bind value index " << (i + 1)
<< " to statement for query " << m_statement;
db->reportExecuteStatementResult(3, SQLError::kDatabaseErr, result);
m_error =
SQLErrorData::create(SQLError::kDatabaseErr, "could not bind value",
result, database->lastErrorMsg());
return false;
}
}
// Step so we can fetch the column names.
result = statement.step();
if (result == SQLResultRow) {
int columnCount = statement.columnCount();
SQLResultSetRowList* rows = m_resultSet->rows();
for (int i = 0; i < columnCount; i++)
rows->addColumn(statement.getColumnName(i));
do {
for (int i = 0; i < columnCount; i++)
rows->addResult(statement.getColumnValue(i));
result = statement.step();
} while (result == SQLResultRow);
if (result != SQLResultDone) {
db->reportExecuteStatementResult(4, SQLError::kDatabaseErr, result);
m_error = SQLErrorData::create(SQLError::kDatabaseErr,
"could not iterate results", result,
database->lastErrorMsg());
return false;
}
} else if (result == SQLResultDone) {
// Didn't find anything, or was an insert
if (db->lastActionWasInsert())
m_resultSet->setInsertId(database->lastInsertRowID());
} else if (result == SQLResultFull) {
// Return the Quota error - the delegate will be asked for more space and
// this statement might be re-run.
setFailureDueToQuota(db);
return false;
} else if (result == SQLResultConstraint) {
db->reportExecuteStatementResult(6, SQLError::kConstraintErr, result);
m_error = SQLErrorData::create(
SQLError::kConstraintErr,
"could not execute statement due to a constaint failure", result,
database->lastErrorMsg());
return false;
} else {
db->reportExecuteStatementResult(5, SQLError::kDatabaseErr, result);
m_error = SQLErrorData::create(SQLError::kDatabaseErr,
"could not execute statement", result,
database->lastErrorMsg());
return false;
}
// FIXME: If the spec allows triggers, and we want to be "accurate" in a
// different way, we'd use sqlite3_total_changes() here instead of
// sqlite3_changed, because that includes rows modified from within a trigger.
// For now, this seems sufficient.
m_resultSet->setRowsAffected(database->lastChanges());
db->reportExecuteStatementResult(0, -1, 0); // OK
return true;
}
void SQLStatementBackend::setVersionMismatchedError(Database* database) {
ASSERT(!m_error && !m_resultSet->isValid());
database->reportExecuteStatementResult(7, SQLError::kVersionErr, 0);
m_error = SQLErrorData::create(
SQLError::kVersionErr,
"current version of the database and `oldVersion` argument do not match");
}
void SQLStatementBackend::setFailureDueToQuota(Database* database) {
ASSERT(!m_error && !m_resultSet->isValid());
database->reportExecuteStatementResult(8, SQLError::kQuotaErr, 0);
m_error = SQLErrorData::create(SQLError::kQuotaErr,
"there was not enough remaining storage "
"space, or the storage quota was reached and "
"the user declined to allow more space");
}
void SQLStatementBackend::clearFailureDueToQuota() {
if (lastExecutionFailedDueToQuota())
m_error = nullptr;
}
bool SQLStatementBackend::lastExecutionFailedDueToQuota() const {
return m_error && m_error->code() == SQLError::kQuotaErr;
}
} // namespace blink
| 40.380435 | 80 | 0.656169 | [
"vector"
] |
d6775e3056d8379777db5f90cda618131c17ba79 | 7,911 | cpp | C++ | src/qt/qtwebkit/Source/WebCore/html/track/WebVTTTokenizer.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebCore/html/track/WebVTTTokenizer.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/html/track/WebVTTTokenizer.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2017-03-19T13:03:23.000Z | 2017-03-19T13:03:23.000Z | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(VIDEO_TRACK)
#include "WebVTTTokenizer.h"
#include "MarkupTokenizerInlines.h"
namespace WebCore {
#define WEBVTT_BEGIN_STATE(stateName) BEGIN_STATE(WebVTTTokenizerState, stateName)
#define WEBVTT_ADVANCE_TO(stateName) ADVANCE_TO(WebVTTTokenizerState, stateName)
WebVTTTokenizer::WebVTTTokenizer()
: m_inputStreamPreprocessor(this)
{
reset();
}
template <typename CharacterType>
inline bool vectorEqualsString(const Vector<CharacterType, 32>& vector, const String& string)
{
if (vector.size() != string.length())
return false;
if (!string.length())
return true;
return equal(string.impl(), vector.data(), vector.size());
}
void WebVTTTokenizer::reset()
{
m_state = WebVTTTokenizerState::DataState;
m_token = 0;
m_buffer.clear();
}
bool WebVTTTokenizer::nextToken(SegmentedString& source, WebVTTToken& token)
{
// If we have a token in progress, then we're supposed to be called back
// with the same token so we can finish it.
ASSERT(!m_token || m_token == &token || token.type() == WebVTTTokenTypes::Uninitialized);
m_token = &token;
if (source.isEmpty() || !m_inputStreamPreprocessor.peek(source))
return haveBufferedCharacterToken();
UChar cc = m_inputStreamPreprocessor.nextInputCharacter();
// 4.8.10.13.4 WebVTT cue text tokenizer
switch (m_state) {
WEBVTT_BEGIN_STATE(DataState) {
if (cc == '&') {
m_buffer.append(static_cast<LChar>(cc));
WEBVTT_ADVANCE_TO(EscapeState);
} else if (cc == '<') {
if (m_token->type() == WebVTTTokenTypes::Uninitialized
|| vectorEqualsString<UChar>(m_token->characters(), emptyString()))
WEBVTT_ADVANCE_TO(TagState);
else
return emitAndResumeIn(source, WebVTTTokenizerState::TagState);
} else if (cc == kEndOfFileMarker)
return emitEndOfFile(source);
else {
bufferCharacter(cc);
WEBVTT_ADVANCE_TO(DataState);
}
}
END_STATE()
WEBVTT_BEGIN_STATE(EscapeState) {
if (cc == ';') {
if (vectorEqualsString(m_buffer, "&"))
bufferCharacter('&');
else if (vectorEqualsString(m_buffer, "<"))
bufferCharacter('<');
else if (vectorEqualsString(m_buffer, ">"))
bufferCharacter('>');
else {
m_buffer.append(static_cast<LChar>(cc));
m_token->appendToCharacter(m_buffer);
}
m_buffer.clear();
WEBVTT_ADVANCE_TO(DataState);
} else if (isASCIIAlphanumeric(cc)) {
m_buffer.append(static_cast<LChar>(cc));
WEBVTT_ADVANCE_TO(EscapeState);
} else if (cc == kEndOfFileMarker) {
m_token->appendToCharacter(m_buffer);
return emitEndOfFile(source);
} else {
if (!vectorEqualsString(m_buffer, "&"))
m_token->appendToCharacter(m_buffer);
m_buffer.clear();
WEBVTT_ADVANCE_TO(DataState);
}
}
END_STATE()
WEBVTT_BEGIN_STATE(TagState) {
if (isTokenizerWhitespace(cc)) {
m_token->beginEmptyStartTag();
WEBVTT_ADVANCE_TO(StartTagAnnotationState);
} else if (cc == '.') {
m_token->beginEmptyStartTag();
WEBVTT_ADVANCE_TO(StartTagClassState);
} else if (cc == '/') {
WEBVTT_ADVANCE_TO(EndTagOpenState);
} else if (WTF::isASCIIDigit(cc)) {
m_token->beginTimestampTag(cc);
WEBVTT_ADVANCE_TO(TimestampTagState);
} else if (cc == '>' || cc == kEndOfFileMarker) {
m_token->beginEmptyStartTag();
return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
} else {
m_token->beginStartTag(cc);
WEBVTT_ADVANCE_TO(StartTagState);
}
}
END_STATE()
WEBVTT_BEGIN_STATE(StartTagState) {
if (isTokenizerWhitespace(cc))
WEBVTT_ADVANCE_TO(StartTagAnnotationState);
else if (cc == '.')
WEBVTT_ADVANCE_TO(StartTagClassState);
else if (cc == '>' || cc == kEndOfFileMarker)
return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
else {
m_token->appendToName(cc);
WEBVTT_ADVANCE_TO(StartTagState);
}
}
END_STATE()
WEBVTT_BEGIN_STATE(StartTagClassState) {
if (isTokenizerWhitespace(cc)) {
m_token->addNewClass();
WEBVTT_ADVANCE_TO(StartTagAnnotationState);
} else if (cc == '.') {
m_token->addNewClass();
WEBVTT_ADVANCE_TO(StartTagClassState);
} else if (cc == '>' || cc == kEndOfFileMarker) {
m_token->addNewClass();
return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
} else {
m_token->appendToClass(cc);
WEBVTT_ADVANCE_TO(StartTagClassState);
}
}
END_STATE()
WEBVTT_BEGIN_STATE(StartTagAnnotationState) {
if (cc == '>' || cc == kEndOfFileMarker) {
m_token->addNewAnnotation();
return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
}
m_token->appendToAnnotation(cc);
WEBVTT_ADVANCE_TO(StartTagAnnotationState);
}
END_STATE()
WEBVTT_BEGIN_STATE(EndTagOpenState) {
if (cc == '>' || cc == kEndOfFileMarker) {
m_token->beginEndTag('\0');
return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
}
m_token->beginEndTag(cc);
WEBVTT_ADVANCE_TO(EndTagState);
}
END_STATE()
WEBVTT_BEGIN_STATE(EndTagState) {
if (cc == '>' || cc == kEndOfFileMarker)
return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
m_token->appendToName(cc);
WEBVTT_ADVANCE_TO(EndTagState);
}
END_STATE()
WEBVTT_BEGIN_STATE(TimestampTagState) {
if (cc == '>' || cc == kEndOfFileMarker)
return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
m_token->appendToTimestamp(cc);
WEBVTT_ADVANCE_TO(TimestampTagState);
}
END_STATE()
}
ASSERT_NOT_REACHED();
return false;
}
}
#endif
| 34.395652 | 93 | 0.636835 | [
"vector"
] |
d68a3a79714335059c030117834e710b16e5677f | 13,409 | cpp | C++ | QP/v5.4.2/qpcpp/examples/msp430/dpp_msp-exp430g2/qk/bsp.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/msp430/dpp_msp-exp430g2/qk/bsp.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/msp430/dpp_msp-exp430g2/qk/bsp.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | //****************************************************************************
// Product: DPP example on MSP-EXP430G2 board, preemptive QK kernel
// Last updated for version 5.4.0
// Last updated on 2015-05-13
//
// Q u a n t u m L e a P s
// ---------------------------
// innovating embedded systems
//
// Copyright (C) Quantum Leaps, LLC. All rights reserved.
//
// This program is open source software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Alternatively, this program may be distributed and modified under the
// terms of Quantum Leaps commercial licenses, which expressly supersede
// the GNU General Public License and are specifically designed for
// licensees interested in retaining the proprietary status of their code.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Contact information:
// Web : http://www.state-machine.com
// Email: info@state-machine.com
//****************************************************************************
#include "qpcpp.h"
#include "dpp.h"
#include "bsp.h"
#include <msp430g2553.h> // MSP430 variant used
// add other drivers if necessary...
// namespace DPP *************************************************************
namespace DPP {
Q_DEFINE_THIS_FILE
// Local-scope objects -------------------------------------------------------
// 8MHz clock setting, see BSP_init()
#define BSP_MCK 8000000U
#define BSP_SMCLK 8000000U
#define LED1 (1U << 0)
#define LED2 (1U << 6)
// Buttons on the MSP-EXP430G2 board
#define BTN1 (1U << 3)
// random seed
static uint32_t l_rnd;
#ifdef Q_SPY
#define TXD (1U << 2)
#define RXD (1U << 1)
QP::QSTimeCtr QS_tickTime_;
static uint8_t const l_timerA_ISR = 0U;
enum AppRecords { // application-specific trace records
PHILO_STAT = QP::QS_USER
};
#endif
// ISRs used in this project =================================================
extern "C" {
//............................................................................
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
__interrupt void TIMER0_A0_ISR(void); // prototype
#pragma vector=TIMER0_A0_VECTOR
__interrupt void TIMER0_A0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(TIMER0_A0_VECTOR))) TIMER0_A0_ISR (void)
#else
#error Compiler not supported!
#endif
{
QK_ISR_ENTRY(); // inform QK about entering the ISR
TACTL &= ~TAIFG; // clear the interrupt pending flag
QP::QF::TICK_X(0U, &l_timerA_ISR); // process time events for rate 0
// Perform the debouncing of buttons. The algorithm for debouncing
// adapted from the book "Embedded Systems Dictionary" by Jack Ganssle
// and Michael Barr, page 71.
//
static struct ButtonsDebouncing {
uint8_t depressed;
uint8_t previous;
} buttons = { (uint8_t)~0U, (uint8_t)~0U }; // state of button debouncing
uint8_t current;
uint8_t tmp;
current = ~P1IN; // read P1 port with the state of BTN1
tmp = buttons.depressed; // save the debounced depressed buttons
buttons.depressed |= (buttons.previous & current); // set depressed
buttons.depressed &= (buttons.previous | current); // clear released
buttons.previous = current; // update the history
tmp ^= buttons.depressed; // changed debounced depressed
if ((tmp & BTN1) != 0U) { // debounced BTN1 state changed?
if ((buttons.depressed & BTN1) != 0U) { // is BTN1 depressed?
static QP::QEvt const pauseEvt = { PAUSE_SIG, 0U, 0U};
QP::QF::PUBLISH(&pauseEvt, &l_timerA_ISR);
}
else { // the button is released
static QP::QEvt const serveEvt = { SERVE_SIG, 0U, 0U};
QP::QF::PUBLISH(&serveEvt, &l_timerA_ISR);
}
}
QK_ISR_EXIT(); // inform QK about exiting the ISR
}
} // extern "C"
// BSP functions =============================================================
void BSP_init(void) {
WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
// configure the Basic Clock Module
DCOCTL = 0; // Select lowest DCOx and MODx settings
BCSCTL1 = CALBC1_8MHZ; // Set DCO
DCOCTL = CALDCO_8MHZ;
// configure pins for LEDs
P1DIR |= (LED1 | LED2); // set LED1 and LED2 pins to output
// configure pin for Button
P1DIR &= ~BTN1; // set BTN1 pin as input
P1OUT |= BTN1; // drive output to hi
P1REN |= BTN1; // enable internal pull up register
if (QS_INIT((void *)0) == 0) { // initialize the QS software tracing
Q_ERROR();
}
QS_OBJ_DICTIONARY(&l_timerA_ISR);
QS_USR_DICTIONARY(PHILO_STAT);
}
//............................................................................
void BSP_displayPhilStat(uint8_t n, char const *stat) {
if (stat[0] == 'h') { // is Philo hungry?
P1OUT |= LED1; // turn LED1 on
}
else {
P1OUT &= ~LED1; // turn LED1 off
}
QS_BEGIN(PHILO_STAT, AO_Philo[n]) // application-specific record begin
QS_U8(1, n); // Philosopher number
QS_STR(stat); // Philosopher status
QS_END()
}
void BSP_displayPaused(uint8_t paused) {
// not enouhg LEDs to implement this feature
if (paused != 0U) {
//P1OUT |= LED1;
}
else {
//P1OUT &= ~LED1;
}
}
//............................................................................
uint32_t BSP_random(void) { // a very cheap pseudo-random-number generator
// "Super-Duper" Linear Congruential Generator (LCG)
// LCG(2^32, 3*7*11*13*23, 0, seed)
//
l_rnd = l_rnd * ((uint32_t)3U*7U*11U*13U*23U);
return l_rnd >> 8;
}
//............................................................................
void BSP_randomSeed(uint32_t seed) {
l_rnd = seed;
}
//............................................................................
void BSP_terminate(int16_t result) {
(void)result;
}
} // namespace DPP
// namespace QP **************************************************************
namespace QP {
// QF callbacks ==============================================================
void QF::onStartup(void) {
TACTL = (ID_3 | TASSEL_2 | MC_1); // SMCLK, /8 divider, upmode
TACCR0 = (((BSP_SMCLK / 8U) + DPP::BSP_TICKS_PER_SEC/2U)
/ DPP::BSP_TICKS_PER_SEC);
CCTL0 = CCIE; // CCR0 interrupt enabled
}
//............................................................................
void QF::onCleanup(void) {
}
//............................................................................
void QK::onIdle(void) {
// toggle LED2 on and then off, see NOTE1
QF_INT_DISABLE();
P1OUT |= LED2; // turn LED2 on
P1OUT &= ~LED2; // turn LED2 off
QF_INT_ENABLE();
#ifdef Q_SPY
if (((IFG2 & UCA0TXIFG)) != 0U) { // UART not transmitting?
uint16_t b;
QF_INT_DISABLE();
b = QS::getByte();
QF_INT_ENABLE();
if (b != QS_EOD) {
UCA0TXBUF = (uint8_t)b; // stick the byte to the TX BUF
}
}
#elif defined NDEBUG
// Put the CPU and peripherals to the low-power mode.
// you might need to customize the clock management for your application,
// see the datasheet for your particular MSP430 MCU.
//
__low_power_mode_1(); // Enter LPM1; also ENABLES interrupts
#endif
}
//............................................................................
extern "C"
void Q_onAssert(char const Q_ROM * const file, int line) {
// implement the error-handling policy for your application!!!
QF_INT_DISABLE(); // disable all interrupts
// cause the reset of the CPU...
WDTCTL = WDTPW | WDTHOLD;
__asm(" push &0xFFFE");
// return from function does the reset
}
// QS callbacks ==============================================================
#ifdef Q_SPY
bool QS::onStartup(void const *arg) {
static uint8_t qsBuf[80]; // buffer for QS; RAM is tight!
uint16_t tmp;
initBuf(qsBuf, sizeof(qsBuf));
// configure the UART pins...
P1DIR |= (RXD | TXD); // config RX and TX pins as outputs
P1OUT &= ~(RXD | TXD); // drive RX and TX pins hi
P1SEL |= (RXD | TXD); // select the UART function...
P1SEL2 |= (RXD | TXD); // ... for RXD and TXD
// configure the hardware UART...
UCA0CTL1 |= UCSSEL_2; // select SMCLK for the UART
tmp = BSP_SMCLK / 9600U; // baud-rate value for 9600 bauds
UCA0BR0 = (uint8_t)tmp; // load the baud-rate register low
UCA0BR1 = (uint8_t)(tmp >> 8); // load the baud-rate register hi
UCA0MCTL = UCBRS0; // modulation UCBRSx = 1
UCA0CTL1 &= ~UCSWRST; // initialize USCI state machine
// setup the QS filters...
QS_FILTER_ON(QS_QEP_STATE_ENTRY);
QS_FILTER_ON(QS_QEP_STATE_EXIT);
QS_FILTER_ON(QS_QEP_STATE_INIT);
QS_FILTER_ON(QS_QEP_INIT_TRAN);
QS_FILTER_ON(QS_QEP_INTERN_TRAN);
QS_FILTER_ON(QS_QEP_TRAN);
QS_FILTER_ON(QS_QEP_IGNORED);
// QS_FILTER_ON(QS_QEP_DISPATCH);
QS_FILTER_ON(QS_QEP_UNHANDLED);
// QS_FILTER_ON(QS_QF_ACTIVE_ADD);
// QS_FILTER_ON(QS_QF_ACTIVE_REMOVE);
// QS_FILTER_ON(QS_QF_ACTIVE_SUBSCRIBE);
// QS_FILTER_ON(QS_QF_ACTIVE_UNSUBSCRIBE);
// QS_FILTER_ON(QS_QF_ACTIVE_POST_FIFO);
// QS_FILTER_ON(QS_QF_ACTIVE_POST_LIFO);
// QS_FILTER_ON(QS_QF_ACTIVE_GET);
// QS_FILTER_ON(QS_QF_ACTIVE_GET_LAST);
// QS_FILTER_ON(QS_QF_EQUEUE_INIT);
// QS_FILTER_ON(QS_QF_EQUEUE_POST_FIFO);
// QS_FILTER_ON(QS_QF_EQUEUE_POST_LIFO);
// QS_FILTER_ON(QS_QF_EQUEUE_GET);
// QS_FILTER_ON(QS_QF_EQUEUE_GET_LAST);
// QS_FILTER_ON(QS_QF_MPOOL_INIT);
// QS_FILTER_ON(QS_QF_MPOOL_GET);
// QS_FILTER_ON(QS_QF_MPOOL_PUT);
// QS_FILTER_ON(QS_QF_PUBLISH);
// QS_FILTER_ON(QS_QF_RESERVED8);
// QS_FILTER_ON(QS_QF_NEW);
// QS_FILTER_ON(QS_QF_GC_ATTEMPT);
// QS_FILTER_ON(QS_QF_GC);
QS_FILTER_ON(QS_QF_TICK);
// QS_FILTER_ON(QS_QF_TIMEEVT_ARM);
// QS_FILTER_ON(QS_QF_TIMEEVT_AUTO_DISARM);
// QS_FILTER_ON(QS_QF_TIMEEVT_DISARM_ATTEMPT);
// QS_FILTER_ON(QS_QF_TIMEEVT_DISARM);
// QS_FILTER_ON(QS_QF_TIMEEVT_REARM);
// QS_FILTER_ON(QS_QF_TIMEEVT_POST);
// QS_FILTER_ON(QS_QF_TIMEEVT_CTR);
// QS_FILTER_ON(QS_QF_CRIT_ENTRY);
// QS_FILTER_ON(QS_QF_CRIT_EXIT);
// QS_FILTER_ON(QS_QF_ISR_ENTRY);
// QS_FILTER_ON(QS_QF_ISR_EXIT);
// QS_FILTER_ON(QS_QF_INT_DISABLE);
// QS_FILTER_ON(QS_QF_INT_ENABLE);
// QS_FILTER_ON(QS_QF_ACTIVE_POST_ATTEMPT);
// QS_FILTER_ON(QS_QF_EQUEUE_POST_ATTEMPT);
// QS_FILTER_ON(QS_QF_MPOOL_GET_ATTEMPT);
// QS_FILTER_ON(QS_QF_RESERVED1);
// QS_FILTER_ON(QS_QF_RESERVED0);
// QS_FILTER_ON(QS_QK_MUTEX_LOCK);
// QS_FILTER_ON(QS_QK_MUTEX_UNLOCK);
// QS_FILTER_ON(QS_QK_SCHEDULE);
// QS_FILTER_ON(QS_QK_RESERVED1);
// QS_FILTER_ON(QS_QK_RESERVED0);
// QS_FILTER_ON(QS_QEP_TRAN_HIST);
// QS_FILTER_ON(QS_QEP_TRAN_EP);
// QS_FILTER_ON(QS_QEP_TRAN_XP);
// QS_FILTER_ON(QS_QEP_RESERVED1);
// QS_FILTER_ON(QS_QEP_RESERVED0);
QS_FILTER_ON(QS_SIG_DICT);
QS_FILTER_ON(QS_OBJ_DICT);
QS_FILTER_ON(QS_FUN_DICT);
QS_FILTER_ON(QS_USR_DICT);
QS_FILTER_ON(QS_EMPTY);
QS_FILTER_ON(QS_RESERVED3);
QS_FILTER_ON(QS_RESERVED2);
QS_FILTER_ON(QS_TEST_RUN);
QS_FILTER_ON(QS_TEST_FAIL);
QS_FILTER_ON(QS_ASSERT_FAIL);
return true; // return success
}
//............................................................................
void QS::onCleanup(void) {
}
//............................................................................
QSTimeCtr QS::onGetTime(void) { // invoked with interrupts DISABLED
if ((TACTL & TAIFG) == 0U) { // interrupt not pending?
return DPP::QS_tickTime_ + TAR;
}
else { // the rollover occured, but the timerA_ISR did not run yet
return DPP::QS_tickTime_
+ (((BSP_SMCLK/8U) + DPP::BSP_TICKS_PER_SEC/2U)
/DPP::BSP_TICKS_PER_SEC) + 1U + TAR;
}
}
//............................................................................
void QS::onFlush(void) {
uint16_t b;
QF_INT_DISABLE();
while ((b = getByte()) != QS_EOD) { // next QS byte available?
QF_INT_ENABLE();
while ((IFG2 & UCA0TXIFG) == 0U) { // TX not ready?
}
UCA0TXBUF = (uint8_t)b; // stick the byte to the TX BUF
QF_INT_DISABLE();
}
QF_INT_ENABLE();
}
#endif // Q_SPY
} // namespace QP
//****************************************************************************
// NOTE1:
// One of the LEDs is used to visualize the idle loop activity. The brightness
// of the LED is proportional to the frequency of invcations of the idle loop.
// Please note that the LED is toggled with interrupts locked, so no interrupt
// execution time contributes to the brightness of the User LED.
//
| 34.470437 | 78 | 0.582967 | [
"vector"
] |
d68ad80a4652958c137f1b0f9cd434434a686314 | 4,801 | cpp | C++ | ZOJ/F.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | 1 | 2015-11-03T09:31:07.000Z | 2015-11-03T09:31:07.000Z | ZOJ/F.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | null | null | null | ZOJ/F.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | null | null | null | // File Name: F.cpp
// Author: YangYue
// Created Time: Sun Oct 12 20:36:46 2014
//headers
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <iostream>
#include <vector>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<double,double> PDD;
typedef pair<LL, LL>PLL;
typedef pair<LL,int>PLI;
#define lch(n) ((n<<1))
#define rch(n) ((n<<1)+1)
#define lowbit(i) (i&-i)
#define sqr(x) ((x)*(x))
#define fi first
#define se second
#define MP make_pair
#define PB push_back
const int MaxN = 1000005;
const double eps = 1e-8;
const double DINF = 1e100;
const int INF = 1000000006;
const LL LINF = 1000000000000000005ll;
const int mod = (int) 1e9+7;
PII range[MaxN];
vector<int> edges[MaxN];
vector<int> divisors[MaxN];
int fa[MaxN];
int tmp_f[55][55555];
int f_down[55][55555];
int f_up[55][55555];
int suffix_prod[55][55555];
int prffix_prod[55][55555];
int sons[55555];
int miu[55555];
void add(int &x, int v) {
if (v < 0) v += mod;
x = (x + v) % mod;
}
void mul(int &x, int v) {
if (v < 0) v += mod;
x = (LL) x * v % mod;
}
void dfs_from_botton(int u) {
int sons_cnt = 0;
for (auto &v : edges[u]) {
if (fa[u] == v) continue;
fa[v] = u;
dfs_from_botton(v);
}
for (auto &v : edges[u]) {
if (fa[u] == v) continue;
sons[++sons_cnt] = v;
static int f[55555];
memset(f, 0, sizeof f);
memset(tmp_f[sons_cnt], 0, sizeof tmp_f[sons_cnt]);
for (int d = 1; d <= 50000; ++d)
for (int x = d; x <= 50000; x += d) {
add(f[d], f_down[v][x]);
}
for (int x = range[u].first; x <= range[u].second; ++x)
for (auto &d : divisors[x]) add(tmp_f[sons_cnt][x], f[d] * miu[d]);
}
for (int x = 1; x <= 50000; ++x) prffix_prod[0][x] = suffix_prod[sons_cnt+1][x] = 1;
for (int i = 1; i <= sons_cnt; ++i)
for (int x = 1; x <= 50000; ++x) {
int cur = i > 1 ? prffix_prod[i-1][x] : 1;
prffix_prod[i][x] = (LL) cur * tmp_f[i][x] % mod;
}
for (int x = range[u].first; x <= range[u].second; ++x) f_down[u][x] = prffix_prod[sons_cnt][x];
}
void dfs_from_top(int u) {
int sons_cnt = 0;
for (auto &v : edges[u]) {
if (fa[u] == v) continue;
sons[++sons_cnt] = v;
static int f[55555];
memset(f, 0, sizeof f);
memset(tmp_f[sons_cnt], 0, sizeof tmp_f[sons_cnt]);
for (int d = 1; d <= 50000; ++d)
for (int x = d; x <= 50000; x += d) {
add(f[d], f_down[v][x]);
}
for (int x = range[u].first; x <= range[u].second; ++x)
for (auto &d : divisors[x]) add(tmp_f[sons_cnt][x], f[d] * miu[d]);
}
for (int x = 1; x <= 50000; ++x) prffix_prod[0][x] = suffix_prod[sons_cnt+1][x] = 1;
for (int i = 1; i <= sons_cnt; ++i)
for (int x = 1; x <= 50000; ++x) {
int cur = i > 1 ? prffix_prod[i-1][x] : 1;
prffix_prod[i][x] = (LL) cur * tmp_f[i][x] % mod;
}
for (int i = sons_cnt; i >= 1; --i)
for (int x = 1; x <= 50000; ++x) {
int cur = i < sons_cnt ? suffix_prod[i+1][x] : 1;
suffix_prod[i][x] = (LL) cur * tmp_f[i][x] % mod;
}
for (int idx = 1; idx <= sons_cnt; ++idx) {
int v = sons[idx];
static int f[55555];
memset(f, 0, sizeof f);
for (int d = 1; d <= 50000; ++d)
for (int x = d; x <= 50000; x += d) {
add(f[d], (LL) f_up[u][x] * prffix_prod[idx-1][x] % mod * suffix_prod[idx+1][x] % mod);
}
for (int x = range[v].first; x <= range[v].second; ++x) {
int tmp = 0;
for (auto &d : divisors[x]) {
add(tmp, f[d] * miu[d]);
}
f_up[v][x] = tmp;
}
}
for (auto &v : edges[u]) {
if (fa[u] == v) continue;
dfs_from_top(v);
}
}
bool flag[55555];
int main()
{
//:w
//freopen("in","r",stdin);
miu[1] = 1;
for (int i = 2; i <= 50000; ++i) if (!flag[i])
for (int j = i; j <= 50000; j += i) {
if (j/i % i == 0) miu[j] = 0;
else miu[j] = miu[j/i] * -1;
if (j > i) flag[j] = true;
}
for (int i = 1; i <= 50000; ++i)
for (int j = i; j <= 50000; j += i) divisors[j].push_back(i);
int cases; scanf("%d", &cases);
while (cases--) {
int n = 0;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
edges[i].clear();
scanf("%d", &range[i].first);
}
for (int i = 1; i <= n; ++i) scanf("%d", &range[i].second);
for (int i = 1; i < n; ++i) {
int x, y;
scanf("%d %d", &x, &y);
edges[x].push_back(y);
edges[y].push_back(x);
}
memset(f_down, 0, sizeof f_down);
memset(f_up, 0, sizeof f_up);
dfs_from_botton(1);
for (int x = range[1].first; x <= range[1].second; ++x) f_up[1][x] = 1;
dfs_from_top(1);
for (int i = 1; i <= n; ++i) {
int ans = 0;
for (int x = range[i].first; x <= range[i].second; ++x)
add(ans, (LL) x * f_down[i][x] % mod * f_up[i][x] % mod);
printf("%d%c", ans, i == n ? '\n' : ' ');
}
}
return 0;
}
// hehe ~
| 25.402116 | 97 | 0.550719 | [
"vector"
] |
d6955bf2d9497add0031761c9e298cbe1d9669a1 | 4,632 | cpp | C++ | src/gaia/DebugDraw.cpp | tomrosling/gaia | cb26e9951d399a402d4ab4deca5f75b64cf13700 | [
"MIT"
] | null | null | null | src/gaia/DebugDraw.cpp | tomrosling/gaia | cb26e9951d399a402d4ab4deca5f75b64cf13700 | [
"MIT"
] | null | null | null | src/gaia/DebugDraw.cpp | tomrosling/gaia | cb26e9951d399a402d4ab4deca5f75b64cf13700 | [
"MIT"
] | null | null | null | #include "DebugDraw.hpp"
#include "Renderer.hpp"
namespace gaia
{
struct DebugDraw::DebugVertex
{
Vec3f position;
Vec4u8 colour;
};
static constexpr int BufferSize = 1024 * 1024;
static constexpr int MaxVertices = BufferSize / sizeof(DebugDraw::DebugVertex);
void DebugDraw::Init(Renderer& renderer)
{
// Create a PSO
ComPtr<ID3DBlob> vertexShader = renderer.LoadCompiledShader(L"DebugVertex.cso");
Assert(vertexShader);
ComPtr<ID3DBlob> pixelShader = renderer.LoadCompiledShader(L"DebugPixel.cso");
Assert(pixelShader);
struct PipelineStateStream
{
CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE rootSignature;
CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT inputLayout;
CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY primType;
CD3DX12_PIPELINE_STATE_STREAM_VS vs;
CD3DX12_PIPELINE_STATE_STREAM_PS ps;
CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT dsvFormat;
CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS rtvFormats;
CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL depthStencil;
};
D3D12_INPUT_ELEMENT_DESC inputLayout[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "COLOUR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
D3D12_RT_FORMAT_ARRAY rtvFormats = {};
rtvFormats.NumRenderTargets = 1;
rtvFormats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
PipelineStateStream pipelineStateStream;
pipelineStateStream.rootSignature = &renderer.GetRootSignature();
pipelineStateStream.inputLayout = { inputLayout, (UINT)std::size(inputLayout) };
pipelineStateStream.primType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
pipelineStateStream.vs = CD3DX12_SHADER_BYTECODE(vertexShader.Get());
pipelineStateStream.ps = CD3DX12_SHADER_BYTECODE(pixelShader.Get());
pipelineStateStream.dsvFormat = DXGI_FORMAT_D32_FLOAT;
pipelineStateStream.rtvFormats = rtvFormats;
((D3D12_DEPTH_STENCIL_DESC&)pipelineStateStream.depthStencil).DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
D3D12_PIPELINE_STATE_STREAM_DESC pipelineStateStreamDesc = { sizeof(PipelineStateStream), &pipelineStateStream };
HRESULT result = renderer.GetDevice().CreatePipelineState(&pipelineStateStreamDesc, IID_PPV_ARGS(&m_pipelineState));
Assert(SUCCEEDED(result));
// Create buffers
for (ComPtr<ID3D12Resource>& buf : m_doubleVertexBuffer)
{
buf = renderer.CreateResidentBuffer(BufferSize);
}
m_uploadBuffer = renderer.CreateUploadBuffer(BufferSize);
D3D12_RANGE readRange = {};
m_uploadBuffer->Map(0, &readRange, (void**)&m_mappedVertexBuffer);
Assert(m_mappedVertexBuffer);
}
void DebugDraw::Render(Renderer& renderer)
{
if (m_usedVertices == 0)
return;
// Upload and stall :(
renderer.BeginUploads();
renderer.GetCopyCommandList().CopyBufferRegion(m_doubleVertexBuffer[m_currentBuffer].Get(), 0,
m_uploadBuffer.Get(), 0, m_usedVertices * sizeof(DebugVertex));
renderer.WaitUploads(renderer.EndUploads());
D3D12_VERTEX_BUFFER_VIEW view = {
m_doubleVertexBuffer[m_currentBuffer]->GetGPUVirtualAddress(),
(UINT)m_usedVertices * sizeof(DebugVertex),
sizeof(DebugVertex)
};
ID3D12GraphicsCommandList& commandList = renderer.GetDirectCommandList();
commandList.SetPipelineState(m_pipelineState.Get());
commandList.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_LINELIST);
commandList.IASetVertexBuffers(0, 1, &view);
commandList.DrawInstanced(view.SizeInBytes / view.StrideInBytes, 1, 0, 0);
m_currentBuffer ^= 1;
m_usedVertices = 0;
}
void DebugDraw::Point(Vec3f pos, float halfSize, Vec4u8 col)
{
Vec3f points[] = {
pos + Vec3f(-halfSize, 0.f, 0.f),
pos + Vec3f( halfSize, 0.f, 0.f),
pos + Vec3f(0.f, -halfSize, 0.f),
pos + Vec3f(0.f, halfSize, 0.f),
pos + Vec3f(0.f, 0.f, -halfSize),
pos + Vec3f(0.f, 0.f, halfSize),
};
Lines((int)std::size(points), points, col);
}
void DebugDraw::Lines(int numPoints, const Vec3f* points, Vec4u8 col)
{
Assert(numPoints > 1);
Assert(numPoints % 2 == 0);
Assert(m_usedVertices + numPoints <= MaxVertices);
Assert(m_uploadBuffer);
int vertex = m_usedVertices;
for (int i = 0; i < numPoints; ++i)
{
DebugVertex& v0 = m_mappedVertexBuffer[vertex++];
v0.position = points[i];
v0.colour = col;
}
m_usedVertices = vertex;
}
}
| 35.090909 | 135 | 0.725604 | [
"render"
] |
d696a70868bb667dcb21bac856a76e63fb77ef7a | 6,124 | cpp | C++ | official/recommend/wide_and_deep/infer/mxbase/main.cpp | mindspore-ai/models | 9127b128e2961fd698977e918861dadfad00a44c | [
"Apache-2.0"
] | 77 | 2021-10-15T08:32:37.000Z | 2022-03-30T13:09:11.000Z | official/recommend/wide_and_deep/infer/mxbase/main.cpp | mindspore-ai/models | 9127b128e2961fd698977e918861dadfad00a44c | [
"Apache-2.0"
] | 3 | 2021-10-30T14:44:57.000Z | 2022-02-14T06:57:57.000Z | official/recommend/wide_and_deep/infer/mxbase/main.cpp | mindspore-ai/models | 9127b128e2961fd698977e918861dadfad00a44c | [
"Apache-2.0"
] | 24 | 2021-10-15T08:32:45.000Z | 2022-03-24T18:45:20.000Z | /**
* Copyright 2021 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 <dirent.h>
#include <gflags/gflags.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include "FunctionTimer.h"
#include "MxBase/Log/Log.h"
#include "MxBaseInfer.h"
#include "MxDeepFmPostProcessor.h"
#define LOG_SYS_ERROR(msg) LogError << msg << " error:" << strerror(errno)
#define D_ISREG(ty) ((ty) == DT_REG)
FunctionStats g_infer_stats("WideAndDeep Inference", 1e6);
DEFINE_string(model, "../data/models/wide_and_deep.om", "om model path.");
DEFINE_string(feat_ids, "../data/feat_ids.bin", "feat_ids.");
DEFINE_string(feat_vals, "../data/feat_vals.bin", "feat_vals.");
DEFINE_int32(sample_num, 1, "num of samples");
DEFINE_int32(device, 0, "device id used");
class WideAndDeepInfer : public CBaseInfer {
private:
MSDeepfmPostProcessor m_oPostProcessor;
public:
// the shape of feat_ids & feat_vals. It's defined by the inference model
const int col_per_sample = 39;
// total number of samples
uint64_t sample_num = 1;
explicit WideAndDeepInfer(uint32_t deviceId) : CBaseInfer(deviceId) {}
MSDeepfmPostProcessor &GetPostProcessor() override {
return m_oPostProcessor;
}
void OutputResult(const std::vector<ObjDetectInfo> &objs) override {
}
public:
bool InitPostProcessor(const std::string &configPath,
const std::string &labelPath) {
return m_oPostProcessor.Init(configPath, labelPath, m_oModelDesc) ==
APP_ERR_OK;
}
void UnInitPostProcessor() { m_oPostProcessor.DeInit(); }
bool CheckInputSize(const std::string &featIdPath,
const std::string &featValPath) {
struct stat featIdStat;
struct stat featValStat;
stat(featIdPath.c_str(), &featIdStat);
stat(featValPath.c_str(), &featValStat);
uint64_t featIdSize = featValStat.st_size;
uint64_t idSampleSize = sizeof(int) * col_per_sample;
uint64_t valSampelSize = sizeof(float) * col_per_sample;
sample_num = featIdSize / idSampleSize;
// if the size of feat_ids.bin or feat_vals.bin is not divisible by the
// size of a single sample or the size of two files is not equal to each
// other return false;
if (featIdSize % idSampleSize != 0 ||
featIdSize % valSampelSize != 0 ||
sample_num != (featIdSize / valSampelSize))
return false;
return true;
}
};
template <class Type>
int load_bin_file(char *buffer, const std::string &filename, int struct_num) {
std::ifstream rf(filename, std::ios::out | std::ios::binary);
if (!rf) {
LogError << "Cannot open file!";
return -1;
}
rf.read(buffer, sizeof(Type) * struct_num);
rf.close();
if (!rf.good()) {
LogError << "Error occurred at reading time!";
return -2;
}
return 0;
}
/*
* @description Initialize and run AclProcess module
* @param resourceInfo resource info of deviceIds, model info, single Operator
* Path, etc
* @param file the absolute path of input file
* @return int int code
*/
int main(int argc, char *argv[]) {
FLAGS_logtostderr = 1;
LogInfo << "Usage: --model ../data/models/wide_and_deep.om --device 0";
gflags::ParseCommandLineFlags(&argc, &argv, true);
LogInfo << "OM File Path :" << FLAGS_model;
LogInfo << "deviceId :" << FLAGS_device;
LogInfo << "feat_ids :" << FLAGS_feat_ids;
LogInfo << "feat_vals :" << FLAGS_feat_vals;
LogInfo << "sample_num :" << FLAGS_sample_num;
WideAndDeepInfer infer(FLAGS_device);
if (!infer.CheckInputSize(FLAGS_feat_ids, FLAGS_feat_vals)) {
LogError << "invalid files: " << FLAGS_feat_ids << ", "
<< FLAGS_feat_vals;
LogError
<< "File sizes are not equal or the file size is not divisible by "
"the size of a single sample";
}
if (!infer.Init(FLAGS_model)) {
LogError << "init inference module failed !!!";
return -1;
}
if (!infer.InitPostProcessor("", "")) {
LogError << "init post processor failed !!!";
return -1;
}
infer.Dump();
FunctionTimer timer;
if (FLAGS_sample_num == -1) {
FLAGS_sample_num = infer.sample_num;
}
for (int i = 0; i < FLAGS_sample_num; ++i) {
if (!infer.LoadBinaryAsInput<int>(FLAGS_feat_ids, infer.col_per_sample,
i * infer.col_per_sample, 0)) {
LogError << "load text:" << FLAGS_feat_ids
<< " to device input[0] error!!!";
break;
}
if (!infer.LoadBinaryAsInput<float>(FLAGS_feat_vals,
infer.col_per_sample,
i * infer.col_per_sample, 1)) {
LogError << "load text:" << FLAGS_feat_vals
<< " to device input[0] error!!!";
break;
}
if (FLAGS_sample_num < 1000 || i % 1000 == 0) {
LogInfo << "loading data index " << i;
}
timer.start_timer();
int ret = infer.DoInference();
timer.calculate_time();
g_infer_stats.update_time(timer.get_elapsed_time_in_microseconds());
if (ret != APP_ERR_OK) {
LogError << "Failed to do inference, ret = " << ret;
break;
}
}
infer.UnInitPostProcessor();
infer.UnInit();
return 0;
}
| 31.73057 | 80 | 0.619856 | [
"shape",
"vector",
"model"
] |
d69de6632d54c3bf1bc6f44608baabac10ebbe8e | 13,569 | cpp | C++ | src/prod/src/Common/StringUtility.Test.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Common/StringUtility.Test.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Common/StringUtility.Test.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#include "Common/StringUtility.h"
using namespace Common;
using namespace std;
BOOST_AUTO_TEST_SUITE2(StringUtilityTests)
BOOST_AUTO_TEST_CASE(TrimExtraCharacters)
{
wstring trimmedString1 = StringUtility::LimitNumberOfCharacters(wstring(L"2+3-4+5-6+7"), L'+', 2);
VERIFY_IS_TRUE(trimmedString1 == wstring(L"2+3-4+5-6"));
wstring trimmedString2 = StringUtility::LimitNumberOfCharacters(wstring(L"aabb"), L'b', 0);
VERIFY_IS_TRUE(trimmedString2 == wstring(L"aa"));
wstring trimmedString3 = StringUtility::LimitNumberOfCharacters(wstring(L"babb"), L'b', 0);
VERIFY_IS_TRUE(trimmedString3 == wstring(L""));
wstring trimmedString4 = StringUtility::LimitNumberOfCharacters(wstring(L"bacb"), L'c', 1);
VERIFY_IS_TRUE(trimmedString4 == wstring(L"bacb"));
}
BOOST_AUTO_TEST_CASE(RemoveDotAndGetDouble)
{
wstring trimmedString1 = StringUtility::LimitNumberOfCharacters(wstring(L"17.03.1-ee-3"), L'.', 1);
double trimmedDouble1 = 0.0;
VERIFY_IS_TRUE(trimmedString1 == wstring(L"17.03"));
VERIFY_IS_TRUE(StringUtility::TryFromWString<double>(trimmedString1, trimmedDouble1));
VERIFY_IS_TRUE(trimmedDouble1 == 17.03);
wstring trimmedString2 = StringUtility::LimitNumberOfCharacters(wstring(L"17.06.2-ce-4"), L'.', 1);
double trimmedDouble2 = 0.0;
VERIFY_IS_TRUE(trimmedString2 == wstring(L"17.06"));
VERIFY_IS_TRUE(StringUtility::TryFromWString<double>(trimmedString2, trimmedDouble2));
VERIFY_IS_TRUE(trimmedDouble2 == 17.06);
}
BOOST_AUTO_TEST_CASE(SmokeAreEqualCaseInsensitive)
{
VERIFY_IS_TRUE(StringUtility::AreEqualCaseInsensitive(L"Test UPPER/lower", L"TEST upper/LOWER"));
VERIFY_IS_FALSE(StringUtility::AreEqualCaseInsensitive(L"aaa", L" Aaa"));
VERIFY_IS_FALSE(StringUtility::AreEqualCaseInsensitive(L"aaa", L"aAb"));
}
BOOST_AUTO_TEST_CASE(SmokeAreEqualPrefixPartCaseInsensitive)
{
VERIFY_IS_TRUE(StringUtility::AreEqualPrefixPartCaseInsensitive(wstring(L"servicefabric:/test"), wstring(L"ServiceFabric:/test"), L':'));
VERIFY_IS_TRUE(StringUtility::AreEqualPrefixPartCaseInsensitive(wstring(L"servicefabric:/test"), wstring(L"ServiceFabric:/test"), L':'));
VERIFY_IS_TRUE(StringUtility::AreEqualPrefixPartCaseInsensitive(wstring(L"serviceFabric:/test"), wstring(L"ServiceFabric:/test"), L':'));
VERIFY_IS_TRUE(StringUtility::AreEqualPrefixPartCaseInsensitive(string("Random1_Run"), string("random1_Run"), '_'));
VERIFY_IS_TRUE(StringUtility::AreEqualPrefixPartCaseInsensitive(string("Random1:Run"), string("random1:Run"), '_'));
VERIFY_IS_FALSE(StringUtility::AreEqualPrefixPartCaseInsensitive(wstring(L"random1"), wstring(L"random2"), L','));
VERIFY_IS_FALSE(StringUtility::AreEqualPrefixPartCaseInsensitive(wstring(L"random1:x"), wstring(L"random1:y"), L':'));
VERIFY_IS_FALSE(StringUtility::AreEqualPrefixPartCaseInsensitive(string("random1:"), string("random1:y"), ':'));
VERIFY_IS_FALSE(StringUtility::AreEqualPrefixPartCaseInsensitive(string("random1:Run"), string("random1:run"), ':'));
VERIFY_IS_FALSE(StringUtility::AreEqualPrefixPartCaseInsensitive(string("Random1:Run"), string("random1:run"), ':'));
}
BOOST_AUTO_TEST_CASE(SmokeIsLessCaseInsensitive)
{
VERIFY_IS_TRUE(StringUtility::IsLessCaseInsensitive(L"zzza", L"zzzb"));
VERIFY_IS_FALSE(StringUtility::IsLessCaseInsensitive(L"denial", L"deniAl"));
VERIFY_IS_TRUE(StringUtility::IsLessCaseInsensitive(L"mArket", L"mbA"));
VERIFY_IS_FALSE(StringUtility::IsLessCaseInsensitive(L"cast", L"Bast"));
VERIFY_IS_TRUE(StringUtility::IsLessCaseInsensitive(L"b", L"C"));
VERIFY_IS_TRUE(StringUtility::IsLessCaseInsensitive(L"alt", L"Blt"));
}
BOOST_AUTO_TEST_CASE(SmokeContains1)
{
string big = "Section one-two";
VERIFY_IS_TRUE(StringUtility::Contains(big, string("one")));
VERIFY_IS_TRUE(StringUtility::ContainsCaseInsensitive(big, string("OnE")));
VERIFY_IS_FALSE(StringUtility::Contains(big, string("OnE")));
}
BOOST_AUTO_TEST_CASE(SmokeContains2)
{
wstring big = L"Section one-two";
VERIFY_IS_TRUE(StringUtility::Contains(big, wstring(L"one")));
VERIFY_IS_TRUE(StringUtility::ContainsCaseInsensitive(big, wstring(L"OnE")));
VERIFY_IS_FALSE(StringUtility::Contains(big, wstring(L"OnE")));
}
BOOST_AUTO_TEST_CASE(SmokeSplit1)
{
wstring input = L" a,, , string with, spaces and ,";
vector<wstring> tokens;
StringUtility::Split<wstring>(input, tokens, L" ");
vector<wstring> vect;
vect.push_back(L"a,,");
vect.push_back(L",");
vect.push_back(L"string");
vect.push_back(L"with,");
vect.push_back(L"spaces");
vect.push_back(L"and");
vect.push_back(L",");
VERIFY_IS_TRUE(tokens == vect);
}
BOOST_AUTO_TEST_CASE(SmokeSplit2)
{
wstring input = L" a,, , string with, spaces and ,";
vector<wstring> tokens;
StringUtility::Split<wstring>(input, tokens, L",");
vector<wstring> vect;
vect.push_back(L" a");
vect.push_back(L" ");
vect.push_back(L" string with");
vect.push_back(L" spaces and ");
VERIFY_IS_TRUE(tokens == vect);
}
BOOST_AUTO_TEST_CASE(SmokeSplit3)
{
wstring input = L" a,, , string with, spaces and ,";
vector<wstring> tokens;
StringUtility::Split<wstring>(input, tokens, L", ");
vector<wstring> vect;
vect.push_back(L"a");
vect.push_back(L"string");
vect.push_back(L"with");
vect.push_back(L"spaces");
vect.push_back(L"and");
VERIFY_IS_TRUE(tokens == vect);
}
BOOST_AUTO_TEST_CASE(SmokeSplit4)
{
wstring input = L" a string without any separators";
vector<wstring> tokens;
StringUtility::Split<wstring>(input, tokens, L";");
vector<wstring> vect;
vect.push_back(L" a string without any separators");
VERIFY_IS_TRUE(tokens == vect);
}
BOOST_AUTO_TEST_CASE(SmokeSplit5)
{
wstring input = L" a string without any separators";
wstring token1;
wstring token2;
StringUtility::SplitOnce<wstring,wchar_t>(input, token1, token2, L';');
VERIFY_IS_TRUE(token1 == input);
VERIFY_IS_TRUE(token2 == L"");
}
BOOST_AUTO_TEST_CASE(SmokeSplit6)
{
wstring input = L" a string without any separators";
wstring token1;
wstring token2;
StringUtility::SplitOnce<wstring,wchar_t>(input, token1, token2, L':');
VERIFY_IS_TRUE(token1 == input);
VERIFY_IS_TRUE(token2 == L"");
}
BOOST_AUTO_TEST_CASE(SmokeSplit7)
{
wstring input = L"HeaderName: HeaderValue";
wstring token1;
wstring token2;
StringUtility::SplitOnce<wstring,wchar_t>(input, token1, token2, L':');
VERIFY_IS_TRUE(token1 == L"HeaderName");
VERIFY_IS_TRUE(token2 == L" HeaderValue");
}
BOOST_AUTO_TEST_CASE(SmokeSplit8)
{
wstring input = L"SOAPAction: \"http://tempuri.org/samples\"";
wstring token1;
wstring token2;
StringUtility::SplitOnce<wstring,wchar_t>(input, token1, token2, L':');
VERIFY_IS_TRUE(token1 == L"SOAPAction");
VERIFY_IS_TRUE(token2 == L" \"http://tempuri.org/samples\"");
}
BOOST_AUTO_TEST_CASE(SmokeTrimWhitespace1)
{
wstring input = L" \t \ttest whitespace removal \r\n";
wstring output = L"test whitespace removal";
StringUtility::TrimWhitespaces(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(SmokeTrimWhitespace2)
{
wstring input = L" \t \n Just at the beginning";
wstring output = L"Just at the beginning";
StringUtility::TrimWhitespaces(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(SmokeTrimSpace1)
{
wstring input = L" ";
wstring output = L"";
StringUtility::TrimSpaces(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(SmokeTrimSpace2)
{
wstring input = L"Just at the end ";
wstring output = L"Just at the end";
StringUtility::TrimSpaces(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(SmokeToUpper1)
{
wstring input = L"This is a string like ANY other.";
wstring output = L"THIS IS A STRING LIKE ANY OTHER.";
StringUtility::ToUpper(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(SmokeToUpper2)
{
string input = "This is a string like ANY other.";
string output = "THIS IS A STRING LIKE ANY OTHER.";
StringUtility::ToUpper(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(SmokeToLower1)
{
wstring input = L"This is ANOTHER string like ANY other.";
wstring output = L"this is another string like any other.";
StringUtility::ToLower(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(SmokeToLower2)
{
string input = "This is ANOTHER string like ANY other.";
string output = "this is another string like any other.";
StringUtility::ToLower(input);
VERIFY_IS_TRUE(input == output);
}
BOOST_AUTO_TEST_CASE(StartsWithEndsWith)
{
string s1 = "test";
VERIFY_IS_TRUE(StringUtility::StartsWith(s1, string("t")));
VERIFY_IS_TRUE(StringUtility::StartsWith(s1, string("test")));
VERIFY_IS_TRUE(!StringUtility::StartsWith(s1, string("test1")));
VERIFY_IS_TRUE(StringUtility::EndsWithCaseInsensitive(s1, string("T")));
VERIFY_IS_TRUE(StringUtility::EndsWithCaseInsensitive(s1, string("Test")));
VERIFY_IS_TRUE(!StringUtility::EndsWithCaseInsensitive(s1, string("*Test")));
}
BOOST_AUTO_TEST_CASE(UtfConversion)
{
const wstring utf16Input = L"this is a test string";
string utf8Output;
StringUtility::Utf16ToUtf8(utf16Input, utf8Output);
Trace.WriteInfo(TraceType, "utf8Output = {0}", utf8Output);
const string utf8OutputExpected = "this is a test string";
BOOST_REQUIRE(utf8Output == utf8OutputExpected);
wstring utf16Output;
StringUtility::Utf8ToUtf16(utf8Output, utf16Output);
Trace.WriteInfo(TraceType, "utf16Output = {0}", utf16Output);
BOOST_REQUIRE(utf16Output == utf16Input);
}
BOOST_AUTO_TEST_CASE(CompareDigitsAsNumbers)
{
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)0, (const wchar_t*)L"ac") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)0, (const wchar_t*)0) == 0);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"a", (const wchar_t*)0) == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab", (const wchar_t*)L"ac") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab", (const wchar_t*)L"a") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)"1", (const wchar_t*)L"2") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"0001", (const wchar_t*)L"2") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"10", (const wchar_t*)L"2") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"10", (const wchar_t*)L"0002") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab1", (const wchar_t*)L"ab2") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab0001", (const wchar_t*)L"ab2") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab10", (const wchar_t*)L"ab2") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab0a", (const wchar_t*)L"ab0a") == 0);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab000a", (const wchar_t*)L"ab0a") == 0);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab2a", (const wchar_t*)L"ab11a") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab222a", (const wchar_t*)L"ab222c") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab000222a", (const wchar_t*)L"ab222c") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab000222a000", (const wchar_t*)L"ab222a00") == 0);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"ab000222a10", (const wchar_t*)L"ab222a002") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"2", (const wchar_t*)L"10") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"10", (const wchar_t*)L"2") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"UD2", (const wchar_t*)L"UD10") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"UD10", (const wchar_t*)L"UD2") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"fabric:/UD/2", (const wchar_t*)L"fabric:/UD/10") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"fabric:/UD/10", (const wchar_t*)L"fabric:/UD/2") == 1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"fabric:/UD/UD2", (const wchar_t*)L"fabric:/UD/UD10") == -1);
VERIFY_IS_TRUE(StringUtility::CompareDigitsAsNumbers((const wchar_t*)L"fabric:/UD/UD10", (const wchar_t*)L"fabric:/UD/UD2") == 1);
}
BOOST_AUTO_TEST_SUITE_END()
| 40.504478 | 141 | 0.7086 | [
"vector"
] |
d6a1dd07858485ef77794b2dabcc57e0ca811518 | 2,271 | cpp | C++ | examples/cpp/core/nothing_default/nothing_default.cpp | grisharav/bond | db05b170c83f74d0ea561d109ea90ed63b13cfa6 | [
"MIT"
] | null | null | null | examples/cpp/core/nothing_default/nothing_default.cpp | grisharav/bond | db05b170c83f74d0ea561d109ea90ed63b13cfa6 | [
"MIT"
] | null | null | null | examples/cpp/core/nothing_default/nothing_default.cpp | grisharav/bond | db05b170c83f74d0ea561d109ea90ed63b13cfa6 | [
"MIT"
] | null | null | null | #include "nothing_default_reflection.h"
#include <bond/core/bond.h>
#include <bond/stream/output_buffer.h>
using namespace examples::nothing_default;
template <typename T>
bond::blob Marshal(const T& obj)
{
bond::OutputBuffer buffer;
bond::CompactBinaryWriter<bond::OutputBuffer> writer(buffer);
bond::Marshal(obj, writer);
return buffer.GetBuffer();
}
template <typename T>
void Unmarshal(const bond::InputBuffer& buffer, T& obj)
{
bond::Unmarshal(buffer, obj);
}
int main()
{
Struct_v1 v1;
// Struct_v1 has a required field foo which by default is set to 'nothing'.
// If we try to serialize object v1 w/o initializing the field to some value
// Bond will throw an exception.
try
{
printf("Serializing v1... ");
Marshal(v1);
}
catch(const bond::CoreException& e)
{
printf("%s\n", e.what());
}
// Initialize field by assigning a value to it...
v1.foo = 10;
// ... or for complex fields using set_value() method
v1.baz.set_value();
v1.baz.value().push_back("test1");
v1.baz.value().push_back("test2");
// We can also set a field to 'nothing' using set_nothing() method.
// Optional fields that are set to 'nothing' are omitted when object is
// serialized.
v1.baz.set_nothing();
bond::InputBuffer buffer = Marshal(v1);
// Deserialize the payload into object of type Struct_v2
Struct_v2 v2;
Unmarshal(buffer, v2);
// Struct_v2 has an optional field bar, which didn't exist in Struct_v1.
// It is initialized to 'nothing' by default. By checking if the field is
// 'nothing' after de-serialization we can detect if it was present in the
// payload or not.
if (v2.baz.is_nothing())
{
printf("Field 'baz' was not present in the payload\n");
}
// Accessing field that is set to 'nothing' throws and exception
try
{
double d;
printf("Using field bar... ");
d = v2.bar;
fprintf(stderr, "Accessing field bar should have thrown, but we got %g instead", d);
exit(1); // should not have gotten here
}
catch(const bond::CoreException& e)
{
printf("%s\n", e.what());
}
return 0;
}
| 25.806818 | 92 | 0.628358 | [
"object"
] |
d6a33941efe6ec3443924328bfcfc8bed241b675 | 4,197 | cpp | C++ | Motion/mixingconfig.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | 2 | 2017-11-24T12:34:14.000Z | 2021-09-10T02:18:34.000Z | Motion/mixingconfig.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | null | null | null | Motion/mixingconfig.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | 6 | 2017-11-24T12:34:56.000Z | 2022-03-22T10:05:45.000Z |
#include "stdafx.h"
#include "mixingconfig.h"
const string g_minxingConfigFileName = "mixing_conf.cfg";
cMixingConfig::cMixingConfig():
m_bias_yaw(0)
, m_bias_pitch(0)
, m_bias_roll(0)
, m_bias_heave(0)
,m_rate1_center_yaw(0)
,m_rate1_center_pitch(0)
,m_rate1_center_roll(0)
,m_rate1_center_heave(0)
,m_rate2_center_yaw(0)
,m_rate2_center_pitch(0)
,m_rate2_center_roll(0)
,m_rate2_center_heave(0)
,m_rate3_center_yaw(0)
,m_rate3_center_pitch(0)
,m_rate3_center_roll(0)
,m_rate3_center_heave(0)
{
}
cMixingConfig::~cMixingConfig()
{
//Save(g_minxingConfigFileName);
}
void cMixingConfig::InitDefault()
{
m_inputType = 0;
m_input1_enable = true;
m_rate1_all = 1;
m_rate1_yaw = 1;
m_rate1_pitch = 1;
m_rate1_roll = 1;
m_rate1_heave = 1;
m_input2_enable = false;
m_rate2_all = 1;
m_rate2_yaw = 1;
m_rate2_pitch = 1;
m_rate2_roll = 1;
m_rate2_heave = 1;
m_input3_enable = false;
m_rate3_all = 1;
m_rate3_yaw = 1;
m_rate3_pitch = 1;
m_rate3_roll = 1;
m_rate3_heave = 1;
m_input4_enable = false;
m_rate4_all = 1;
m_rate4_pitch = 1;
m_rate4_roll = 1;
m_rate4_center_pitch = 0;
m_rate4_center_roll = 0;
m_bias_yaw = 0;
m_bias_pitch = 0;
m_bias_roll = 0;
m_bias_heave = 0;
m_rate1_center_yaw= 0;
m_rate1_center_pitch= 0;
m_rate1_center_roll= 0;
m_rate1_center_heave= 0;
m_rate2_center_yaw= 0;
m_rate2_center_pitch= 0;
m_rate2_center_roll= 0;
m_rate2_center_heave= 0;
m_rate3_center_yaw= 0;
m_rate3_center_pitch= 0;
m_rate3_center_roll= 0;
m_rate3_center_heave= 0;
}
void cMixingConfig::UpdateParseData()
{
m_inputType = 0;
const string input = m_options["input"];
if (!input.empty())
{
vector<string> toks;
common::tokenizer(input, "+", "", toks);
for each (auto &str in toks)
{
if (str == "joystick")
{
m_inputType |= INPUT_JOYSTICK;
}
else if (str == "udp")
{
m_inputType |= INPUT_UDP;
}
else if (str == "motionwave")
{
m_inputType |= INPUT_MOTIONWAVE;
}
else if (str == "var")
{
m_inputType |= INPUT_VAR;
}
}
}
m_input1_enable = GetBool("mixing_input1_enable");
m_rate1_all = GetFloat("mixing_rate1_all");
m_rate1_yaw = GetFloat("mixing_rate1_yaw");
m_rate1_pitch = GetFloat("mixing_rate1_pitch");
m_rate1_roll = GetFloat("mixing_rate1_roll");
m_rate1_heave = GetFloat("mixing_rate1_heave");
m_input2_enable = GetBool("mixing_input2_enable");
m_rate2_all = GetFloat("mixing_rate2_all");
m_rate2_yaw = GetFloat("mixing_rate2_yaw");
m_rate2_pitch = GetFloat("mixing_rate2_pitch");
m_rate2_roll = GetFloat("mixing_rate2_roll");
m_rate2_heave = GetFloat("mixing_rate2_heave");
m_input3_enable = GetBool("mixing_input3_enable");
m_rate3_all = GetFloat("mixing_rate3_all");
m_rate3_yaw = GetFloat("mixing_rate3_yaw");
m_rate3_pitch = GetFloat("mixing_rate3_pitch");
m_rate3_roll = GetFloat("mixing_rate3_roll");
m_rate3_heave = GetFloat("mixing_rate3_heave");
m_input4_enable = GetBool("mixing_input4_enable");
m_rate4_all = GetFloat("mixing_rate4_all");
m_rate4_pitch = GetFloat("mixing_rate4_pitch");
m_rate4_roll = GetFloat("mixing_rate4_roll");
m_rate4_center_pitch = GetFloat("mixing_rate4_center_pitch", 0);
m_rate4_center_roll = GetFloat("mixing_rate4_center_roll", 0);
m_bias_yaw = GetFloat("mixing_bias_yaw", 0);
m_bias_pitch = GetFloat("mixing_bias_pitch", 0);
m_bias_roll = GetFloat("mixing_bias_roll", 0);
m_bias_heave = GetFloat("mixing_bias_heave", 0);
m_rate1_center_yaw = GetFloat("mixing_rate1_center_yaw", 0);
m_rate1_center_pitch = GetFloat("mixing_rate1_center_pitch", 0);
m_rate1_center_roll = GetFloat("mixing_rate1_center_roll", 0);
m_rate1_center_heave = GetFloat("mixing_rate1_center_heave", 0);
m_rate2_center_yaw = GetFloat("mixing_rate2_center_yaw", 0);
m_rate2_center_pitch = GetFloat("mixing_rate2_center_pitch", 0);
m_rate2_center_roll = GetFloat("mixing_rate2_center_roll", 0);
m_rate2_center_heave = GetFloat("mixing_rate2_center_heave", 0);
m_rate3_center_yaw = GetFloat("mixing_rate3_center_yaw", 0);
m_rate3_center_pitch = GetFloat("mixing_rate3_center_pitch", 0);
m_rate3_center_roll = GetFloat("mixing_rate3_center_roll", 0);
m_rate3_center_heave = GetFloat("mixing_rate3_center_heave", 0);
}
| 25.131737 | 65 | 0.750298 | [
"vector"
] |
d6ae6a00c6005475b110d8e9c5910a2fc7e1334e | 2,482 | hpp | C++ | DFNs/Executors/CamerasTransformEstimation/CamerasTransformEstimationExecutor.hpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 7 | 2019-02-26T15:09:50.000Z | 2021-09-30T07:39:01.000Z | DFNs/Executors/CamerasTransformEstimation/CamerasTransformEstimationExecutor.hpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | null | null | null | DFNs/Executors/CamerasTransformEstimation/CamerasTransformEstimationExecutor.hpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 1 | 2020-12-06T12:09:05.000Z | 2020-12-06T12:09:05.000Z | /**
* @addtogroup DFNs
* @{
*/
#ifndef CAMERASTRANSFORESTIMATION_EXECUTOR_HPP
#define CAMERASTRANSFORESTIMATION_EXECUTOR_HPP
#include "DFNCommonInterface.hpp"
#include <CamerasTransformEstimation/CamerasTransformEstimationInterface.hpp>
#include <Types/CPP/Matrix.hpp>
#include <Types/CPP/CorrespondenceMap2D.hpp>
#include <Types/CPP/Pose.hpp>
namespace CDFF
{
namespace DFN
{
namespace Executors
{
/**
* All the methods in this file execute the DFN for thecomputation of the camera transform. A DFN instance has to be passed in the constructor of these class. Each method takes the following parameters:
* @param inputMatrix: input fundamental matrix
* @param inputMatches: input 2d matches between 2d features.
* @param outputTransform: output estimated pose of the second camera in the reference frame of the first camera.
* @param success: output boolean telling whether the estimation was successfull.
*
* The main difference between the four methods are input and output types:
* Methods (i) and (ii) have the constant pointer as input, Methods (iii) and (iv) have a constant reference as input;
* Methods (i) and (iii) are non-creation methods, they give constant pointers as output, the output is just the output reference in the DFN;
* When using creation methods, the output has to be initialized to NULL.
* Methods (ii) and (iv) are creation methods, they copy the output of the DFN in the referenced output variable. Method (ii) takes a pointer, method (iv) takes a reference.
*/
void Execute(CamerasTransformEstimationInterface* dfn, MatrixWrapper::Matrix3dConstPtr inputMatrix, CorrespondenceMap2DWrapper::CorrespondenceMap2DConstPtr inputMatches,
PoseWrapper::Pose3DConstPtr& outputTransform, bool& success);
void Execute(CamerasTransformEstimationInterface* dfn, MatrixWrapper::Matrix3dConstPtr inputMatrix, CorrespondenceMap2DWrapper::CorrespondenceMap2DConstPtr inputMatches,
PoseWrapper::Pose3DPtr outputTransform, bool& success);
void Execute(CamerasTransformEstimationInterface* dfn, const MatrixWrapper::Matrix3d& inputMatrix, const CorrespondenceMap2DWrapper::CorrespondenceMap2D& inputMatches,
PoseWrapper::Pose3DConstPtr& outputTransform, bool& success);
void Execute(CamerasTransformEstimationInterface* dfn, const MatrixWrapper::Matrix3d& inputMatrix, const CorrespondenceMap2DWrapper::CorrespondenceMap2D& inputMatches,
PoseWrapper::Pose3D& outputTransform, bool& success);
}
}
}
#endif // CAMERASTRANSFORESTIMATION_EXECUTOR_HPP
/** @} */
| 48.666667 | 201 | 0.810637 | [
"transform"
] |
d6b813607f75ebd122d618552c6fb08ab511f1d1 | 8,070 | cpp | C++ | StaticArray.TestDriver.cpp | innasoboleva/c-study-files | a8ca32ccfab05a70fff6bc7e48b360fc39006d6f | [
"Apache-2.0"
] | null | null | null | StaticArray.TestDriver.cpp | innasoboleva/c-study-files | a8ca32ccfab05a70fff6bc7e48b360fc39006d6f | [
"Apache-2.0"
] | null | null | null | StaticArray.TestDriver.cpp | innasoboleva/c-study-files | a8ca32ccfab05a70fff6bc7e48b360fc39006d6f | [
"Apache-2.0"
] | null | null | null | //
// StaticArray.TestDriver.cpp
// Data Course
//
// Created by Inna Soboleva on 8/21/17.
// Copyright © 2017 Inna Soboleva. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
#include <cassert>
#include "StaticArray.h"
#include "StaticArray.h" // ifndef test
int main()
{
cout << "---TEST INT ARRAY---\n";
// Checking template array of integers
StaticArray<int, 100> a;
// Capacity
cout << "\nTesting StaticArray::capacity\n";
cout << "EXPECTED: 100 ";
cout << "ACTUAL: " << a.capacity() << endl;
assert(100 == a.capacity());
// StaticArray constructor
cout << "\nTesting StaticArray::StaticArray\n";
for (int i = 0; i < a.capacity(); i++)
assert(a[i] == 0); // default value is 0
// StaticArray::operator[ ] getter
cout << "\nTesting the StaticArray::operator[ ] getter\n";
const StaticArray<int, 100> b = a;
for (int i = 0; i < 100; i++)
assert(a[i] == b[i]);
// StaticArray::operator[ ] setter
cout << "\nTesting the StaticArray::operator[ ] setter\n";
a[60] = 12356;
a[70] = 7654321;
cout << "\nTesting StaticArray::operator[ ] setter\n";
cout << "EXPECTED: 12356 for a[60]\n";
cout << "ACTUAL: " << a[60] << endl;
assert(12356 == a[60]);
cout << "EXPECTED: 7654321 for a[70]\n";
cout << "ACTUAL: " << a[70] << endl;
assert(7654321 == a[70]);
a[-1000] = 123123;
cout << "EXPECTED: 123123 for a[-1000]\n";
cout << "ACTUAL: " << a[-1000] << endl;
assert(12356 == a[60]);
assert(7654321 == a[70]);
assert(123123 == a[-6]); // any out-of-range uses dummy
assert(123123 == a[100]); // checks upper end of range
assert(123123 != a[99]); // checks upper end of range
assert(123123 != a[0]); // checks lower end of range
// const object test
cout << "\nConst object test\n";
const StaticArray<int, 100> c; // if this compiles, StaticArray::StaticArray main constructor exists
assert(c.capacity()); // if this compiles, StaticArray::capacity is a getter
assert(c[0] == c[0]); // if this compiles, there is an StaticArray::operator[ ] getter
assert(c[-1] == c[-1]); // tests the getter's range checking
cout << "---TEST DOUBLE ARRAY---\n";
// Checking template array of doubles
StaticArray<double, 100> n;
// Capacity
cout << "\nTesting StaticArray::capacity\n";
cout << "EXPECTED: 100 ";
cout << "ACTUAL: " << n.capacity() << endl;
assert(100 == n.capacity());
// StaticArray constructor
cout << "\nTesting StaticArray::StaticArray\n";
for (int i = 0; i < n.capacity(); i++)
assert(n[i] == 0.0); // default value is 0.0
// StaticArray::operator[ ] getter
cout << "\nTesting the StaticArray::operator[ ] getter\n";
const StaticArray<double, 100> m = n;
for (int i = 0; i < 100; i++)
assert(n[i] == m[i]);
// StaticArray::operator[ ] setter
cout << "\nTesting the StaticArray::operator[ ] setter\n";
n[60] = 12356.1;
n[70] = 4321.2;
cout << "\nTesting StaticArray::operator[ ] setter\n";
cout << "EXPECTED: 12356.1 for n[60]\n";
cout << "ACTUAL: " << n[60] << endl;
assert(12356.1 == n[60]);
cout << "EXPECTED: 4321.2 for n[70]\n";
cout << "ACTUAL: " << n[70] << endl;
assert(4321.2 == n[70]);
n[-1000] = 123123;
cout << "EXPECTED: 123123 for n[-1000]\n";
cout << "ACTUAL: " << n[-1000] << endl;
assert(12356.1 == n[60]);
assert(4321.2 == n[70]);
assert(123123 == n[-6]); // any out-of-range uses dummy
assert(123123 == n[100]); // checks upper end of range
assert(123123 != n[99]); // checks upper end of range
assert(123123 != n[0]); // checks lower end of range
// const object test
cout << "\nConst object test\n";
const StaticArray<double, 100> v; // if this compiles, StaticArray::StaticArray main constructor exists
assert(v.capacity()); // if this compiles, StaticArray::capacity is a getter
assert(v[0] == v[0]); // if this compiles, there is an StaticArray::operator[ ] getter
assert(v[-1] == v[-1]); // tests the getter's range checking
cout << "---TEST CHARS ARRAY---\n";
// Checking template array of chars
StaticArray<char, 100> e;
// Capacity
cout << "\nTesting StaticArray::capacity\n";
cout << "EXPECTED: 100 ";
cout << "ACTUAL: " << e.capacity() << endl;
assert(100 == e.capacity());
// StaticArray constructor
cout << "\nTesting StaticArray::StaticArray\n";
for (int i = 0; i < e.capacity(); i++)
assert(e[i] == '\0'); // default value is null terminator
// StaticArray::operator[ ] getter
cout << "\nTesting the StaticArray::operator[ ] getter\n";
const StaticArray<char, 100> r = e;
for (int i = 0; i < 100; i++)
assert(e[i] == r[i]);
// StaticArray::operator[ ] setter
cout << "\nTesting the StaticArray::operator[ ] setter\n";
e[60] = 'g';
e[70] = 'h';
cout << "\nTesting StaticArray::operator[ ] setter\n";
cout << "EXPECTED: g for e[60]\n";
cout << "ACTUAL: " << e[60] << endl;
assert('g' == e[60]);
cout << "EXPECTED: h for e[70]\n";
cout << "ACTUAL: " << e[70] << endl;
assert('h' == e[70]);
e[-1000] = 'j';
cout << "EXPECTED: j for e[-1000]\n";
cout << "ACTUAL: " << e[-1000] << endl;
assert('g' == e[60]);
assert('h' == e[70]);
assert('j' == e[-6]); // any out-of-range uses dummy
assert('j' == e[100]); // checks upper end of range
assert('j' != e[99]); // checks upper end of range
assert('j' != e[0]); // checks lower end of range
// const object test
cout << "\nConst object test\n";
const StaticArray<char, 100> j; // if this compiles, StaticArray::StaticArray main constructor exists
assert(j.capacity()); // if this compiles, StaticArray::capacity is a getter
assert(j[0] == j[0]); // if this compiles, there is an StaticArray::operator[ ] getter
assert(j[-1] == j[-1]); // tests the getter's range checking
cout << "---TEST STRING ARRAY---\n";
// Checking template array of strings
StaticArray<string, 100> s;
// Capacity
cout << "\nTesting StaticArray::capacity\n";
cout << "EXPECTED: 100 ";
cout << "ACTUAL: " << s.capacity() << endl;
assert(100 == s.capacity());
// StaticArray constructor
cout << "\nTesting StaticArray::StaticArray\n";
for (int i = 0; i < s.capacity(); i++)
assert(s[i] == "\0"); //default value is null terminator
// StaticArray::operator[ ] getter
cout << "\nTesting the StaticArray::operator[ ] getter\n";
const StaticArray<string, 100> l = s;
for (int i = 0; i < 100; i++)
assert(s[i] == l[i]);
// StaticArray::operator[ ] setter
cout << "\nTesting the StaticArray::operator[ ] setter\n";
s[60] = "go";
s[70] = "wait";
cout << "\nTesting StaticArray::operator[ ] setter\n";
cout << "EXPECTED: \"go\" for s[60]\n";
cout << "ACTUAL: " << s[60] << endl;
assert("go" == s[60]);
cout << "EXPECTED: \"wait\" for s[70]\n";
cout << "ACTUAL: " << s[70] << endl;
assert("wait" == s[70]);
s[-1000] = "run";
cout << "EXPECTED: \"run\" for s[-1000]\n";
cout << "ACTUAL: " << s[-1000] << endl;
assert("go" == s[60]);
assert("wait" == s[70]);
assert("run" == s[-6]); // any out-of-range uses dummy
assert("run" == s[100]); // checks upper end of range
assert("run" != s[99]); // checks upper end of range
assert("run" != s[0]); // checks lower end of range
// const object test
cout << "\nConst object test\n";
const StaticArray<string, 100> p; // if this compiles, StaticArray::StaticArray main constructor exists
assert(p.capacity()); // if this compiles, StaticArray::capacity is a getter
assert(p[0] == p[0]); // if this compiles, there is an StaticArray::operator[ ] getter
assert(p[-1] == p[-1]); // tests the getter's range checking
return 0;
}
| 37.18894 | 107 | 0.570632 | [
"object"
] |
d6bb06f008d25e7afe253dee644bfa60c6fd7b79 | 1,243 | cpp | C++ | 4rth_Sem_c++_backup/PRACTICE/C/h.cpp | SayanGhoshBDA/code-backup | 8b6135facc0e598e9686b2e8eb2d69dd68198b80 | [
"MIT"
] | 16 | 2018-11-26T08:39:42.000Z | 2019-05-08T10:09:52.000Z | 4rth_Sem_c++_backup/PRACTICE/C/h.cpp | SayanGhoshBDA/code-backup | 8b6135facc0e598e9686b2e8eb2d69dd68198b80 | [
"MIT"
] | 8 | 2020-05-04T06:29:26.000Z | 2022-02-12T05:33:16.000Z | 4rth_Sem_c++_backup/PRACTICE/C/h.cpp | SayanGhoshBDA/code-backup | 8b6135facc0e598e9686b2e8eb2d69dd68198b80 | [
"MIT"
] | 5 | 2020-02-11T16:02:21.000Z | 2021-02-05T07:48:30.000Z | #include<iostream>
#include<vector>
#include<string>
#include<fstream>
using namespace std;
// file handling in c++
int main()
{
string steveQuote = "A day without sunshine is like, you know, night";
ofstream writer("stevequote.txt"); // to make a file name stevequote.txt
if(! writer)
{
// if cannot write to the file
cout<<"\nError opening file"<<endl;
return -2;
}
else
{
// inserted the quote to the first line of the file and then ended the line with a newline
writer << steveQuote<<endl;
writer.close();
}
ofstream writer2("stevequote.txt",ios::app);
// to append at the end of the file contents present
// ios :: in = to open a file to read input
// ios::trunc = Default
// ios::binary = Treat the file as binary
// ios::out = open a file to write output
if(! writer2)
{
cout<<"\n Error opening file"<<endl;
return -1;
}
else
{
writer2<<"\n\t\t\t -Steve Martin"<<endl;
writer2.close();
}
// Now reading the file stream
char letter;
ifstream reader("stevequote.txt");
if(! reader)
{
cout<<"Error opening file "<<endl;
return -1;
}
else
{
for(int i = 0; ! reader.eof(); i++)
{
reader.get(letter);
cout<<letter;
}
}
cout<<endl;
reader.close();
return 0;
}
| 18.833333 | 92 | 0.641191 | [
"vector"
] |
d6bdb1ac2ce4e9839cb649885ffc2de2dc0ae977 | 3,422 | cpp | C++ | cpp/binaryTree/binaryTreeLevelTraversal.cpp | locmpham/codingtests | 3805fc98c0fa0dbee52e12531f6205e77b52899e | [
"MIT"
] | null | null | null | cpp/binaryTree/binaryTreeLevelTraversal.cpp | locmpham/codingtests | 3805fc98c0fa0dbee52e12531f6205e77b52899e | [
"MIT"
] | null | null | null | cpp/binaryTree/binaryTreeLevelTraversal.cpp | locmpham/codingtests | 3805fc98c0fa0dbee52e12531f6205e77b52899e | [
"MIT"
] | null | null | null | /*
LEETCODE# 102
Given the root of a binary tree, return the level order traversal of its nodes' values.
(i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
*/
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
vector<vector<int>> levelOrder(TreeNode* root) {
deque<pair<TreeNode *, int>> queue;
vector<vector<int>> result(1000, vector<int>{});
int level = 0;
queue.push_back(make_pair(root, level));
//cout << "start" << endl;
while (!queue.empty()) {
auto elem = queue.front();
queue.pop_front();
//cout << "Level " << elem.second << endl;
TreeNode *node = elem.first;
level = elem.second;
if (node == NULL) {
//cout << "node=NULL" << endl;
continue;
}
else {
//cout << node->val << "." << level << endl;
result[level].push_back(node->val);
queue.push_back(make_pair(node->left, level+1));
queue.push_back(make_pair(node->right, level+1));
}
}
result.resize(level);
/*
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result[i].size(); j++) {
cout << result[i][j] << endl;
}
}*/
return result;
}
// Print a list of sub arrays
//
void printSubsets(string heading, vector<vector<int>> subsets) {
cout << heading <<"[";
for (auto subset : subsets) {
cout << "[";
for (auto x : subset) {
cout << x << ",";
}
cout << "],";
}
cout << "]" << endl;
}
// Traverse a BST BFS and print every node
//
void printBSTbfs(string heading, TreeNode *root) {
deque<TreeNode *> queue;
cout << heading << "[";;
queue.push_back(root);
while(!queue.empty()) {
TreeNode *node = queue.front();
queue.pop_front();
if (node == NULL) {
cout << "null,";
continue;
}
cout << node->val << ",";
queue.push_back(node->left);
queue.push_back(node->right);
}
cout << "]" << endl;
}
int main() {
TreeNode *root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
printBSTbfs("Tree: ", root);
vector<vector<int>> result = levelOrder(root);
printSubsets("Result: ", result);
root->val = 1;
root->left->val = 2;
root->right->val = 3;
root->left->left = root->right->left;
root->right->left = NULL;
root->left->left->val = 4;
root->right->right = new TreeNode(5);
printBSTbfs("Tree: ", root);
result = levelOrder(root);
printSubsets("Result: ", result);
return 0;
}
| 22.513158 | 92 | 0.532729 | [
"vector"
] |
d6c1ce9a4f9ec89dfbb392cc3dd8f864e0a5f2b3 | 3,606 | hpp | C++ | include/zrp/json_misc.hpp | omegacoleman/zrp | 8c3013c60a7c6d2a7817015e438d122f023c4bef | [
"BSL-1.0"
] | 12 | 2021-05-23T16:25:34.000Z | 2021-11-23T12:25:17.000Z | include/zrp/json_misc.hpp | omegacoleman/zrp | 8c3013c60a7c6d2a7817015e438d122f023c4bef | [
"BSL-1.0"
] | null | null | null | include/zrp/json_misc.hpp | omegacoleman/zrp | 8c3013c60a7c6d2a7817015e438d122f023c4bef | [
"BSL-1.0"
] | null | null | null | // SPDX-License-Identifier: BSL-1.0
// copyleft 2021 youcai <omegacoleman@gmail.com>
// 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)
#pragma once
#include "zrp/bindings.hpp"
#include "zrp/file.hpp"
#include "zrp/fmt_misc.hpp"
namespace zrp {
template<class T>
void extract( json::object const& obj, T& t, const string& key ) {
t = value_to<T>( obj.at( key ) );
}
template<class T, class InputType>
// requires ConvertibleTo<InputType, T>
void extract_with_default(json::object const& obj, T& t, const string& key, const InputType& default_value) {
if (auto ptr = obj.if_contains(key)) {
t = value_to<T>(*ptr);
} else {
t = default_value;
}
}
auto inline brace_color(int indent_level) {
switch (indent_level % 5) {
case 0:
return fmt::color::dark_cyan;
case 1:
return fmt::color::dark_green;
case 2:
return fmt::color::dark_olive_green;
case 3:
return fmt::color::dark_blue;
case 4:
return fmt::color::dark_salmon;
}
return fmt::color::dark_cyan;
}
struct indent_t {
stack<string> s_;
int level() const {
return s_.size();
}
string str() const {
if (s_.empty()) {
return "";
}
return s_.top();
}
string brace(const string& br) const {
return fmt::format(may(fmt::fg(brace_color(level()))), "{}", br);
}
void push() {
s_.push(str() + " ");
}
void pop() {
s_.pop();
}
};
inline void pretty_print(const json::value& jv, indent_t indent = {})
{
switch(jv.kind())
{
case json::kind::object:
{
fmt::print("{}\n", indent.brace("{"), "\n");
indent.push();
auto const& obj = jv.get_object();
if(! obj.empty())
{
auto it = obj.begin();
for(;;)
{
fmt::print("{}", indent.str());
fmt::print(may(fmt::fg(fmt::terminal_color::blue) | fmt::emphasis::bold), "{}", json::serialize(it->key()));
fmt::print(" : ");
pretty_print(it->value(), indent);
if(++it == obj.end())
break;
fmt::print(",\n");
}
}
indent.pop();
fmt::print("\n{}{}", indent.str(), indent.brace("}"));
break;
}
case json::kind::array:
{
fmt::print("{}\n", indent.brace("["), "\n");
indent.push();
auto const& arr = jv.get_array();
if(! arr.empty())
{
auto it = arr.begin();
for(;;)
{
fmt::print("{}", indent.str());
pretty_print(*it, indent);
if(++it == arr.end())
break;
fmt::print(",\n");
}
}
indent.pop();
fmt::print("\n{}{}", indent.str(), indent.brace("]"));
break;
}
case json::kind::string:
{
fmt::print(may(fmt::fg(fmt::terminal_color::green)), "{}", json::serialize(jv.get_string()));
break;
}
case json::kind::uint64:
fmt::print("{}", jv.get_uint64());
break;
case json::kind::int64:
fmt::print("{}", jv.get_int64());
break;
case json::kind::double_:
fmt::print("{}", jv.get_double());
break;
case json::kind::bool_:
if(jv.get_bool())
fmt::print(may(fmt::emphasis::italic), "true");
else
fmt::print(may(fmt::emphasis::italic), "false");
break;
case json::kind::null:
fmt::print(may(fmt::emphasis::strikethrough), "null");
break;
}
if(indent.level() == 0)
fmt::print("\n");
}
inline json::value parse_file(const string_view filename)
{
string filename_s{filename};
file f(filename_s.c_str(), "r");
json::stream_parser p;
while (!f.eof())
{
char buf[4096];
auto const nread = f.read(buf, sizeof(buf));
p.write(buf, nread);
}
p.finish();
return p.release();
}
};
| 20.843931 | 149 | 0.585413 | [
"object"
] |
d6c8ea4a3daf31c9fda4fd543e650a6557f3ae35 | 29,791 | hpp | C++ | libs/boost_1_72_0/boost/smart_ptr/shared_ptr.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/smart_ptr/shared_ptr.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/smart_ptr/shared_ptr.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | #ifndef BOOST_SMART_PTR_SHARED_PTR_HPP_INCLUDED
#define BOOST_SMART_PTR_SHARED_PTR_HPP_INCLUDED
//
// shared_ptr.hpp
//
// (C) Copyright Greg Colvin and Beman Dawes 1998, 1999.
// Copyright (c) 2001-2008 Peter Dimov
//
// 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)
//
// See http://www.boost.org/libs/smart_ptr/ for documentation.
//
#include <boost/config.hpp> // for broken compiler workarounds
// In order to avoid circular dependencies with Boost.TR1
// we make sure that our include of <memory> doesn't try to
// pull in the TR1 headers: that's why we use this header
// rather than including <memory> directly:
#include <boost/config/no_tr1/memory.hpp> // std::auto_ptr
#include <boost/assert.hpp>
#include <boost/checked_delete.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/smart_ptr/detail/shared_count.hpp>
#include <boost/smart_ptr/detail/sp_convertible.hpp>
#include <boost/smart_ptr/detail/sp_disable_deprecated.hpp>
#include <boost/smart_ptr/detail/sp_noexcept.hpp>
#include <boost/smart_ptr/detail/sp_nullptr_t.hpp>
#include <boost/throw_exception.hpp>
#if !defined(BOOST_SP_NO_ATOMIC_ACCESS)
#include <boost/smart_ptr/detail/spinlock_pool.hpp>
#endif
#include <algorithm> // for std::swap
#include <cstddef> // for std::size_t
#include <functional> // for std::less
#include <typeinfo> // for std::bad_cast
#if !defined(BOOST_NO_IOSTREAM)
#if !defined(BOOST_NO_IOSFWD)
#include <iosfwd> // for std::basic_ostream
#else
#include <ostream>
#endif
#endif
#if defined(BOOST_SP_DISABLE_DEPRECATED)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
namespace boost {
template <class T> class shared_ptr;
template <class T> class weak_ptr;
template <class T> class enable_shared_from_this;
class enable_shared_from_raw;
namespace movelib {
template <class T, class D> class unique_ptr;
} // namespace movelib
namespace detail {
// sp_element, element_type
template <class T> struct sp_element { typedef T type; };
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T> struct sp_element<T[]> { typedef T type; };
#if !defined(__BORLANDC__) || !BOOST_WORKAROUND(__BORLANDC__, < 0x600)
template <class T, std::size_t N> struct sp_element<T[N]> { typedef T type; };
#endif
#endif // !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION )
// sp_dereference, return type of operator*
template <class T> struct sp_dereference { typedef T &type; };
template <> struct sp_dereference<void> { typedef void type; };
#if !defined(BOOST_NO_CV_VOID_SPECIALIZATIONS)
template <> struct sp_dereference<void const> { typedef void type; };
template <> struct sp_dereference<void volatile> { typedef void type; };
template <> struct sp_dereference<void const volatile> { typedef void type; };
#endif // !defined(BOOST_NO_CV_VOID_SPECIALIZATIONS)
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T> struct sp_dereference<T[]> { typedef void type; };
#if !defined(__BORLANDC__) || !BOOST_WORKAROUND(__BORLANDC__, < 0x600)
template <class T, std::size_t N> struct sp_dereference<T[N]> {
typedef void type;
};
#endif
#endif // !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION )
// sp_member_access, return type of operator->
template <class T> struct sp_member_access { typedef T *type; };
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T> struct sp_member_access<T[]> { typedef void type; };
#if !defined(__BORLANDC__) || !BOOST_WORKAROUND(__BORLANDC__, < 0x600)
template <class T, std::size_t N> struct sp_member_access<T[N]> {
typedef void type;
};
#endif
#endif // !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION )
// sp_array_access, return type of operator[]
template <class T> struct sp_array_access { typedef void type; };
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T> struct sp_array_access<T[]> { typedef T &type; };
#if !defined(__BORLANDC__) || !BOOST_WORKAROUND(__BORLANDC__, < 0x600)
template <class T, std::size_t N> struct sp_array_access<T[N]> {
typedef T &type;
};
#endif
#endif // !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION )
// sp_extent, for operator[] index check
template <class T> struct sp_extent {
enum _vt { value = 0 };
};
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T, std::size_t N> struct sp_extent<T[N]> {
enum _vt { value = N };
};
#endif // !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION )
// enable_shared_from_this support
template <class X, class Y, class T>
inline void
sp_enable_shared_from_this(boost::shared_ptr<X> const *ppx, Y const *py,
boost::enable_shared_from_this<T> const *pe) {
if (pe != 0) {
pe->_internal_accept_owner(ppx, const_cast<Y *>(py));
}
}
template <class X, class Y>
inline void sp_enable_shared_from_this(boost::shared_ptr<X> *ppx, Y const *py,
boost::enable_shared_from_raw const *pe);
#ifdef _MANAGED
// Avoid C4793, ... causes native code generation
struct sp_any_pointer {
template <class T> sp_any_pointer(T *) {}
};
inline void sp_enable_shared_from_this(sp_any_pointer, sp_any_pointer,
sp_any_pointer) {}
#else // _MANAGED
inline void sp_enable_shared_from_this(...) {}
#endif // _MANAGED
#if !defined(BOOST_NO_SFINAE) && \
!defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && \
!defined(BOOST_NO_AUTO_PTR)
// rvalue auto_ptr support based on a technique by Dave Abrahams
template <class T, class R> struct sp_enable_if_auto_ptr {};
template <class T, class R> struct sp_enable_if_auto_ptr<std::auto_ptr<T>, R> {
typedef R type;
};
#endif
// sp_assert_convertible
template <class Y, class T>
inline void sp_assert_convertible() BOOST_SP_NOEXCEPT {
#if !defined(BOOST_SP_NO_SP_CONVERTIBLE)
// static_assert( sp_convertible< Y, T >::value );
typedef char tmp[sp_convertible<Y, T>::value ? 1 : -1];
(void)sizeof(tmp);
#else
T *p = static_cast<Y *>(0);
(void)p;
#endif
}
// pointer constructor helper
template <class T, class Y>
inline void sp_pointer_construct(boost::shared_ptr<T> *ppx, Y *p,
boost::detail::shared_count &pn) {
boost::detail::shared_count(p).swap(pn);
boost::detail::sp_enable_shared_from_this(ppx, p, p);
}
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T, class Y>
inline void sp_pointer_construct(boost::shared_ptr<T[]> * /*ppx*/, Y *p,
boost::detail::shared_count &pn) {
sp_assert_convertible<Y[], T[]>();
boost::detail::shared_count(p, boost::checked_array_deleter<T>()).swap(pn);
}
template <class T, std::size_t N, class Y>
inline void sp_pointer_construct(boost::shared_ptr<T[N]> * /*ppx*/, Y *p,
boost::detail::shared_count &pn) {
sp_assert_convertible<Y[N], T[N]>();
boost::detail::shared_count(p, boost::checked_array_deleter<T>()).swap(pn);
}
#endif // !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION )
// deleter constructor helper
template <class T, class Y>
inline void sp_deleter_construct(boost::shared_ptr<T> *ppx, Y *p) {
boost::detail::sp_enable_shared_from_this(ppx, p, p);
}
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class T, class Y>
inline void sp_deleter_construct(boost::shared_ptr<T[]> * /*ppx*/, Y * /*p*/) {
sp_assert_convertible<Y[], T[]>();
}
template <class T, std::size_t N, class Y>
inline void sp_deleter_construct(boost::shared_ptr<T[N]> * /*ppx*/, Y * /*p*/) {
sp_assert_convertible<Y[N], T[N]>();
}
#endif // !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION )
struct sp_internal_constructor_tag {};
} // namespace detail
//
// shared_ptr
//
// An enhanced relative of scoped_ptr with reference counted copy semantics.
// The object pointed to is deleted when the last shared_ptr pointing to it
// is destroyed or reset.
//
template <class T> class shared_ptr {
private:
// Borland 5.5.1 specific workaround
typedef shared_ptr<T> this_type;
public:
typedef typename boost::detail::sp_element<T>::type element_type;
BOOST_CONSTEXPR shared_ptr() BOOST_SP_NOEXCEPT : px(0), pn() {}
#if !defined(BOOST_NO_CXX11_NULLPTR)
BOOST_CONSTEXPR shared_ptr(boost::detail::sp_nullptr_t) BOOST_SP_NOEXCEPT
: px(0),
pn() {}
#endif
BOOST_CONSTEXPR
shared_ptr(boost::detail::sp_internal_constructor_tag, element_type *px_,
boost::detail::shared_count const &pn_) BOOST_SP_NOEXCEPT
: px(px_),
pn(pn_) {}
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
BOOST_CONSTEXPR
shared_ptr(boost::detail::sp_internal_constructor_tag, element_type *px_,
boost::detail::shared_count &&pn_) BOOST_SP_NOEXCEPT
: px(px_),
pn(std::move(pn_)) {}
#endif
template <class Y>
explicit shared_ptr(Y *p)
: px(p), pn() // Y must be complete
{
boost::detail::sp_pointer_construct(this, p, pn);
}
//
// Requirements: D's copy constructor must not throw
//
// shared_ptr will release p by calling d(p)
//
template <class Y, class D> shared_ptr(Y *p, D d) : px(p), pn(p, d) {
boost::detail::sp_deleter_construct(this, p);
}
#if !defined(BOOST_NO_CXX11_NULLPTR)
template <class D>
shared_ptr(boost::detail::sp_nullptr_t p, D d) : px(p), pn(p, d) {}
#endif
// As above, but with allocator. A's copy constructor shall not throw.
template <class Y, class D, class A>
shared_ptr(Y *p, D d, A a) : px(p), pn(p, d, a) {
boost::detail::sp_deleter_construct(this, p);
}
#if !defined(BOOST_NO_CXX11_NULLPTR)
template <class D, class A>
shared_ptr(boost::detail::sp_nullptr_t p, D d, A a) : px(p), pn(p, d, a) {}
#endif
// generated copy constructor, destructor are fine...
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
// ... except in C++0x, move disables the implicit copy
shared_ptr(shared_ptr const &r) BOOST_SP_NOEXCEPT : px(r.px), pn(r.pn) {}
#endif
template <class Y>
explicit shared_ptr(weak_ptr<Y> const &r)
: pn(r.pn) // may throw
{
boost::detail::sp_assert_convertible<Y, T>();
// it is now safe to copy r.px, as pn(r.pn) did not throw
px = r.px;
}
template <class Y>
shared_ptr(weak_ptr<Y> const &r,
boost::detail::sp_nothrow_tag) BOOST_SP_NOEXCEPT
: px(0),
pn(r.pn, boost::detail::sp_nothrow_tag()) {
if (!pn.empty()) {
px = r.px;
}
}
template <class Y>
#if !defined(BOOST_SP_NO_SP_CONVERTIBLE)
shared_ptr(shared_ptr<Y> const &r,
typename boost::detail::sp_enable_if_convertible<Y, T>::type =
boost::detail::sp_empty())
#else
shared_ptr(shared_ptr<Y> const &r)
#endif
BOOST_SP_NOEXCEPT : px(r.px),
pn(r.pn) {
boost::detail::sp_assert_convertible<Y, T>();
}
// aliasing
template <class Y>
shared_ptr(shared_ptr<Y> const &r, element_type *p) BOOST_SP_NOEXCEPT
: px(p),
pn(r.pn) {}
#ifndef BOOST_NO_AUTO_PTR
template <class Y>
explicit shared_ptr(std::auto_ptr<Y> &r) : px(r.get()), pn() {
boost::detail::sp_assert_convertible<Y, T>();
Y *tmp = r.get();
pn = boost::detail::shared_count(r);
boost::detail::sp_deleter_construct(this, tmp);
}
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template <class Y> shared_ptr(std::auto_ptr<Y> &&r) : px(r.get()), pn() {
boost::detail::sp_assert_convertible<Y, T>();
Y *tmp = r.get();
pn = boost::detail::shared_count(r);
boost::detail::sp_deleter_construct(this, tmp);
}
#elif !defined(BOOST_NO_SFINAE) && \
!defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class Ap>
explicit shared_ptr(
Ap r, typename boost::detail::sp_enable_if_auto_ptr<Ap, int>::type = 0)
: px(r.get()), pn() {
typedef typename Ap::element_type Y;
boost::detail::sp_assert_convertible<Y, T>();
Y *tmp = r.get();
pn = boost::detail::shared_count(r);
boost::detail::sp_deleter_construct(this, tmp);
}
#endif // BOOST_NO_SFINAE, BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
#endif // BOOST_NO_AUTO_PTR
#if !defined(BOOST_NO_CXX11_SMART_PTR) && \
!defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template <class Y, class D>
shared_ptr(std::unique_ptr<Y, D> &&r) : px(r.get()), pn() {
boost::detail::sp_assert_convertible<Y, T>();
typename std::unique_ptr<Y, D>::pointer tmp = r.get();
if (tmp != 0) {
pn = boost::detail::shared_count(r);
boost::detail::sp_deleter_construct(this, tmp);
}
}
#endif
template <class Y, class D>
shared_ptr(boost::movelib::unique_ptr<Y, D> r) : px(r.get()), pn() {
boost::detail::sp_assert_convertible<Y, T>();
typename boost::movelib::unique_ptr<Y, D>::pointer tmp = r.get();
if (tmp != 0) {
pn = boost::detail::shared_count(r);
boost::detail::sp_deleter_construct(this, tmp);
}
}
// assignment
shared_ptr &operator=(shared_ptr const &r) BOOST_SP_NOEXCEPT {
this_type(r).swap(*this);
return *this;
}
#if !defined(BOOST_MSVC) || (BOOST_MSVC >= 1400)
template <class Y>
shared_ptr &operator=(shared_ptr<Y> const &r) BOOST_SP_NOEXCEPT {
this_type(r).swap(*this);
return *this;
}
#endif
#ifndef BOOST_NO_AUTO_PTR
template <class Y> shared_ptr &operator=(std::auto_ptr<Y> &r) {
this_type(r).swap(*this);
return *this;
}
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template <class Y> shared_ptr &operator=(std::auto_ptr<Y> &&r) {
this_type(static_cast<std::auto_ptr<Y> &&>(r)).swap(*this);
return *this;
}
#elif !defined(BOOST_NO_SFINAE) && \
!defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <class Ap>
typename boost::detail::sp_enable_if_auto_ptr<Ap, shared_ptr &>::type
operator=(Ap r) {
this_type(r).swap(*this);
return *this;
}
#endif // BOOST_NO_SFINAE, BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
#endif // BOOST_NO_AUTO_PTR
#if !defined(BOOST_NO_CXX11_SMART_PTR) && \
!defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template <class Y, class D> shared_ptr &operator=(std::unique_ptr<Y, D> &&r) {
this_type(static_cast<std::unique_ptr<Y, D> &&>(r)).swap(*this);
return *this;
}
#endif
template <class Y, class D>
shared_ptr &operator=(boost::movelib::unique_ptr<Y, D> r) {
// this_type( static_cast< unique_ptr<Y, D> && >( r ) ).swap( *this );
boost::detail::sp_assert_convertible<Y, T>();
typename boost::movelib::unique_ptr<Y, D>::pointer p = r.get();
shared_ptr tmp;
if (p != 0) {
tmp.px = p;
tmp.pn = boost::detail::shared_count(r);
boost::detail::sp_deleter_construct(&tmp, p);
}
tmp.swap(*this);
return *this;
}
// Move support
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
shared_ptr(shared_ptr &&r) BOOST_SP_NOEXCEPT : px(r.px), pn() {
pn.swap(r.pn);
r.px = 0;
}
template <class Y>
#if !defined(BOOST_SP_NO_SP_CONVERTIBLE)
shared_ptr(shared_ptr<Y> &&r,
typename boost::detail::sp_enable_if_convertible<Y, T>::type =
boost::detail::sp_empty())
#else
shared_ptr(shared_ptr<Y> &&r)
#endif
BOOST_SP_NOEXCEPT : px(r.px),
pn() {
boost::detail::sp_assert_convertible<Y, T>();
pn.swap(r.pn);
r.px = 0;
}
shared_ptr &operator=(shared_ptr &&r) BOOST_SP_NOEXCEPT {
this_type(static_cast<shared_ptr &&>(r)).swap(*this);
return *this;
}
template <class Y>
shared_ptr &operator=(shared_ptr<Y> &&r) BOOST_SP_NOEXCEPT {
this_type(static_cast<shared_ptr<Y> &&>(r)).swap(*this);
return *this;
}
// aliasing move
template <class Y>
shared_ptr(shared_ptr<Y> &&r, element_type *p) BOOST_SP_NOEXCEPT : px(p),
pn() {
pn.swap(r.pn);
r.px = 0;
}
#endif
#if !defined(BOOST_NO_CXX11_NULLPTR)
shared_ptr &operator=(boost::detail::sp_nullptr_t) BOOST_SP_NOEXCEPT {
this_type().swap(*this);
return *this;
}
#endif
void reset() BOOST_SP_NOEXCEPT { this_type().swap(*this); }
template <class Y>
void reset(Y *p) // Y must be complete
{
BOOST_ASSERT(p == 0 || p != px); // catch self-reset errors
this_type(p).swap(*this);
}
template <class Y, class D> void reset(Y *p, D d) {
this_type(p, d).swap(*this);
}
template <class Y, class D, class A> void reset(Y *p, D d, A a) {
this_type(p, d, a).swap(*this);
}
template <class Y>
void reset(shared_ptr<Y> const &r, element_type *p) BOOST_SP_NOEXCEPT {
this_type(r, p).swap(*this);
}
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template <class Y>
void reset(shared_ptr<Y> &&r, element_type *p) BOOST_SP_NOEXCEPT {
this_type(static_cast<shared_ptr<Y> &&>(r), p).swap(*this);
}
#endif
typename boost::detail::sp_dereference<T>::type
operator*() const BOOST_SP_NOEXCEPT_WITH_ASSERT {
BOOST_ASSERT(px != 0);
return *px;
}
typename boost::detail::sp_member_access<T>::type
operator->() const BOOST_SP_NOEXCEPT_WITH_ASSERT {
BOOST_ASSERT(px != 0);
return px;
}
typename boost::detail::sp_array_access<T>::type
operator[](std::ptrdiff_t i) const BOOST_SP_NOEXCEPT_WITH_ASSERT {
BOOST_ASSERT(px != 0);
BOOST_ASSERT(i >= 0 && (i < boost::detail::sp_extent<T>::value ||
boost::detail::sp_extent<T>::value == 0));
return static_cast<typename boost::detail::sp_array_access<T>::type>(px[i]);
}
element_type *get() const BOOST_SP_NOEXCEPT { return px; }
// implicit conversion to "bool"
#include <boost/smart_ptr/detail/operator_bool.hpp>
bool unique() const BOOST_SP_NOEXCEPT { return pn.unique(); }
long use_count() const BOOST_SP_NOEXCEPT { return pn.use_count(); }
void swap(shared_ptr &other) BOOST_SP_NOEXCEPT {
std::swap(px, other.px);
pn.swap(other.pn);
}
template <class Y>
bool owner_before(shared_ptr<Y> const &rhs) const BOOST_SP_NOEXCEPT {
return pn < rhs.pn;
}
template <class Y>
bool owner_before(weak_ptr<Y> const &rhs) const BOOST_SP_NOEXCEPT {
return pn < rhs.pn;
}
void *_internal_get_deleter(boost::detail::sp_typeinfo_ const &ti) const
BOOST_SP_NOEXCEPT {
return pn.get_deleter(ti);
}
void *_internal_get_local_deleter(boost::detail::sp_typeinfo_ const &ti) const
BOOST_SP_NOEXCEPT {
return pn.get_local_deleter(ti);
}
void *_internal_get_untyped_deleter() const BOOST_SP_NOEXCEPT {
return pn.get_untyped_deleter();
}
bool _internal_equiv(shared_ptr const &r) const BOOST_SP_NOEXCEPT {
return px == r.px && pn == r.pn;
}
boost::detail::shared_count _internal_count() const BOOST_SP_NOEXCEPT {
return pn;
}
// Tasteless as this may seem, making all members public allows member
// templates to work in the absence of member template friends. (Matthew
// Langston)
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
private:
template <class Y> friend class shared_ptr;
template <class Y> friend class weak_ptr;
#endif
element_type *px; // contained pointer
boost::detail::shared_count pn; // reference counter
}; // shared_ptr
template <class T, class U>
inline bool operator==(shared_ptr<T> const &a,
shared_ptr<U> const &b) BOOST_SP_NOEXCEPT {
return a.get() == b.get();
}
template <class T, class U>
inline bool operator!=(shared_ptr<T> const &a,
shared_ptr<U> const &b) BOOST_SP_NOEXCEPT {
return a.get() != b.get();
}
#if __GNUC__ == 2 && __GNUC_MINOR__ <= 96
// Resolve the ambiguity between our op!= and the one in rel_ops
template <class T>
inline bool operator!=(shared_ptr<T> const &a,
shared_ptr<T> const &b) BOOST_SP_NOEXCEPT {
return a.get() != b.get();
}
#endif
#if !defined(BOOST_NO_CXX11_NULLPTR)
template <class T>
inline bool operator==(shared_ptr<T> const &p,
boost::detail::sp_nullptr_t) BOOST_SP_NOEXCEPT {
return p.get() == 0;
}
template <class T>
inline bool operator==(boost::detail::sp_nullptr_t,
shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
return p.get() == 0;
}
template <class T>
inline bool operator!=(shared_ptr<T> const &p,
boost::detail::sp_nullptr_t) BOOST_SP_NOEXCEPT {
return p.get() != 0;
}
template <class T>
inline bool operator!=(boost::detail::sp_nullptr_t,
shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
return p.get() != 0;
}
#endif
template <class T, class U>
inline bool operator<(shared_ptr<T> const &a,
shared_ptr<U> const &b) BOOST_SP_NOEXCEPT {
return a.owner_before(b);
}
template <class T>
inline void swap(shared_ptr<T> &a, shared_ptr<T> &b) BOOST_SP_NOEXCEPT {
a.swap(b);
}
template <class T, class U>
shared_ptr<T> static_pointer_cast(shared_ptr<U> const &r) BOOST_SP_NOEXCEPT {
(void)static_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = static_cast<E *>(r.get());
return shared_ptr<T>(r, p);
}
template <class T, class U>
shared_ptr<T> const_pointer_cast(shared_ptr<U> const &r) BOOST_SP_NOEXCEPT {
(void)const_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = const_cast<E *>(r.get());
return shared_ptr<T>(r, p);
}
template <class T, class U>
shared_ptr<T> dynamic_pointer_cast(shared_ptr<U> const &r) BOOST_SP_NOEXCEPT {
(void)dynamic_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = dynamic_cast<E *>(r.get());
return p ? shared_ptr<T>(r, p) : shared_ptr<T>();
}
template <class T, class U>
shared_ptr<T>
reinterpret_pointer_cast(shared_ptr<U> const &r) BOOST_SP_NOEXCEPT {
(void)reinterpret_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = reinterpret_cast<E *>(r.get());
return shared_ptr<T>(r, p);
}
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template <class T, class U>
shared_ptr<T> static_pointer_cast(shared_ptr<U> &&r) BOOST_SP_NOEXCEPT {
(void)static_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = static_cast<E *>(r.get());
return shared_ptr<T>(std::move(r), p);
}
template <class T, class U>
shared_ptr<T> const_pointer_cast(shared_ptr<U> &&r) BOOST_SP_NOEXCEPT {
(void)const_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = const_cast<E *>(r.get());
return shared_ptr<T>(std::move(r), p);
}
template <class T, class U>
shared_ptr<T> dynamic_pointer_cast(shared_ptr<U> &&r) BOOST_SP_NOEXCEPT {
(void)dynamic_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = dynamic_cast<E *>(r.get());
return p ? shared_ptr<T>(std::move(r), p) : shared_ptr<T>();
}
template <class T, class U>
shared_ptr<T> reinterpret_pointer_cast(shared_ptr<U> &&r) BOOST_SP_NOEXCEPT {
(void)reinterpret_cast<T *>(static_cast<U *>(0));
typedef typename shared_ptr<T>::element_type E;
E *p = reinterpret_cast<E *>(r.get());
return shared_ptr<T>(std::move(r), p);
}
#endif // !defined( BOOST_NO_CXX11_RVALUE_REFERENCES )
// get_pointer() enables boost::mem_fn to recognize shared_ptr
template <class T>
inline typename shared_ptr<T>::element_type *
get_pointer(shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
return p.get();
}
// operator<<
#if !defined(BOOST_NO_IOSTREAM)
#if defined(BOOST_NO_TEMPLATED_IOSTREAMS) || \
(defined(__GNUC__) && (__GNUC__ < 3))
template <class Y>
std::ostream &operator<<(std::ostream &os, shared_ptr<Y> const &p) {
os << p.get();
return os;
}
#else
// in STLport's no-iostreams mode no iostream symbols can be used
#ifndef _STLP_NO_IOSTREAMS
#if defined(BOOST_MSVC) && \
BOOST_WORKAROUND(BOOST_MSVC, < 1300 && __SGI_STL_PORT)
// MSVC6 has problems finding std::basic_ostream through the using declaration
// in namespace _STL
using std::basic_ostream;
template <class E, class T, class Y>
basic_ostream<E, T> &operator<<(basic_ostream<E, T> &os, shared_ptr<Y> const &p)
#else
template <class E, class T, class Y>
std::basic_ostream<E, T> &operator<<(std::basic_ostream<E, T> &os,
shared_ptr<Y> const &p)
#endif
{
os << p.get();
return os;
}
#endif // _STLP_NO_IOSTREAMS
#endif // __GNUC__ < 3
#endif // !defined(BOOST_NO_IOSTREAM)
// get_deleter
namespace detail {
template <class D, class T>
D *basic_get_deleter(shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
return static_cast<D *>(p._internal_get_deleter(BOOST_SP_TYPEID_(D)));
}
template <class D, class T>
D *basic_get_local_deleter(D *, shared_ptr<T> const &p) BOOST_SP_NOEXCEPT;
template <class D, class T>
D const *basic_get_local_deleter(D const *,
shared_ptr<T> const &p) BOOST_SP_NOEXCEPT;
class esft2_deleter_wrapper {
private:
shared_ptr<void const volatile> deleter_;
public:
esft2_deleter_wrapper() BOOST_SP_NOEXCEPT {}
template <class T>
void set_deleter(shared_ptr<T> const &deleter) BOOST_SP_NOEXCEPT {
deleter_ = deleter;
}
template <typename D> D *get_deleter() const BOOST_SP_NOEXCEPT {
return boost::detail::basic_get_deleter<D>(deleter_);
}
template <class T> void operator()(T *) BOOST_SP_NOEXCEPT_WITH_ASSERT {
BOOST_ASSERT(deleter_.use_count() <= 1);
deleter_.reset();
}
};
} // namespace detail
template <class D, class T>
D *get_deleter(shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
D *d = boost::detail::basic_get_deleter<D>(p);
if (d == 0) {
d = boost::detail::basic_get_local_deleter(d, p);
}
if (d == 0) {
boost::detail::esft2_deleter_wrapper *del_wrapper =
boost::detail::basic_get_deleter<boost::detail::esft2_deleter_wrapper>(
p);
// The following get_deleter method call is fully qualified because
// older versions of gcc (2.95, 3.2.3) fail to compile it when written
// del_wrapper->get_deleter<D>()
if (del_wrapper)
d = del_wrapper->::boost::detail::esft2_deleter_wrapper::get_deleter<D>();
}
return d;
}
// atomic access
#if !defined(BOOST_SP_NO_ATOMIC_ACCESS)
template <class T>
inline bool atomic_is_lock_free(shared_ptr<T> const * /*p*/) BOOST_SP_NOEXCEPT {
return false;
}
template <class T>
shared_ptr<T> atomic_load(shared_ptr<T> const *p) BOOST_SP_NOEXCEPT {
boost::detail::spinlock_pool<2>::scoped_lock lock(p);
return *p;
}
template <class T, class M>
inline shared_ptr<T>
atomic_load_explicit(shared_ptr<T> const *p,
/*memory_order mo*/ M) BOOST_SP_NOEXCEPT {
return atomic_load(p);
}
template <class T>
void atomic_store(shared_ptr<T> *p, shared_ptr<T> r) BOOST_SP_NOEXCEPT {
boost::detail::spinlock_pool<2>::scoped_lock lock(p);
p->swap(r);
}
template <class T, class M>
inline void atomic_store_explicit(shared_ptr<T> *p, shared_ptr<T> r,
/*memory_order mo*/ M) BOOST_SP_NOEXCEPT {
atomic_store(p, r); // std::move( r )
}
template <class T>
shared_ptr<T> atomic_exchange(shared_ptr<T> *p,
shared_ptr<T> r) BOOST_SP_NOEXCEPT {
boost::detail::spinlock &sp =
boost::detail::spinlock_pool<2>::spinlock_for(p);
sp.lock();
p->swap(r);
sp.unlock();
return r; // return std::move( r )
}
template <class T, class M>
shared_ptr<T> inline atomic_exchange_explicit(shared_ptr<T> *p, shared_ptr<T> r,
/*memory_order mo*/ M)
BOOST_SP_NOEXCEPT {
return atomic_exchange(p, r); // std::move( r )
}
template <class T>
bool atomic_compare_exchange(shared_ptr<T> *p, shared_ptr<T> *v,
shared_ptr<T> w) BOOST_SP_NOEXCEPT {
boost::detail::spinlock &sp =
boost::detail::spinlock_pool<2>::spinlock_for(p);
sp.lock();
if (p->_internal_equiv(*v)) {
p->swap(w);
sp.unlock();
return true;
} else {
shared_ptr<T> tmp(*p);
sp.unlock();
tmp.swap(*v);
return false;
}
}
template <class T, class M>
inline bool
atomic_compare_exchange_explicit(shared_ptr<T> *p, shared_ptr<T> *v,
shared_ptr<T> w, /*memory_order success*/ M,
/*memory_order failure*/ M) BOOST_SP_NOEXCEPT {
return atomic_compare_exchange(p, v, w); // std::move( w )
}
#endif // !defined(BOOST_SP_NO_ATOMIC_ACCESS)
// hash_value
template <class T> struct hash;
template <class T>
std::size_t hash_value(boost::shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
return boost::hash<typename boost::shared_ptr<T>::element_type *>()(p.get());
}
} // namespace boost
#include <boost/smart_ptr/detail/local_sp_deleter.hpp>
namespace boost {
namespace detail {
template <class D, class T>
D *basic_get_local_deleter(D *, shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
return static_cast<D *>(
p._internal_get_local_deleter(BOOST_SP_TYPEID_(local_sp_deleter<D>)));
}
template <class D, class T>
D const *basic_get_local_deleter(D const *,
shared_ptr<T> const &p) BOOST_SP_NOEXCEPT {
return static_cast<D *>(
p._internal_get_local_deleter(BOOST_SP_TYPEID_(local_sp_deleter<D>)));
}
} // namespace detail
} // namespace boost
#if defined(BOOST_SP_DISABLE_DEPRECATED)
#pragma GCC diagnostic pop
#endif
#endif // #ifndef BOOST_SMART_PTR_SHARED_PTR_HPP_INCLUDED
| 26.457371 | 80 | 0.670437 | [
"object"
] |
d6d12e7e1a4f518c9d96e4ebb6bfdfc32f139960 | 3,254 | cpp | C++ | Steamhammer/Source/ProductionGoal.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | 10 | 2017-07-06T18:47:02.000Z | 2019-03-22T04:49:41.000Z | Steamhammer/Source/ProductionGoal.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | null | null | null | Steamhammer/Source/ProductionGoal.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | 6 | 2017-09-05T14:40:19.000Z | 2018-11-01T08:00:53.000Z | #include "ProductionGoal.h"
#include "BuildingManager.h"
#include "The.h"
using namespace UAlbertaBot;
// An upgrade or research goal may already be done.
bool ProductionGoal::alreadyAchieved() const
{
if (act.isTech())
{
return
BWAPI::Broodwar->self()->hasResearched(act.getTechType()) ||
BWAPI::Broodwar->self()->isResearching(act.getTechType());
}
if (act.isUpgrade())
{
int level = BWAPI::Broodwar->self()->getUpgradeLevel(act.getUpgradeType());
int max = BWAPI::Broodwar->self()->getMaxUpgradeLevel(act.getUpgradeType());
return
level >= max ||
level == max - 1 && BWAPI::Broodwar->self()->isUpgrading(act.getUpgradeType());
}
return false;
}
bool ProductionGoal::failure() const
{
// The goal fails if no possible unit could become its parent,
// including buildings not yet started by BuildingManager.
return
alreadyAchieved() ||
!act.hasEventualProducer() && !BuildingManager::Instance().isBeingBuilt(act.whatBuilds());
}
ProductionGoal::ProductionGoal(const MacroAct & macroAct)
: parent(nullptr)
, attempted(false)
, act(macroAct)
{
UAB_ASSERT(act.isAddon() || act.isUpgrade() || act.isTech(), "unsupported goal");
//BWAPI::Broodwar->printf("create goal %s", act.getName().c_str());
}
// Meant to be called once per frame to try to carry out the goal.
void ProductionGoal::update()
{
// Clear any former parent that is lost.
if (parent && !parent->exists())
{
parent = nullptr;
attempted = false;
}
// Add a parent if necessary and possible.
if (!parent)
{
std::vector<BWAPI::Unit> producers;
act.getCandidateProducers(producers);
if (!producers.empty())
{
parent = *producers.begin(); // we don't care which one
//BWAPI::Broodwar->printf("%s has parent %s of %d",
// act.getName().c_str(), UnitTypeName(parent).c_str(), producers.size());
}
}
// Achieve the goal if possible.
if (parent && act.canProduce(parent))
{
//BWAPI::Broodwar->printf("attempt goal %s", act.getName().c_str());
attempted = true;
act.produce(parent);
}
}
// Meant to be called once per frame to see if the goal is completed and can be dropped.
bool ProductionGoal::done()
{
// TODO this check is approximate
bool done = parent && (parent->getAddon() || parent->isUpgrading() || parent->isResearching());
if (done)
{
if (attempted)
{
//BWAPI::Broodwar->printf("completed goal %s", act.getName().c_str());
}
else
{
// The goal was "completed" but not attempted. That means it hit a race condition:
// It took the same parent as another goal which was attempted and succeeded.
// The goal went bad and has to be retried with a new parent.
//BWAPI::Broodwar->printf("retry goal %s", act.getName().c_str());
parent = nullptr;
done = false;
}
}
// No need to check every frame whether the goal has failed.
else if (BWAPI::Broodwar->getFrameCount() % 32 == 22 && failure())
{
//BWAPI::Broodwar->printf("failed goal %s", act.getName().c_str());
done = true;
}
return done;
}
| 29.053571 | 99 | 0.622004 | [
"vector"
] |
d6d678b26b9426a3685dd077159cc1903474fb2e | 3,146 | cpp | C++ | NinjaVsZombie/POC - C++/source/TestTileEngineState.cpp | Cabrra/SPG-Project | 7602de287b750c882f9fe9e2bc57e0492d36a76f | [
"MIT"
] | null | null | null | NinjaVsZombie/POC - C++/source/TestTileEngineState.cpp | Cabrra/SPG-Project | 7602de287b750c882f9fe9e2bc57e0492d36a76f | [
"MIT"
] | null | null | null | NinjaVsZombie/POC - C++/source/TestTileEngineState.cpp | Cabrra/SPG-Project | 7602de287b750c882f9fe9e2bc57e0492d36a76f | [
"MIT"
] | null | null | null | ///Used to test the tile engine
#include "TestTileEngineState.h"
#include "../SGD Wrappers/SGD_AudioManager.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include "../SGD Wrappers/SGD_InputManager.h"
#include <cassert>
#include "MainMenuState.h"
#include "LevelManager.h"
#include "Map.h"
#include "TileSet.h"
#include "Game.h"
/**************************************************************/
// GetInstance
// - store the ONLY instance in global memory
// - return the only instance by pointer
/*static*/ TestTileEngineState* TestTileEngineState::GetInstance(void)
{
static TestTileEngineState s_Instance;
return &s_Instance;
}
/*virtual*/ void TestTileEngineState::Enter(void)
{
manager = new LevelManager();
if (manager->LoadFile("resource/XML/testfile.xml") == false)
manager->SaveFile();
//use when checking for load
//assert(manager->LoadFile("testfile.xml") != false
//&& "Level Failed To Load!!!");
}
/**************************************************************/
// Exit
// - deallocate / unload resources
/*virtual*/ void TestTileEngineState::Exit(void)
{
delete manager;
manager = nullptr;
}
/**************************************************************/
// Input
// - handle user input
/*virtual*/ bool TestTileEngineState::Input(void)
{
SGD::InputManager* pInput = SGD::InputManager::GetInstance();
if (pInput->IsKeyPressed(SGD::Key::Escape) == true)
{
Game::GetInstance()->ChangeState(MainMenuState::GetInstance());
}
if (pInput->IsKeyPressed(SGD::Key::UpArrow) == true)
{
}
if (pInput->IsKeyPressed(SGD::Key::DownArrow) == true)
{
}
if (pInput->IsKeyPressed(SGD::Key::LeftArrow) == true)
{
Game::GetInstance()->SetWorldSpace({ Game::GetInstance()->GetWorldSpace().x + Game::GetInstance()->GetScreenWidth(),
Game::GetInstance()->GetWorldSpace().y });
Game::GetInstance()->SetWorldCamera({ { Game::GetInstance()->GetWorldCamera().left - Game::GetInstance()->GetScreenWidth(),
Game::GetInstance()->GetWorldCamera().top }, SGD::Size{ Game::GetInstance()->GetScreenWidth(), Game::GetInstance()->GetScreenHeight() } });
}
if (pInput->IsKeyPressed(SGD::Key::RightArrow) == true)
{
Game::GetInstance()->SetWorldSpace({ Game::GetInstance()->GetWorldSpace().x - Game::GetInstance()->GetScreenWidth(),
Game::GetInstance()->GetWorldSpace().y });
Game::GetInstance()->SetWorldCamera({ { Game::GetInstance()->GetWorldCamera().left + Game::GetInstance()->GetScreenWidth(),
Game::GetInstance()->GetWorldCamera().top }, SGD::Size{ Game::GetInstance()->GetScreenWidth(), Game::GetInstance()->GetScreenHeight() } });
}
return true;
}
/**************************************************************/
// Update
// - update entities / animations
/*virtual*/ void TestTileEngineState::Update(float elapsedTime)
{
manager->GetMap()->Update(elapsedTime);
}
/**************************************************************/
// Render
// - render entities / menu options
/*virtual*/ void TestTileEngineState::Render(void)
{
//SGD::GraphicsManager::GetInstance()->DrawString("HEY MAN", SGD::Point(200, 200), SGD::Color(255, 255, 255));
manager->GetMap()->Render();
} | 29.961905 | 142 | 0.625874 | [
"render"
] |
d6de2a74ec4f2526e4c2496c76643d79166c2977 | 21,707 | cc | C++ | ui/display/win/scaling_util_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ui/display/win/scaling_util_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ui/display/win/scaling_util_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 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 "ui/display/win/scaling_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/display/win/test/screen_util_win.h"
#include "ui/gfx/geometry/rect.h"
namespace display {
namespace win {
namespace test {
namespace {
const wchar_t kFakeDisplayName[] = L"Fake Display";
DisplayInfo CreateDisplayInfo(int x, int y, int width, int height,
float scale_factor) {
MONITORINFOEX monitor_info = CreateMonitorInfo(gfx::Rect(x, y, width, height),
gfx::Rect(x, y, width, height),
kFakeDisplayName);
return DisplayInfo(monitor_info, scale_factor, 1.0f);
}
::testing::AssertionResult AssertOffsetsEqual(
const char* lhs_expr,
const char* rhs_expr,
const DisplayPlacement& lhs,
const DisplayPlacement& rhs) {
if (lhs.position == rhs.position &&
lhs.offset == rhs.offset &&
lhs.offset_reference == rhs.offset_reference) {
return ::testing::AssertionSuccess();
}
return ::testing::AssertionFailure() <<
"Value of: " << rhs_expr << "\n Actual: " << rhs.ToString() <<
"\nExpected: " << lhs_expr << "\nWhich is: " << lhs.ToString();
}
#define EXPECT_OFFSET_EQ(a, b) \
EXPECT_PRED_FORMAT2(AssertOffsetsEqual, a, b);
TEST(ScalingUtilTest, DisplayInfosTouchBottom) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(1, 2, 1, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(0, 2, 2, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(1, 2, 2, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(2, 2, 2, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(3, 2, 2, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchLeft) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(0, 1, 1, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(0, 0, 1, 2, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(0, 1, 1, 2, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(0, 2, 1, 2, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(0, 3, 1, 2, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchTop) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(1, 0, 1, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(0, 0, 2, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(1, 0, 2, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(2, 0, 2, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 3, 1, 1.0f),
CreateDisplayInfo(3, 0, 2, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchRight) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(2, 1, 1, 1, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(2, 0, 1, 2, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(2, 1, 1, 2, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(2, 2, 1, 2, 1.0f)));
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 3, 1.0f),
CreateDisplayInfo(2, 3, 1, 2, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchBottomRightCorner) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(2, 2, 1, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchBottomLeftCorner) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(0, 2, 1, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchUpperLeftCorner) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(0, 0, 1, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchUpperRightCorner) {
EXPECT_TRUE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(2, 0, 1, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchNone) {
EXPECT_FALSE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(3, 1, 1, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchNoneShareXAxis) {
EXPECT_FALSE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(5, 2, 1, 1, 1.0f)));
EXPECT_FALSE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(-2, 1, 1, 1, 1.0f)));
}
TEST(ScalingUtilTest, DisplayInfosTouchNoneShareYAxis) {
EXPECT_FALSE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(2, 3, 1, 1, 1.0f)));
EXPECT_FALSE(DisplayInfosTouch(CreateDisplayInfo(1, 1, 1, 1, 1.0f),
CreateDisplayInfo(0, -1, 1, 1, 1.0f)));
}
TEST(ScalingUtilTest, CalculateDisplayPlacementNoScaleRight) {
// Top edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT, 0, DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(800, 0, 1024, 768, 1.0f)));
// Bottom edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
0,
DisplayPlacement::BOTTOM_RIGHT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(800, -168, 1024, 768, 1.0f)));
// Offset to the top
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
-10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(800, -10, 1024, 768, 1.0f)));
// Offset to the bottom.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(800, 10, 1024, 768, 1.0f)));
}
TEST(ScalingUtilTest, CalculateDisplayPlacementNoScaleLeft) {
// Top edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-1024, 0, 1024, 768, 1.0f)));
// Bottom edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
0,
DisplayPlacement::BOTTOM_RIGHT),
CalculateDisplayPlacement(
CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-1024, -168, 1024, 768, 1.0f)));
// Offset to the top.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
-10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(
CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-1024, -10, 1024, 768, 1.0f)));
// Offset to the bottom.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-1024, 10, 1024, 768, 1.0f)));
}
TEST(ScalingUtilTest, CalculateDisplayPlacementNoScaleTop) {
// Left edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(0, -768, 1024, 768, 1.0f)));
// Right edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
0,
DisplayPlacement::BOTTOM_RIGHT),
CalculateDisplayPlacement(
CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-224, -768, 1024, 768, 1.0f)));
// Offset to the right.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(10, -768, 1024, 768, 1.0f)));
// Offset to the left.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
-10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-10, -768, 1024, 768, 1.0f)));
}
TEST(ScalingUtilTest, CalculateDisplayPlacementNoScaleBottom) {
// Left edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(0, 600, 1024, 768, 1.0f)));
// Right edge aligned.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
0,
DisplayPlacement::BOTTOM_RIGHT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-224, 600, 1024, 768, 1.0f)));
// Offset to the right
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(10, 600, 1024, 768, 1.0f)));
// Offset to the left
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
-10,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(0, 0, 800, 600, 1.0f),
CreateDisplayInfo(-10, 600, 1024, 768, 1.0f)));
}
TEST(ScalingUtilTest, CalculateDisplayPlacementNoScaleOddDimensions) {
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
5,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(35, 72, 24, 24, 1.0f),
CreateDisplayInfo(59, 77, 7, 9, 1.0f)));
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
2,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(1, 7, 30, 40, 1.0f),
CreateDisplayInfo(-701, 9, 702, 2, 1.0f)));
}
TEST(ScalingUtilTest, CalculateDisplayPlacement1_5xScale) {
// Side by side to the right.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(900, 50, 1000, 700, 1.5f)));
// Side-by-side to the left.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(-900, 50, 1000, 700, 1.5f)));
// Side-by-side to the top.
// Note that -33 would be the normal enclosing rect offset.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
-34,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(50, -650, 1000, 700, 1.5f)));
// Side-by-side on the bottom.
// Note that -33 would be the normal enclosing rect offset.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
-34,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(50, 650, 1000, 700, 1.5f)));
// Side by side to the right.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(900, 50, 1000, 700, 1.5f)));
// Side-by-side to the left.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(-900, 50, 1000, 700, 1.5f)));
// Side-by-side to the top.
// Note that -33 would be the normal enclosing rect offset.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
-34,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(50, -650, 1000, 700, 1.5f)));
// Side-by-side to the bottom.
// Note that -33 would be the normal enclosing rect offset.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
-34,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(50, 650, 1000, 700, 1.5f)));
}
TEST(ScalingUtilTest, CalculateDisplayPlacement2xScale) {
// Side by side to the right.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(900, 50, 1000, 700, 2.0f)));
// Side-by-side to the left.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(-900, 50, 1000, 700, 2.0f)));
// Side-by-side to the top.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
-25,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(50, -650, 1000, 700, 2.0f)));
// Side-by-side on the bottom.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
-25,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 1.0f),
CreateDisplayInfo(50, 650, 1000, 700, 2.0f)));
// Side by side to the right.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::RIGHT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(900, 50, 1000, 700, 2.0f)));
// Side-by-side to the left.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::LEFT,
0,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(-900, 50, 1000, 700, 2.0f)));
// Side-by-side to the top.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::TOP,
-25,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(50, -650, 1000, 700, 2.0f)));
// Side-by-side to the bottom.
EXPECT_OFFSET_EQ(
DisplayPlacement(DisplayPlacement::BOTTOM,
-25,
DisplayPlacement::TOP_LEFT),
CalculateDisplayPlacement(CreateDisplayInfo(100, 50, 800, 600, 2.0f),
CreateDisplayInfo(50, 650, 1000, 700, 2.0f)));
}
TEST(ScalingUtilTest, SquaredDistanceBetweenRectsFullyIntersecting) {
gfx::Rect rect1(0, 0, 100, 100);
gfx::Rect rect2(5, 5, 10, 10);
EXPECT_EQ(0, SquaredDistanceBetweenRects(rect1, rect2));
EXPECT_EQ(0, SquaredDistanceBetweenRects(rect2, rect1));
}
TEST(ScalingUtilTest, SquaredDistanceBetweenRectsPartiallyIntersecting) {
gfx::Rect rect1(0, 0, 10, 10);
gfx::Rect rect2(5, 5, 10, 10);
EXPECT_EQ(0, SquaredDistanceBetweenRects(rect1, rect2));
EXPECT_EQ(0, SquaredDistanceBetweenRects(rect2, rect1));
}
TEST(ScalingUtilTest, SquaredDistanceBetweenRectsTouching) {
gfx::Rect ref(2, 2, 2, 2);
gfx::Rect top_left(0, 0, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, top_left));
EXPECT_EQ(0, SquaredDistanceBetweenRects(top_left, ref));
gfx::Rect top_left_partial_top(1, 0, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, top_left_partial_top));
EXPECT_EQ(0, SquaredDistanceBetweenRects(top_left_partial_top, ref));
gfx::Rect top(2, 0, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, top));
EXPECT_EQ(0, SquaredDistanceBetweenRects(top, ref));
gfx::Rect top_right_partial_top(3, 0, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, top_right_partial_top));
EXPECT_EQ(0, SquaredDistanceBetweenRects(top_right_partial_top, ref));
gfx::Rect top_right(4, 0, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, top_right));
EXPECT_EQ(0, SquaredDistanceBetweenRects(top_right, ref));
gfx::Rect top_left_partial_left(0, 1, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, top_left_partial_left));
EXPECT_EQ(0, SquaredDistanceBetweenRects(top_left_partial_left, ref));
gfx::Rect left(0, 2, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, left));
EXPECT_EQ(0, SquaredDistanceBetweenRects(left, ref));
gfx::Rect bottom_left_partial(0, 3, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, bottom_left_partial));
EXPECT_EQ(0, SquaredDistanceBetweenRects(bottom_left_partial, ref));
gfx::Rect bottom_left(0, 4, 2, 2);
EXPECT_EQ(0, SquaredDistanceBetweenRects(ref, bottom_left));
EXPECT_EQ(0, SquaredDistanceBetweenRects(bottom_left, ref));
}
TEST(ScalingUtilTest, SquaredDistanceBetweenRectsOverlapping) {
gfx::Rect ref(5, 5, 2, 2);
gfx::Rect top_left_partial_top(4, 0, 2, 2);
EXPECT_EQ(9, SquaredDistanceBetweenRects(ref, top_left_partial_top));
EXPECT_EQ(9, SquaredDistanceBetweenRects(top_left_partial_top, ref));
gfx::Rect top(5, 0, 2, 2);
EXPECT_EQ(9, SquaredDistanceBetweenRects(ref, top));
EXPECT_EQ(9, SquaredDistanceBetweenRects(top, ref));
gfx::Rect top_right_partial(6, 0, 2, 2);
EXPECT_EQ(9, SquaredDistanceBetweenRects(ref, top_right_partial));
EXPECT_EQ(9, SquaredDistanceBetweenRects(top_right_partial, ref));
gfx::Rect top_left_partial_left(0, 4, 2, 2);
EXPECT_EQ(9, SquaredDistanceBetweenRects(ref, top_left_partial_left));
EXPECT_EQ(9, SquaredDistanceBetweenRects(top_left_partial_left, ref));
gfx::Rect left(0, 5, 2, 2);
EXPECT_EQ(9, SquaredDistanceBetweenRects(ref, left));
EXPECT_EQ(9, SquaredDistanceBetweenRects(left, ref));
gfx::Rect bottom_left_partial(0, 6, 2, 2);
EXPECT_EQ(9, SquaredDistanceBetweenRects(ref, bottom_left_partial));
EXPECT_EQ(9, SquaredDistanceBetweenRects(bottom_left_partial, ref));
}
TEST(ScalingUtilTest, SquaredDistanceBetweenRectsDiagonals) {
gfx::Rect ref(5, 5, 2, 2);
gfx::Rect top_left(0, 0, 2, 2);
EXPECT_EQ(18, SquaredDistanceBetweenRects(ref, top_left));
EXPECT_EQ(18, SquaredDistanceBetweenRects(top_left, ref));
gfx::Rect top_right(10, 0, 2, 2);
EXPECT_EQ(18, SquaredDistanceBetweenRects(ref, top_right));
EXPECT_EQ(18, SquaredDistanceBetweenRects(top_right, ref));
}
} // namespace
} // namespace test
} // namespace win
} // namespace display
| 42.067829 | 80 | 0.610448 | [
"geometry"
] |
d6e5fb2c577d049ad9d6d3eaec0b03fd5260cd04 | 33,150 | cpp | C++ | src/cless/rsolvers/roe_cl.cpp | roarkhabegger/athena-public-version | 3446d2f4601c1dbbfd7a98d4f53335d97e21e195 | [
"BSD-3-Clause"
] | 1 | 2021-03-05T20:59:04.000Z | 2021-03-05T20:59:04.000Z | src/cless/rsolvers/roe_cl.cpp | roarkhabegger/athena-public-version | 3446d2f4601c1dbbfd7a98d4f53335d97e21e195 | [
"BSD-3-Clause"
] | null | null | null | src/cless/rsolvers/roe_cl.cpp | roarkhabegger/athena-public-version | 3446d2f4601c1dbbfd7a98d4f53335d97e21e195 | [
"BSD-3-Clause"
] | 2 | 2019-02-26T18:49:13.000Z | 2019-07-22T17:04:41.000Z | //========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file roe_cl.cpp
// \brief Roe's linearized Riemann solver for the collisionless system.
//
// Computes 1D fluxes using Roe's linearization. When Roe's method fails because of
// negative density or pressure in the intermediate states, HLLE fluxes are used instead.
//
// REFERENCES:
// - P. Roe, "Approximate Riemann solvers, parameter vectors, and difference schemes",
// JCP, 43, 357 (1981).
// C/C++ headers
#include <algorithm> // max()
#include <cmath> // sqrt()
// Athena++ headers
#include "../cless.hpp"
#include "../../athena.hpp"
#include "../../athena_arrays.hpp"
#include "../../eos/eos.hpp"
// prototype for function to compute eigenvalues and eigenvectors of Roe's matrix A
inline void RoeEigensystemCL(const Real wroe[], Real eigenvalues[],
Real right_eigenmatrix[][(NWAVECL)], Real left_eigenmatrix[][(NWAVECL)]);
// set to 1 to test intermediate states
#define TEST_INTERMEDIATE_STATES 1
//----------------------------------------------------------------------------------------
//! \func
void Cless::RiemannSolverCL(const int kl, const int ku, const int jl, const int ju,
const int il, const int iu, const int ivx, const int ip12,
AthenaArray<Real> &wl, AthenaArray<Real> &wr, AthenaArray<Real> &flx) {
// get proper directional dependence
int ivy = IVX + ((ivx -IVX )+1)%3;
int ivz = IVX + ((ivx -IVX )+2)%3;
// diagnol comp
int ip11 = IP11 + ((ivx -IVX ) )%3;
int ip22 = IP11 + ((ivx -IVX )+1)%3;
int ip33 = IP11 + ((ivx -IVX )+2)%3;
// off-diag comp
int ip13 = IP12 + ((ip12-IP12)+1)%3;
int ip23 = IP12 + ((ip12-IP12)+2)%3;
Real wli[NWAVECL],wri[NWAVECL];
Real wroe[NWAVECL],fl[NWAVECL],fr[NWAVECL],flxi[NWAVECL];
Real coeff[NWAVECL];
Real ev[NWAVECL],rem[NWAVECL][NWAVECL],lem[NWAVECL][NWAVECL];
Real du[NWAVECL],a[NWAVECL],u[NWAVECL];
for (int k=kl; k<=ku; ++k) {
for (int j=jl; j<=ju; ++j) {
#pragma omg simd
for (int i=il; i<=iu; ++i) {
//--- Step 1. Load L/R states into local variables
wli[IDN ]=wl(IDN ,k,j,i);
wli[IVX ]=wl(ivx ,k,j,i);
wli[IVY ]=wl(ivy ,k,j,i);
wli[IVZ ]=wl(ivz ,k,j,i);
wli[IP11]=wl(ip11,k,j,i);
wli[IP22]=wl(ip22,k,j,i);
wli[IP33]=wl(ip33,k,j,i);
wli[IP12]=wl(ip12,k,j,i);
wli[IP13]=wl(ip13,k,j,i);
wli[IP23]=wl(ip23,k,j,i);
wri[IDN ]=wr(IDN ,k,j,i);
wri[IVX ]=wr(ivx ,k,j,i);
wri[IVY ]=wr(ivy ,k,j,i);
wri[IVZ ]=wr(ivz ,k,j,i);
wri[IP11]=wr(ip11,k,j,i);
wri[IP22]=wr(ip22,k,j,i);
wri[IP33]=wr(ip33,k,j,i);
wri[IP12]=wr(ip12,k,j,i);
wri[IP13]=wr(ip13,k,j,i);
wri[IP23]=wr(ip23,k,j,i);
// get some necessary conserved variables
Real e11l = wli[IP11] + wli[IDN]*wli[IVX]*wli[IVX];
Real e11r = wri[IP11] + wri[IDN]*wri[IVX]*wri[IVX];
Real e22l = wli[IP22] + wli[IDN]*wli[IVY]*wli[IVY];
Real e22r = wri[IP22] + wri[IDN]*wri[IVY]*wri[IVY];
Real e33l = wli[IP33] + wli[IDN]*wli[IVZ]*wli[IVZ];
Real e33r = wri[IP33] + wri[IDN]*wri[IVZ]*wri[IVZ];
Real e12l = wli[IP12] + wli[IDN]*wli[IVX]*wli[IVY];
Real e12r = wri[IP12] + wri[IDN]*wri[IVX]*wri[IVY];
Real e13l = wli[IP13] + wli[IDN]*wli[IVX]*wli[IVZ];
Real e13r = wri[IP13] + wri[IDN]*wri[IVX]*wri[IVZ];
Real e23l = wli[IP23] + wli[IDN]*wli[IVY]*wli[IVZ];
Real e23r = wri[IP23] + wri[IDN]*wri[IVY]*wri[IVZ];
//--- Step 2. Compute Roe-averaged data from left- and right-states
Real sqrtdl = std::sqrt(wli[IDN]);
Real sqrtdr = std::sqrt(wri[IDN]);
Real isqrtdl = 1.0/sqrtdl;
Real isqrtdr = 1.0/sqrtdr;
Real isdlpdr = 1.0/(sqrtdl + sqrtdr);
Real isdlpdrSQR = SQR(isdlpdr);
// Stress tensor components are Sij = Pij/d, so Sij sqrt(d) = Pij/sqrt(d)
// c.f. Eqn. 6.21 of Brown (1996) PhD thesis
wroe[IDN ] = sqrtdl*sqrtdr;
wroe[IVX ] = ( sqrtdl*wli[IVX ] + sqrtdr*wri[IVX ])*isdlpdr;
wroe[IVY ] = ( sqrtdl*wli[IVY ] + sqrtdr*wri[IVY ])*isdlpdr;
wroe[IVZ ] = ( sqrtdl*wli[IVZ ] + sqrtdr*wri[IVZ ])*isdlpdr;
wroe[IP11] = (isqrtdl*wli[IP11] + isqrtdr*wri[IP11])*isdlpdr;
wroe[IP22] = (isqrtdl*wli[IP22] + isqrtdr*wri[IP22])*isdlpdr;
wroe[IP33] = (isqrtdl*wli[IP33] + isqrtdr*wri[IP33])*isdlpdr;
wroe[IP12] = (isqrtdl*wli[IP12] + isqrtdr*wri[IP12])*isdlpdr;
wroe[IP13] = (isqrtdl*wli[IP13] + isqrtdr*wri[IP13])*isdlpdr;
wroe[IP23] = (isqrtdl*wli[IP23] + isqrtdr*wri[IP23])*isdlpdr;
// add ui uj terms of Brown (1996) to Sij, this is necessary b/c the system
// is solved in terms of the 'specific enthalpy Hij = 3 Sij + ui uj, but written
// in terms of Sij
wroe[IP11]+=ONE_3RD*sqrtdl*sqrtdr*(wri[IVX]-wli[IVX])*(wri[IVX]-wli[IVX])*isdlpdrSQR;
wroe[IP22]+=ONE_3RD*sqrtdl*sqrtdr*(wri[IVY]-wli[IVY])*(wri[IVY]-wli[IVY])*isdlpdrSQR;
wroe[IP33]+=ONE_3RD*sqrtdl*sqrtdr*(wri[IVZ]-wli[IVZ])*(wri[IVZ]-wli[IVZ])*isdlpdrSQR;
wroe[IP12]+=ONE_3RD*sqrtdl*sqrtdr*(wri[IVX]-wli[IVX])*(wri[IVY]-wli[IVY])*isdlpdrSQR;
wroe[IP13]+=ONE_3RD*sqrtdl*sqrtdr*(wri[IVX]-wli[IVX])*(wri[IVZ]-wli[IVZ])*isdlpdrSQR;
wroe[IP23]+=ONE_3RD*sqrtdl*sqrtdr*(wri[IVY]-wli[IVY])*(wri[IVZ]-wli[IVZ])*isdlpdrSQR;
//--- Step 3. Compute eigenvalues and eigenmatrices using Roe-averaged values
RoeEigensystemCL(wroe,ev,rem,lem);
//--- Step 4. Compute L/R fluxes
Real vxl = wli[IVX];
Real vxr = wri[IVX];
fl[IDN ] = wli[IDN]*vxl;
fr[IDN ] = wri[IDN]*vxr;
fl[IVX ] = wli[IDN]*wli[IVX]*vxl + wli[IP11];
fr[IVX ] = wri[IDN]*wri[IVX]*vxr + wri[IP11];
fl[IVY ] = wli[IDN]*wli[IVY]*vxl + wli[IP12];
fr[IVY ] = wri[IDN]*wri[IVY]*vxr + wri[IP12];
fl[IVZ ] = wli[IDN]*wli[IVZ]*vxl + wli[IP13];
fr[IVZ ] = wri[IDN]*wri[IVZ]*vxr + wri[IP13];
fl[IP11] = e11l*vxl + 2.0*wli[IP11]*wli[IVX];
fr[IP11] = e11r*vxr + 2.0*wri[IP11]*wri[IVX];
fl[IP22] = e22l*vxl + 2.0*wli[IP12]*wli[IVY];
fr[IP22] = e22r*vxr + 2.0*wri[IP12]*wri[IVY];
fl[IP33] = e33l*vxl + 2.0*wli[IP13]*wli[IVZ];
fr[IP33] = e33r*vxr + 2.0*wri[IP13]*wri[IVZ];
fl[IP12] = e12l*vxl + ( wli[IP12]*wli[IVX] + wli[IP11]*wli[IVY] );
fr[IP12] = e12r*vxr + ( wri[IP12]*wri[IVX] + wri[IP11]*wri[IVY] );
fl[IP13] = e13l*vxl + ( wli[IP13]*wli[IVX] + wli[IP11]*wli[IVZ] );
fr[IP13] = e13r*vxr + ( wri[IP13]*wri[IVX] + wri[IP11]*wri[IVZ] );
fl[IP23] = e23l*vxl + ( wli[IP13]*wli[IVY] + wli[IP12]*wli[IVZ] );
fr[IP23] = e23r*vxr + ( wri[IP13]*wri[IVY] + wri[IP12]*wri[IVZ] );
//--- Step 5. Compute projection of dU onto L eigenvectors ("vector A")
du[IDN ] = wri[IDN] - wli[IDN];
du[IVX ] = wri[IDN]*wri[IVX] - wli[IDN]*wli[IVX];
du[IVY ] = wri[IDN]*wri[IVY] - wli[IDN]*wli[IVY];
du[IVZ ] = wri[IDN]*wri[IVZ] - wli[IDN]*wli[IVZ];
du[IP11] = e11r - e11l;
du[IP22] = e22r - e22l;
du[IP33] = e33r - e33l;
du[IP12] = e12r - e12l;
du[IP13] = e13r - e13l;
du[IP23] = e23r - e23l;
a[IDN ] = lem[IDN ][IDN ]*du[IDN ];
a[IDN ] += lem[IDN ][IVX ]*du[IVX ];
a[IDN ] += lem[IDN ][IVY ]*du[IVY ];
a[IDN ] += lem[IDN ][IVZ ]*du[IVZ ];
a[IDN ] += lem[IDN ][IP11]*du[IP11];
a[IDN ] += lem[IDN ][IP22]*du[IP22];
a[IDN ] += lem[IDN ][IP33]*du[IP33];
a[IDN ] += lem[IDN ][IP12]*du[IP12];
a[IDN ] += lem[IDN ][IP13]*du[IP13];
a[IDN ] += lem[IDN ][IP23]*du[IP23];
a[IVX ] = lem[IVX ][IDN ]*du[IDN ];
a[IVX ] += lem[IVX ][IVX ]*du[IVX ];
a[IVX ] += lem[IVX ][IVY ]*du[IVY ];
a[IVX ] += lem[IVX ][IVZ ]*du[IVZ ];
a[IVX ] += lem[IVX ][IP11]*du[IP11];
a[IVX ] += lem[IVX ][IP22]*du[IP22];
a[IVX ] += lem[IVX ][IP33]*du[IP33];
a[IVX ] += lem[IVX ][IP12]*du[IP12];
a[IVX ] += lem[IVX ][IP13]*du[IP13];
a[IVX ] += lem[IVX ][IP23]*du[IP23];
a[IVY ] = lem[IVY ][IDN ]*du[IDN ];
a[IVY ] += lem[IVY ][IVX ]*du[IVX ];
a[IVY ] += lem[IVY ][IVY ]*du[IVY ];
a[IVY ] += lem[IVY ][IVZ ]*du[IVZ ];
a[IVY ] += lem[IVY ][IP11]*du[IP11];
a[IVY ] += lem[IVY ][IP22]*du[IP22];
a[IVY ] += lem[IVY ][IP33]*du[IP33];
a[IVY ] += lem[IVY ][IP12]*du[IP12];
a[IVY ] += lem[IVY ][IP13]*du[IP13];
a[IVY ] += lem[IVY ][IP23]*du[IP23];
a[IVZ ] = lem[IVZ ][IDN ]*du[IDN ];
a[IVZ ] += lem[IVZ ][IVX ]*du[IVX ];
a[IVZ ] += lem[IVZ ][IVY ]*du[IVY ];
a[IVZ ] += lem[IVZ ][IVZ ]*du[IVZ ];
a[IVZ ] += lem[IVZ ][IP11]*du[IP11];
a[IVZ ] += lem[IVZ ][IP22]*du[IP22];
a[IVZ ] += lem[IVZ ][IP33]*du[IP33];
a[IVZ ] += lem[IVZ ][IP12]*du[IP12];
a[IVZ ] += lem[IVZ ][IP13]*du[IP13];
a[IVZ ] += lem[IVZ ][IP23]*du[IP23];
a[IP11] = lem[IP11][IDN ]*du[IDN ];
a[IP11] += lem[IP11][IVX ]*du[IVX ];
a[IP11] += lem[IP11][IVY ]*du[IVY ];
a[IP11] += lem[IP11][IVZ ]*du[IVZ ];
a[IP11] += lem[IP11][IP11]*du[IP11];
a[IP11] += lem[IP11][IP22]*du[IP22];
a[IP11] += lem[IP11][IP33]*du[IP33];
a[IP11] += lem[IP11][IP12]*du[IP12];
a[IP11] += lem[IP11][IP13]*du[IP13];
a[IP11] += lem[IP11][IP23]*du[IP23];
a[IP22] = lem[IP22][IDN ]*du[IDN ];
a[IP22] += lem[IP22][IVX ]*du[IVX ];
a[IP22] += lem[IP22][IVY ]*du[IVY ];
a[IP22] += lem[IP22][IVZ ]*du[IVZ ];
a[IP22] += lem[IP22][IP11]*du[IP11];
a[IP22] += lem[IP22][IP22]*du[IP22];
a[IP22] += lem[IP22][IP33]*du[IP33];
a[IP22] += lem[IP22][IP12]*du[IP12];
a[IP22] += lem[IP22][IP13]*du[IP13];
a[IP22] += lem[IP22][IP23]*du[IP23];
a[IP33] = lem[IP33][IDN ]*du[IDN ];
a[IP33] += lem[IP33][IVX ]*du[IVX ];
a[IP33] += lem[IP33][IVY ]*du[IVY ];
a[IP33] += lem[IP33][IVZ ]*du[IVZ ];
a[IP33] += lem[IP33][IP11]*du[IP11];
a[IP33] += lem[IP33][IP22]*du[IP22];
a[IP33] += lem[IP33][IP33]*du[IP33];
a[IP33] += lem[IP33][IP12]*du[IP12];
a[IP33] += lem[IP33][IP13]*du[IP13];
a[IP33] += lem[IP33][IP23]*du[IP23];
a[IP12] = lem[IP12][IDN ]*du[IDN ];
a[IP12] += lem[IP12][IVX ]*du[IVX ];
a[IP12] += lem[IP12][IVY ]*du[IVY ];
a[IP12] += lem[IP12][IVZ ]*du[IVZ ];
a[IP12] += lem[IP12][IP11]*du[IP11];
a[IP12] += lem[IP12][IP22]*du[IP22];
a[IP12] += lem[IP12][IP33]*du[IP33];
a[IP12] += lem[IP12][IP12]*du[IP12];
a[IP12] += lem[IP12][IP13]*du[IP13];
a[IP12] += lem[IP12][IP23]*du[IP23];
a[IP13] = lem[IP13][IDN ]*du[IDN ];
a[IP13] += lem[IP13][IVX ]*du[IVX ];
a[IP13] += lem[IP13][IVY ]*du[IVY ];
a[IP13] += lem[IP13][IVZ ]*du[IVZ ];
a[IP13] += lem[IP13][IP11]*du[IP11];
a[IP13] += lem[IP13][IP22]*du[IP22];
a[IP13] += lem[IP13][IP33]*du[IP33];
a[IP13] += lem[IP13][IP12]*du[IP12];
a[IP13] += lem[IP13][IP13]*du[IP13];
a[IP13] += lem[IP13][IP23]*du[IP23];
a[IP23] = lem[IP23][IDN ]*du[IDN ];
a[IP23] += lem[IP23][IVX ]*du[IVX ];
a[IP23] += lem[IP23][IVY ]*du[IVY ];
a[IP23] += lem[IP23][IVZ ]*du[IVZ ];
a[IP23] += lem[IP23][IP11]*du[IP11];
a[IP23] += lem[IP23][IP22]*du[IP22];
a[IP23] += lem[IP23][IP33]*du[IP33];
a[IP23] += lem[IP23][IP12]*du[IP12];
a[IP23] += lem[IP23][IP13]*du[IP13];
a[IP23] += lem[IP23][IP23]*du[IP23];
//--- Step 6. Check that the density and pressure in the intermediate states are
// positive. If not, set a flag that will be checked below.
int hlle_flag = 0;
if (TEST_INTERMEDIATE_STATES) {
u[IDN ] = wli[IDN];
u[IVX ] = wli[IDN]*wli[IVX];
u[IVY ] = wli[IDN]*wli[IVY];
u[IVZ ] = wli[IDN]*wli[IVZ];
u[IE11] = e11l;
u[IE22] = e22l;
u[IE33] = e33l;
u[IE12] = e12l;
u[IE13] = e13l;
u[IE23] = e23l;
// jump across wave[0]
u[IDN ] += a[0]*rem[IDN ][0];
if (u[IDN] < 0.0) hlle_flag=1;
u[IVX ] += a[0]*rem[IVX ][0];
u[IVY ] += a[0]*rem[IVY ][0];
u[IVZ ] += a[0]*rem[IVZ ][0];
u[IE11] += a[0]*rem[IP11][0];
u[IE22] += a[0]*rem[IP22][0];
u[IE33] += a[0]*rem[IP33][0];
Real p11 = u[IE11] - SQR(u[IVX])/u[IDN];
Real p22 = u[IE22] - SQR(u[IVY])/u[IDN];
Real p33 = u[IE33] - SQR(u[IVZ])/u[IDN];
if (p11 < 0.0) hlle_flag=2;
if (p22 < 0.0) hlle_flag=3;
if (p33 < 0.0) hlle_flag=4;
// jump across wave[1]
u[IDN ] += a[1]*rem[IDN ][1];
if (u[IDN] < 0.0) hlle_flag=1;
u[IVX ] += a[1]*rem[IVX ][1];
u[IVY ] += a[1]*rem[IVY ][1];
u[IVZ ] += a[1]*rem[IVZ ][1];
u[IE11] += a[1]*rem[IP11][1];
u[IE22] += a[1]*rem[IP22][1];
u[IE33] += a[1]*rem[IP33][1];
p11 = u[IE11] - SQR(u[IVX])/u[IDN];
p22 = u[IE22] - SQR(u[IVY])/u[IDN];
p33 = u[IE33] - SQR(u[IVZ])/u[IDN];
if (p11 < 0.0) hlle_flag=2;
if (p22 < 0.0) hlle_flag=3;
if (p33 < 0.0) hlle_flag=4;
// jump across wave[2]
u[IDN ] += a[2]*rem[IDN ][2];
if (u[IDN] < 0.0) hlle_flag=1;
u[IVX ] += a[2]*rem[IVX ][2];
u[IVY ] += a[2]*rem[IVY ][2];
u[IVZ ] += a[2]*rem[IVZ ][2];
u[IE11] += a[2]*rem[IP11][2];
u[IE22] += a[2]*rem[IP22][2];
u[IE33] += a[2]*rem[IP33][2];
p11 = u[IE11] - SQR(u[IVX])/u[IDN];
p22 = u[IE22] - SQR(u[IVY])/u[IDN];
p33 = u[IE33] - SQR(u[IVZ])/u[IDN];
if (p11 < 0.0) hlle_flag=2;
if (p22 < 0.0) hlle_flag=3;
if (p33 < 0.0) hlle_flag=4;
// jump across wave[3]
u[IDN ] += a[3]*rem[IDN ][3];
if (u[IDN] < 0.0) hlle_flag=1;
u[IVX ] += a[3]*rem[IVX ][3];
u[IVY ] += a[3]*rem[IVY ][3];
u[IVZ ] += a[3]*rem[IVZ ][3];
u[IE11] += a[3]*rem[IP11][3];
u[IE22] += a[3]*rem[IP22][3];
u[IE33] += a[3]*rem[IP33][3];
p11 = u[IE11] - SQR(u[IVX])/u[IDN];
p22 = u[IE22] - SQR(u[IVY])/u[IDN];
p33 = u[IE33] - SQR(u[IVZ])/u[IDN];
if (p11 < 0.0) hlle_flag=2;
if (p22 < 0.0) hlle_flag=3;
if (p33 < 0.0) hlle_flag=4;
}
//--- Step 7. Compute Roe flux
coeff[IDN ] = 0.5*fabs(ev[IDN ])*a[IDN ];
coeff[IVX ] = 0.5*fabs(ev[IVX ])*a[IVX ];
coeff[IVY ] = 0.5*fabs(ev[IVY ])*a[IVY ];
coeff[IVZ ] = 0.5*fabs(ev[IVZ ])*a[IVZ ];
coeff[IP11] = 0.5*fabs(ev[IP11])*a[IP11];
coeff[IP22] = 0.5*fabs(ev[IP22])*a[IP22];
coeff[IP33] = 0.5*fabs(ev[IP33])*a[IP33];
coeff[IP12] = 0.5*fabs(ev[IP12])*a[IP12];
coeff[IP13] = 0.5*fabs(ev[IP13])*a[IP13];
coeff[IP23] = 0.5*fabs(ev[IP23])*a[IP23];
flxi[IDN ] = 0.5*(fl[IDN] + fr[IDN]);
flxi[IDN ] -= rem[IDN ][IDN ]*coeff[IDN ];
flxi[IDN ] -= rem[IDN ][IVX ]*coeff[IVX ];
flxi[IDN ] -= rem[IDN ][IVY ]*coeff[IVY ];
flxi[IDN ] -= rem[IDN ][IVZ ]*coeff[IVZ ];
flxi[IDN ] -= rem[IDN ][IP11]*coeff[IP11];
flxi[IDN ] -= rem[IDN ][IP22]*coeff[IP22];
flxi[IDN ] -= rem[IDN ][IP33]*coeff[IP33];
flxi[IDN ] -= rem[IDN ][IP12]*coeff[IP12];
flxi[IDN ] -= rem[IDN ][IP13]*coeff[IP13];
flxi[IDN ] -= rem[IDN ][IP23]*coeff[IP23];
flxi[IVX ] = 0.5*(fl[IVX] + fr[IVX]);
flxi[IVX ] -= rem[IVX ][IDN ]*coeff[IDN ];
flxi[IVX ] -= rem[IVX ][IVX ]*coeff[IVX ];
flxi[IVX ] -= rem[IVX ][IVY ]*coeff[IVY ];
flxi[IVX ] -= rem[IVX ][IVZ ]*coeff[IVZ ];
flxi[IVX ] -= rem[IVX ][IP11]*coeff[IP11];
flxi[IVX ] -= rem[IVX ][IP22]*coeff[IP22];
flxi[IVX ] -= rem[IVX ][IP33]*coeff[IP33];
flxi[IVX ] -= rem[IVX ][IP12]*coeff[IP12];
flxi[IVX ] -= rem[IVX ][IP13]*coeff[IP13];
flxi[IVX ] -= rem[IVX ][IP23]*coeff[IP23];
flxi[IVY ] = 0.5*(fl[IVY] + fr[IVY]);
flxi[IVY ] -= rem[IVY ][IDN ]*coeff[IDN ];
flxi[IVY ] -= rem[IVY ][IVX ]*coeff[IVX ];
flxi[IVY ] -= rem[IVY ][IVY ]*coeff[IVY ];
flxi[IVY ] -= rem[IVY ][IVZ ]*coeff[IVZ ];
flxi[IVY ] -= rem[IVY ][IP11]*coeff[IP11];
flxi[IVY ] -= rem[IVY ][IP22]*coeff[IP22];
flxi[IVY ] -= rem[IVY ][IP33]*coeff[IP33];
flxi[IVY ] -= rem[IVY ][IP12]*coeff[IP12];
flxi[IVY ] -= rem[IVY ][IP13]*coeff[IP13];
flxi[IVY ] -= rem[IVY ][IP23]*coeff[IP23];
flxi[IVZ ] = 0.5*(fl[IVZ] + fr[IVZ]);
flxi[IVZ ] -= rem[IVZ ][IDN ]*coeff[IDN ];
flxi[IVZ ] -= rem[IVZ ][IVX ]*coeff[IVX ];
flxi[IVZ ] -= rem[IVZ ][IVY ]*coeff[IVY ];
flxi[IVZ ] -= rem[IVZ ][IVZ ]*coeff[IVZ ];
flxi[IVZ ] -= rem[IVZ ][IP11]*coeff[IP11];
flxi[IVZ ] -= rem[IVZ ][IP22]*coeff[IP22];
flxi[IVZ ] -= rem[IVZ ][IP33]*coeff[IP33];
flxi[IVZ ] -= rem[IVZ ][IP12]*coeff[IP12];
flxi[IVZ ] -= rem[IVZ ][IP13]*coeff[IP13];
flxi[IVZ ] -= rem[IVZ ][IP23]*coeff[IP23];
flxi[IP11] = 0.5*(fl[IP11] + fr[IP11]);
flxi[IP11] -= rem[IP11][IDN ]*coeff[IDN ];
flxi[IP11] -= rem[IP11][IVX ]*coeff[IVX ];
flxi[IP11] -= rem[IP11][IVY ]*coeff[IVY ];
flxi[IP11] -= rem[IP11][IVZ ]*coeff[IVZ ];
flxi[IP11] -= rem[IP11][IP11]*coeff[IP11];
flxi[IP11] -= rem[IP11][IP22]*coeff[IP22];
flxi[IP11] -= rem[IP11][IP33]*coeff[IP33];
flxi[IP11] -= rem[IP11][IP12]*coeff[IP12];
flxi[IP11] -= rem[IP11][IP13]*coeff[IP13];
flxi[IP11] -= rem[IP11][IP23]*coeff[IP23];
flxi[IP22] = 0.5*(fl[IP22] + fr[IP22]);
flxi[IP22] -= rem[IP22][IDN ]*coeff[IDN ];
flxi[IP22] -= rem[IP22][IVX ]*coeff[IVX ];
flxi[IP22] -= rem[IP22][IVY ]*coeff[IVY ];
flxi[IP22] -= rem[IP22][IVZ ]*coeff[IVZ ];
flxi[IP22] -= rem[IP22][IP11]*coeff[IP11];
flxi[IP22] -= rem[IP22][IP22]*coeff[IP22];
flxi[IP22] -= rem[IP22][IP33]*coeff[IP33];
flxi[IP22] -= rem[IP22][IP12]*coeff[IP12];
flxi[IP22] -= rem[IP22][IP13]*coeff[IP13];
flxi[IP22] -= rem[IP22][IP23]*coeff[IP23];
flxi[IP33] = 0.5*(fl[IP33] + fr[IP33]);
flxi[IP33] -= rem[IP33][IDN ]*coeff[IDN ];
flxi[IP33] -= rem[IP33][IVX ]*coeff[IVX ];
flxi[IP33] -= rem[IP33][IVY ]*coeff[IVY ];
flxi[IP33] -= rem[IP33][IVZ ]*coeff[IVZ ];
flxi[IP33] -= rem[IP33][IP11]*coeff[IP11];
flxi[IP33] -= rem[IP33][IP22]*coeff[IP22];
flxi[IP33] -= rem[IP33][IP33]*coeff[IP33];
flxi[IP33] -= rem[IP33][IP12]*coeff[IP12];
flxi[IP33] -= rem[IP33][IP13]*coeff[IP13];
flxi[IP33] -= rem[IP33][IP23]*coeff[IP23];
flxi[IP12] = 0.5*(fl[IP12] + fr[IP12]);
flxi[IP12] -= rem[IP12][IDN ]*coeff[IDN ];
flxi[IP12] -= rem[IP12][IVX ]*coeff[IVX ];
flxi[IP12] -= rem[IP12][IVY ]*coeff[IVY ];
flxi[IP12] -= rem[IP12][IVZ ]*coeff[IVZ ];
flxi[IP12] -= rem[IP12][IP11]*coeff[IP11];
flxi[IP12] -= rem[IP12][IP22]*coeff[IP22];
flxi[IP12] -= rem[IP12][IP33]*coeff[IP33];
flxi[IP12] -= rem[IP12][IP12]*coeff[IP12];
flxi[IP12] -= rem[IP12][IP13]*coeff[IP13];
flxi[IP12] -= rem[IP12][IP23]*coeff[IP23];
flxi[IP13] = 0.5*(fl[IP13] + fr[IP13]);
flxi[IP13] -= rem[IP13][IDN ]*coeff[IDN ];
flxi[IP13] -= rem[IP13][IVX ]*coeff[IVX ];
flxi[IP13] -= rem[IP13][IVY ]*coeff[IVY ];
flxi[IP13] -= rem[IP13][IVZ ]*coeff[IVZ ];
flxi[IP13] -= rem[IP13][IP11]*coeff[IP11];
flxi[IP13] -= rem[IP13][IP22]*coeff[IP22];
flxi[IP13] -= rem[IP13][IP33]*coeff[IP33];
flxi[IP13] -= rem[IP13][IP12]*coeff[IP12];
flxi[IP13] -= rem[IP13][IP13]*coeff[IP13];
flxi[IP13] -= rem[IP13][IP23]*coeff[IP23];
flxi[IP23] = 0.5*(fl[IP23] + fr[IP23]);
flxi[IP23] -= rem[IP23][IDN ]*coeff[IDN ];
flxi[IP23] -= rem[IP23][IVX ]*coeff[IVX ];
flxi[IP23] -= rem[IP23][IVY ]*coeff[IVY ];
flxi[IP23] -= rem[IP23][IVZ ]*coeff[IVZ ];
flxi[IP23] -= rem[IP23][IP11]*coeff[IP11];
flxi[IP23] -= rem[IP23][IP22]*coeff[IP22];
flxi[IP23] -= rem[IP23][IP33]*coeff[IP33];
flxi[IP23] -= rem[IP23][IP12]*coeff[IP12];
flxi[IP23] -= rem[IP23][IP13]*coeff[IP13];
flxi[IP23] -= rem[IP23][IP23]*coeff[IP23];
//--- Step 8. Overwrite with upwind flux if flow is supersonic
if (ev[0] >= 0.0) {
flxi[IDN ] = fl[IDN ];
flxi[IVX ] = fl[IVX ];
flxi[IVY ] = fl[IVY ];
flxi[IVZ ] = fl[IVZ ];
flxi[IP11] = fl[IP11];
flxi[IP22] = fl[IP22];
flxi[IP33] = fl[IP33];
flxi[IP12] = fl[IP12];
flxi[IP13] = fl[IP13];
flxi[IP23] = fl[IP23];
}
if (ev[NWAVECL-1] <= 0.0) {
flxi[IDN ] = fr[IDN ];
flxi[IVX ] = fr[IVX ];
flxi[IVY ] = fr[IVY ];
flxi[IVZ ] = fr[IVZ ];
flxi[IP11] = fr[IP11];
flxi[IP22] = fr[IP22];
flxi[IP33] = fr[IP33];
flxi[IP12] = fr[IP12];
flxi[IP13] = fr[IP13];
flxi[IP23] = fr[IP23];
}
//--- Step 9. Overwrite with HLLE flux if any of intermediate states are negative
if (hlle_flag != 0) {
// Compute hlle flux -- see hlle_cl.cpp for steps
Real cl = std::sqrt(3.0*wli[IP11]/wli[IDN]);
Real cr = std::sqrt(3.0*wri[IP11]/wri[IDN]);
Real a = std::sqrt(3.0*wroe[IP11]);
Real al = std::min((wroe[IVX] - a),(wli[IVX] - cl));
Real ar = std::max((wroe[IVX] + a),(wri[IVX] + cr));
Real bp = ar > 0.0 ? ar : 0.0;
Real bm = al < 0.0 ? al : 0.0;
Real vxl = wli[IVX] - bm;
Real vxr = wri[IVX] - bp;
fl[IDN ] = wli[IDN]*vxl;
fr[IDN ] = wri[IDN]*vxr;
fl[IVX ] = wli[IDN]*wli[IVX]*vxl + wli[IP11];
fr[IVX ] = wri[IDN]*wri[IVX]*vxr + wri[IP11];
fl[IVY ] = wli[IDN]*wli[IVY]*vxl + wli[IP12];
fr[IVY ] = wri[IDN]*wri[IVY]*vxr + wri[IP12];
fl[IVZ ] = wli[IDN]*wli[IVZ]*vxl + wli[IP13];
fr[IVZ ] = wri[IDN]*wri[IVZ]*vxr + wri[IP13];
fl[IP11] = (wli[IP11] + wli[IDN]*wli[IVX]*wli[IVX])*vxl + 2.0*wli[IP11]*wli[IVX];
fr[IP11] = (wri[IP11] + wri[IDN]*wri[IVX]*wri[IVX])*vxr + 2.0*wri[IP11]*wri[IVX];
fl[IP22] = (wli[IP22] + wli[IDN]*wli[IVY]*wli[IVY])*vxl + 2.0*wli[IP12]*wli[IVY];
fr[IP22] = (wri[IP22] + wri[IDN]*wri[IVY]*wri[IVY])*vxr + 2.0*wri[IP12]*wri[IVY];
fl[IP33] = (wli[IP33] + wli[IDN]*wli[IVZ]*wli[IVZ])*vxl + 2.0*wli[IP13]*wli[IVZ];
fr[IP33] = (wri[IP33] + wri[IDN]*wri[IVZ]*wri[IVZ])*vxr + 2.0*wri[IP13]*wri[IVZ];
fl[IP12] = (wli[IP12] + wli[IDN]*wli[IVX]*wli[IVY])*vxl + ( wli[IP12]*wli[IVX]
+ wli[IP11]*wli[IVY] );
fr[IP12] = (wri[IP12] + wri[IDN]*wri[IVX]*wri[IVY])*vxr + ( wri[IP12]*wri[IVX]
+ wri[IP11]*wri[IVY] );
fl[IP13] = (wli[IP13] + wli[IDN]*wli[IVX]*wli[IVZ])*vxl + ( wli[IP13]*wli[IVX]
+ wli[IP11]*wli[IVZ] );
fr[IP13] = (wri[IP13] + wri[IDN]*wri[IVX]*wri[IVZ])*vxr + ( wri[IP13]*wri[IVX]
+ wri[IP11]*wri[IVZ] );
fl[IP23] = (wli[IP23] + wli[IDN]*wli[IVY]*wli[IVZ])*vxl + ( wli[IP13]*wli[IVY]
+ wli[IP12]*wli[IVZ] );
fr[IP23] = (wri[IP23] + wri[IDN]*wri[IVY]*wri[IVZ])*vxr + ( wri[IP13]*wri[IVY]
+ wri[IP12]*wri[IVZ] );
Real tmp=0.0;
if (bp != bm) tmp = 0.5*(bp + bm)/(bp - bm);
flxi[IDN ] = 0.5*(fl[IDN ]+fr[IDN ]) + (fl[IDN ]-fr[IDN ])*tmp;
flxi[IVX ] = 0.5*(fl[IVX ]+fr[IVX ]) + (fl[IVX ]-fr[IVX ])*tmp;
flxi[IVY ] = 0.5*(fl[IVY ]+fr[IVY ]) + (fl[IVY ]-fr[IVY ])*tmp;
flxi[IVZ ] = 0.5*(fl[IVZ ]+fr[IVZ ]) + (fl[IVZ ]-fr[IVZ ])*tmp;
flxi[IP11] = 0.5*(fl[IP11]+fr[IP11]) + (fl[IP11]-fr[IP11])*tmp;
flxi[IP22] = 0.5*(fl[IP22]+fr[IP22]) + (fl[IP22]-fr[IP22])*tmp;
flxi[IP33] = 0.5*(fl[IP33]+fr[IP33]) + (fl[IP33]-fr[IP33])*tmp;
flxi[IP12] = 0.5*(fl[IP12]+fr[IP12]) + (fl[IP12]-fr[IP12])*tmp;
flxi[IP13] = 0.5*(fl[IP13]+fr[IP13]) + (fl[IP13]-fr[IP13])*tmp;
flxi[IP23] = 0.5*(fl[IP23]+fr[IP23]) + (fl[IP23]-fr[IP23])*tmp;
}
flx(IDN ,k,j,i) = flxi[IDN ];
flx(ivx ,k,j,i) = flxi[IVX ];
flx(ivy ,k,j,i) = flxi[IVY ];
flx(ivz ,k,j,i) = flxi[IVZ ];
flx(ip11,k,j,i) = flxi[IP11];
flx(ip22,k,j,i) = flxi[IP22];
flx(ip33,k,j,i) = flxi[IP33];
flx(ip12,k,j,i) = flxi[IP12];
flx(ip13,k,j,i) = flxi[IP13];
flx(ip23,k,j,i) = flxi[IP23];
}
}}
return;
}
//----------------------------------------------------------------------------------------
// \!fn RoeEigensystemCL()
// \brief computes eigenvalues and eigenvectors for hydrodynamics
//
// PURPOSE: Functions to evaluate the eigenvalues, and left- and right-eigenvectors of
// "Roe's matrix A" for the linearized system in the CONSERVED variables, i.e.
// U,t = AU,x, where U=(d,d*vx,d*vy,d*vz,[E],[By,Bz]). The eigenvalues are returned
// through the argument list as a vector of length NWAVECL. The eigenvectors are returned
// as matrices of size (NWAVECL)x(NWAVECL), with right-eigenvectors stored as COLUMNS
// (so R_i = right_eigenmatrix[*][i]), and left-eigenvectors stored as ROWS
// (so L_i = left_eigenmatrix[i][*]).
// - Input: v1,v2,v3,h = Roe averaged velocities and enthalpy
// - Output: eigenvalues[], right_eigenmatrix[][], left_eigenmatrix[][];
//
// REFERENCES:
// - P. Cargo & G. Gallice, "Roe matrices for ideal MHD and systematic construction of
// Roe matrices for systems of conservation laws", JCP, 136, 446 (1997)
//
// - J. Stone, T. Gardiner, P. Teuben, J. Hawley, & J. Simon "Athena: A new code for
// astrophysical MHD", ApJS, (2008), Appendix B Equation numbers refer to this paper.
inline void RoeEigensystemCL(const Real wroe[], Real eigenvalues[],
Real right_eigenmatrix[][(NWAVECL)], Real left_eigenmatrix[][(NWAVECL)]) {
// get all variables
Real d = wroe[IDN ];
Real v1 = wroe[IVX ];
Real v2 = wroe[IVY ];
Real v3 = wroe[IVZ ];
Real S11 = wroe[IP11];
Real S22 = wroe[IP22];
Real S33 = wroe[IP33];
Real S12 = wroe[IP12];
Real S13 = wroe[IP13];
Real S23 = wroe[IP23];
Real a = std::sqrt(S11);
Real sqt3 = std::sqrt(3.0);
Real sqt3a = sqt3*a;
Real a2 = S11;
Real inva = 1.0/a;
Real inva2 = 1.0/a2;
// compute eigenvalues
eigenvalues[0] = v1 - sqt3a;
eigenvalues[1] = v1 - a;
eigenvalues[2] = v1 - a;
eigenvalues[3] = v1;
eigenvalues[4] = v1;
eigenvalues[5] = v1;
eigenvalues[6] = v1;
eigenvalues[7] = v1 + a;
eigenvalues[8] = v1 + a;
eigenvalues[9] = v1 + sqt3a;
// Right-eigenvectors, stored as COLUMNS
right_eigenmatrix[0][0] = 1.0;
right_eigenmatrix[1][0] = v1 - sqt3a;
right_eigenmatrix[2][0] = v2 - sqt3*S12*inva;
right_eigenmatrix[3][0] = v3 - sqt3*S13*inva;
right_eigenmatrix[4][0] = SQR(v1 - sqt3a);
right_eigenmatrix[5][0] = SQR(v2) - 2.0*sqt3*v2*S12*inva + S22 + 2.0*SQR(S12*inva);
right_eigenmatrix[6][0] = SQR(v3) - 2.0*sqt3*v3*S13*inva + S33 + 2.0*SQR(S13*inva);
right_eigenmatrix[7][0] = (v2-sqt3*S12*inva)*(v1-sqt3a);
right_eigenmatrix[8][0] = (v3-sqt3*S13*inva)*(v1-sqt3a);
right_eigenmatrix[9][0] = v2*v3 + 2.0*S12*S13*inva2 + S23 - sqt3*(S13*v2+S12*v3)*inva;
right_eigenmatrix[0][1] = 0.0;
right_eigenmatrix[1][1] = 0.0;
right_eigenmatrix[2][1] = inva;
right_eigenmatrix[3][1] = 0.0;
right_eigenmatrix[4][1] = 0.0;
right_eigenmatrix[5][1] = 2.0*(a*v2-S12)*inva2;
right_eigenmatrix[6][1] = 0.0;
right_eigenmatrix[7][1] = v1*inva - 1.0;
right_eigenmatrix[8][1] = 0.0;
right_eigenmatrix[9][1] = (a*v3 - S13)*inva2;
right_eigenmatrix[0][2] = 0.0;
right_eigenmatrix[1][2] = 0.0;
right_eigenmatrix[2][2] = 0.0;
right_eigenmatrix[3][2] = -inva;
right_eigenmatrix[4][2] = 0.0;
right_eigenmatrix[5][2] = 0.0;
right_eigenmatrix[6][2] = 2.0*(S13-a*v3)*inva2;
right_eigenmatrix[7][2] = 0.0;
right_eigenmatrix[8][2] = 1.0-v1*inva;
right_eigenmatrix[9][2] = (S12-a*v2)*inva2;
right_eigenmatrix[0][3] = 0.0;
right_eigenmatrix[1][3] = 0.0;
right_eigenmatrix[2][3] = 0.0;
right_eigenmatrix[3][3] = 0.0;
right_eigenmatrix[4][3] = 0.0;
right_eigenmatrix[5][3] = 1.0;
right_eigenmatrix[6][3] = 0.0;
right_eigenmatrix[7][3] = 0.0;
right_eigenmatrix[8][3] = 0.0;
right_eigenmatrix[9][3] = 0.0;
right_eigenmatrix[0][4] = 0.0;
right_eigenmatrix[1][4] = 0.0;
right_eigenmatrix[2][4] = 0.0;
right_eigenmatrix[3][4] = 0.0;
right_eigenmatrix[4][4] = 0.0;
right_eigenmatrix[5][4] = 0.0;
right_eigenmatrix[6][4] = 1.0;
right_eigenmatrix[7][4] = 0.0;
right_eigenmatrix[8][4] = 0.0;
right_eigenmatrix[9][4] = 0.0;
right_eigenmatrix[0][5] = 1.0;
right_eigenmatrix[1][5] = v1;
right_eigenmatrix[2][5] = v2;
right_eigenmatrix[3][5] = v3;
right_eigenmatrix[4][5] = SQR(v1);
right_eigenmatrix[5][5] = SQR(v2) + S22 - 4.0*SQR(S12*inva);
right_eigenmatrix[6][5] = SQR(v3) + S33 - 4.0*SQR(S13*inva);
right_eigenmatrix[7][5] = v1*v2;
right_eigenmatrix[8][5] = v1*v3;
right_eigenmatrix[9][5] = v2*v3 + S23 - 4.0*S12*S13*inva2;
right_eigenmatrix[0][6] = 0.0;
right_eigenmatrix[1][6] = 0.0;
right_eigenmatrix[2][6] = 0.0;
right_eigenmatrix[3][6] = 0.0;
right_eigenmatrix[4][6] = 0.0;
right_eigenmatrix[5][6] = 0.0;
right_eigenmatrix[6][6] = 0.0;
right_eigenmatrix[7][6] = 0.0;
right_eigenmatrix[8][6] = 0.0;
right_eigenmatrix[9][6] = 1.0;
right_eigenmatrix[0][7] = 0.0;
right_eigenmatrix[1][7] = 0.0;
right_eigenmatrix[2][7] = 0.0;
right_eigenmatrix[3][7] = inva;
right_eigenmatrix[4][7] = 0.0;
right_eigenmatrix[5][7] = 0.0;
right_eigenmatrix[6][7] = 2.0*(S13 + a*v3)*inva2;
right_eigenmatrix[7][7] = 0.0;
right_eigenmatrix[8][7] = 1.0+v1*inva;
right_eigenmatrix[9][7] = (S12 + a*v2)*inva2;
right_eigenmatrix[0][8] = 0.0;
right_eigenmatrix[1][8] = 0.0;
right_eigenmatrix[2][8] = inva;
right_eigenmatrix[3][8] = 0.0;
right_eigenmatrix[4][8] = 0.0;
right_eigenmatrix[5][8] = 2.0*(a*v2 + S12)*inva2;
right_eigenmatrix[6][8] = 0.0;
right_eigenmatrix[7][8] = 1.0+v1*inva;
right_eigenmatrix[8][8] = 0.0;
right_eigenmatrix[9][8] = (a*v3 + S13)*inva2;
right_eigenmatrix[0][9] = 1.0;
right_eigenmatrix[1][9] = v1 + sqt3a;
right_eigenmatrix[2][9] = v2 + sqt3*S12*inva;
right_eigenmatrix[3][9] = v3 + sqt3*S13*inva;
right_eigenmatrix[4][9] = SQR(v1 + sqt3a);
right_eigenmatrix[5][9] = SQR(v2) + 2.0*sqt3*v2*S12*inva + S22 + 2.0*SQR(S12*inva);
right_eigenmatrix[6][9] = SQR(v3) + 2.0*sqt3*v3*S13*inva + S33 + 2.0*SQR(S13*inva);
right_eigenmatrix[7][9] = (v2+sqt3*S12*inva)*(v1+sqt3a);
right_eigenmatrix[8][9] = (v3+sqt3*S13*inva)*(v1+sqt3a);
right_eigenmatrix[9][9] = v2*v3 + 2.0*S12*S13*inva2 + S23 + sqt3*(S13*v2+S12*v3)*inva;
// Left-eigenvectors, stored as ROWS
left_eigenmatrix[0][0] = v1*(v1 + sqt3a)*inva2/6.0;
left_eigenmatrix[0][1] = -(2.0*v1 + sqt3a)*inva2/6.0;
left_eigenmatrix[0][2] = 0.0;
left_eigenmatrix[0][3] = 0.0;
left_eigenmatrix[0][4] = inva2/6.0;
left_eigenmatrix[0][5] = 0.0;
left_eigenmatrix[0][6] = 0.0;
left_eigenmatrix[0][7] = 0.0;
left_eigenmatrix[0][8] = 0.0;
left_eigenmatrix[0][9] = 0.0;
left_eigenmatrix[1][0] = -0.5*(v1 + a)*(a2*v2 - S12*v1)*inva2;
left_eigenmatrix[1][1] = 0.5*(v2 - S12*(2*v1 + a)*inva2);
left_eigenmatrix[1][2] = 0.5*(v1+a);
left_eigenmatrix[1][3] = 0.0;
left_eigenmatrix[1][4] = 0.5*S12*inva2;
left_eigenmatrix[1][5] = 0.0;
left_eigenmatrix[1][6] = 0.0;
left_eigenmatrix[1][7] = -0.5;
left_eigenmatrix[1][8] = 0.0;
left_eigenmatrix[1][9] = 0.0;
left_eigenmatrix[2][0] = 0.5*(v1 + a)*(a2*v3 - S13*v1)*inva2;
left_eigenmatrix[2][1] = -0.5*(v3 - S13*(2.0*v1 + a)*inva2);
left_eigenmatrix[2][2] = 0.0;
left_eigenmatrix[2][3] = -0.5*(v1+a);
left_eigenmatrix[2][4] = -0.5*S13*inva2;
left_eigenmatrix[2][5] = 0.0;
left_eigenmatrix[2][6] = 0.0;
left_eigenmatrix[2][7] = 0.0;
left_eigenmatrix[2][8] = 0.5;
left_eigenmatrix[2][9] = 0.0;
left_eigenmatrix[3][0] = SQR(v2) + 2.0*S12*(2.0*S12 - v1*v2)*inva2 - S22;
left_eigenmatrix[3][1] = 2.0*S12*v2*inva2;
left_eigenmatrix[3][2] = 2.0*(S12*v1*inva2 - v2);
left_eigenmatrix[3][3] = 0.0;
left_eigenmatrix[3][4] = 0.0;
left_eigenmatrix[3][5] = 1.0;
left_eigenmatrix[3][6] = 0.0;
left_eigenmatrix[3][7] = -2.0*S12*inva2;
left_eigenmatrix[3][8] = 0.0;
left_eigenmatrix[3][9] = 0.0;
left_eigenmatrix[4][0] = SQR(v3) + 2.0*S13*(2.0*S13 - v1*v3)*inva2 - S33;
left_eigenmatrix[4][1] = 2.0*S13*v3*inva2;
left_eigenmatrix[4][2] = 0.0;
left_eigenmatrix[4][3] = 2.0*(S13*v1*inva2 - v3);
left_eigenmatrix[4][4] = 0.0;
left_eigenmatrix[4][5] = 0.0;
left_eigenmatrix[4][6] = 1.0;
left_eigenmatrix[4][7] = 0.0;
left_eigenmatrix[4][8] = -2.0*S13*inva2;
left_eigenmatrix[4][9] = 0.0;
left_eigenmatrix[5][0] = 1.0 - SQR(v1)*inva2/3.0;
left_eigenmatrix[5][1] = 2.0*v1*inva2/3.0;
left_eigenmatrix[5][2] = 0.0;
left_eigenmatrix[5][3] = 0.0;
left_eigenmatrix[5][4] = -inva2/3.0;
left_eigenmatrix[5][5] = 0.0;
left_eigenmatrix[5][6] = 0.0;
left_eigenmatrix[5][7] = 0.0;
left_eigenmatrix[5][8] = 0.0;
left_eigenmatrix[5][9] = 0.0;
left_eigenmatrix[6][0] = -(S13*v1*v2 + S12*(v1*v3 - 4.0*S13) + a2*(S23 - v2*v3))*inva2;
left_eigenmatrix[6][1] = (S13*v2 + S12*v3)*inva2;
left_eigenmatrix[6][2] = S13*v1*inva2 - v3;
left_eigenmatrix[6][3] = S12*v1*inva2 - v2;
left_eigenmatrix[6][4] = 0.0;
left_eigenmatrix[6][5] = 0.0;
left_eigenmatrix[6][6] = 0.0;
left_eigenmatrix[6][7] = -S13*inva2;
left_eigenmatrix[6][8] = -S12*inva2;
left_eigenmatrix[6][9] = 1.0;
left_eigenmatrix[7][0] = -0.5*(a - v1)*(a2*v3 - S13*v1)*inva2;
left_eigenmatrix[7][1] = -0.5*(v3 - S13*(2.0*v1 - a)*inva2);
left_eigenmatrix[7][2] = 0.0;
left_eigenmatrix[7][3] = -0.5*(v1 - a);
left_eigenmatrix[7][4] = -0.5*S13*inva2;
left_eigenmatrix[7][5] = 0.0;
left_eigenmatrix[7][6] = 0.0;
left_eigenmatrix[7][7] = 0.0;
left_eigenmatrix[7][8] = 0.5;
left_eigenmatrix[7][9] = 0.0;
left_eigenmatrix[8][0] = -0.5*(a - v1)*(a2*v2 - S12*v1)*inva2;
left_eigenmatrix[8][1] = -0.5*(v2 - S12*(2.0*v1 - a)*inva2);
left_eigenmatrix[8][2] = -0.5*(v1 - a);
left_eigenmatrix[8][3] = 0.0;
left_eigenmatrix[8][4] = -0.5*S12*inva2;
left_eigenmatrix[8][5] = 0.0;
left_eigenmatrix[8][6] = 0.0;
left_eigenmatrix[8][7] = 0.5;
left_eigenmatrix[8][8] = 0.0;
left_eigenmatrix[8][9] = 0.0;
left_eigenmatrix[9][0] = v1*(v1 - sqt3a)*inva2/6.0;
left_eigenmatrix[9][1] = -(2.0*v1 - sqt3a)*inva2/6.0;
left_eigenmatrix[9][2] = 0.0;
left_eigenmatrix[9][3] = 0.0;
left_eigenmatrix[9][4] = inva2/6.0;
left_eigenmatrix[9][5] = 0.0;
left_eigenmatrix[9][6] = 0.0;
left_eigenmatrix[9][7] = 0.0;
left_eigenmatrix[9][8] = 0.0;
left_eigenmatrix[9][9] = 0.0;
}
| 36.792453 | 90 | 0.576048 | [
"vector"
] |
d6e696aeda443bf06a57c0e573d6f20bd4d02a87 | 327 | cpp | C++ | Codeforces 677A.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | Codeforces 677A.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | Codeforces 677A.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
int n, h, a, ans = 0;
vector<int> fh;
scanf("%d %d", &n, &h);
for(int i = 0; i < n; i++) scanf("%d", &a), fh.push_back(a);
for(int i = 0; i < n; i++){
if(fh[i] <= h) ans+=1;
else ans+=2;
}
printf("%d", ans);
return 0;
} | 20.4375 | 64 | 0.446483 | [
"vector"
] |
d6e7628fd5739c3a37e9d6f23cd293de2687b7bd | 14,261 | cpp | C++ | brlycmbd/CrdBrlyTtb/DlgBrlyTtbNew_blks.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyTtb/DlgBrlyTtbNew_blks.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyTtb/DlgBrlyTtbNew_blks.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | /**
* \file DlgBrlyTtbNew_blks.cpp
* job handler for job DlgBrlyTtbNew (implementation of blocks)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 11 Jan 2021
*/
// IP header --- ABOVE
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class DlgBrlyTtbNew::VecVDo
******************************************************************************/
uint DlgBrlyTtbNew::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butcncclick") return BUTCNCCLICK;
if (s == "butcreclick") return BUTCRECLICK;
return(0);
};
string DlgBrlyTtbNew::VecVDo::getSref(
const uint ix
) {
if (ix == BUTCNCCLICK) return("ButCncClick");
if (ix == BUTCRECLICK) return("ButCreClick");
return("");
};
/******************************************************************************
class DlgBrlyTtbNew::VecVSge
******************************************************************************/
uint DlgBrlyTtbNew::VecVSge::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "idle") return IDLE;
if (s == "create") return CREATE;
if (s == "done") return DONE;
return(0);
};
string DlgBrlyTtbNew::VecVSge::getSref(
const uint ix
) {
if (ix == IDLE) return("idle");
if (ix == CREATE) return("create");
if (ix == DONE) return("done");
return("");
};
void DlgBrlyTtbNew::VecVSge::fillFeed(
Feed& feed
) {
feed.clear();
for (unsigned int i = 1; i <= 3; i++) feed.appendIxSrefTitles(i, getSref(i), getSref(i));
};
/******************************************************************************
class DlgBrlyTtbNew::ContIac
******************************************************************************/
DlgBrlyTtbNew::ContIac::ContIac(
const uint numFDetPupAli
, const string& DetTxfTit
, const string& DetTxfSta
, const string& DetTxfSto
) :
Block()
{
this->numFDetPupAli = numFDetPupAli;
this->DetTxfTit = DetTxfTit;
this->DetTxfSta = DetTxfSta;
this->DetTxfSto = DetTxfSto;
mask = {NUMFDETPUPALI, DETTXFTIT, DETTXFSTA, DETTXFSTO};
};
bool DlgBrlyTtbNew::ContIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacDlgBrlyTtbNew");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemIacDlgBrlyTtbNew";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFDetPupAli", numFDetPupAli)) add(NUMFDETPUPALI);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "DetTxfTit", DetTxfTit)) add(DETTXFTIT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "DetTxfSta", DetTxfSta)) add(DETTXFSTA);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "DetTxfSto", DetTxfSto)) add(DETTXFSTO);
};
return basefound;
};
void DlgBrlyTtbNew::ContIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContIacDlgBrlyTtbNew";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemIacDlgBrlyTtbNew";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "numFDetPupAli", numFDetPupAli);
writeStringAttr(wr, itemtag, "sref", "DetTxfTit", DetTxfTit);
writeStringAttr(wr, itemtag, "sref", "DetTxfSta", DetTxfSta);
writeStringAttr(wr, itemtag, "sref", "DetTxfSto", DetTxfSto);
xmlTextWriterEndElement(wr);
};
set<uint> DlgBrlyTtbNew::ContIac::comm(
const ContIac* comp
) {
set<uint> items;
if (numFDetPupAli == comp->numFDetPupAli) insert(items, NUMFDETPUPALI);
if (DetTxfTit == comp->DetTxfTit) insert(items, DETTXFTIT);
if (DetTxfSta == comp->DetTxfSta) insert(items, DETTXFSTA);
if (DetTxfSto == comp->DetTxfSto) insert(items, DETTXFSTO);
return(items);
};
set<uint> DlgBrlyTtbNew::ContIac::diff(
const ContIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFDETPUPALI, DETTXFTIT, DETTXFSTA, DETTXFSTO};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class DlgBrlyTtbNew::ContInf
******************************************************************************/
DlgBrlyTtbNew::ContInf::ContInf(
const uint numFSge
) :
Block()
{
this->numFSge = numFSge;
mask = {NUMFSGE};
};
void DlgBrlyTtbNew::ContInf::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContInfDlgBrlyTtbNew";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemInfDlgBrlyTtbNew";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "numFSge", numFSge);
xmlTextWriterEndElement(wr);
};
set<uint> DlgBrlyTtbNew::ContInf::comm(
const ContInf* comp
) {
set<uint> items;
if (numFSge == comp->numFSge) insert(items, NUMFSGE);
return(items);
};
set<uint> DlgBrlyTtbNew::ContInf::diff(
const ContInf* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFSGE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class DlgBrlyTtbNew::StatApp
******************************************************************************/
void DlgBrlyTtbNew::StatApp::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
, const string& shortMenu
) {
if (difftag.length() == 0) difftag = "StatAppDlgBrlyTtbNew";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemAppDlgBrlyTtbNew";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeStringAttr(wr, itemtag, "sref", "shortMenu", shortMenu);
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class DlgBrlyTtbNew::StatShr
******************************************************************************/
DlgBrlyTtbNew::StatShr::StatShr(
const bool ButCncActive
, const bool ButCreActive
) :
Block()
{
this->ButCncActive = ButCncActive;
this->ButCreActive = ButCreActive;
mask = {BUTCNCACTIVE, BUTCREACTIVE};
};
void DlgBrlyTtbNew::StatShr::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "StatShrDlgBrlyTtbNew";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemShrDlgBrlyTtbNew";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeBoolAttr(wr, itemtag, "sref", "ButCncActive", ButCncActive);
writeBoolAttr(wr, itemtag, "sref", "ButCreActive", ButCreActive);
xmlTextWriterEndElement(wr);
};
set<uint> DlgBrlyTtbNew::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (ButCncActive == comp->ButCncActive) insert(items, BUTCNCACTIVE);
if (ButCreActive == comp->ButCreActive) insert(items, BUTCREACTIVE);
return(items);
};
set<uint> DlgBrlyTtbNew::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {BUTCNCACTIVE, BUTCREACTIVE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class DlgBrlyTtbNew::Tag
******************************************************************************/
void DlgBrlyTtbNew::Tag::writeXML(
const uint ixBrlyVLocale
, xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "TagDlgBrlyTtbNew";
string itemtag;
if (shorttags) itemtag = "Ti";
else itemtag = "TagitemDlgBrlyTtbNew";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
if (ixBrlyVLocale == VecBrlyVLocale::ENUS) {
writeStringAttr(wr, itemtag, "sref", "Cpt", "Create new timetable");
writeStringAttr(wr, itemtag, "sref", "DetCptAli", "Airline alliance");
writeStringAttr(wr, itemtag, "sref", "DetCptTit", "Name");
writeStringAttr(wr, itemtag, "sref", "DetCptSta", "Validity start");
writeStringAttr(wr, itemtag, "sref", "DetCptSto", "Validity stop");
} else if (ixBrlyVLocale == VecBrlyVLocale::DECH) {
writeStringAttr(wr, itemtag, "sref", "Cpt", "Neuen Flugplan erstellen");
writeStringAttr(wr, itemtag, "sref", "DetCptAli", "Luftfahrtallianz");
writeStringAttr(wr, itemtag, "sref", "DetCptTit", "Name");
writeStringAttr(wr, itemtag, "sref", "DetCptSta", "G\\u00fcltigkeitsbeginn");
writeStringAttr(wr, itemtag, "sref", "DetCptSto", "G\\u00fcltigkeitsende");
};
writeStringAttr(wr, itemtag, "sref", "ButCnc", StrMod::cap(VecBrlyVTag::getTitle(VecBrlyVTag::CANCEL, ixBrlyVLocale)));
writeStringAttr(wr, itemtag, "sref", "ButCre", StrMod::cap(VecBrlyVTag::getTitle(VecBrlyVTag::CREATE, ixBrlyVLocale)));
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class DlgBrlyTtbNew::DpchAppData
******************************************************************************/
DlgBrlyTtbNew::DpchAppData::DpchAppData() :
DpchAppBrly(VecBrlyVDpch::DPCHAPPDLGBRLYTTBNEWDATA)
{
};
string DlgBrlyTtbNew::DpchAppData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(CONTIAC)) ss.push_back("contiac");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void DlgBrlyTtbNew::DpchAppData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string scrJref;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppDlgBrlyTtbNewData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) {
jref = Scr::descramble(scrJref);
add(JREF);
};
if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC);
} else {
contiac = ContIac();
};
};
/******************************************************************************
class DlgBrlyTtbNew::DpchAppDo
******************************************************************************/
DlgBrlyTtbNew::DpchAppDo::DpchAppDo() :
DpchAppBrly(VecBrlyVDpch::DPCHAPPDLGBRLYTTBNEWDO)
{
ixVDo = 0;
};
string DlgBrlyTtbNew::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void DlgBrlyTtbNew::DpchAppDo::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string scrJref;
string srefIxVDo;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppDlgBrlyTtbNewDo");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) {
jref = Scr::descramble(scrJref);
add(JREF);
};
if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) {
ixVDo = VecVDo::getIx(srefIxVDo);
add(IXVDO);
};
} else {
};
};
/******************************************************************************
class DlgBrlyTtbNew::DpchEngData
******************************************************************************/
DlgBrlyTtbNew::DpchEngData::DpchEngData(
const ubigint jref
, ContIac* contiac
, ContInf* continf
, Feed* feedFDetPupAli
, Feed* feedFSge
, StatShr* statshr
, const set<uint>& mask
) :
DpchEngBrly(VecBrlyVDpch::DPCHENGDLGBRLYTTBNEWDATA, jref)
{
if (find(mask, ALL)) this->mask = {JREF, CONTIAC, CONTINF, FEEDFDETPUPALI, FEEDFSGE, STATAPP, STATSHR, TAG};
else this->mask = mask;
if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac;
if (find(this->mask, CONTINF) && continf) this->continf = *continf;
if (find(this->mask, FEEDFDETPUPALI) && feedFDetPupAli) this->feedFDetPupAli = *feedFDetPupAli;
if (find(this->mask, FEEDFSGE) && feedFSge) this->feedFSge = *feedFSge;
if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr;
};
string DlgBrlyTtbNew::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(CONTINF)) ss.push_back("continf");
if (has(FEEDFDETPUPALI)) ss.push_back("feedFDetPupAli");
if (has(FEEDFSGE)) ss.push_back("feedFSge");
if (has(STATAPP)) ss.push_back("statapp");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void DlgBrlyTtbNew::DpchEngData::merge(
DpchEngBrly* dpcheng
) {
DpchEngData* src = (DpchEngData*) dpcheng;
if (src->has(JREF)) {jref = src->jref; add(JREF);};
if (src->has(CONTIAC)) {contiac = src->contiac; add(CONTIAC);};
if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);};
if (src->has(FEEDFDETPUPALI)) {feedFDetPupAli = src->feedFDetPupAli; add(FEEDFDETPUPALI);};
if (src->has(FEEDFSGE)) {feedFSge = src->feedFSge; add(FEEDFSGE);};
if (src->has(STATAPP)) add(STATAPP);
if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);};
if (src->has(TAG)) add(TAG);
};
void DlgBrlyTtbNew::DpchEngData::writeXML(
const uint ixBrlyVLocale
, xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchEngDlgBrlyTtbNewData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/brly");
if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref));
if (has(CONTIAC)) contiac.writeXML(wr);
if (has(CONTINF)) continf.writeXML(wr);
if (has(FEEDFDETPUPALI)) feedFDetPupAli.writeXML(wr);
if (has(FEEDFSGE)) feedFSge.writeXML(wr);
if (has(STATAPP)) StatApp::writeXML(wr);
if (has(STATSHR)) statshr.writeXML(wr);
if (has(TAG)) Tag::writeXML(ixBrlyVLocale, wr);
xmlTextWriterEndElement(wr);
};
| 28.183794 | 121 | 0.620503 | [
"vector"
] |
d6eaba223c1328543c6122969ed7da01edef8a5f | 3,425 | cpp | C++ | solutions/1008/20120322T192647Z-4199705.cpp | Mistereo/timus-solutions | 062540304c33312b75e0e8713c4b36c80fb220ab | [
"MIT"
] | 11 | 2019-10-29T15:34:53.000Z | 2022-03-14T14:45:09.000Z | solutions/1008/20120322T192647Z-4199705.cpp | Mistereo/timus-solutions | 062540304c33312b75e0e8713c4b36c80fb220ab | [
"MIT"
] | null | null | null | solutions/1008/20120322T192647Z-4199705.cpp | Mistereo/timus-solutions | 062540304c33312b75e0e8713c4b36c80fb220ab | [
"MIT"
] | 6 | 2018-06-30T12:06:55.000Z | 2021-03-20T08:46:33.000Z | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
//#define ONLINE_JUDGE
#define mp make_pair
int A[15][15];
int dx[] = { 1, 0, -1, 0 };
int dy[] = { 0, 1, 0, -1 };
queue< pair<int, int> > Q;
int main (int argc, const char * argv[])
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
//CODE
int x, y;
char str[20];
gets(str);
int scanResult = sscanf(str, "%d%d", &x, &y);
if (scanResult==2) {
string s; cin >> s;
vector< pair<int, int> > Answer;
Answer.push_back(mp(x,y));
queue< pair<int, int> > Q;
Q.push(mp(x,y));
while (s!="." && !Q.empty()) {
x = Q.front().first;
y = Q.front().second;
Q.pop();
for (int i=0; s.size(); i++) {
if (s[i] == 'R') {
Answer.push_back(mp(x+1,y));
Q.push(mp(x+1,y));
} else if(s[i]=='T') {
Answer.push_back(mp(x,y+1));
Q.push(mp(x,y+1));
} else if(s[i]=='B') {
Answer.push_back(mp(x,y-1));
Q.push(mp(x,y-1));
} else if(s[i]=='L') {
Answer.push_back(mp(x-1,y));
Q.push(mp(x-1,y));
} else {
cin >> s;
break;
}
}
}
sort(Answer.begin(), Answer.end());
printf("%d\n", Answer.size());
for (int i=0; i<Answer.size(); i++) {
printf("%d %d\n", Answer[i].first, Answer[i].second);
}
} else {
for (int i=0; i<15; i++)
for (int j=0; j<15; j++)
A[i][j]=0;
int n = x;
int as, bs; scanf("%d%d", &as, &bs);
Q.push(make_pair(as, bs));
for (int i=1; i<n; i++) {
int a,b; scanf("%d%d", &a, &b);
A[a][b] = 1;
}
A[as][bs] = 2;
printf("%d %d\n", as, bs);
while (!Q.empty()) {
auto x = Q.front();
Q.pop();
if (A[x.first+dx[0]][x.second+dy[0]] == 1) {
A[x.first+dx[0]][x.second+dy[0]] = 2;
printf("R");
Q.push(make_pair(x.first+dx[0], x.second+dy[0]));
}
if (A[x.first+dx[1]][x.second+dy[1]] == 1) {
A[x.first+dx[1]][x.second+dy[1]] = 2;
printf("T");
Q.push(make_pair(x.first+dx[1], x.second+dy[1]));
}
if (A[x.first+dx[2]][x.second+dy[2]] == 1) {
A[x.first+dx[2]][x.second+dy[2]] = 2;
printf("L");
Q.push(make_pair(x.first+dx[2], x.second+dy[2]));
}
if (A[x.first+dx[3]][x.second+dy[3]] == 1) {
A[x.first+dx[3]][x.second+dy[3]] = 2;
printf("B");
Q.push(make_pair(x.first+dx[3], x.second+dy[3]));
}
printf(!Q.empty() ? ",\n" : ".");
}
}
//END
#ifndef ONLINE_JUDGE
fclose(stdout);
#endif
return 0;
} | 30.309735 | 66 | 0.388321 | [
"vector"
] |
d6ee1c881c58e398721548537ceb58a80f986208 | 6,817 | cpp | C++ | opt/optimize_enums/EnumInSwitch.cpp | parind/redex | a919919298f45e7ff33f03be7f819dc04e533182 | [
"MIT"
] | null | null | null | opt/optimize_enums/EnumInSwitch.cpp | parind/redex | a919919298f45e7ff33f03be7f819dc04e533182 | [
"MIT"
] | null | null | null | opt/optimize_enums/EnumInSwitch.cpp | parind/redex | a919919298f45e7ff33f03be7f819dc04e533182 | [
"MIT"
] | null | null | null | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "EnumInSwitch.h"
#include "Resolver.h"
namespace optimize_enums {
bool has_all_but_branch(boost::optional<Info> info) {
return info && info->array_field && info->invoke && info->aget;
}
// If exactly one of the input registers is holding the case key for an enum,
// return an info struct with that register filled in. Otherwise, return none.
boost::optional<Info> get_enum_reg(const Environment& env,
IRInstruction* insn) {
if (insn->srcs_size() == 1) {
// *-switch or if-*z
auto reg = insn->src(0);
auto info = env.get(reg).get_constant();
if (has_all_but_branch(info)) {
info->reg = reg;
return info;
}
} else {
// if-* v1 v2
// Only one of the registers should have the case key in it. Return that
// one. If both registers do then return none.
always_assert(insn->srcs_size() == 2);
uint16_t l_reg = insn->src(0);
uint16_t r_reg = insn->src(1);
boost::optional<Info> left = env.get(l_reg).get_constant();
boost::optional<Info> right = env.get(r_reg).get_constant();
bool l_has = has_all_but_branch(left);
bool r_has = has_all_but_branch(right);
if (l_has && !r_has) {
left->reg = l_reg;
return left;
} else if (!l_has && r_has) {
right->reg = r_reg;
return right;
}
}
return boost::none;
}
void analyze_default(cfg::InstructionIterator it, Environment* env) {
auto insn = it->insn;
if (insn->has_dest()) {
env->set(insn->dest(), Domain::top());
if (insn->dest_is_wide()) {
env->set(insn->dest() + 1, Domain::top());
}
}
if (insn->has_move_result_any()) {
env->set(RESULT_REGISTER, Domain::top());
}
}
void analyze_sget(cfg::InstructionIterator it, Environment* env) {
auto insn = it->insn;
auto op = insn->opcode();
if (op == OPCODE_SGET_OBJECT) {
auto field = resolve_field(insn->get_field(), FieldSearch::Static);
if (field != nullptr) {
Info info;
info.array_field = field;
env->set(RESULT_REGISTER, Domain(info));
return;
}
}
analyze_default(it, env);
}
void analyze_invoke(cfg::InstructionIterator it, Environment* env) {
auto insn = it->insn;
DexMethodRef* ref = insn->get_method();
if (ref->get_name()->str() == "ordinal") {
// All methods named `ordinal` is overly broad, but we throw out false
// positives later
Info info;
info.invoke = it;
env->set(RESULT_REGISTER, Domain(info));
} else {
analyze_default(it, env);
}
}
void analyze_branch(cfg::InstructionIterator it, Environment* env) {
auto insn = it->insn;
auto info = get_enum_reg(*env, insn);
if (has_all_but_branch(info)) {
info->branch = it;
env->set(*info->reg, Domain(*info));
} else {
analyze_default(it, env);
}
}
void analyze_aget(cfg::InstructionIterator it, Environment* env) {
auto insn = it->insn;
auto info = env->get(insn->src(0)).get_constant();
const auto& invoke_info = env->get(insn->src(1)).get_constant();
if (info && invoke_info && info->array_field != nullptr &&
invoke_info->invoke != boost::none) {
// Combine the information from each register.
// Later, we'll make sure array_field is of the right enum
info->invoke = invoke_info->invoke;
info->aget = it;
env->set(RESULT_REGISTER, Domain(*info));
} else {
analyze_default(it, env);
}
}
void analyze_move_result(cfg::InstructionIterator it, Environment* env) {
auto insn = it->insn;
if (!insn->dest_is_wide()) {
env->set(insn->dest(), env->get(RESULT_REGISTER));
} else {
analyze_default(it, env);
}
}
void analyze_move(cfg::InstructionIterator it, Environment* env) {
auto insn = it->insn;
auto op = insn->opcode();
if (op == OPCODE_MOVE) {
env->set(insn->dest(), env->get(insn->src(0)));
} else {
analyze_default(it, env);
}
}
void Iterator::analyze_node(cfg::Block* const& block, Environment* env) const {
auto ii = ir_list::InstructionIterable(*block);
for (auto it = ii.begin(); it != ii.end(); ++it) {
auto cfg_it = block->to_cfg_instruction_iterator(it);
analyze_insn(cfg_it, env);
}
}
std::vector<Info> Iterator::collect() const {
std::vector<Info> result;
for (cfg::Block* b : m_cfg->blocks()) {
Environment env = get_entry_state_at(b);
auto ii = ir_list::InstructionIterable(*b);
for (auto it = ii.begin(); it != ii.end(); ++it) {
auto insn = it->insn;
auto op = insn->opcode();
const auto& cfg_it = b->to_cfg_instruction_iterator(it);
if (is_branch(op)) {
auto info = get_enum_reg(env, insn);
if (info && info->branch == boost::none) {
// We check to make sure info.branch is none because we want to only
// get the first branch of the if-else chain.
info->branch = cfg_it;
result.emplace_back(*info);
}
}
analyze_insn(cfg_it, &env);
}
}
return result;
}
void Iterator::analyze_insn(cfg::InstructionIterator it,
Environment* env) const {
auto op = it->insn->opcode();
switch (op) {
case OPCODE_MOVE:
case OPCODE_MOVE_WIDE:
case OPCODE_MOVE_OBJECT:
analyze_move(it, env);
break;
case OPCODE_MOVE_RESULT:
case OPCODE_MOVE_RESULT_WIDE:
case OPCODE_MOVE_RESULT_OBJECT:
case IOPCODE_MOVE_RESULT_PSEUDO:
case IOPCODE_MOVE_RESULT_PSEUDO_OBJECT:
case IOPCODE_MOVE_RESULT_PSEUDO_WIDE:
analyze_move_result(it, env);
break;
case OPCODE_SWITCH:
case OPCODE_IF_EQ:
case OPCODE_IF_NE:
case OPCODE_IF_LT:
case OPCODE_IF_GE:
case OPCODE_IF_GT:
case OPCODE_IF_LE:
case OPCODE_IF_EQZ:
case OPCODE_IF_NEZ:
case OPCODE_IF_LTZ:
case OPCODE_IF_GEZ:
case OPCODE_IF_GTZ:
case OPCODE_IF_LEZ:
analyze_branch(it, env);
break;
case OPCODE_AGET:
case OPCODE_AGET_WIDE:
case OPCODE_AGET_OBJECT:
case OPCODE_AGET_BOOLEAN:
case OPCODE_AGET_BYTE:
case OPCODE_AGET_CHAR:
case OPCODE_AGET_SHORT:
analyze_aget(it, env);
break;
case OPCODE_SGET:
case OPCODE_SGET_WIDE:
case OPCODE_SGET_OBJECT:
case OPCODE_SGET_BOOLEAN:
case OPCODE_SGET_BYTE:
case OPCODE_SGET_CHAR:
case OPCODE_SGET_SHORT:
analyze_sget(it, env);
break;
case OPCODE_INVOKE_VIRTUAL:
case OPCODE_INVOKE_SUPER:
case OPCODE_INVOKE_DIRECT:
case OPCODE_INVOKE_STATIC:
case OPCODE_INVOKE_INTERFACE:
analyze_invoke(it, env);
break;
default:
analyze_default(it, env);
break;
}
}
Environment Iterator::analyze_edge(
cfg::Edge* const&, const Environment& exit_state_at_source) const {
return exit_state_at_source;
}
} // namespace optimize_enums
| 28.404167 | 79 | 0.658794 | [
"vector"
] |
d6ef94f2a185ae7971b642bd855fff22d596c357 | 1,533 | hpp | C++ | src/enemyCollisionFunctions.hpp | evanbowman/Blind-Jump | 971bbfabb7a43a0de90c6131035b081b94a0bc08 | [
"BSD-2-Clause"
] | 79 | 2016-11-05T12:41:46.000Z | 2022-03-23T07:05:01.000Z | src/enemyCollisionFunctions.hpp | evanbowman/Blind-Jump | 971bbfabb7a43a0de90c6131035b081b94a0bc08 | [
"BSD-2-Clause"
] | 14 | 2017-02-28T02:47:43.000Z | 2021-04-25T20:08:15.000Z | src/enemyCollisionFunctions.hpp | evanbowman/Blind-Jump | 971bbfabb7a43a0de90c6131035b081b94a0bc08 | [
"BSD-2-Clause"
] | 22 | 2017-02-12T00:12:30.000Z | 2021-12-04T08:44:35.000Z | #pragma once
#include "wall.hpp"
// Simple bounding box collision checking
inline void checkCollision(std::vector<wall> walls, bool & CollisionDown,
bool & CollisionUp, bool & CollisionRight,
bool & CollisionLeft, float posY, float posX) {
bool foundCollision[4] = {0, 0, 0, 0};
for (int i = 0; i < walls.size(); i++) {
if ((posX + 6 < (walls[i].getPosX() + walls[i].width) &&
(posX + 6 > (walls[i].getPosX()))) &&
(fabs((posY + 16) - walls[i].getPosY()) <= 13) &&
foundCollision[0] == 0) {
CollisionLeft = 1;
foundCollision[0] = 1;
}
if ((posX + 24 > (walls[i].getPosX()) &&
(posX + 24 < (walls[i].getPosX() + walls[i].width))) &&
(fabs((posY + 16) - walls[i].getPosY()) <= 13) &&
foundCollision[1] == 0) {
CollisionRight = 1;
foundCollision[1] = 1;
}
if (((posY + 22 < (walls[i].getPosY() + walls[i].height)) &&
(posY + 22 > (walls[i].getPosY()))) &&
(fabs((posX)-walls[i].getPosX()) <= 16) && foundCollision[2] == 0) {
CollisionUp = 1;
foundCollision[2] = 1;
}
if (((posY + 36 > walls[i].getPosY()) &&
(posY + 36 < walls[i].getPosY() + walls[i].height)) &&
(fabs((posX)-walls[i].getPosX()) <= 16) && foundCollision[3] == 0) {
CollisionDown = 1;
foundCollision[3] = 1;
}
}
}
| 35.651163 | 80 | 0.463144 | [
"vector"
] |
d6f233e27cab0161226b7a6292a16817837062f9 | 660 | cpp | C++ | aboutdialog.cpp | dmitrysl/qt-mclaut-notifier | c5559de2c0d7f106e5a7e6ffe53065373632b803 | [
"MIT"
] | 1 | 2015-04-03T11:46:32.000Z | 2015-04-03T11:46:32.000Z | aboutdialog.cpp | dmitrysl/qt-mclaut-notifier | c5559de2c0d7f106e5a7e6ffe53065373632b803 | [
"MIT"
] | 3 | 2015-09-03T07:34:53.000Z | 2015-09-03T09:14:03.000Z | aboutdialog.cpp | dmitrysl/qt-mclaut-notifier | c5559de2c0d7f106e5a7e6ffe53065373632b803 | [
"MIT"
] | null | null | null | #include <QVBoxLayout>
#include <QLabel>
#include <QDebug>
#include "aboutdialog.h"
AboutDialog::AboutDialog(const QRect &geometry, QWidget *parent) : QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout;
QLabel *label = new QLabel("Developer: ", this);
layout->addWidget(label);
layout->addWidget(new QLabel("Dmitry Slepchenko", this));
this->setGeometry(QRect(geometry.x() + 100, geometry.y() + 100, 250, 80));
setLayout(layout);
}
AboutDialog::~AboutDialog()
{
}
void AboutDialog::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event)
#ifdef QT_DEBUG
qDebug() << "close about dialog";
#endif
}
| 22.758621 | 83 | 0.662121 | [
"geometry"
] |
d6fc3a83c330b75bac261284f6ed8833e495b15c | 7,203 | cpp | C++ | src/FlatPieceMemoryStorage.cpp | a-pavlov/qtplayer | 10dfb7e1c8bac9cebb1925dd890b1d4b42d036f4 | [
"Apache-2.0"
] | null | null | null | src/FlatPieceMemoryStorage.cpp | a-pavlov/qtplayer | 10dfb7e1c8bac9cebb1925dd890b1d4b42d036f4 | [
"Apache-2.0"
] | null | null | null | src/FlatPieceMemoryStorage.cpp | a-pavlov/qtplayer | 10dfb7e1c8bac9cebb1925dd890b1d4b42d036f4 | [
"Apache-2.0"
] | null | null | null | #include "FlatPieceMemoryStorage.h"
#include <QDebug>
#include <QMutexLocker>
#include <cassert>
#include <algorithm>
FlatPieceMemoryStorage::FlatPieceMemoryStorage(int pieceLength
, int maxCachePieces
, qlonglong fileOffset
, qlonglong fileSize) :
buffer(new unsigned char[pieceLength * maxCachePieces])
, pieceLen(pieceLength)
, cacheSizeInPieces(maxCachePieces)
, fOffset(fileOffset)
, fSize(fileSize)
, absRPos(fileOffset)
, updatingBuffer(false) {
absWPos = firstPieceOffset();
}
FlatPieceMemoryStorage::~FlatPieceMemoryStorage() {
delete[] buffer;
}
int FlatPieceMemoryStorage::read(unsigned char* buf, size_t len) {
int bytesRequested = static_cast<int>(len);
mutex.lock();
if (absRPos >= absWPos) {
// no bytes available for reading
bufferNotEmpty.wait(&mutex);
}
assert(absWPos > absRPos);
int localRPos = posInCacheByAbsPos(absRPos); // reading offset in flat cache
int localWPos = posInCacheByAbsPos(absWPos); // writing offset in flat cache
mutex.unlock();
int distance = localWPos - localRPos;
/*
case 1: wpos > rpos - forward to the writing position
| w->| |
|***********|
| r->|xx |
case 2: wpos < rpos - forward to the end of cache + forward from the beginning of cache to the writing position
|w->| |
|***********|
| r->|xxxx|
|xxx |
*/
int bytesToBeCopied = distance > 0 ? std::min(bytesRequested, distance) : (cacheSize() - localRPos) + std::min(bytesRequested - cacheSize() + localRPos, localWPos);
assert(distance != 0);
assert(bytesToBeCopied > 0);
int obtainBytes = -1;
if (distance > 0 || (cacheSize() - localRPos) > static_cast<int>(len)) {
// forward direction to the writing position or to the end of cache if enough bytes
obtainBytes = std::min(bytesRequested, distance > 0 ? localWPos - localRPos : cacheSize() - localRPos);
memcpy(buf, buffer + localRPos, obtainBytes);
}
else {
// forward direction to the end of cache, tail bytes
int tailBytes = cacheSize() - localRPos;
if (tailBytes > 0) {
memcpy(buf, buffer + localRPos, tailBytes);
}
// forward direction from zero to writing position
// calculate remain bytes
obtainBytes = std::min(bytesRequested - tailBytes, localWPos);
if (obtainBytes > 0) {
memcpy(buf + tailBytes, buffer, obtainBytes);
}
obtainBytes += tailBytes;
}
assert(obtainBytes == bytesToBeCopied);
assert(obtainBytes != -1);
mutex.lock();
absRPos += obtainBytes;
requestSlots(absRPos / pieceLen);
bufferNotFull.wakeAll();
mutex.unlock();
return obtainBytes;
}
void FlatPieceMemoryStorage::write(const unsigned char* buf
, int len
, int offset
, int pieceIndex) {
mutex.lock();
// check this piece in our list
auto itr = std::lower_bound(slotList.begin(), slotList.end()
, qMakePair(pieceIndex, Range<int>())
, [](const Slot& l, const Slot& r){ return l.first < r.first; });
if (itr != slotList.end() && itr->first == pieceIndex) {
updatingBuffer = true;
int dataPos = posInCacheByPiece(pieceIndex) + offset;
assert(dataPos >= 0);
mutex.unlock();
memcpy(buffer + dataPos, buf, len);
mutex.lock();
// update current slot bytes available
itr->second += qMakePair(offset, offset + len);
// move forward writing position as much as possible
for (; itr != slotList.end(); ++itr) {
int writingSlot = absWPos / pieceLen;
// writing position in current slot
if (writingSlot == itr->first) {
// set writing position to new position if bytes available greater than last writing position
absWPos = std::max(pieceAbsPos(itr->first) + itr->second.bytesAvailable(), absWPos);
}
// slot is not full, do not continue
if (itr->second.bytesAvailable() < pieceLen) {
break;
}
}
if (absWPos > absRPos) {
// wake up reading only if absolute writing position greater than absolute reading position
bufferNotEmpty.wakeAll();
}
bufferNotUpdating.wakeAll();
updatingBuffer = false;
} else {
qDebug() << "skip piece " << pieceIndex << " data offset " << offset << " length " << len;
emit pieceOutOfRangeReceived(len, offset, pieceIndex);
}
mutex.unlock();
}
int FlatPieceMemoryStorage::seek(quint64 pos) {
mutex.lock();
if (updatingBuffer) bufferNotUpdating.wait(&mutex);
assert(!updatingBuffer);
qlonglong newAbsPos = pos + fOffset;
absRPos = newAbsPos;
int currentPieceIndex = absWPos / pieceLen;
int newPieceIndex = newAbsPos / pieceLen;
absWPos = (currentPieceIndex == newPieceIndex) ? absWPos : pieceAbsPos(newPieceIndex);
requestSlots(newPieceIndex);
mutex.unlock();
return 0;
}
qlonglong FlatPieceMemoryStorage::absoluteReadingPosition() {
QMutexLocker lock(&mutex);
return absRPos;
}
qlonglong FlatPieceMemoryStorage::absoluteWritingPosition() {
QMutexLocker lock(&mutex);
return absWPos;
}
void checkSlotsInvariant(const QList<Slot>& list) {
auto startSlotIndex = -1;
for (auto slot : list) {
if (startSlotIndex != -1) {
assert(++startSlotIndex == slot.first);
}
else {
startSlotIndex = slot.first;
}
}
}
void FlatPieceMemoryStorage::requestSlots(int pieceIndexStartFrom) {
slotList.erase(std::remove_if(slotList.begin(), slotList.end()
, [=](Slot slot) {
return slot.first < pieceIndexStartFrom;
})
, slotList.end());
if (!slotList.isEmpty()) {
assert(pieceIndexStartFrom <= slotList.begin()->first);
int gapSize = slotList.begin()->first - pieceIndexStartFrom;
// remove out of cache size elements in slot list
if (gapSize >= cacheSizeInPieces) {
slotList.clear();
} else {
while (gapSize + slotList.size() > cacheSizeInPieces) {
slotList.removeLast();
}
}
// prepend slots
if (!slotList.isEmpty()) {
int slotIndex = slotList.begin()->first;
assert(pieceIndexStartFrom <= slotIndex);
while (slotIndex != pieceIndexStartFrom) {
slotList.prepend(qMakePair(--slotIndex, Range<int>()));
}
pieceIndexStartFrom = slotList.last().first + 1;
}
}
// append slots
while (slotList.size() < cacheSizeInPieces && pieceIndexStartFrom <= lastPiece()) {
slotList.append(qMakePair(pieceIndexStartFrom++, Range<int>()));
}
checkSlotsInvariant(slotList);
QList<int> rp;
std::transform(slotList.begin(), slotList.end(), std::back_inserter(rp), [](Slot s) { return s.first; });
emit piecesRequested(rp);
}
| 30.782051 | 168 | 0.602666 | [
"transform"
] |
d6ff22660177fcbe684143cd8ed9415a7db62c81 | 3,124 | hpp | C++ | include/hipipe/core/stream/for_each.hpp | iterait/hipipe | c2a6cc13857dce93e5ae3f76a86e8f029ca3f921 | [
"BSL-1.0",
"MIT"
] | 16 | 2018-10-08T09:00:14.000Z | 2021-07-11T12:35:09.000Z | include/hipipe/core/stream/for_each.hpp | iterait/hipipe | c2a6cc13857dce93e5ae3f76a86e8f029ca3f921 | [
"BSL-1.0",
"MIT"
] | 19 | 2018-09-26T13:55:40.000Z | 2019-08-28T13:47:04.000Z | include/hipipe/core/stream/for_each.hpp | iterait/hipipe | c2a6cc13857dce93e5ae3f76a86e8f029ca3f921 | [
"BSL-1.0",
"MIT"
] | null | null | null | /****************************************************************************
* hipipe library
* Copyright (c) 2017, Cognexa Solutions s.r.o.
* Copyright (c) 2018, Iterait a.s.
* Author(s) Filip Matzner
*
* This file is distributed under the MIT License.
* See the accompanying file LICENSE.txt for the complete license agreement.
****************************************************************************/
#pragma once
#include <hipipe/core/stream/template_arguments.hpp>
#include <hipipe/core/stream/transform.hpp>
#include <hipipe/core/utility/tuple.hpp>
namespace hipipe::stream {
namespace detail {
// Wrap the given function so that its return value is ignored
// and so that it can be forwarded to stream::transform.
template<typename Fun, typename... FromTypes>
struct wrap_void_fun_for_transform {
Fun fun;
utility::maybe_tuple<FromTypes...> operator()(FromTypes&... args)
{
static_assert(std::is_invocable_v<Fun, FromTypes&...>,
"hipipe::stream::for_each: "
"Cannot apply the given function to the given `from<>` columns.");
std::invoke(fun, args...);
// we can force std::move here because the old
// data are going to be ignored anyway
return {std::move(args)...};
}
};
} // namespace detail
/// \ingroup Stream
/// \brief Apply a function to a subset of stream columns.
///
/// The given function is applied to a subset of columns given by FromColumns.
/// The function is applied lazily, i.e., only when the range is iterated.
///
/// Example:
/// \code
/// HIPIPE_DEFINE_COLUMN(Int, int)
/// HIPIPE_DEFINE_COLUMN(Double, double)
/// std::vector<std::tuple<Int, Double>> data = {{3, 5.}, {1, 2.}};
/// auto rng = data
/// | for_each(from<Int, Double>, [](int& v, double& d) { std::cout << c + d; });
/// \endcode
///
/// \param f The columns to be exctracted out of the tuple of columns and passed to fun.
/// \param fun The function to be applied.
/// \param d The dimension in which the function is applied. Choose 0 for the function to
/// be applied to the whole batch.
template<typename... FromColumns, typename Fun, int Dim = 1>
auto for_each(from_t<FromColumns...> f, Fun fun, dim_t<Dim> d = dim_t<1>{})
{
static_assert(
((utility::ndims<typename FromColumns::data_type>::value >= Dim) && ...),
"hipipe::stream::for_each: The dimension in which to apply the operation "
" needs to be at most the lowest dimension of all the from<> columns.");
// a bit of function type erasure to speed up compilation
using FunT = std::function<
void(utility::ndim_type_t<typename FromColumns::data_type, Dim>&...)>;
// wrap the function to be compatible with stream::transform
detail::wrap_void_fun_for_transform<
FunT, utility::ndim_type_t<typename FromColumns::data_type, Dim>...>
fun_wrapper{std::move(fun)};
// apply the dummy transformation
return stream::transform(f, to<FromColumns...>, std::move(fun_wrapper), d);
}
} // namespace hipipe::stream
| 39.05 | 89 | 0.622279 | [
"vector",
"transform"
] |
d903ede5b2d2f0f4bfccf1956ddf1b1e65ee96f2 | 2,108 | cpp | C++ | Arrays/Maximum-gap.cpp | anuanu0-0/Essential-dsa-questions | a9c225afd039dd58f9fbb692852878eb306b65a4 | [
"MIT"
] | null | null | null | Arrays/Maximum-gap.cpp | anuanu0-0/Essential-dsa-questions | a9c225afd039dd58f9fbb692852878eb306b65a4 | [
"MIT"
] | null | null | null | Arrays/Maximum-gap.cpp | anuanu0-0/Essential-dsa-questions | a9c225afd039dd58f9fbb692852878eb306b65a4 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/**
* @brief Given an integer array nums, return the maximum difference between two successive
* elements in its sorted form. If the array contains less than two elements, return 0.
* You must write an algorithm that runs in linear time and uses linear extra space.
* Concept : Bucket sort, pigeonhole principle
* @param nums Container with elements for which max gap is to be found.
* @return ** int Return max gap between successive elements if container was sorted.
*/
int maximumGap(vector<int> &nums)
{
if (nums.size() < 2)
return 0;
int minVal = INT_MAX, maxVal = INT_MIN;
for (int num : nums)
{
minVal = min(minVal, num);
maxVal = max(maxVal, num);
}
// Giving overflow error for this bucket size declaration
// int bucketSize = ceil((maxVal - minVal) / (nums.size()-1));
int bucketSize = (int)ceil((double)(maxVal - minVal) / (nums.size() - 1));
// Store min and max of each bucket
vector<int> minBucket(nums.size() - 1, INT_MAX), maxBucket(nums.size() - 1, INT_MIN);
int bucketIndex;
// Store min value and max value of each bucket in respective buckets
// based on the bucket index. Ignore minVal and maxVal calculated above.
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == minVal || nums[i] == maxVal)
continue;
// Calculate the bucket index to put the element
bucketIndex = (nums[i] - minVal) / bucketSize;
minBucket[bucketIndex] = min(minBucket[bucketIndex], nums[i]);
maxBucket[bucketIndex] = max(maxBucket[bucketIndex], nums[i]);
}
// Calculate the maximum gap by taking the difference of min value
// of current bucket and max value of previous non empty bucket
int maxGap = 0;
for (int i = 0; i < nums.size() - 1; i++)
{
// Ignore an empty bucket
if (maxBucket[i] == INT_MIN)
continue;
maxGap = max(maxGap, minBucket[i] - minVal);
minVal = maxBucket[i];
}
return max(maxGap, maxVal - minVal);
} | 35.133333 | 94 | 0.63093 | [
"vector"
] |
d90537a5250612bd5cb39e207bbc06527c3c1012 | 980 | cpp | C++ | solutions/uva_11286_conformity.cpp | pvchaumier/uva | 66923f62a0165f6ab6c7d37d487569cd7b308e6f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/uva_11286_conformity.cpp | pvchaumier/uva | 66923f62a0165f6ab6c7d37d487569cd7b308e6f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/uva_11286_conformity.cpp | pvchaumier/uva | 66923f62a0165f6ab6c7d37d487569cd7b308e6f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <string>
using namespace std;
void solution(int n);
int main(int argc, char const *argv[])
{
int n(0);
while (cin >> n && n != 0)
solution(n);
return 0;
}
void solution(int n)
{
vector<int> v(5);
map<string, int> m;
string tmp("");
int course1(0), course2(0), course3(0), course4(0), course5(0);
int max_popularity(0);
int res(0);
while (n--)
{
cin >> v[0] >> v[1] >> v[2] >> v[3] >> v[4];
sort(v.begin(), v.end());
tmp = to_string(v[0]) + to_string(v[1]) + to_string(v[2]) +
to_string(v[3]) + to_string(v[4]);
if (m.find(tmp) != m.end())
m[tmp]++;
else
m[tmp] = 1;
max_popularity = max(max_popularity, m[tmp]);
}
for (auto x: m)
{
if (x.second == max_popularity)
res += x.second;
}
cout << res << endl;
}
| 18.846154 | 68 | 0.491837 | [
"vector"
] |
d90b82ef72475dfa26ea3c39b9d55c29682d0ad1 | 6,692 | hpp | C++ | tests/src/BaseKmerTests.hpp | adbailey4/embed_fast5 | 4416fab3927a4f3deae2f4637ff6c7344b4098c9 | [
"MIT"
] | null | null | null | tests/src/BaseKmerTests.hpp | adbailey4/embed_fast5 | 4416fab3927a4f3deae2f4637ff6c7344b4098c9 | [
"MIT"
] | 1 | 2021-12-14T13:31:42.000Z | 2022-03-12T17:41:30.000Z | tests/src/BaseKmerTests.hpp | adbailey4/embed_fast5 | 4416fab3927a4f3deae2f4637ff6c7344b4098c9 | [
"MIT"
] | null | null | null | //
// Created by Andrew Bailey on 5/23/20.
//
#ifndef EMBED_FAST5_TESTS_SRC_BASEKMERTESTS_HPP_
#define EMBED_FAST5_TESTS_SRC_BASEKMERTESTS_HPP_
// embed source
#include "BaseKmer.hpp"
#include "TestFiles.hpp"
//boost
#include <boost/filesystem.hpp>
// gtest
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace boost::filesystem;
using namespace std;
using namespace embed_utils;
using namespace test_files;
TEST (BaseKmerTests, test_Event) {
Redirect a(true, true);
Event e(1, 2);
EXPECT_EQ(1, e.descaled_event_mean);
EXPECT_EQ(2, e.posterior_probability);
}
TEST (BaseKmerTests, test_PosKmer) {
Redirect a(true, true);
Event e(1, 2);
Event e2(1.1, 2.2);
PosKmer k("ATGCC", 1);
k.add_event(e);
k.add_event(e2);
k.add_event(1.02, 2.1);
EXPECT_EQ("ATGCC", k.kmer);
EXPECT_FLOAT_EQ(2.2, k.events.front().posterior_probability);
EXPECT_EQ(1, k.num_events());
PosKmer k2("ATGCC", 2);
k2.add_event(e);
k2.add_event(e2);
k2.add_event(1.02, 2.1);
EXPECT_EQ("ATGCC", k2.kmer);
EXPECT_FLOAT_EQ(2.2, k2.events.back().posterior_probability);
EXPECT_EQ(2, k2.num_events());
}
TEST (BaseKmerTests, test_PosKmer_kde) {
Redirect a(true, true);
PosKmer k("ATGCC");
k.add_event(1, 1);
k.add_event(2, 0.5);
k.add_event(3, 1);
k.add_event(4, 0.5);
k.add_event(5, 1);
k.add_event(6, 0.5);
k.add_event(7, 1);
k.add_event(8, 0.5);
k.add_event(9, 1);
k.add_event(10, 1);
EXPECT_EQ(10, k.num_events());
ASSERT_THROW(k.get_hist(0,10,10), AssertionFailureException);
vector<uint64_t> hist{1,1,1,1,1,1,1,1,1,1};
ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,10.1,10)));
ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,10.1,10, 0.5)));
hist = {1,0,1,0,1,0,1,0,1,1};
ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,10.1,10, 0.51)));
hist = {0,1,1,1,1,1,1,1,1,1,1};
ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,11,11)));
}
TEST (BaseKmerTests, test_Position) {
Redirect a(true, true);
string kmer = "ATGCC";
Event e(1, 2);
Event e2(1.1, 2.2);
Event e3 = e;
shared_ptr<PosKmer> k = make_shared<PosKmer>(kmer, 1);
k->add_event(e);
k->add_event(e2);
shared_ptr<PosKmer> k2 = k;
Position p(1);
p.add_kmer(move(k));
ASSERT_THROW({(p.add_kmer)(k2);}, AssertionFailureException);
p.soft_add_kmer_event(kmer, e3);
EXPECT_EQ(kmer, p.get_pos_kmer(kmer)->kmer);
EXPECT_EQ(1, p.position);
EXPECT_FLOAT_EQ(2.2, p.get_pos_kmer(kmer)->events.front().posterior_probability);
}
TEST (BaseKmerTests, test_ContigStrand) {
Redirect a(true, true);
string kmer = "ATGCC";
Event e(1, 2);
Event e2(1.1, 2.2);
shared_ptr<PosKmer> k = make_shared<PosKmer>(kmer, 1);
k->add_event(e);
k->add_event(e2);
string contig = "asd";
string strand = "+";
uint64_t num_positions = 10;
ContigStrand cs(contig, strand, num_positions, "t");
EXPECT_EQ(num_positions, cs.positions.capacity());
EXPECT_EQ("asd", cs.get_contig());
EXPECT_EQ("+", cs.get_strand());
for (uint64_t i=0; i < num_positions; i++){
EXPECT_EQ(i, cs.positions[i].position);
}
uint64_t pos = 1;
cs.add_kmer(pos, k);
EXPECT_FLOAT_EQ(2.2, cs.positions[pos].get_pos_kmer(kmer)->events.front().posterior_probability);
EXPECT_FLOAT_EQ(2.2, cs.get_position(pos).get_pos_kmer(kmer)->events.front().posterior_probability);
float c = 2;
float b = 3.3;
cs.add_event(pos, kmer, c, b);
EXPECT_FLOAT_EQ(3.3, cs.get_position(pos).get_pos_kmer(kmer)->events.front().posterior_probability);
}
TEST (BaseKmerTests, test_Kmer) {
Redirect a(true, true);
Event e(1, 2);
Event e2(1.1, 2.2);
shared_ptr<PosKmer> k = make_shared<PosKmer>("ATGCC", 1);
k->add_event(e);
k->add_event(e2);
k->add_event(1.02, 2.1);
EXPECT_EQ("ATGCC", k->kmer);
EXPECT_FLOAT_EQ(2.2, k->events.front().posterior_probability);
EXPECT_EQ(1, k->num_events());
Kmer kmer("ATGCC");
string contig_strand = "asdf+t";
uint64_t pos = 1;
kmer.add_pos_kmer(contig_strand, pos, k);
EXPECT_EQ(contig_strand, get<0>(kmer.contig_positions[0]));
EXPECT_EQ(pos, get<1>(kmer.contig_positions[0]));
EXPECT_EQ(k, kmer.get_pos_kmer(contig_strand, pos));
EXPECT_TRUE(kmer.has_pos_kmer(contig_strand, pos));
EXPECT_FALSE(kmer.has_pos_kmer(contig_strand, 2));
kmer.soft_add_pos_kmer(contig_strand, pos, k);
EXPECT_EQ(1, kmer.contig_positions.size());
EXPECT_EQ(1, kmer.pos_kmer_map.size());
ContigStrandPosition csp = kmer.split_pos_kmer_map_key("asdf+t1234");
EXPECT_EQ("asdf", csp.contig);
EXPECT_EQ("+", csp.strand);
EXPECT_EQ("t", csp.nanopore_strand);
EXPECT_EQ(1234, csp.position);
}
TEST (BaseKmerTests, test_ByKmer_kde) {
Redirect a(true, true);
shared_ptr<PosKmer> k = make_shared<PosKmer>("ATGCC");
k->add_event(1, 1);
k->add_event(2, 0.5);
k->add_event(3, 1);
k->add_event(4, 0.5);
k->add_event(5, 1);
k->add_event(6, 0.5);
k->add_event(7, 1);
k->add_event(8, 0.5);
k->add_event(9, 1);
k->add_event(10, 1);
shared_ptr<PosKmer> k2 = make_shared<PosKmer>("ATGCC");
k2->add_event(1, 1);
k2->add_event(2, 0.5);
k2->add_event(3, 1);
k2->add_event(4, 0.5);
k2->add_event(5, 1);
k2->add_event(6, 0.5);
k2->add_event(7, 1);
k2->add_event(8, 0.5);
k2->add_event(9, 1);
k2->add_event(10, 1);
Kmer kmer("ATGCC");
kmer.add_pos_kmer("asdf", 1, k);
kmer.add_pos_kmer("asdf", 2, k2);
ASSERT_THROW(kmer.get_hist(0,10,10), AssertionFailureException);
vector<uint64_t> hist{2,2,2,2,2,2,2,2,2,2};
ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,10.1,10)));
ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,10.1,10, 0.5)));
hist = {2,0,2,0,2,0,2,0,2,2};
ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,10.1,10, 0.51)));
hist = {0,2,2,2,2,2,2,2,2,2,2};
ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,11,11)));
}
TEST (BaseKmerTests, test_ByKmer) {
Redirect a(true, true);
Event e(1, 2);
Event e2(1.1, 2.2);
shared_ptr<PosKmer> k = make_shared<PosKmer>("ATGCC", 1);
k->add_event(e);
k->add_event(e2);
k->add_event(1.02, 2.1);
EXPECT_EQ("ATGCC", k->kmer);
EXPECT_FLOAT_EQ(2.2, k->events.front().posterior_probability);
EXPECT_EQ(1, k->num_events());
string contig_strand = "asdf";
uint64_t pos = 1;
uint64_t kmer_length = 5;
ByKmer by_kmer({'A', 'C', 'T', 'G'}, kmer_length);
for (auto &k: all_string_permutations("ACTG", kmer_length)) {
by_kmer.get_kmer(k);
}
ASSERT_THROW(by_kmer.get_kmer("AAFAA"), AssertionFailureException);
by_kmer.add_kmer_ptr(contig_strand, pos, k);
EXPECT_EQ(1, by_kmer.get_kmer("ATGCC").pos_kmer_map.size());
by_kmer.add_kmer_ptr(contig_strand, pos, k);
EXPECT_EQ(1, by_kmer.get_kmer("ATGCC").pos_kmer_map.size());
}
#endif //EMBED_FAST5_TESTS_SRC_BASEKMERTESTS_HPP_
| 30.83871 | 102 | 0.682756 | [
"vector"
] |
d90e0dd81fccf39e4949c2009c104784c8b6f4e1 | 66,568 | cc | C++ | Mysql/sql/sql_load.cc | clockzhong/WrapLAMP | fa7ad07da3f1759e74966a554befa47bbbbb8dd5 | [
"Apache-2.0"
] | 1 | 2015-12-24T16:44:50.000Z | 2015-12-24T16:44:50.000Z | Mysql/sql/sql_load.cc | clockzhong/WrapLAMP | fa7ad07da3f1759e74966a554befa47bbbbb8dd5 | [
"Apache-2.0"
] | 1 | 2015-12-24T18:23:56.000Z | 2015-12-24T18:24:26.000Z | Mysql/sql/sql_load.cc | clockzhong/WrapLAMP | fa7ad07da3f1759e74966a554befa47bbbbb8dd5 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Copy data from a textfile to table */
/* 2006-12 Erik Wetterberg : LOAD XML added */
#include "sql_load.h"
#include "sql_cache.h" // query_cache_*
#include "sql_base.h" // fill_record_n_invoke_before_triggers
#include <my_dir.h>
#include "sql_view.h" // check_key_in_view
#include "sql_insert.h" // check_that_all_fields_are_given_values,
// prepare_triggers_for_insert_stmt,
// write_record
#include "auth_common.h"// INSERT_ACL, UPDATE_ACL
#include "log_event.h" // Delete_file_log_event,
// Execute_load_query_log_event,
// LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F
#include <m_ctype.h>
#include "rpl_mi.h"
#include "rpl_slave.h"
#include "table_trigger_dispatcher.h" // Table_trigger_dispatcher
#include "sql_show.h"
#include "item_timefunc.h" // Item_func_now_local
#include "rpl_rli.h" // Relay_log_info
#include "log.h"
#include "pfs_file_provider.h"
#include "mysql/psi/mysql_file.h"
#include <algorithm>
using std::min;
using std::max;
class XML_TAG {
public:
int level;
String field;
String value;
XML_TAG(int l, String f, String v);
};
XML_TAG::XML_TAG(int l, String f, String v)
{
level= l;
field.append(f);
value.append(v);
}
#define GET (stack_pos != stack ? *--stack_pos : my_b_get(&cache))
#define PUSH(A) *(stack_pos++)=(A)
class READ_INFO {
File file;
uchar *buffer, /* Buffer for read text */
*end_of_buff; /* Data in bufferts ends here */
uint buff_length; /* Length of buffer */
const uchar *field_term_ptr, *line_term_ptr;
const char *line_start_ptr, *line_start_end;
size_t field_term_length,line_term_length,enclosed_length;
int field_term_char,line_term_char,enclosed_char,escape_char;
int *stack,*stack_pos;
bool found_end_of_line,start_of_line,eof;
bool need_end_io_cache;
IO_CACHE cache;
int level; /* for load xml */
public:
bool error,line_cuted,found_null,enclosed;
uchar *row_start, /* Found row starts here */
*row_end; /* Found row ends here */
const CHARSET_INFO *read_charset;
READ_INFO(File file,uint tot_length,const CHARSET_INFO *cs,
const String &field_term,
const String &line_start,
const String &line_term,
const String &enclosed,
int escape,bool get_it_from_net, bool is_fifo);
~READ_INFO();
int read_field();
int read_fixed_length(void);
int next_line(void);
char unescape(char chr);
int terminator(const uchar *ptr, size_t length);
bool find_start_of_fields();
/* load xml */
List<XML_TAG> taglist;
int read_value(int delim, String *val);
int read_xml();
int clear_level(int level);
/*
We need to force cache close before destructor is invoked to log
the last read block
*/
void end_io_cache()
{
::end_io_cache(&cache);
need_end_io_cache = 0;
}
/*
Either this method, or we need to make cache public
Arg must be set from mysql_load() since constructor does not see
either the table or THD value
*/
void set_io_cache_arg(void* arg) { cache.arg = arg; }
/**
skip all data till the eof.
*/
void skip_data_till_eof()
{
while (GET != my_b_EOF)
;
}
};
static int read_fixed_length(THD *thd, COPY_INFO &info, TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values, READ_INFO &read_info,
ulong skip_lines);
static int read_sep_field(THD *thd, COPY_INFO &info, TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values, READ_INFO &read_info,
const String &enclosed, ulong skip_lines);
static int read_xml_field(THD *thd, COPY_INFO &info, TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values, READ_INFO &read_info,
ulong skip_lines);
#ifndef EMBEDDED_LIBRARY
static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex,
const char* db_arg, /* table's database */
const char* table_name_arg,
bool is_concurrent,
enum enum_duplicates duplicates,
bool transactional_table,
int errocode);
#endif /* EMBEDDED_LIBRARY */
/*
Execute LOAD DATA query
SYNOPSYS
mysql_load()
thd - current thread
ex - sql_exchange object representing source file and its parsing rules
table_list - list of tables to which we are loading data
fields_vars - list of fields and variables to which we read
data from file
set_fields - list of fields mentioned in set clause
set_values - expressions to assign to fields in previous list
handle_duplicates - indicates whenever we should emit error or
replace row if we will meet duplicates.
read_file_from_client - is this LOAD DATA LOCAL ?
RETURN VALUES
TRUE - error / FALSE - success
*/
int mysql_load(THD *thd,sql_exchange *ex,TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values,
enum enum_duplicates handle_duplicates,
bool read_file_from_client)
{
char name[FN_REFLEN];
File file;
int error= 0;
const String *field_term= ex->field.field_term;
const String *escaped= ex->field.escaped;
const String *enclosed= ex->field.enclosed;
bool is_fifo=0;
SELECT_LEX *select= thd->lex->select_lex;
#ifndef EMBEDDED_LIBRARY
LOAD_FILE_INFO lf_info;
THD::killed_state killed_status= THD::NOT_KILLED;
bool is_concurrent;
bool transactional_table;
#endif
const char *db = table_list->db; // This is never null
/*
If path for file is not defined, we will use the current database.
If this is not set, we will use the directory where the table to be
loaded is located
*/
const char *tdb= thd->db().str ? thd->db().str : db; //Result is never null
ulong skip_lines= ex->skip_lines;
DBUG_ENTER("mysql_load");
/*
Bug #34283
mysqlbinlog leaves tmpfile after termination if binlog contains
load data infile, so in mixed mode we go to row-based for
avoiding the problem.
*/
thd->set_current_stmt_binlog_format_row_if_mixed();
#ifdef EMBEDDED_LIBRARY
read_file_from_client = 0; //server is always in the same process
#endif
if (escaped->length() > 1 || enclosed->length() > 1)
{
my_message(ER_WRONG_FIELD_TERMINATORS,ER(ER_WRONG_FIELD_TERMINATORS),
MYF(0));
DBUG_RETURN(TRUE);
}
/* Report problems with non-ascii separators */
if (!escaped->is_ascii() || !enclosed->is_ascii() ||
!field_term->is_ascii() ||
!ex->line.line_term->is_ascii() || !ex->line.line_start->is_ascii())
{
push_warning(thd, Sql_condition::SL_WARNING,
WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED,
ER(WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED));
}
if (open_and_lock_tables(thd, table_list, 0))
DBUG_RETURN(true);
if (select->setup_tables(thd, table_list, false))
DBUG_RETURN(true);
if (run_before_dml_hook(thd))
DBUG_RETURN(true);
if (table_list->is_view() && select->resolve_derived(thd, false))
DBUG_RETURN(true); /* purecov: inspected */
TABLE_LIST *const insert_table_ref=
table_list->is_updatable() && // View must be updatable
!table_list->is_multiple_tables() && // Multi-table view not allowed
!table_list->is_derived() ? // derived tables not allowed
table_list->updatable_base_table() : NULL;
if (insert_table_ref == NULL ||
check_key_in_view(thd, table_list, insert_table_ref))
{
my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "LOAD");
DBUG_RETURN(TRUE);
}
if (select->derived_table_count &&
select->check_view_privileges(thd, INSERT_ACL, SELECT_ACL))
DBUG_RETURN(true); /* purecov: inspected */
if (table_list->is_merged())
{
if (table_list->prepare_check_option(thd))
DBUG_RETURN(TRUE);
if (handle_duplicates == DUP_REPLACE &&
table_list->prepare_replace_filter(thd))
DBUG_RETURN(true);
}
// Pass the check option down to the underlying table:
insert_table_ref->check_option= table_list->check_option;
/*
Let us emit an error if we are loading data to table which is used
in subselect in SET clause like we do it for INSERT.
The main thing to fix to remove this restriction is to ensure that the
table is marked to be 'used for insert' in which case we should never
mark this table as 'const table' (ie, one that has only one row).
*/
if (unique_table(thd, insert_table_ref, table_list->next_global, 0))
{
my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name);
DBUG_RETURN(TRUE);
}
TABLE *const table= insert_table_ref->table;
for (Field **cur_field= table->field; *cur_field; ++cur_field)
(*cur_field)->reset_warnings();
#ifndef EMBEDDED_LIBRARY
transactional_table= table->file->has_transactions();
is_concurrent= (table_list->lock_type == TL_WRITE_CONCURRENT_INSERT);
#endif
if (!fields_vars.elements)
{
Field_iterator_table_ref field_iterator;
field_iterator.set(table_list);
for (; !field_iterator.end_of_fields(); field_iterator.next())
{
Item *item;
if (!(item= field_iterator.create_item(thd)))
DBUG_RETURN(TRUE);
fields_vars.push_back(item->real_item());
}
bitmap_set_all(table->write_set);
/*
Let us also prepare SET clause, altough it is probably empty
in this case.
*/
if (setup_fields(thd, Ref_ptr_array(), set_fields, INSERT_ACL, NULL,
false, true) ||
setup_fields(thd, Ref_ptr_array(), set_values, SELECT_ACL, NULL,
false, false))
DBUG_RETURN(TRUE);
}
else
{ // Part field list
/*
Because fields_vars may contain user variables,
pass false for column_update in first call below.
*/
if (setup_fields(thd, Ref_ptr_array(), fields_vars, INSERT_ACL, NULL,
false, false) ||
setup_fields(thd, Ref_ptr_array(), set_fields, INSERT_ACL, NULL,
false, true))
DBUG_RETURN(TRUE);
/*
Special updatability test is needed because fields_vars may contain
a mix of column references and user variables.
*/
Item *item;
List_iterator<Item> it(fields_vars);
while ((item= it++))
{
if ((item->type() == Item::FIELD_ITEM ||
item->type() == Item::REF_ITEM) &&
item->field_for_view_update() == NULL)
{
my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), item->item_name.ptr());
DBUG_RETURN(true);
}
}
/* We explicitly ignore the return value */
(void)check_that_all_fields_are_given_values(thd, table, table_list);
/* Fix the expressions in SET clause */
if (setup_fields(thd, Ref_ptr_array(), set_values, SELECT_ACL, NULL,
false, false))
DBUG_RETURN(TRUE);
}
const int escape_char= (escaped->length() && (ex->escaped_given() ||
!(thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)))
? (*escaped)[0] : INT_MAX;
/*
* LOAD DATA INFILE fff INTO TABLE xxx SET columns2
sets all columns, except if file's row lacks some: in that case,
defaults are set by read_fixed_length() and read_sep_field(),
not by COPY_INFO.
* LOAD DATA INFILE fff INTO TABLE xxx (columns1) SET columns2=
may need a default for columns other than columns1 and columns2.
*/
const bool manage_defaults= fields_vars.elements != 0;
COPY_INFO info(COPY_INFO::INSERT_OPERATION,
&fields_vars, &set_fields,
manage_defaults,
handle_duplicates, escape_char);
if (info.add_function_default_columns(table, table->write_set))
DBUG_RETURN(TRUE);
prepare_triggers_for_insert_stmt(table);
uint tot_length=0;
bool use_blobs= 0, use_vars= 0;
List_iterator_fast<Item> it(fields_vars);
Item *item;
while ((item= it++))
{
Item *real_item= item->real_item();
if (real_item->type() == Item::FIELD_ITEM)
{
Field *field= ((Item_field*)real_item)->field;
if (field->flags & BLOB_FLAG)
{
use_blobs= 1;
tot_length+= 256; // Will be extended if needed
}
else
tot_length+= field->field_length;
}
else if (item->type() == Item::STRING_ITEM)
use_vars= 1;
}
if (use_blobs && !ex->line.line_term->length() && !field_term->length())
{
my_message(ER_BLOBS_AND_NO_TERMINATED,ER(ER_BLOBS_AND_NO_TERMINATED),
MYF(0));
DBUG_RETURN(TRUE);
}
if (use_vars && !field_term->length() && !enclosed->length())
{
my_error(ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR, MYF(0));
DBUG_RETURN(TRUE);
}
#ifndef EMBEDDED_LIBRARY
if (read_file_from_client)
{
(void)net_request_file(thd->get_protocol_classic()->get_net(),
ex->file_name);
file = -1;
}
else
#endif
{
if (!dirname_length(ex->file_name))
{
strxnmov(name, FN_REFLEN-1, mysql_real_data_home, tdb, NullS);
(void) fn_format(name, ex->file_name, name, "",
MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
}
else
{
(void) fn_format(name, ex->file_name, mysql_real_data_home, "",
MY_RELATIVE_PATH | MY_UNPACK_FILENAME |
MY_RETURN_REAL_PATH);
}
if (thd->slave_thread & ((SYSTEM_THREAD_SLAVE_SQL |
(SYSTEM_THREAD_SLAVE_WORKER))!=0))
{
#if defined(HAVE_REPLICATION) && !defined(MYSQL_CLIENT)
Relay_log_info* rli= thd->rli_slave->get_c_rli();
if (strncmp(rli->slave_patternload_file, name,
rli->slave_patternload_file_size))
{
/*
LOAD DATA INFILE in the slave SQL Thread can only read from
--slave-load-tmpdir". This should never happen. Please, report a bug.
*/
sql_print_error("LOAD DATA INFILE in the slave SQL Thread can only read from --slave-load-tmpdir. " \
"Please, report a bug.");
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--slave-load-tmpdir");
DBUG_RETURN(TRUE);
}
#else
/*
This is impossible and should never happen.
*/
DBUG_ASSERT(FALSE);
#endif
}
else if (!is_secure_file_path(name))
{
/* Read only allowed from within dir specified by secure_file_priv */
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
DBUG_RETURN(TRUE);
}
#if !defined(_WIN32)
MY_STAT stat_info;
if (!my_stat(name, &stat_info, MYF(MY_WME)))
DBUG_RETURN(TRUE);
// if we are not in slave thread, the file must be:
if (!thd->slave_thread &&
!((stat_info.st_mode & S_IFLNK) != S_IFLNK && // symlink
((stat_info.st_mode & S_IFREG) == S_IFREG || // regular file
(stat_info.st_mode & S_IFIFO) == S_IFIFO))) // named pipe
{
my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), name);
DBUG_RETURN(TRUE);
}
if ((stat_info.st_mode & S_IFIFO) == S_IFIFO)
is_fifo= 1;
#endif
if ((file= mysql_file_open(key_file_load,
name, O_RDONLY, MYF(MY_WME))) < 0)
DBUG_RETURN(TRUE);
}
READ_INFO read_info(file,tot_length,
ex->cs ? ex->cs : thd->variables.collation_database,
*field_term,*ex->line.line_start, *ex->line.line_term,
*enclosed,
info.escape_char, read_file_from_client, is_fifo);
if (read_info.error)
{
if (file >= 0)
mysql_file_close(file, MYF(0)); // no files in net reading
DBUG_RETURN(TRUE); // Can't allocate buffers
}
#ifndef EMBEDDED_LIBRARY
if (mysql_bin_log.is_open())
{
lf_info.thd = thd;
lf_info.wrote_create_file = 0;
lf_info.last_pos_in_file = HA_POS_ERROR;
lf_info.log_delayed= transactional_table;
read_info.set_io_cache_arg((void*) &lf_info);
}
#endif /*!EMBEDDED_LIBRARY*/
thd->count_cuted_fields= CHECK_FIELD_WARN; /* calc cuted fields */
thd->cuted_fields=0L;
/* Skip lines if there is a line terminator */
if (ex->line.line_term->length() && ex->filetype != FILETYPE_XML)
{
/* ex->skip_lines needs to be preserved for logging */
while (skip_lines > 0)
{
skip_lines--;
if (read_info.next_line())
break;
}
}
if (!(error=MY_TEST(read_info.error)))
{
table->next_number_field=table->found_next_number_field;
if (thd->lex->is_ignore() ||
handle_duplicates == DUP_REPLACE)
table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
if (handle_duplicates == DUP_REPLACE &&
(!table->triggers ||
!table->triggers->has_delete_triggers()))
table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
table->file->ha_start_bulk_insert((ha_rows) 0);
table->copy_blobs=1;
if (ex->filetype == FILETYPE_XML) /* load xml */
error= read_xml_field(thd, info, insert_table_ref, fields_vars,
set_fields, set_values, read_info,
skip_lines);
else if (!field_term->length() && !enclosed->length())
error= read_fixed_length(thd, info, insert_table_ref, fields_vars,
set_fields, set_values, read_info,
skip_lines);
else
error= read_sep_field(thd, info, insert_table_ref, fields_vars,
set_fields, set_values, read_info,
*enclosed, skip_lines);
if (thd->locked_tables_mode <= LTM_LOCK_TABLES &&
table->file->ha_end_bulk_insert() && !error)
{
table->file->print_error(my_errno(), MYF(0));
error= 1;
}
table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
table->next_number_field=0;
}
if (file >= 0)
mysql_file_close(file, MYF(0));
free_blobs(table); /* if pack_blob was used */
table->copy_blobs=0;
thd->count_cuted_fields= CHECK_FIELD_IGNORE;
/*
simulated killing in the middle of per-row loop
must be effective for binlogging
*/
DBUG_EXECUTE_IF("simulate_kill_bug27571",
{
error=1;
thd->killed= THD::KILL_QUERY;
};);
#ifndef EMBEDDED_LIBRARY
killed_status= (error == 0) ? THD::NOT_KILLED : thd->killed;
#endif
/*
We must invalidate the table in query cache before binlog writing and
ha_autocommit_...
*/
query_cache.invalidate_single(thd, insert_table_ref, false);
if (error)
{
if (read_file_from_client)
read_info.skip_data_till_eof();
#ifndef EMBEDDED_LIBRARY
if (mysql_bin_log.is_open())
{
{
/*
Make sure last block (the one which caused the error) gets
logged. This is needed because otherwise after write of (to
the binlog, not to read_info (which is a cache))
Delete_file_log_event the bad block will remain in read_info
(because pre_read is not called at the end of the last
block; remember pre_read is called whenever a new block is
read from disk). At the end of mysql_load(), the destructor
of read_info will call end_io_cache() which will flush
read_info, so we will finally have this in the binlog:
Append_block # The last successfull block
Delete_file
Append_block # The failing block
which is nonsense.
Or could also be (for a small file)
Create_file # The failing block
which is nonsense (Delete_file is not written in this case, because:
Create_file has not been written, so Delete_file is not written, then
when read_info is destroyed end_io_cache() is called which writes
Create_file.
*/
read_info.end_io_cache();
/* If the file was not empty, wrote_create_file is true */
if (lf_info.wrote_create_file)
{
int errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
/* since there is already an error, the possible error of
writing binary log will be ignored */
if (thd->get_transaction()->cannot_safely_rollback(
Transaction_ctx::STMT))
(void) write_execute_load_query_log_event(thd, ex,
table_list->db,
table_list->table_name,
is_concurrent,
handle_duplicates,
transactional_table,
errcode);
else
{
Delete_file_log_event d(thd, db, transactional_table);
(void) mysql_bin_log.write_event(&d);
}
}
}
}
#endif /*!EMBEDDED_LIBRARY*/
error= -1; // Error on read
goto err;
}
my_snprintf(name, sizeof(name),
ER(ER_LOAD_INFO),
(long) info.stats.records, (long) info.stats.deleted,
(long) (info.stats.records - info.stats.copied),
(long) thd->get_stmt_da()->current_statement_cond_count());
#ifndef EMBEDDED_LIBRARY
if (mysql_bin_log.is_open())
{
/*
We need to do the job that is normally done inside
binlog_query() here, which is to ensure that the pending event
is written before tables are unlocked and before any other
events are written. We also need to update the table map
version for the binary log to mark that table maps are invalid
after this point.
*/
if (thd->is_current_stmt_binlog_format_row())
error= thd->binlog_flush_pending_rows_event(TRUE, transactional_table);
else
{
/*
As already explained above, we need to call end_io_cache() or the last
block will be logged only after Execute_load_query_log_event (which is
wrong), when read_info is destroyed.
*/
read_info.end_io_cache();
if (lf_info.wrote_create_file)
{
int errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
error= write_execute_load_query_log_event(thd, ex,
table_list->db, table_list->table_name,
is_concurrent,
handle_duplicates,
transactional_table,
errcode);
}
/*
Flushing the IO CACHE while writing the execute load query log event
may result in error (for instance, because the max_binlog_size has been
reached, and rotation of the binary log failed).
*/
error= error || mysql_bin_log.get_log_file()->error;
}
if (error)
goto err;
}
#endif /*!EMBEDDED_LIBRARY*/
/* ok to client sent only after binlog write and engine commit */
my_ok(thd, info.stats.copied + info.stats.deleted, 0L, name);
err:
DBUG_ASSERT(table->file->has_transactions() ||
!(info.stats.copied || info.stats.deleted) ||
thd->get_transaction()->cannot_safely_rollback(
Transaction_ctx::STMT));
table->file->ha_release_auto_increment();
table->auto_increment_field_not_null= FALSE;
DBUG_RETURN(error);
}
#ifndef EMBEDDED_LIBRARY
/* Not a very useful function; just to avoid duplication of code */
static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex,
const char* db_arg, /* table's database */
const char* table_name_arg,
bool is_concurrent,
enum enum_duplicates duplicates,
bool transactional_table,
int errcode)
{
char *load_data_query,
*end,
*fname_start,
*fname_end,
*p= NULL;
size_t pl= 0;
List<Item> fv;
Item *item;
String *str;
String pfield, pfields;
int n;
const char *tbl= table_name_arg;
const char *tdb= (thd->db().str != NULL ? thd->db().str : db_arg);
String string_buf;
if (thd->db().str == NULL || strcmp(db_arg, thd->db().str))
{
/*
If used database differs from table's database,
prefix table name with database name so that it
becomes a FQ name.
*/
string_buf.set_charset(system_charset_info);
append_identifier(thd, &string_buf, db_arg, strlen(db_arg));
string_buf.append(".");
}
append_identifier(thd, &string_buf, table_name_arg,
strlen(table_name_arg));
tbl= string_buf.c_ptr_safe();
Load_log_event lle(thd, ex, tdb, tbl, fv, is_concurrent,
duplicates, thd->lex->is_ignore(),
transactional_table);
/*
force in a LOCAL if there was one in the original.
*/
if (thd->lex->local_file)
lle.set_fname_outside_temp_buf(ex->file_name, strlen(ex->file_name));
/*
prepare fields-list and SET if needed; print_query won't do that for us.
*/
if (!thd->lex->load_field_list.is_empty())
{
List_iterator<Item> li(thd->lex->load_field_list);
pfields.append(" (");
n= 0;
while ((item= li++))
{
if (n++)
pfields.append(", ");
if (item->type() == Item::FIELD_ITEM ||
item->type() == Item::REF_ITEM)
append_identifier(thd, &pfields, item->item_name.ptr(),
strlen(item->item_name.ptr()));
else
item->print(&pfields, QT_ORDINARY);
}
pfields.append(")");
}
if (!thd->lex->load_update_list.is_empty())
{
List_iterator<Item> lu(thd->lex->load_update_list);
List_iterator<String> ls(thd->lex->load_set_str_list);
pfields.append(" SET ");
n= 0;
while ((item= lu++))
{
str= ls++;
if (n++)
pfields.append(", ");
append_identifier(thd, &pfields, item->item_name.ptr(),
strlen(item->item_name.ptr()));
// Extract exact Item value
str->copy();
pfields.append(str->ptr());
str->mem_free();
}
/*
Clear the SET string list once the SET command is reconstructed
as we donot require the list anymore.
*/
thd->lex->load_set_str_list.empty();
}
p= pfields.c_ptr_safe();
pl= strlen(p);
if (!(load_data_query= (char *)thd->alloc(lle.get_query_buffer_length() + 1 + pl)))
return TRUE;
lle.print_query(FALSE, ex->cs ? ex->cs->csname : NULL,
load_data_query, &end,
&fname_start, &fname_end);
strcpy(end, p);
end += pl;
Execute_load_query_log_event
e(thd, load_data_query, end-load_data_query,
static_cast<uint>(fname_start - load_data_query - 1),
static_cast<uint>(fname_end - load_data_query),
(duplicates == DUP_REPLACE) ? binary_log::LOAD_DUP_REPLACE :
(thd->lex->is_ignore() ? binary_log::LOAD_DUP_IGNORE :
binary_log::LOAD_DUP_ERROR),
transactional_table, FALSE, FALSE, errcode);
return mysql_bin_log.write_event(&e);
}
#endif
/****************************************************************************
** Read of rows of fixed size + optional garbage + optional newline
****************************************************************************/
static int
read_fixed_length(THD *thd, COPY_INFO &info, TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values, READ_INFO &read_info,
ulong skip_lines)
{
List_iterator_fast<Item> it(fields_vars);
TABLE *table= table_list->table;
bool err;
DBUG_ENTER("read_fixed_length");
while (!read_info.read_fixed_length())
{
if (thd->killed)
{
thd->send_kill_message();
DBUG_RETURN(1);
}
if (skip_lines)
{
/*
We could implement this with a simple seek if:
- We are not using DATA INFILE LOCAL
- escape character is ""
- line starting prefix is ""
*/
skip_lines--;
continue;
}
it.rewind();
uchar *pos=read_info.row_start;
restore_record(table, s->default_values);
/*
Check whether default values of the fields not specified in column list
are correct or not.
*/
if (validate_default_values_of_unset_fields(thd, table))
{
read_info.error= true;
break;
}
Item *item;
while ((item= it++))
{
/*
There is no variables in fields_vars list in this format so
this conversion is safe (no need to check for STRING_ITEM).
*/
DBUG_ASSERT(item->real_item()->type() == Item::FIELD_ITEM);
Item_field *sql_field= static_cast<Item_field*>(item->real_item());
Field *field= sql_field->field;
if (field == table->next_number_field)
table->auto_increment_field_not_null= TRUE;
/*
No fields specified in fields_vars list can be null in this format.
Mark field as not null, we should do this for each row because of
restore_record...
*/
field->set_notnull();
if (pos == read_info.row_end)
{
thd->cuted_fields++; /* Not enough fields */
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_TOO_FEW_RECORDS,
ER(ER_WARN_TOO_FEW_RECORDS),
thd->get_stmt_da()->current_row_for_condition());
if (field->type() == FIELD_TYPE_TIMESTAMP && !field->maybe_null())
{
// Specific of TIMESTAMP NOT NULL: set to CURRENT_TIMESTAMP.
Item_func_now_local::store_in(field);
}
}
else
{
uint length;
uchar save_chr;
if ((length=(uint) (read_info.row_end-pos)) >
field->field_length)
length=field->field_length;
save_chr=pos[length]; pos[length]='\0'; // Safeguard aganst malloc
field->store((char*) pos,length,read_info.read_charset);
pos[length]=save_chr;
if ((pos+=length) > read_info.row_end)
pos= read_info.row_end; /* Fills rest with space */
}
}
if (pos != read_info.row_end)
{
thd->cuted_fields++; /* To long row */
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_TOO_MANY_RECORDS,
ER(ER_WARN_TOO_MANY_RECORDS),
thd->get_stmt_da()->current_row_for_condition());
}
if (thd->killed ||
fill_record_n_invoke_before_triggers(thd, set_fields, set_values,
table, TRG_EVENT_INSERT,
table->s->fields))
DBUG_RETURN(1);
switch (table_list->view_check_option(thd)) {
case VIEW_CHECK_SKIP:
read_info.next_line();
goto continue_loop;
case VIEW_CHECK_ERROR:
DBUG_RETURN(-1);
}
err= write_record(thd, table, &info, NULL);
table->auto_increment_field_not_null= FALSE;
if (err)
DBUG_RETURN(1);
/*
We don't need to reset auto-increment field since we are restoring
its default value at the beginning of each loop iteration.
*/
if (read_info.next_line()) // Skip to next line
break;
if (read_info.line_cuted)
{
thd->cuted_fields++; /* To long row */
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_TOO_MANY_RECORDS,
ER(ER_WARN_TOO_MANY_RECORDS),
thd->get_stmt_da()->current_row_for_condition());
}
thd->get_stmt_da()->inc_current_row_for_condition();
continue_loop:;
}
DBUG_RETURN(MY_TEST(read_info.error));
}
class Field_tmp_nullability_guard
{
public:
explicit Field_tmp_nullability_guard(Item *item)
:m_field(NULL)
{
if (item->type() == Item::FIELD_ITEM)
{
m_field= ((Item_field *) item)->field;
/*
Enable temporary nullability for items that corresponds
to table fields.
*/
m_field->set_tmp_nullable();
}
}
~Field_tmp_nullability_guard()
{
if (m_field)
m_field->reset_tmp_nullable();
}
private:
Field *m_field;
};
static int
read_sep_field(THD *thd, COPY_INFO &info, TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values, READ_INFO &read_info,
const String &enclosed, ulong skip_lines)
{
List_iterator_fast<Item> it(fields_vars);
Item *item;
TABLE *table= table_list->table;
size_t enclosed_length;
bool err;
DBUG_ENTER("read_sep_field");
enclosed_length=enclosed.length();
for (;;it.rewind())
{
if (thd->killed)
{
thd->send_kill_message();
DBUG_RETURN(1);
}
restore_record(table, s->default_values);
/*
Check whether default values of the fields not specified in column list
are correct or not.
*/
if (validate_default_values_of_unset_fields(thd, table))
{
read_info.error= true;
break;
}
while ((item= it++))
{
uint length;
uchar *pos;
Item *real_item;
if (read_info.read_field())
break;
/* If this line is to be skipped we don't want to fill field or var */
if (skip_lines)
continue;
pos=read_info.row_start;
length=(uint) (read_info.row_end-pos);
real_item= item->real_item();
Field_tmp_nullability_guard fld_tmp_nullability_guard(real_item);
if ((!read_info.enclosed &&
(enclosed_length && length == 4 &&
!memcmp(pos, STRING_WITH_LEN("NULL")))) ||
(length == 1 && read_info.found_null))
{
if (real_item->type() == Item::FIELD_ITEM)
{
Field *field= ((Item_field *)real_item)->field;
if (field->reset()) // Set to 0
{
my_error(ER_WARN_NULL_TO_NOTNULL, MYF(0), field->field_name,
thd->get_stmt_da()->current_row_for_condition());
DBUG_RETURN(1);
}
if (!field->real_maybe_null() &&
field->type() == FIELD_TYPE_TIMESTAMP)
{
// Specific of TIMESTAMP NOT NULL: set to CURRENT_TIMESTAMP.
Item_func_now_local::store_in(field);
}
else
{
/*
Set field to NULL. Later we will clear temporary nullability flag
and check NOT NULL constraint.
*/
field->set_null();
}
}
else if (item->type() == Item::STRING_ITEM)
{
DBUG_ASSERT(NULL != dynamic_cast<Item_user_var_as_out_param*>(item));
((Item_user_var_as_out_param *)item)->set_null_value(
read_info.read_charset);
}
continue;
}
if (real_item->type() == Item::FIELD_ITEM)
{
Field *field= ((Item_field *)real_item)->field;
field->set_notnull();
read_info.row_end[0]=0; // Safe to change end marker
if (field == table->next_number_field)
table->auto_increment_field_not_null= TRUE;
field->store((char*) pos, length, read_info.read_charset);
}
else if (item->type() == Item::STRING_ITEM)
{
DBUG_ASSERT(NULL != dynamic_cast<Item_user_var_as_out_param*>(item));
((Item_user_var_as_out_param *)item)->set_value((char*) pos, length,
read_info.read_charset);
}
}
if (thd->is_error())
read_info.error= true;
if (read_info.error)
break;
if (skip_lines)
{
skip_lines--;
continue;
}
if (item)
{
/* Have not read any field, thus input file is simply ended */
if (item == fields_vars.head())
break;
for (; item ; item= it++)
{
Item *real_item= item->real_item();
if (real_item->type() == Item::FIELD_ITEM)
{
Field *field= ((Item_field *)real_item)->field;
/*
We set to 0. But if the field is DEFAULT NULL, the "null bit"
turned on by restore_record() above remains so field will be NULL.
*/
if (field->reset())
{
my_error(ER_WARN_NULL_TO_NOTNULL, MYF(0),field->field_name,
thd->get_stmt_da()->current_row_for_condition());
DBUG_RETURN(1);
}
if (field->type() == FIELD_TYPE_TIMESTAMP && !field->maybe_null())
// Specific of TIMESTAMP NOT NULL: set to CURRENT_TIMESTAMP.
Item_func_now_local::store_in(field);
/*
QQ: We probably should not throw warning for each field.
But how about intention to always have the same number
of warnings in THD::cuted_fields (and get rid of cuted_fields
in the end ?)
*/
thd->cuted_fields++;
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_TOO_FEW_RECORDS,
ER(ER_WARN_TOO_FEW_RECORDS),
thd->get_stmt_da()->current_row_for_condition());
}
else if (item->type() == Item::STRING_ITEM)
{
DBUG_ASSERT(NULL != dynamic_cast<Item_user_var_as_out_param*>(item));
((Item_user_var_as_out_param *)item)->set_null_value(
read_info.read_charset);
}
}
}
if (thd->killed ||
fill_record_n_invoke_before_triggers(thd, set_fields, set_values,
table, TRG_EVENT_INSERT,
table->s->fields))
DBUG_RETURN(1);
if (!table->triggers)
{
/*
If there is no trigger for the table then check the NOT NULL constraint
for every table field.
For the table that has BEFORE-INSERT trigger installed checking for
NOT NULL constraint is done inside function
fill_record_n_invoke_before_triggers() after all trigger instructions
has been executed.
*/
it.rewind();
while ((item= it++))
{
Item *real_item= item->real_item();
if (real_item->type() == Item::FIELD_ITEM)
((Item_field *) real_item)->field->check_constraints(ER_WARN_NULL_TO_NOTNULL);
}
}
if (thd->is_error())
DBUG_RETURN(1);
switch (table_list->view_check_option(thd)) {
case VIEW_CHECK_SKIP:
read_info.next_line();
goto continue_loop;
case VIEW_CHECK_ERROR:
DBUG_RETURN(-1);
}
err= write_record(thd, table, &info, NULL);
table->auto_increment_field_not_null= FALSE;
if (err)
DBUG_RETURN(1);
/*
We don't need to reset auto-increment field since we are restoring
its default value at the beginning of each loop iteration.
*/
if (read_info.next_line()) // Skip to next line
break;
if (read_info.line_cuted)
{
thd->cuted_fields++; /* To long row */
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_TOO_MANY_RECORDS, ER(ER_WARN_TOO_MANY_RECORDS),
thd->get_stmt_da()->current_row_for_condition());
if (thd->killed)
DBUG_RETURN(1);
}
thd->get_stmt_da()->inc_current_row_for_condition();
continue_loop:;
}
DBUG_RETURN(MY_TEST(read_info.error));
}
/****************************************************************************
** Read rows in xml format
****************************************************************************/
static int
read_xml_field(THD *thd, COPY_INFO &info, TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values, READ_INFO &read_info,
ulong skip_lines)
{
List_iterator_fast<Item> it(fields_vars);
Item *item;
TABLE *table= table_list->table;
const CHARSET_INFO *cs= read_info.read_charset;
DBUG_ENTER("read_xml_field");
for ( ; ; it.rewind())
{
if (thd->killed)
{
thd->send_kill_message();
DBUG_RETURN(1);
}
// read row tag and save values into tag list
if (read_info.read_xml())
break;
List_iterator_fast<XML_TAG> xmlit(read_info.taglist);
xmlit.rewind();
XML_TAG *tag= NULL;
#ifndef DBUG_OFF
DBUG_PRINT("read_xml_field", ("skip_lines=%d", (int) skip_lines));
while ((tag= xmlit++))
{
DBUG_PRINT("read_xml_field", ("got tag:%i '%s' '%s'",
tag->level, tag->field.c_ptr(),
tag->value.c_ptr()));
}
#endif
restore_record(table, s->default_values);
/*
Check whether default values of the fields not specified in column list
are correct or not.
*/
if (validate_default_values_of_unset_fields(thd, table))
{
read_info.error= true;
break;
}
while ((item= it++))
{
/* If this line is to be skipped we don't want to fill field or var */
if (skip_lines)
continue;
/* find field in tag list */
xmlit.rewind();
tag= xmlit++;
while(tag && strcmp(tag->field.c_ptr(), item->item_name.ptr()) != 0)
tag= xmlit++;
item= item->real_item();
if (!tag) // found null
{
if (item->type() == Item::FIELD_ITEM)
{
Field *field= (static_cast<Item_field*>(item))->field;
field->reset();
field->set_null();
if (field == table->next_number_field)
table->auto_increment_field_not_null= TRUE;
if (!field->maybe_null())
{
if (field->type() == FIELD_TYPE_TIMESTAMP)
// Specific of TIMESTAMP NOT NULL: set to CURRENT_TIMESTAMP.
Item_func_now_local::store_in(field);
else if (field != table->next_number_field)
field->set_warning(Sql_condition::SL_WARNING,
ER_WARN_NULL_TO_NOTNULL, 1);
}
}
else
{
DBUG_ASSERT(NULL != dynamic_cast<Item_user_var_as_out_param*>(item));
((Item_user_var_as_out_param *) item)->set_null_value(cs);
}
continue;
}
if (item->type() == Item::FIELD_ITEM)
{
Field *field= ((Item_field *)item)->field;
field->set_notnull();
if (field == table->next_number_field)
table->auto_increment_field_not_null= TRUE;
field->store((char *) tag->value.ptr(), tag->value.length(), cs);
}
else
{
DBUG_ASSERT(NULL != dynamic_cast<Item_user_var_as_out_param*>(item));
((Item_user_var_as_out_param *) item)->set_value(
(char *) tag->value.ptr(),
tag->value.length(), cs);
}
}
if (read_info.error)
break;
if (skip_lines)
{
skip_lines--;
continue;
}
if (item)
{
/* Have not read any field, thus input file is simply ended */
if (item == fields_vars.head())
break;
for ( ; item; item= it++)
{
if (item->type() == Item::FIELD_ITEM)
{
/*
QQ: We probably should not throw warning for each field.
But how about intention to always have the same number
of warnings in THD::cuted_fields (and get rid of cuted_fields
in the end ?)
*/
thd->cuted_fields++;
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_TOO_FEW_RECORDS,
ER(ER_WARN_TOO_FEW_RECORDS),
thd->get_stmt_da()->current_row_for_condition());
}
else
{
DBUG_ASSERT(NULL != dynamic_cast<Item_user_var_as_out_param*>(item));
((Item_user_var_as_out_param *)item)->set_null_value(cs);
}
}
}
if (thd->killed ||
fill_record_n_invoke_before_triggers(thd, set_fields, set_values,
table, TRG_EVENT_INSERT,
table->s->fields))
DBUG_RETURN(1);
switch (table_list->view_check_option(thd)) {
case VIEW_CHECK_SKIP:
read_info.next_line();
goto continue_loop;
case VIEW_CHECK_ERROR:
DBUG_RETURN(-1);
}
if (write_record(thd, table, &info, NULL))
DBUG_RETURN(1);
/*
We don't need to reset auto-increment field since we are restoring
its default value at the beginning of each loop iteration.
*/
thd->get_stmt_da()->inc_current_row_for_condition();
continue_loop:;
}
DBUG_RETURN(MY_TEST(read_info.error) || thd->is_error());
} /* load xml end */
/* Unescape all escape characters, mark \N as null */
char
READ_INFO::unescape(char chr)
{
/* keep this switch synchornous with the ESCAPE_CHARS macro */
switch(chr) {
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
case 'b': return '\b';
case '0': return 0; // Ascii null
case 'Z': return '\032'; // Win32 end of file
case 'N': found_null=1;
/* fall through */
default: return chr;
}
}
/*
Read a line using buffering
If last line is empty (in line mode) then it isn't outputed
*/
READ_INFO::READ_INFO(File file_par, uint tot_length, const CHARSET_INFO *cs,
const String &field_term,
const String &line_start,
const String &line_term,
const String &enclosed_par,
int escape, bool get_it_from_net, bool is_fifo)
:file(file_par), buff_length(tot_length), escape_char(escape),
found_end_of_line(false), eof(false), need_end_io_cache(false),
error(false), line_cuted(false), found_null(false), read_charset(cs)
{
/*
Field and line terminators must be interpreted as sequence of unsigned char.
Otherwise, non-ascii terminators will be negative on some platforms,
and positive on others (depending on the implementation of char).
*/
field_term_ptr=
static_cast<const uchar*>(static_cast<const void*>(field_term.ptr()));
field_term_length= field_term.length();
line_term_ptr=
static_cast<const uchar*>(static_cast<const void*>(line_term.ptr()));
line_term_length= line_term.length();
level= 0; /* for load xml */
if (line_start.length() == 0)
{
line_start_ptr=0;
start_of_line= 0;
}
else
{
line_start_ptr= line_start.ptr();
line_start_end=line_start_ptr+line_start.length();
start_of_line= 1;
}
/* If field_terminator == line_terminator, don't use line_terminator */
if (field_term_length == line_term_length &&
!memcmp(field_term_ptr,line_term_ptr,field_term_length))
{
line_term_length=0;
line_term_ptr= NULL;
}
enclosed_char= (enclosed_length=enclosed_par.length()) ?
(uchar) enclosed_par[0] : INT_MAX;
field_term_char= field_term_length ? field_term_ptr[0] : INT_MAX;
line_term_char= line_term_length ? line_term_ptr[0] : INT_MAX;
/* Set of a stack for unget if long terminators */
size_t length= max<size_t>(cs->mbmaxlen, max(field_term_length, line_term_length)) + 1;
set_if_bigger(length,line_start.length());
stack=stack_pos=(int*) sql_alloc(sizeof(int)*length);
if (!(buffer=(uchar*) my_malloc(key_memory_READ_INFO,
buff_length+1, MYF(MY_WME))))
error= true; /* purecov: inspected */
else
{
end_of_buff=buffer+buff_length;
if (init_io_cache(&cache,(get_it_from_net) ? -1 : file, 0,
(get_it_from_net) ? READ_NET :
(is_fifo ? READ_FIFO : READ_CACHE),0L,1,
MYF(MY_WME)))
{
my_free(buffer); /* purecov: inspected */
buffer= NULL;
error= true;
}
else
{
/*
init_io_cache() will not initialize read_function member
if the cache is READ_NET. So we work around the problem with a
manual assignment
*/
need_end_io_cache = 1;
#ifndef EMBEDDED_LIBRARY
if (get_it_from_net)
cache.read_function = _my_b_net_read;
if (mysql_bin_log.is_open())
cache.pre_read = cache.pre_close =
(IO_CACHE_CALLBACK) log_loaded_block;
#endif
}
}
}
READ_INFO::~READ_INFO()
{
if (need_end_io_cache)
::end_io_cache(&cache);
if (buffer != NULL)
my_free(buffer);
List_iterator<XML_TAG> xmlit(taglist);
XML_TAG *t;
while ((t= xmlit++))
delete(t);
}
/**
The logic here is similar with my_mbcharlen, except for GET and PUSH
@param[in] cs charset info
@param[in] chr the first char of sequence
@param[out] len the length of multi-byte char
*/
#define GET_MBCHARLEN(cs, chr, len) \
do { \
len= my_mbcharlen((cs), (chr)); \
if (len == 0 && my_mbmaxlenlen((cs)) == 2) \
{ \
int chr1= GET; \
if (chr1 != my_b_EOF) \
{ \
len= my_mbcharlen_2((cs), (chr), chr1); \
/* Character is gb18030 or invalid (len = 0) */ \
DBUG_ASSERT(len == 0 || len == 2 || len == 4); \
} \
if (len != 0) \
PUSH(chr1); \
} \
} while (0)
inline int READ_INFO::terminator(const uchar *ptr, size_t length)
{
int chr=0; // Keep gcc happy
size_t i;
for (i=1 ; i < length ; i++)
{
chr= GET;
if (chr != *++ptr)
{
break;
}
}
if (i == length)
return 1;
PUSH(chr);
while (i-- > 1)
PUSH(*--ptr);
return 0;
}
int READ_INFO::read_field()
{
int chr,found_enclosed_char;
uchar *to,*new_buffer;
found_null=0;
if (found_end_of_line)
return 1; // One have to call next_line
/* Skip until we find 'line_start' */
if (start_of_line)
{ // Skip until line_start
start_of_line=0;
if (find_start_of_fields())
return 1;
}
if ((chr=GET) == my_b_EOF)
{
found_end_of_line=eof=1;
return 1;
}
to=buffer;
if (chr == enclosed_char)
{
found_enclosed_char=enclosed_char;
*to++=(uchar) chr; // If error
}
else
{
found_enclosed_char= INT_MAX;
PUSH(chr);
}
for (;;)
{
while ( to < end_of_buff)
{
chr = GET;
if (chr == my_b_EOF)
goto found_eof;
if (chr == escape_char)
{
if ((chr=GET) == my_b_EOF)
{
*to++= (uchar) escape_char;
goto found_eof;
}
/*
When escape_char == enclosed_char, we treat it like we do for
handling quotes in SQL parsing -- you can double-up the
escape_char to include it literally, but it doesn't do escapes
like \n. This allows: LOAD DATA ... ENCLOSED BY '"' ESCAPED BY '"'
with data like: "fie""ld1", "field2"
*/
if (escape_char != enclosed_char || chr == escape_char)
{
*to++ = (uchar) unescape((char) chr);
continue;
}
PUSH(chr);
chr= escape_char;
}
if (chr == line_term_char && found_enclosed_char == INT_MAX)
{
if (terminator(line_term_ptr,line_term_length))
{ // Maybe unexpected linefeed
enclosed=0;
found_end_of_line=1;
row_start=buffer;
row_end= to;
return 0;
}
}
if (chr == found_enclosed_char)
{
if ((chr=GET) == found_enclosed_char)
{ // Remove dupplicated
*to++ = (uchar) chr;
continue;
}
// End of enclosed field if followed by field_term or line_term
if (chr == my_b_EOF ||
(chr == line_term_char && terminator(line_term_ptr,
line_term_length)))
{ // Maybe unexpected linefeed
enclosed=1;
found_end_of_line=1;
row_start=buffer+1;
row_end= to;
return 0;
}
if (chr == field_term_char &&
terminator(field_term_ptr,field_term_length))
{
enclosed=1;
row_start=buffer+1;
row_end= to;
return 0;
}
/*
The string didn't terminate yet.
Store back next character for the loop
*/
PUSH(chr);
/* copy the found term character to 'to' */
chr= found_enclosed_char;
}
else if (chr == field_term_char && found_enclosed_char == INT_MAX)
{
if (terminator(field_term_ptr,field_term_length))
{
enclosed=0;
row_start=buffer;
row_end= to;
return 0;
}
}
uint ml;
GET_MBCHARLEN(read_charset, chr, ml);
if (ml == 0)
{
*to= '\0';
my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
read_charset->csname, buffer);
error= true;
return 1;
}
if (ml > 1 &&
to + ml <= end_of_buff)
{
uchar* p= to;
*to++ = chr;
for (uint i= 1; i < ml; i++)
{
chr= GET;
if (chr == my_b_EOF)
{
/*
Need to back up the bytes already ready from illformed
multi-byte char
*/
to-= i;
goto found_eof;
}
*to++ = chr;
}
if (my_ismbchar(read_charset,
(const char *)p,
(const char *)to))
continue;
for (uint i= 0; i < ml; i++)
PUSH(*--to);
chr= GET;
}
else if (ml > 1)
{
// Buffer is too small, exit while loop, and reallocate.
PUSH(chr);
break;
}
*to++ = (uchar) chr;
}
/*
** We come here if buffer is too small. Enlarge it and continue
*/
if (!(new_buffer=(uchar*) my_realloc(key_memory_READ_INFO,
(char*) buffer,buff_length+1+IO_SIZE,
MYF(MY_WME))))
return (error= true);
to=new_buffer + (to-buffer);
buffer=new_buffer;
buff_length+=IO_SIZE;
end_of_buff=buffer+buff_length;
}
found_eof:
enclosed=0;
found_end_of_line=eof=1;
row_start=buffer;
row_end=to;
return 0;
}
/*
Read a row with fixed length.
NOTES
The row may not be fixed size on disk if there are escape
characters in the file.
IMPLEMENTATION NOTE
One can't use fixed length with multi-byte charset **
RETURN
0 ok
1 error
*/
int READ_INFO::read_fixed_length()
{
int chr;
uchar *to;
if (found_end_of_line)
return 1; // One have to call next_line
if (start_of_line)
{ // Skip until line_start
start_of_line=0;
if (find_start_of_fields())
return 1;
}
to=row_start=buffer;
while (to < end_of_buff)
{
if ((chr=GET) == my_b_EOF)
goto found_eof;
if (chr == escape_char)
{
if ((chr=GET) == my_b_EOF)
{
*to++= (uchar) escape_char;
goto found_eof;
}
*to++ =(uchar) unescape((char) chr);
continue;
}
if (chr == line_term_char)
{
if (terminator(line_term_ptr,line_term_length))
{ // Maybe unexpected linefeed
found_end_of_line=1;
row_end= to;
return 0;
}
}
*to++ = (uchar) chr;
}
row_end=to; // Found full line
return 0;
found_eof:
found_end_of_line=eof=1;
row_start=buffer;
row_end=to;
return to == buffer ? 1 : 0;
}
int READ_INFO::next_line()
{
line_cuted=0;
start_of_line= line_start_ptr != 0;
if (found_end_of_line || eof)
{
found_end_of_line=0;
return eof;
}
found_end_of_line=0;
if (!line_term_length)
return 0; // No lines
for (;;)
{
int chr = GET;
uint ml;
if (chr == my_b_EOF)
{
eof= 1;
return 1;
}
GET_MBCHARLEN(read_charset, chr, ml);
if (ml > 1)
{
for (uint i=1;
chr != my_b_EOF && i < ml;
i++)
chr = GET;
if (chr == escape_char)
continue;
}
if (chr == my_b_EOF)
{
eof=1;
return 1;
}
if (chr == escape_char)
{
line_cuted=1;
if (GET == my_b_EOF)
return 1;
continue;
}
if (chr == line_term_char && terminator(line_term_ptr,line_term_length))
return 0;
line_cuted=1;
}
}
bool READ_INFO::find_start_of_fields()
{
int chr;
try_again:
do
{
if ((chr=GET) == my_b_EOF)
{
found_end_of_line=eof=1;
return 1;
}
} while ((char) chr != line_start_ptr[0]);
for (const char *ptr=line_start_ptr+1 ; ptr != line_start_end ; ptr++)
{
chr=GET; // Eof will be checked later
if ((char) chr != *ptr)
{ // Can't be line_start
PUSH(chr);
while (--ptr != line_start_ptr)
{ // Restart with next char
PUSH( *ptr);
}
goto try_again;
}
}
return 0;
}
/*
Clear taglist from tags with a specified level
*/
int READ_INFO::clear_level(int level_arg)
{
DBUG_ENTER("READ_INFO::read_xml clear_level");
List_iterator<XML_TAG> xmlit(taglist);
xmlit.rewind();
XML_TAG *tag;
while ((tag= xmlit++))
{
if(tag->level >= level_arg)
{
xmlit.remove();
delete tag;
}
}
DBUG_RETURN(0);
}
/*
Convert an XML entity to Unicode value.
Return -1 on error;
*/
static int
my_xml_entity_to_char(const char *name, size_t length)
{
if (length == 2)
{
if (!memcmp(name, "gt", length))
return '>';
if (!memcmp(name, "lt", length))
return '<';
}
else if (length == 3)
{
if (!memcmp(name, "amp", length))
return '&';
}
else if (length == 4)
{
if (!memcmp(name, "quot", length))
return '"';
if (!memcmp(name, "apos", length))
return '\'';
}
return -1;
}
/**
@brief Convert newline, linefeed, tab to space
@param chr character
@details According to the "XML 1.0" standard,
only space (#x20) characters, carriage returns,
line feeds or tabs are considered as spaces.
Convert all of them to space (#x20) for parsing simplicity.
*/
static int
my_tospace(int chr)
{
return (chr == '\t' || chr == '\r' || chr == '\n') ? ' ' : chr;
}
/*
Read an xml value: handle multibyte and xml escape
*/
int READ_INFO::read_value(int delim, String *val)
{
int chr;
String tmp;
for (chr= GET; my_tospace(chr) != delim && chr != my_b_EOF;)
{
uint ml;
GET_MBCHARLEN(read_charset, chr, ml);
if (ml == 0)
{
chr= my_b_EOF;
val->length(0);
return chr;
}
if (ml > 1)
{
DBUG_PRINT("read_xml",("multi byte"));
for (uint i= 1; i < ml; i++)
{
val->append(chr);
/*
Don't use my_tospace() in the middle of a multi-byte character
TODO: check that the multi-byte sequence is valid.
*/
chr= GET;
if (chr == my_b_EOF)
return chr;
}
}
if(chr == '&')
{
tmp.length(0);
for (chr= my_tospace(GET) ; chr != ';' ; chr= my_tospace(GET))
{
if (chr == my_b_EOF)
return chr;
tmp.append(chr);
}
if ((chr= my_xml_entity_to_char(tmp.ptr(), tmp.length())) >= 0)
val->append(chr);
else
{
val->append('&');
val->append(tmp);
val->append(';');
}
}
else
val->append(chr);
chr= GET;
}
return my_tospace(chr);
}
/*
Read a record in xml format
tags and attributes are stored in taglist
when tag set in ROWS IDENTIFIED BY is closed, we are ready and return
*/
int READ_INFO::read_xml()
{
DBUG_ENTER("READ_INFO::read_xml");
int chr, chr2, chr3;
int delim= 0;
String tag, attribute, value;
bool in_tag= false;
tag.length(0);
attribute.length(0);
value.length(0);
for (chr= my_tospace(GET); chr != my_b_EOF ; )
{
switch(chr){
case '<': /* read tag */
/* TODO: check if this is a comment <!-- comment --> */
chr= my_tospace(GET);
if(chr == '!')
{
chr2= GET;
chr3= GET;
if(chr2 == '-' && chr3 == '-')
{
chr2= 0;
chr3= 0;
chr= my_tospace(GET);
while(chr != '>' || chr2 != '-' || chr3 != '-')
{
if(chr == '-')
{
chr3= chr2;
chr2= chr;
}
else if (chr2 == '-')
{
chr2= 0;
chr3= 0;
}
chr= my_tospace(GET);
if (chr == my_b_EOF)
goto found_eof;
}
break;
}
}
tag.length(0);
while(chr != '>' && chr != ' ' && chr != '/' && chr != my_b_EOF)
{
if(chr != delim) /* fix for the '<field name =' format */
tag.append(chr);
chr= my_tospace(GET);
}
// row tag should be in ROWS IDENTIFIED BY '<row>' - stored in line_term
if((tag.length() == line_term_length -2) &&
(memcmp(tag.ptr(), line_term_ptr + 1, tag.length()) == 0))
{
DBUG_PRINT("read_xml", ("start-of-row: %i %s %s",
level,tag.c_ptr_safe(), line_term_ptr));
}
if(chr == ' ' || chr == '>')
{
level++;
clear_level(level + 1);
}
if (chr == ' ')
in_tag= true;
else
in_tag= false;
break;
case ' ': /* read attribute */
while(chr == ' ') /* skip blanks */
chr= my_tospace(GET);
if(!in_tag)
break;
while(chr != '=' && chr != '/' && chr != '>' && chr != my_b_EOF)
{
attribute.append(chr);
chr= my_tospace(GET);
}
break;
case '>': /* end tag - read tag value */
in_tag= false;
chr= read_value('<', &value);
if(chr == my_b_EOF)
goto found_eof;
/* save value to list */
if(tag.length() > 0 && value.length() > 0)
{
DBUG_PRINT("read_xml", ("lev:%i tag:%s val:%s",
level,tag.c_ptr_safe(), value.c_ptr_safe()));
taglist.push_front( new XML_TAG(level, tag, value));
}
tag.length(0);
value.length(0);
attribute.length(0);
break;
case '/': /* close tag */
chr= my_tospace(GET);
/* Decrease the 'level' only when (i) It's not an */
/* (without space) empty tag i.e. <tag/> or, (ii) */
/* It is of format <row col="val" .../> */
if(chr != '>' || in_tag)
{
level--;
in_tag= false;
}
if(chr != '>') /* if this is an empty tag <tag /> */
tag.length(0); /* we should keep tag value */
while(chr != '>' && chr != my_b_EOF)
{
tag.append(chr);
chr= my_tospace(GET);
}
if((tag.length() == line_term_length -2) &&
(memcmp(tag.ptr(), line_term_ptr + 1, tag.length()) == 0))
{
DBUG_PRINT("read_xml", ("found end-of-row %i %s",
level, tag.c_ptr_safe()));
DBUG_RETURN(0); //normal return
}
chr= my_tospace(GET);
break;
case '=': /* attribute name end - read the value */
//check for tag field and attribute name
if(!memcmp(tag.c_ptr_safe(), STRING_WITH_LEN("field")) &&
!memcmp(attribute.c_ptr_safe(), STRING_WITH_LEN("name")))
{
/*
this is format <field name="xx">xx</field>
where actual fieldname is in attribute
*/
delim= my_tospace(GET);
tag.length(0);
attribute.length(0);
chr= '<'; /* we pretend that it is a tag */
level--;
break;
}
//check for " or '
chr= GET;
if (chr == my_b_EOF)
goto found_eof;
if(chr == '"' || chr == '\'')
{
delim= chr;
}
else
{
delim= ' '; /* no delimiter, use space */
PUSH(chr);
}
chr= read_value(delim, &value);
if(attribute.length() > 0 && value.length() > 0)
{
DBUG_PRINT("read_xml", ("lev:%i att:%s val:%s\n",
level + 1,
attribute.c_ptr_safe(),
value.c_ptr_safe()));
taglist.push_front(new XML_TAG(level + 1, attribute, value));
}
attribute.length(0);
value.length(0);
if (chr != ' ')
chr= my_tospace(GET);
break;
default:
chr= my_tospace(GET);
} /* end switch */
} /* end while */
found_eof:
DBUG_PRINT("read_xml",("Found eof"));
eof= 1;
DBUG_RETURN(1);
}
| 29.428824 | 109 | 0.572197 | [
"object"
] |
d90fba0c737fb8631cca9831dfe20452e2ef0e37 | 3,857 | cpp | C++ | libdariadb/storage/pages/index.cpp | lysevi/memseries | e9c2e34b0723ea6e040ecdcce3d57153d32b061e | [
"Apache-2.0"
] | 24 | 2016-06-14T20:09:37.000Z | 2021-03-21T23:11:52.000Z | libdariadb/storage/pages/index.cpp | lysevi/dariadb | e9c2e34b0723ea6e040ecdcce3d57153d32b061e | [
"Apache-2.0"
] | 326 | 2016-03-18T08:04:33.000Z | 2017-07-03T08:47:37.000Z | libdariadb/storage/pages/index.cpp | lysevi/dariadb | e9c2e34b0723ea6e040ecdcce3d57153d32b061e | [
"Apache-2.0"
] | 8 | 2016-06-16T14:28:02.000Z | 2022-01-20T04:19:35.000Z | #ifdef MSVC
#define _CRT_SECURE_NO_WARNINGS // for fopen
#endif
#include <libdariadb/storage/bloom_filter.h>
#include <libdariadb/storage/pages/index.h>
#include <algorithm>
#include <cstring>
#include <fstream>
using namespace dariadb;
using namespace dariadb::storage;
using dariadb::utils::inInterval;
inline bool check_index_rec(IndexReccord &it, dariadb::Time from, dariadb::Time to) {
return inInterval(from, to, it.stat.minTime) || inInterval(from, to, it.stat.maxTime) ||
inInterval(it.stat.minTime, it.stat.maxTime, from) ||
inInterval(it.stat.minTime, it.stat.maxTime, to);
}
inline bool check_blooms(const IndexReccord &_index_it, dariadb::Id id,
dariadb::Flag flag) {
auto id_check_result = false;
id_check_result = _index_it.target_id == id;
auto flag_bloom_result = false;
if (flag == dariadb::Flag(0) ||
dariadb::storage::bloom_check(_index_it.stat.flag_bloom, flag)) {
flag_bloom_result = true;
}
return id_check_result && flag_bloom_result;
}
PageIndex::~PageIndex() {}
PageIndex_ptr PageIndex::open(const std::string &_filename) {
PageIndex_ptr res = std::make_shared<PageIndex>();
res->filename = _filename;
res->iheader = readIndexFooter(_filename);
return res;
}
ChunkLinkList PageIndex::get_chunks_links(const dariadb::IdArray &ids, dariadb::Time from,
dariadb::Time to, dariadb::Flag flag) {
ChunkLinkList result;
IndexReccord *records = new IndexReccord[this->iheader.recs_count];
auto index_file = std::fopen(filename.c_str(), "rb");
if (index_file == nullptr) {
delete[] records;
THROW_EXCEPTION("can`t open file ", this->filename);
}
auto readed = std::fread(records, sizeof(IndexReccord), iheader.recs_count, index_file);
if (readed < iheader.recs_count) {
delete[] records;
THROW_EXCEPTION("engine: index read error - ", this->filename);
}
std::fclose(index_file);
for (uint32_t pos = 0; pos < this->iheader.recs_count; ++pos) {
auto _index_it = records[pos];
if (check_index_rec(_index_it, from, to)) {
bool bloom_result = false;
if (ids.size() == size_t(0)) {
bloom_result = true;
} else {
for (auto i : ids) {
bloom_result = check_blooms(_index_it, i, flag);
if (bloom_result) {
break;
}
}
}
if (bloom_result) {
ChunkLink sub_result;
sub_result.id = _index_it.chunk_id;
sub_result.index_rec_number = pos;
sub_result.minTime = _index_it.stat.minTime;
sub_result.maxTime = _index_it.stat.maxTime;
sub_result.meas_id = _index_it.target_id;
result.push_back(sub_result);
}
}
}
delete[] records;
return result;
}
std::vector<IndexReccord> PageIndex::readReccords() {
std::vector<IndexReccord> records;
records.resize(iheader.recs_count);
auto index_file = std::fopen(filename.c_str(), "rb");
if (index_file == nullptr) {
THROW_EXCEPTION("can`t open file ", this->filename);
}
auto readed =
std::fread(records.data(), sizeof(IndexReccord), iheader.recs_count, index_file);
if (readed < iheader.recs_count) {
THROW_EXCEPTION("engine: index read error - ", this->filename);
}
std::fclose(index_file);
return records;
}
IndexFooter PageIndex::readIndexFooter(std::string ifile) {
std::ifstream istream;
istream.open(ifile, std::fstream::in | std::fstream::binary);
if (!istream.is_open()) {
THROW_EXCEPTION("can't open file. filename=", ifile);
}
istream.seekg(-(int)sizeof(IndexFooter), istream.end);
IndexFooter result;
memset(&result, 0, sizeof(IndexFooter));
istream.read((char *)&result, sizeof(IndexFooter));
istream.close();
if (!result.check()) {
THROW_EXCEPTION("IndexFooter magic number check.");
}
return result;
}
| 31.614754 | 90 | 0.670469 | [
"vector"
] |
d9108aa52072d727491fb58e3da58878408d9332 | 7,220 | cpp | C++ | tests/unit/src/utility.cpp | carlbrown/scraps | 78925a738540415ec04b9cbe23cb319421f44978 | [
"Apache-2.0"
] | null | null | null | tests/unit/src/utility.cpp | carlbrown/scraps | 78925a738540415ec04b9cbe23cb319421f44978 | [
"Apache-2.0"
] | null | null | null | tests/unit/src/utility.cpp | carlbrown/scraps | 78925a738540415ec04b9cbe23cb319421f44978 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2016 BitTorrent 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 "gtest.h"
#include <scraps/utility.h>
#if SCRAPS_MACOS
#import <Foundation/NSProcessInfo.h>
#endif
#include <array>
using namespace scraps;
TEST(utility, Clamp) {
EXPECT_EQ(Clamp(5l, 0, 10), 5l);
EXPECT_EQ(Clamp(5l, 6, 10), 6l);
EXPECT_EQ(Clamp(5l, 0, 5), 5l);
EXPECT_EQ(Clamp(0.25, 0, 5), 0.25);
EXPECT_EQ(Clamp(1, 0.0, 5.0), 1.0);
EXPECT_EQ(Clamp(-0.5, -1.0, 5.0), -0.5);
}
TEST(utility, JSONEscape) { ASSERT_EQ("asd\\\\ \\\"asd\\u0009", JSONEscape("asd\\ \"asd\t")); };
TEST(utility, HexToDec) {
static_assert(HexToDec('0') == 0, "test failed");
static_assert(HexToDec('a') == 10, "test failed");
static_assert(HexToDec('f') == 15, "test failed");
static_assert(HexToDec('A') == 10, "test failed");
static_assert(HexToDec('F') == 15, "test failed");
static_assert(HexToDec('g') == -1, "test failed");
static_assert(HexToDec('-') == -1, "test failed");
static_assert(HexToDec(' ') == -1, "test failed");
}
TEST(utility, DecToHex) {
static_assert(DecToHex(0) == '0', "test failed");
static_assert(DecToHex(10) == 'a', "test failed");
static_assert(DecToHex(15) == 'f', "test failed");
static_assert(DecToHex(-1) == -1, "test failed");
static_assert(DecToHex(17) == -1, "test failed");
static_assert(DecToHex(20) == -1, "test failed");
}
TEST(utility, ToBytes) {
{
std::string str{"AB"};
std::array<scraps::Byte, 1> expected = {scraps::Byte{0xAB}};
std::array<scraps::Byte, 1> actual{};
EXPECT_TRUE(ToBytes(str, actual));
EXPECT_EQ(expected, actual);
}
{
std::string str{"0xAB"};
std::array<scraps::Byte, 1> expected = {scraps::Byte{0xAB}};
std::array<scraps::Byte, 1> actual{};
EXPECT_TRUE(ToBytes(str, actual));
EXPECT_EQ(expected, actual);
}
{
// differing sizes
std::string str{"ABCDEF"};
std::array<scraps::Byte, 2> actual{};
EXPECT_FALSE(ToBytes(str, actual));
}
{
// invalid characters
std::string str{"hello world!"};
std::array<scraps::Byte, 6> actual{};
EXPECT_FALSE(ToBytes(str, actual));
}
{
// zero length
std::string str{};
std::array<scraps::Byte, 0> expected{};
std::array<scraps::Byte, 0> actual{};
EXPECT_TRUE(ToBytes(str, actual));
EXPECT_EQ(expected, actual);
}
}
TEST(utility, ToHex) {
std::array<scraps::Byte, 8> bytes = {
scraps::Byte{0x01}, scraps::Byte{0x23}, scraps::Byte{0x45}, scraps::Byte{0x67},
scraps::Byte{0x89}, scraps::Byte{0xAB}, scraps::Byte{0xCD}, scraps::Byte{0xEF},
};
EXPECT_EQ(ToHex(bytes), "0123456789abcdef");
uint8_t dims[3][3] = {{0x01, 0x23, 0x45}, {0x67, 0x89, 0xAB}, {0xCD, 0xEF, 0x01}};
EXPECT_EQ(ToHex(gsl::as_span(dims)), "0123456789abcdef01");
uint8_t(*dynDims)[3] = dims;
EXPECT_EQ(ToHex(gsl::as_span(dynDims, 3)), "0123456789abcdef01");
}
TEST(utility, PhysicalMemory) {
#if SCRAPS_MACOS
EXPECT_EQ(PhysicalMemory(), [NSProcessInfo processInfo].physicalMemory);
#endif
EXPECT_GT(PhysicalMemory(), 0);
}
TEST(utility, NonatomicIteration) {
std::vector<int> numbers = {1, 2, 3, 4};
NonatomicIteration(numbers, [&](int x) {
if (x == 2) {
numbers.erase(numbers.begin() + 2);
}
EXPECT_NE(x, 3);
if (x == 4) {
numbers.push_back(5);
}
});
EXPECT_EQ(numbers.size(), 4);
EXPECT_EQ(numbers, std::vector<int>({1, 2, 4, 5}));
}
TEST(utility, Trim) {
std::string s1(" \t\r\n ");
std::string s2(" \r\nc");
std::string s3("c \t");
std::string s4(" \rc ");
EXPECT_EQ(gsl::to_string(Trim(gsl::string_span<>(s1))), std::string{""});
EXPECT_EQ(gsl::to_string(Trim(gsl::string_span<>(s2))), std::string{"c"});
EXPECT_EQ(gsl::to_string(Trim(gsl::string_span<>(s3))), std::string{"c"});
EXPECT_EQ(gsl::to_string(Trim(gsl::string_span<>(s4))), std::string{"c"});
}
TEST(utility, URLEncode) {
EXPECT_EQ("gro%C3%9Fp%C3%B6sna", URLEncode("großpösna"));
EXPECT_EQ("-_.+", URLEncode("-_. "));
};
TEST(utility, URLDecode) {
EXPECT_EQ("großpösna", URLDecode("gro%C3%9Fp%C3%B6sna"));
EXPECT_EQ("-_. ", URLDecode("-_.+"));
};
TEST(utility, ParseAddressAndPort) {
{
auto result = ParseAddressAndPort("google.com:443", 80);
EXPECT_EQ(std::get<0>(result), "google.com");
EXPECT_EQ(std::get<1>(result), 443);
}
{
auto result = ParseAddressAndPort("google.com", 80);
EXPECT_EQ(std::get<0>(result), "google.com");
EXPECT_EQ(std::get<1>(result), 80);
}
};
TEST(utility, Demangle) {
EXPECT_EQ(Demangle(typeid(scraps::GenericByte).name()), "scraps::GenericByte");
}
TEST(utility, ByteFromFile) {
char path[] = "tempfile-XXXXXX";
int fd = mkstemp(path);
FILE* f = fdopen(fd, "w");
fprintf(f, "test");
fclose(f);
auto _ = gsl::finally([&] { unlink(path); });
auto bytes = BytesFromFile(path);
ASSERT_TRUE(bytes);
EXPECT_EQ(bytes->size(), 4);
EXPECT_EQ(memcmp(bytes->data(), "test", std::min<size_t>(bytes->size(), 4)), 0);
}
TEST(utility, CaseInsensitiveEquals) {
EXPECT_TRUE(CaseInsensitiveEquals("test", "test"));
EXPECT_TRUE(CaseInsensitiveEquals("test", "Test"));
EXPECT_TRUE(CaseInsensitiveEquals("test", "TEST"));
EXPECT_FALSE(CaseInsensitiveEquals("test", "test1"));
EXPECT_FALSE(CaseInsensitiveEquals("test", ""));
EXPECT_FALSE(CaseInsensitiveEquals("tes", "test"));
}
TEST(utility, Split) {
{
std::vector<std::string> v;
auto in = "foo bar"s;
Split(in.begin(), in.end(), std::back_inserter(v), ' ');
EXPECT_EQ(v, (std::vector<std::string>{"foo", "bar"}));
}
{
std::vector<std::string> v;
auto in = " foo bar"s;
Split(in.begin(), in.end(), std::back_inserter(v), ' ');
EXPECT_EQ(v, (std::vector<std::string>{"", "foo", "bar"}));
}
{
std::vector<std::string> v;
auto in = "foo bar "s;
Split(in.begin(), in.end(), std::back_inserter(v), ' ');
EXPECT_EQ(v, (std::vector<std::string>{"foo", "bar", ""}));
}
{
std::vector<std::string> v;
auto in = "foo bar "s;
Split(in.begin(), in.end(), std::back_inserter(v), ' ');
EXPECT_EQ(v, (std::vector<std::string>{"foo", "bar", "", ""}));
}
{
std::vector<std::string> v;
auto in = " "s;
Split(in.begin(), in.end(), std::back_inserter(v), ' ');
EXPECT_EQ(v, (std::vector<std::string>{"", ""}));
}
}
| 29.834711 | 96 | 0.590859 | [
"vector"
] |
d914a2edaa8fb5fa8854f3b66f13df38783b2b42 | 8,072 | cpp | C++ | DEM/Src/L2/Physics/Prop/PropTrigger.cpp | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | 2 | 2017-04-30T20:24:29.000Z | 2019-02-12T08:36:26.000Z | DEM/Src/L2/Physics/Prop/PropTrigger.cpp | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | DEM/Src/L2/Physics/Prop/PropTrigger.cpp | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | #include "PropTrigger.h"
#include <Game/Mgr/EntityManager.h>
#include <Game/GameServer.h>
#include <Scripting/Prop/PropScriptable.h>
#include <Physics/PhysicsServer.h>
#include <Physics/Level.h>
#include <Events/Subscription.h>
#include <Loading/EntityFactory.h>
#include <DB/DBServer.h>
#include <gfx2/ngfxserver2.h>
namespace Attr
{
DefineInt(TrgShapeType);
DefineFloat4(TrgShapeParams);
DefineFloat(TrgPeriod);
DefineBool(TrgEnabled);
DefineFloat(TrgTimeLastTriggered);
};
BEGIN_ATTRS_REGISTRATION(PropTrigger)
RegisterIntWithDefault(TrgShapeType, ReadOnly, (int)Physics::CShape::Sphere);
RegisterFloat4WithDefault(TrgShapeParams, ReadOnly, vector4(1.f, 1.f, 1.f, 1.f));
RegisterFloat(TrgPeriod, ReadOnly);
RegisterBool(TrgEnabled, ReadWrite);
RegisterFloat(TrgTimeLastTriggered, ReadWrite);
END_ATTRS_REGISTRATION
namespace Properties
{
ImplementRTTI(Properties::CPropTrigger, CPropTransformable);
ImplementFactory(Properties::CPropTrigger);
RegisterProperty(CPropTrigger);
using namespace Physics;
static nString OnTriggerEnter("OnTriggerEnter");
static nString OnTriggerApply("OnTriggerApply");
static nString OnTriggerLeave("OnTriggerLeave");
CPropTrigger::~CPropTrigger()
{
}
//---------------------------------------------------------------------
void CPropTrigger::GetAttributes(nArray<DB::CAttrID>& Attrs)
{
Attrs.Append(Attr::TrgShapeType);
Attrs.Append(Attr::TrgShapeParams);
Attrs.Append(Attr::TrgPeriod);
Attrs.Append(Attr::TrgEnabled);
Attrs.Append(Attr::TrgTimeLastTriggered);
CPropTransformable::GetAttributes(Attrs);
}
//---------------------------------------------------------------------
void CPropTrigger::Activate()
{
CPropTransformable::Activate();
Period = GetEntity()->Get<float>(Attr::TrgPeriod);
if (Period > 0.f) TimeLastTriggered = GetEntity()->Get<float>(Attr::TrgTimeLastTriggered);
const vector4& ShapeParams = GetEntity()->Get<vector4>(Attr::TrgShapeParams);
switch (GetEntity()->Get<int>(Attr::TrgShapeType))
{
case CShape::Box:
pCollShape = (CShape*)PhysicsSrv->CreateBoxShape(GetEntity()->Get<matrix44>(Attr::Transform),
InvalidMaterial, vector3(ShapeParams.x, ShapeParams.y, ShapeParams.z));
break;
case CShape::Sphere:
pCollShape = (CShape*)PhysicsSrv->CreateSphereShape(GetEntity()->Get<matrix44>(Attr::Transform),
InvalidMaterial, ShapeParams.x);
break;
case CShape::Capsule:
pCollShape = (CShape*)PhysicsSrv->CreateCapsuleShape(GetEntity()->Get<matrix44>(Attr::Transform),
InvalidMaterial, ShapeParams.x, ShapeParams.y);
break;
default: n_error("Entity '%s': CPropTrigger::Activate(): Shape type %d unsupported\n",
GetEntity()->GetUniqueID().CStr(),
GetEntity()->Get<int>(Attr::TrgShapeType));
}
n_assert(pCollShape);
pCollShape->SetCategoryBits(Physics::None);
pCollShape->SetCollideBits(Physics::None);
pCollShape->Attach(PhysicsSrv->GetLevel()->GetODEDynamicSpaceID()); //???here or when enabled only?
SetEnabled(GetEntity()->Get<bool>(Attr::TrgEnabled));
PROP_SUBSCRIBE_PEVENT(OnPropsActivated, CPropTrigger, OnPropsActivated);
PROP_SUBSCRIBE_PEVENT(ExposeSI, CPropTrigger, ExposeSI);
PROP_SUBSCRIBE_PEVENT(OnSave, CPropTrigger, OnSave);
PROP_SUBSCRIBE_PEVENT(OnRenderDebug, CPropTrigger, OnRenderDebug);
}
//---------------------------------------------------------------------
void CPropTrigger::Deactivate()
{
UNSUBSCRIBE_EVENT(OnPropsActivated);
UNSUBSCRIBE_EVENT(ExposeSI);
UNSUBSCRIBE_EVENT(OnSave);
UNSUBSCRIBE_EVENT(OnRenderDebug);
SetEnabled(false);
pCollShape->Detach();
pCollShape = NULL;
CPropTransformable::Deactivate();
}
//---------------------------------------------------------------------
void CPropTrigger::SetEnabled(bool Enable)
{
if (Enabled == Enable) return;
if (Enable)
{
//???reset timestamp?
//pCollShape->Attach(PhysicsSrv->GetLevel()->GetODEDynamicSpaceID());
PROP_SUBSCRIBE_PEVENT(OnBeginFrame, CPropTrigger, OnBeginFrame);
}
else
{
UNSUBSCRIBE_EVENT(OnBeginFrame);
//pCollShape->Detach();
}
Enabled = Enable;
}
//---------------------------------------------------------------------
bool CPropTrigger::OnPropsActivated(const CEventBase& Event)
{
CPropScriptable* pScriptable = GetEntity()->FindProperty<CPropScriptable>();
pScriptObj = pScriptable ? pScriptable->GetScriptObject() : NULL;
OK;
}
//---------------------------------------------------------------------
bool CPropTrigger::OnBeginFrame(const Events::CEventBase& Event)
{
nArray<Game::PEntity> *pInsideNow, *pInsideLastFrame;
if (SwapArrays)
{
pInsideNow = &EntitiesInsideLastFrame;
pInsideLastFrame = &EntitiesInsideNow;
}
else
{
pInsideNow = &EntitiesInsideNow;
pInsideLastFrame = &EntitiesInsideLastFrame;
}
pCollShape->SetCategoryBits(Physics::Trigger);
pCollShape->SetCollideBits(Physics::Dynamic); //!!!later set Trigger bit only on entities who want to collide with trigger!
nArray<CContactPoint> Contacts;
pCollShape->Collide(Physics::CFilterSet(), Contacts);
pCollShape->SetCategoryBits(Physics::None);
pCollShape->SetCollideBits(Physics::None);
uint Stamp = PhysicsSrv->GetUniqueStamp();
pInsideNow->Clear();
for (int i = 0; i < Contacts.Size(); i++)
{
Physics::CEntity* pPhysEnt = Contacts[i].GetEntity();
if (pPhysEnt && pPhysEnt->GetStamp() != Stamp)
{
pPhysEnt->SetStamp(Stamp);
Game::CEntity* pEnt = EntityMgr->GetEntityByID(pPhysEnt->GetUserData());
if (pEnt)
{
pInsideNow->Append(pEnt); //???!!!sort to faster search?!
if (!pInsideLastFrame->Contains(pEnt))
{
if (pScriptObj)
{
//???notify pEnt too by local or even global event?
pScriptObj->RunFunctionData(OnTriggerEnter.Get(), nString(pEnt->GetUniqueID().CStr()));
//???here or from OnTriggerEnter if needed for this trigger?
//pScriptObj->RunFunctionData(OnTriggerApply, nString(pEnt->GetUniqueID().CStr()))
}
}
}
}
}
for (int i = 0; i < pInsideLastFrame->Size(); i++)
{
Game::CEntity* pEnt = pInsideLastFrame->At(i);
if (!pInsideNow->Contains(pEnt) && pEnt->IsActive())
if (pScriptObj)
pScriptObj->RunFunctionData(OnTriggerLeave.Get(), nString(pEnt->GetUniqueID().CStr()));
}
if (Period > 0.f && GameSrv->GetTime() - TimeLastTriggered >= Period)
{
for (int i = 0; i < pInsideNow->Size(); i++)
if (pScriptObj)
pScriptObj->RunFunctionData(OnTriggerLeave.Get(), nString(pInsideNow->At(i)->GetUniqueID().CStr()));
TimeLastTriggered = (float)GameSrv->GetTime();
}
SwapArrays = !SwapArrays;
OK;
}
//---------------------------------------------------------------------
bool CPropTrigger::OnSave(const CEventBase& Event)
{
GetEntity()->Set<bool>(Attr::TrgEnabled, Enabled);
if (Period > 0.f) GetEntity()->Set<float>(Attr::TrgTimeLastTriggered, TimeLastTriggered);
OK;
}
//---------------------------------------------------------------------
bool CPropTrigger::OnRenderDebug(const Events::CEventBase& Event)
{
static const vector4 ColorOn(0.9f, 0.58f, 1.0f, 0.3f); // purple
static const vector4 ColorOff(0.0f, 0.0f, 0.0f, 0.08f); // black
const vector4& ShapeParams = GetEntity()->Get<vector4>(Attr::TrgShapeParams);
matrix44 Tfm;
switch (GetEntity()->Get<int>(Attr::TrgShapeType))
{
case CShape::Box:
Tfm.scale(vector3(ShapeParams.x, ShapeParams.y, ShapeParams.z));
Tfm *= GetEntity()->Get<matrix44>(Attr::Transform);
nGfxServer2::Instance()->DrawShape(nGfxServer2::Box, Tfm, Enabled ? ColorOn : ColorOff);
break;
case CShape::Sphere:
Tfm.scale(vector3(ShapeParams.x, ShapeParams.x, ShapeParams.x));
Tfm *= GetEntity()->Get<matrix44>(Attr::Transform);
nGfxServer2::Instance()->DrawShape(nGfxServer2::Sphere, Tfm, Enabled ? ColorOn : ColorOff);
break;
default: break; //!!!capsule rendering!
}
OK;
}
//---------------------------------------------------------------------
} // namespace Properties
| 32.813008 | 125 | 0.652131 | [
"shape",
"transform"
] |
d9181175030166929575f4e2377e7fd794444547 | 13,573 | cc | C++ | extractor/rule_extractor.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 114 | 2015-01-11T05:41:03.000Z | 2021-08-31T03:47:12.000Z | extractor/rule_extractor.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 29 | 2015-01-09T01:00:09.000Z | 2019-09-25T06:04:02.000Z | extractor/rule_extractor.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 50 | 2015-02-13T13:48:39.000Z | 2019-08-07T09:45:11.000Z | #include "rule_extractor.h"
#include <map>
#include "alignment.h"
#include "data_array.h"
#include "features/feature.h"
#include "phrase_builder.h"
#include "phrase_location.h"
#include "rule.h"
#include "rule_extractor_helper.h"
#include "scorer.h"
#include "target_phrase_extractor.h"
using namespace std;
namespace extractor {
RuleExtractor::RuleExtractor(
shared_ptr<DataArray> source_data_array,
shared_ptr<DataArray> target_data_array,
shared_ptr<Alignment> alignment,
shared_ptr<PhraseBuilder> phrase_builder,
shared_ptr<Scorer> scorer,
shared_ptr<Vocabulary> vocabulary,
int max_rule_span,
int min_gap_size,
int max_nonterminals,
int max_rule_symbols,
bool require_aligned_terminal,
bool require_aligned_chunks,
bool require_tight_phrases) :
target_data_array(target_data_array),
source_data_array(source_data_array),
phrase_builder(phrase_builder),
scorer(scorer),
max_rule_span(max_rule_span),
min_gap_size(min_gap_size),
max_nonterminals(max_nonterminals),
max_rule_symbols(max_rule_symbols),
require_tight_phrases(require_tight_phrases) {
helper = make_shared<RuleExtractorHelper>(
source_data_array, target_data_array, alignment, max_rule_span,
max_rule_symbols, require_aligned_terminal, require_aligned_chunks,
require_tight_phrases);
target_phrase_extractor = make_shared<TargetPhraseExtractor>(
target_data_array, alignment, phrase_builder, helper, vocabulary,
max_rule_span, require_tight_phrases);
}
RuleExtractor::RuleExtractor(
shared_ptr<DataArray> source_data_array,
shared_ptr<PhraseBuilder> phrase_builder,
shared_ptr<Scorer> scorer,
shared_ptr<TargetPhraseExtractor> target_phrase_extractor,
shared_ptr<RuleExtractorHelper> helper,
int max_rule_span,
int min_gap_size,
int max_nonterminals,
int max_rule_symbols,
bool require_tight_phrases) :
source_data_array(source_data_array),
phrase_builder(phrase_builder),
scorer(scorer),
target_phrase_extractor(target_phrase_extractor),
helper(helper),
max_rule_span(max_rule_span),
min_gap_size(min_gap_size),
max_nonterminals(max_nonterminals),
max_rule_symbols(max_rule_symbols),
require_tight_phrases(require_tight_phrases) {}
RuleExtractor::RuleExtractor() {}
RuleExtractor::~RuleExtractor() {}
vector<Rule> RuleExtractor::ExtractRules(const Phrase& phrase,
const PhraseLocation& location) const {
int num_subpatterns = location.num_subpatterns;
vector<int> matchings = *location.matchings;
// Calculate statistics for the (sampled) occurrences of the source phrase.
map<Phrase, double> source_phrase_counter;
map<Phrase, map<Phrase, map<PhraseAlignment, int>>> alignments_counter;
for (auto i = matchings.begin(); i != matchings.end(); i += num_subpatterns) {
vector<int> matching(i, i + num_subpatterns);
vector<Extract> extracts = ExtractAlignments(phrase, matching);
for (Extract e: extracts) {
source_phrase_counter[e.source_phrase] += e.pairs_count;
alignments_counter[e.source_phrase][e.target_phrase][e.alignment] += 1;
}
}
// Compute the feature scores and find the most likely (frequent) alignment
// for each pair of source-target phrases.
int num_samples = matchings.size() / num_subpatterns;
vector<Rule> rules;
for (auto source_phrase_entry: alignments_counter) {
Phrase source_phrase = source_phrase_entry.first;
for (auto target_phrase_entry: source_phrase_entry.second) {
Phrase target_phrase = target_phrase_entry.first;
int max_locations = 0, num_locations = 0;
PhraseAlignment most_frequent_alignment;
for (auto alignment_entry: target_phrase_entry.second) {
num_locations += alignment_entry.second;
if (alignment_entry.second > max_locations) {
most_frequent_alignment = alignment_entry.first;
max_locations = alignment_entry.second;
}
}
features::FeatureContext context(source_phrase, target_phrase,
source_phrase_counter[source_phrase], num_locations, num_samples);
vector<double> scores = scorer->Score(context);
rules.push_back(Rule(source_phrase, target_phrase, scores,
most_frequent_alignment));
}
}
return rules;
}
vector<Extract> RuleExtractor::ExtractAlignments(
const Phrase& phrase, const vector<int>& matching) const {
vector<Extract> extracts;
int sentence_id = source_data_array->GetSentenceId(matching[0]);
int source_sent_start = source_data_array->GetSentenceStart(sentence_id);
// Get the span in the opposite sentence for each word in the source-target
// sentece pair.
vector<int> source_low, source_high, target_low, target_high;
helper->GetLinksSpans(source_low, source_high, target_low, target_high,
sentence_id);
int num_subpatterns = matching.size();
vector<int> chunklen(num_subpatterns);
for (size_t i = 0; i < num_subpatterns; ++i) {
chunklen[i] = phrase.GetChunkLen(i);
}
// Basic checks to see if we can extract phrase pairs for this occurrence.
if (!helper->CheckAlignedTerminals(matching, chunklen, source_low,
source_sent_start) ||
!helper->CheckTightPhrases(matching, chunklen, source_low,
source_sent_start)) {
return extracts;
}
int source_back_low = -1, source_back_high = -1;
int source_phrase_low = matching[0] - source_sent_start;
int source_phrase_high = matching.back() + chunklen.back() -
source_sent_start;
int target_phrase_low = -1, target_phrase_high = -1;
// Find target span and reflected source span for the source phrase.
if (!helper->FindFixPoint(source_phrase_low, source_phrase_high, source_low,
source_high, target_phrase_low, target_phrase_high,
target_low, target_high, source_back_low,
source_back_high, sentence_id, min_gap_size, 0,
max_nonterminals - matching.size() + 1, true, true,
false)) {
return extracts;
}
// Get spans for nonterminal gaps.
bool met_constraints = true;
int num_symbols = phrase.GetNumSymbols();
vector<pair<int, int>> source_gaps, target_gaps;
if (!helper->GetGaps(source_gaps, target_gaps, matching, chunklen, source_low,
source_high, target_low, target_high, source_phrase_low,
source_phrase_high, source_back_low, source_back_high,
sentence_id, source_sent_start, num_symbols,
met_constraints)) {
return extracts;
}
// Find target phrases aligned with the initial source phrase.
bool starts_with_x = source_back_low != source_phrase_low;
bool ends_with_x = source_back_high != source_phrase_high;
Phrase source_phrase = phrase_builder->Extend(
phrase, starts_with_x, ends_with_x);
unordered_map<int, int> source_indexes = helper->GetSourceIndexes(
matching, chunklen, starts_with_x, source_sent_start);
if (met_constraints) {
AddExtracts(extracts, source_phrase, source_indexes, target_gaps,
target_low, target_phrase_low, target_phrase_high, sentence_id);
}
if (source_gaps.size() >= max_nonterminals ||
source_phrase.GetNumSymbols() >= max_rule_symbols ||
source_back_high - source_back_low + min_gap_size > max_rule_span) {
// Cannot add any more nonterminals.
return extracts;
}
// Extend the source phrase by adding a leading and/or trailing nonterminal
// and find target phrases aligned with the extended source phrase.
for (int i = 0; i < 2; ++i) {
for (int j = 1 - i; j < 2; ++j) {
AddNonterminalExtremities(extracts, matching, chunklen, source_phrase,
source_back_low, source_back_high, source_low, source_high,
target_low, target_high, target_gaps, sentence_id, source_sent_start,
starts_with_x, ends_with_x, i, j);
}
}
return extracts;
}
void RuleExtractor::AddExtracts(
vector<Extract>& extracts, const Phrase& source_phrase,
const unordered_map<int, int>& source_indexes,
const vector<pair<int, int>>& target_gaps, const vector<int>& target_low,
int target_phrase_low, int target_phrase_high, int sentence_id) const {
auto target_phrases = target_phrase_extractor->ExtractPhrases(
target_gaps, target_low, target_phrase_low, target_phrase_high,
source_indexes, sentence_id);
if (target_phrases.size() > 0) {
// Split the probability equally across all target phrases that can be
// aligned with a single occurrence of the source phrase.
double pairs_count = 1.0 / target_phrases.size();
for (auto target_phrase: target_phrases) {
extracts.push_back(Extract(source_phrase, target_phrase.first,
pairs_count, target_phrase.second));
}
}
}
void RuleExtractor::AddNonterminalExtremities(
vector<Extract>& extracts, const vector<int>& matching,
const vector<int>& chunklen, const Phrase& source_phrase,
int source_back_low, int source_back_high, const vector<int>& source_low,
const vector<int>& source_high, const vector<int>& target_low,
const vector<int>& target_high, vector<pair<int, int>> target_gaps,
int sentence_id, int source_sent_start, int starts_with_x, int ends_with_x,
int extend_left, int extend_right) const {
int source_x_low = source_back_low, source_x_high = source_back_high;
// Check if the extended source phrase will remain tight.
if (require_tight_phrases) {
if (source_low[source_back_low - extend_left] == -1 ||
source_low[source_back_high + extend_right - 1] == -1) {
return;
}
}
// Check if we can add a nonterminal to the left.
if (extend_left) {
if (starts_with_x || source_back_low < min_gap_size) {
return;
}
source_x_low = source_back_low - min_gap_size;
if (require_tight_phrases) {
while (source_x_low >= 0 && source_low[source_x_low] == -1) {
--source_x_low;
}
}
if (source_x_low < 0) {
return;
}
}
// Check if we can add a nonterminal to the right.
if (extend_right) {
int source_sent_len = source_data_array->GetSentenceLength(sentence_id);
if (ends_with_x || source_back_high + min_gap_size > source_sent_len) {
return;
}
source_x_high = source_back_high + min_gap_size;
if (require_tight_phrases) {
while (source_x_high <= source_sent_len &&
source_low[source_x_high - 1] == -1) {
++source_x_high;
}
}
if (source_x_high > source_sent_len) {
return;
}
}
// More length checks.
int new_nonterminals = extend_left + extend_right;
if (source_x_high - source_x_low > max_rule_span ||
target_gaps.size() + new_nonterminals > max_nonterminals ||
source_phrase.GetNumSymbols() + new_nonterminals > max_rule_symbols) {
return;
}
// Find the target span for the extended phrase and the reflected source span.
int target_x_low = -1, target_x_high = -1;
if (!helper->FindFixPoint(source_x_low, source_x_high, source_low,
source_high, target_x_low, target_x_high,
target_low, target_high, source_x_low,
source_x_high, sentence_id, 1, 1,
new_nonterminals, extend_left, extend_right,
true)) {
return;
}
// Check gap integrity for the leading nonterminal.
if (extend_left) {
int source_gap_low = -1, source_gap_high = -1;
int target_gap_low = -1, target_gap_high = -1;
if ((require_tight_phrases && source_low[source_x_low] == -1) ||
!helper->FindFixPoint(source_x_low, source_back_low, source_low,
source_high, target_gap_low, target_gap_high,
target_low, target_high, source_gap_low,
source_gap_high, sentence_id, 0, 0, 0, false,
false, false)) {
return;
}
target_gaps.insert(target_gaps.begin(),
make_pair(target_gap_low, target_gap_high));
}
// Check gap integrity for the trailing nonterminal.
if (extend_right) {
int target_gap_low = -1, target_gap_high = -1;
int source_gap_low = -1, source_gap_high = -1;
if ((require_tight_phrases && source_low[source_x_high - 1] == -1) ||
!helper->FindFixPoint(source_back_high, source_x_high, source_low,
source_high, target_gap_low, target_gap_high,
target_low, target_high, source_gap_low,
source_gap_high, sentence_id, 0, 0, 0, false,
false, false)) {
return;
}
target_gaps.push_back(make_pair(target_gap_low, target_gap_high));
}
// Find target phrases aligned with the extended source phrase.
Phrase new_source_phrase = phrase_builder->Extend(source_phrase, extend_left,
extend_right);
unordered_map<int, int> source_indexes = helper->GetSourceIndexes(
matching, chunklen, extend_left || starts_with_x, source_sent_start);
AddExtracts(extracts, new_source_phrase, source_indexes, target_gaps,
target_low, target_x_low, target_x_high, sentence_id);
}
} // namespace extractor
| 39.456395 | 80 | 0.686436 | [
"vector"
] |
d91ade8c1a3ee3854a5fb9f84c9514592e3f6c67 | 1,415 | cpp | C++ | 3041 Asteroids/main.cpp | sqc1999-oi/POJ | 450afa9485bcf5398f9cb7efd5a3b8c40de60e03 | [
"MIT"
] | 1 | 2016-07-18T12:05:16.000Z | 2016-07-18T12:05:16.000Z | 3041 Asteroids/main.cpp | sqc1999/POJ | 450afa9485bcf5398f9cb7efd5a3b8c40de60e03 | [
"MIT"
] | null | null | null | 3041 Asteroids/main.cpp | sqc1999/POJ | 450afa9485bcf5398f9cb7efd5a3b8c40de60e03 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int INF = 0x7fffffff;
struct Edge { int From, To, Cap, Flow; };
int a[1002], p[1002];
vector<Edge> Edges;
vector<int> G[1002];
void AddEdge(int from, int to, int cap)
{
G[from].push_back(Edges.size());
Edges.push_back(Edge{ from,to,cap,0 });
G[to].push_back(Edges.size());
Edges.push_back(Edge{ to,from,0,0 });
}
int MaxFlow(int s, int t)
{
int flow = 0;
while (true)
{
memset(a, 0, sizeof a);
queue<int> q;
q.push(s);
a[s] = INF;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = 0; i < G[u].size(); i++)
{
Edge &e = Edges[G[u][i]];
if (!a[e.To] && e.Cap>e.Flow)
{
a[e.To] = min(a[e.From], e.Cap - e.Flow);
p[e.To] = G[u][i];
q.push(e.To);
}
}
if (a[t]) break;
}
if (!a[t]) break;
for (int u = t; u != s; u = Edges[p[u]].From)
{
Edges[p[u]].Flow += a[t];
Edges[p[u] ^ 1].Flow -= a[t];
}
flow += a[t];
}
return flow;
}
int main()
{
ios::sync_with_stdio(false);
int n, k;
cin >> n >> k;
for (int i = 1; i <= k; i++)
{
int r, c;
cin >> r >> c;
AddEdge(r, c + n, 1);
}
for (int i = 1; i <= n; i++) AddEdge(0, i, 1);
for (int i = n + 1; i <= n * 2; i++) AddEdge(i, n * 2 + 1, 1);
cout << MaxFlow(0, n * 2 + 1);
}
| 20.507246 | 64 | 0.491166 | [
"vector"
] |
d91c6512123b2338de3dc676c036e47750dc6351 | 2,320 | cpp | C++ | C++/letter-combinations-of-a-phone-number.cpp | xenron/sandbox-dev-lintcode | 114145723af43eafc84ff602ad3ac7b353a9fc38 | [
"MIT"
] | 695 | 2015-04-18T16:11:56.000Z | 2022-03-11T13:28:44.000Z | C++/letter-combinations-of-a-phone-number.cpp | Abd-Elrazek/LintCode | 8f6ee0ff38cb7cf8bf9fca800243823931604155 | [
"MIT"
] | 4 | 2015-07-04T13:07:35.000Z | 2020-08-11T11:32:29.000Z | C++/letter-combinations-of-a-phone-number.cpp | Abd-Elrazek/LintCode | 8f6ee0ff38cb7cf8bf9fca800243823931604155 | [
"MIT"
] | 338 | 2015-04-28T04:39:03.000Z | 2022-03-16T03:00:15.000Z | // Time: O(n * 4^n)
// Space: O(n)
// Iterative solution.
class Solution {
public:
/**
* @param digits A digital string
* @return all posible letter combinations
*/
vector<string> letterCombinations(string& digits) {
if (digits.empty()) {
return {};
}
vector<string> result = {""};
vector<string> lookup = {"", "", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
for (int i = digits.size() - 1; i >= 0; --i) {
const string& choices = lookup[digits[i] - '0'];
const int n = result.size(), m = choices.length();
for (int j = n; j < m * n; ++j) {
result.emplace_back(result[j % n]);
}
for (int j = 0; j < m * n; ++j) {
result[j].insert(result[j].end(), choices[j / n]);
}
}
for (auto& s : result) {
reverse(s.begin(), s.end());
}
return result;
}
};
// Time: O(n * 4^n)
// Space: O(n)
// Recursion solution.
class Solution2 {
public:
/**
* @param digits A digital string
* @return all posible letter combinations
*/
vector<string> letterCombinations(string& digits) {
if (digits.empty()) {
return {};
}
vector<string> result = {};
vector<string> lookup = {"", "", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
string combination;
int len = 0;
letterCombinationsRecu(digits, lookup, &combination, &len, &result);
return result;
}
void letterCombinationsRecu(const string& digits, vector<string>& lookup,
string *combination,
int *len, vector<string> *result) {
if (*len == digits.size()) {
result->emplace_back(*combination);
} else {
for (const auto& c : lookup[digits[*len] - '0']) {
combination->insert(combination->end(), c), ++(*len);
letterCombinationsRecu(digits, lookup, combination, len, result);
combination->pop_back(), --(*len);
}
}
}
};
| 30.12987 | 81 | 0.456034 | [
"vector"
] |
0ba693f04034127c0d1624b775d08f88e30210cf | 1,005 | cpp | C++ | book/Chap5/logicerror.cpp | mjakebarrington/CPP-Exercises | 9bb01f66ae9861c4d5323738fb478f15ad7e691c | [
"MIT"
] | null | null | null | book/Chap5/logicerror.cpp | mjakebarrington/CPP-Exercises | 9bb01f66ae9861c4d5323738fb478f15ad7e691c | [
"MIT"
] | null | null | null | book/Chap5/logicerror.cpp | mjakebarrington/CPP-Exercises | 9bb01f66ae9861c4d5323738fb478f15ad7e691c | [
"MIT"
] | null | null | null | /*
* This is a simple logic error example provided by the book.
* The program will compile and run, but will not yield the correct results.
*/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double>temps;
double temp = 0;
double sum = 0;
double high_temp = 0;
double low_temp = 0;
while (cin>>temp)
{
temps.push_back(temp);
}
for (int i=0; i<temps.size(); ++i)
{
// high_temp is initialized at 0, so our logic assumes there will be a temp over 0.
// Don't ship this to a researcher at one of the poles!
if(temps[i] > high_temp)high_temp=temps[i];
// low_temp is initialized at 0, so our logic assumes we will have a negative temperature.
// imagine trying to use this logic to collect temperature data in the Sahara!
if(temps[i] < low_temp)low_temp=temps[i];
sum += temps[i];
}
cout<<"High Temperature: "<<high_temp<<endl;
cout<<"Low Temperature: "<<low_temp<<endl;
cout<<"Average Temperature: "<<sum/temps.size()<<endl;
return 0;
}
| 25.125 | 92 | 0.686567 | [
"vector"
] |
0ba858dcb0c07b39f693090cea8b0898bbf5d7cc | 8,051 | cpp | C++ | OpenGL_3DJV1/LoaderOBJ/LoaderOBJ.cpp | Epono/5A-3DJV-OpenGL_Project | 59ea1aac67780f4b53687beb46085e10c2ca4d4c | [
"MIT"
] | null | null | null | OpenGL_3DJV1/LoaderOBJ/LoaderOBJ.cpp | Epono/5A-3DJV-OpenGL_Project | 59ea1aac67780f4b53687beb46085e10c2ca4d4c | [
"MIT"
] | null | null | null | OpenGL_3DJV1/LoaderOBJ/LoaderOBJ.cpp | Epono/5A-3DJV-OpenGL_Project | 59ea1aac67780f4b53687beb46085e10c2ca4d4c | [
"MIT"
] | null | null | null | //
// LoaderOBJ.cpp : Defines the entry point for the console application.
//
// Specifique a Windows
#if _WIN32
#include <Windows.h>
#define FREEGLUT_LIB_PRAGMAS 0
#pragma comment(lib, "freeglut.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glew32s.lib")
#endif
// Entete OpenGL
#define GLEW_STATIC 1
#include <GL/glew.h>
//#include <gl/GL.h>
//#include "GL/glext.h"
// FreeGLUT
#include "GL/freeglut.h"
// STB
//#define STB_IMAGE_IMPLEMENTATION
//#include "stb-master/stb_image.h"
#include "../common/tiny_obj_loader.h"
#include <cstdio>
#include <cmath>
#include <vector>
#include <string>
#include "../common/EsgiShader.h"
EsgiShader basicShader;
int previousTime = 0;
GLuint cubeVBO;
GLuint cubeIBO;
GLuint cubeElementCount;
GLuint objectVBO;
GLuint objectIBO;
GLuint objectElementCount;
GLenum elementType = GL_UNSIGNED_INT;
GLuint textureObj;
/*
struct Camera
{
} g_Camera;*/
void InitCube()
{
std::string inputfile = "cube.obj";
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err = tinyobj::LoadObj(shapes, materials, inputfile.c_str());
const std::vector<unsigned int> &indices = shapes[0].mesh.indices;
const std::vector<float> &positions = shapes[0].mesh.positions;
const std::vector<float> &normals = shapes[0].mesh.normals;
const std::vector<float> &texcoords = shapes[0].mesh.texcoords;
glGenBuffers(1, &cubeVBO);
glGenBuffers(1, &cubeIBO);
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(float), &positions[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cubeIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
cubeElementCount = indices.size();
}
void PrepareCube(GLuint program)
{
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
auto positionLocation = glGetAttribLocation(program, "a_position");
glEnableVertexAttribArray(positionLocation);
glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, 0);
}
void CleanCube()
{
glDeleteBuffers(1, &cubeVBO);
glDeleteBuffers(1, &cubeIBO);
}
void InitObject()
{
std::string inputfile = "suzanne.obj";
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err = tinyobj::LoadObj(shapes, materials, inputfile.c_str());
const std::vector<unsigned int> &indices = shapes[0].mesh.indices;
const std::vector<float> &positions = shapes[0].mesh.positions;
const std::vector<float> &normals = shapes[0].mesh.normals;
const std::vector<float> &texcoords = shapes[0].mesh.texcoords;
glGenBuffers(1, &objectVBO);
glGenBuffers(1, &objectIBO);
glBindBuffer(GL_ARRAY_BUFFER, objectVBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(float), &positions[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, objectIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
objectElementCount = indices.size();
}
void PrepareObject(GLuint program)
{
glBindBuffer(GL_ARRAY_BUFFER, objectVBO);
auto positionLocation = glGetAttribLocation(program, "a_position");
glEnableVertexAttribArray(positionLocation);
glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, 0);
}
void CleanObject()
{
glDeleteBuffers(1, &objectVBO);
glDeleteBuffers(1, &objectIBO);
}
void Initialize()
{
printf("Version Pilote OpenGL : %s\n", glGetString(GL_VERSION));
printf("Type de GPU : %s\n", glGetString(GL_RENDERER));
printf("Fabricant : %s\n", glGetString(GL_VENDOR));
printf("Version GLSL : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
int numExtensions;
glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
GLenum error = glewInit();
if (error != GL_NO_ERROR) {
// TODO
}
for (int index = 0; index < numExtensions; ++index)
{
printf("Extension[%d] : %s\n", index, glGetStringi(GL_EXTENSIONS, index));
}
basicShader.LoadVertexShader("basic.vs");
basicShader.LoadFragmentShader("basic.fs");
basicShader.Create();
previousTime = glutGet(GLUT_ELAPSED_TIME);
InitCube();
InitObject();
}
void Terminate()
{
glDeleteTextures(1, &textureObj);
CleanObject();
CleanCube();
basicShader.Destroy();
}
// ---
void Identity(float *matrix)
{
memset(matrix, 0, sizeof(float) * 16);
matrix[0] = 1.0f; matrix[5] = 1.0f; matrix[10] = 1.0f; matrix[15] = 1.0f;
}
void Orthographic(float *matrix, float L, float R, float T, float B, float N, float F)
{
memset(matrix, 0, sizeof(float) * 16);
matrix[0] = 2.f / (R-L);
matrix[5] = 2.f / (T-B);
matrix[10] = -2.f / (F-N);
matrix[12] = -(R+L) / (R-L);
matrix[13] = -(T+B) / (T-B);
matrix[14] = -(F+N) / (F-N);
matrix[15] = 1.f;
}
#define M_PI 3.141592f
void Perspective(float *m, float fov, float width_, float height_, float znear, float zfar)
{
memset(m, 0, sizeof(float) * 16);
float aspect = width_ / height_;
float xymax = znear * tan(fov * 0.5f * M_PI/180.0f);
float ymin = -xymax;
float xmin = -xymax;
float width = xymax - xmin;
float height = xymax - ymin;
float depth = zfar - znear;
float q = -(zfar + znear) / depth;
float qn = -2 * (zfar * znear) / depth;
float w = 2 * znear / width;
w = w / aspect;
float h = 2 * znear / height;
m[0] = w; m[1] = 0; m[2] = 0; m[3] = 0;
m[4] = 0; m[5] = h; m[6] = 0; m[7] = 0;
m[8] = 0; m[9] = 0; m[10] = q; m[11] = -1;
m[12] = 0; m[13] = 0; m[14] = qn; m[15] = 0;
}
void Translate(float *matrix, float tx, float ty, float tz = 0.f)
{
memset(matrix, 0, sizeof(float) * 16);
matrix[0] = 1.f;
matrix[5] = 1.f;
matrix[10] = 1.f;
matrix[12] = tx;
matrix[13] = ty;
matrix[14] = tz;
matrix[15] = 1.f;
}
void Render()
{
glViewport(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
glClearColor(0.f, 0.5f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
//glCullFace(GL_FRONT);
GLuint program = basicShader.GetProgram();
glUseProgram(program);
float w = (float)glutGet(GLUT_WINDOW_WIDTH);
float h = (float)glutGet(GLUT_WINDOW_HEIGHT);
// variables uniformes (constantes) durant le rendu de la primitive
float projection[16];
//Orthographic(projection, -w/2, w/2, -h/2, h/2, -1.f, 1.f);
//Orthographic(projection, 0, w, h, 0, -1.f, 1.f);
Perspective(projection, 45.f, w, h, 0.01f, 1000.f);
int currentTime = glutGet(GLUT_ELAPSED_TIME);
int delta = currentTime - previousTime;
previousTime = currentTime;
static float time = 1.f;
time += delta/1000.f;
GLint timeLocation = glGetUniformLocation(program, "u_time");
glUniform1f(timeLocation, time);
float viewTransform[16];
Identity(viewTransform);
viewTransform[14] = -7.f;
float worldTransform[16];
Identity(worldTransform);
worldTransform[12] = sin(time) * 5.f;
GLint projectionLocation = glGetUniformLocation(program, "u_projectionMatrix");
GLint viewLocation = glGetUniformLocation(program, "u_viewMatrix");
GLint worldLocation = glGetUniformLocation(program, "u_worldMatrix");
glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, projection);
glUniformMatrix4fv(viewLocation, 1, GL_FALSE, viewTransform);
glUniformMatrix4fv(worldLocation, 1, GL_FALSE, worldTransform);
PrepareCube(program);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cubeIBO);
glDrawElements(GL_TRIANGLES, cubeElementCount, elementType, 0);
PrepareObject(program);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, objectIBO);
glDrawElements(GL_TRIANGLES, objectElementCount, elementType, 0);
glUseProgram(0);
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("OBJ Loader");
#ifdef FREEGLUT
// Note: glutSetOption n'est disponible qu'avec freeGLUT
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS);
#endif
Initialize();
glutDisplayFunc(Render);
glutMainLoop();
Terminate();
return 0;
}
| 25.640127 | 107 | 0.71457 | [
"mesh",
"render",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.