hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
002ffe877490ef43d0206adc11aade85d3f56abc | 3,493 | cpp | C++ | RtkServer/mainwindow.cpp | CORAL-CMU/Qt | 85f29279e70121d5108c6d9295b2ba09826fba85 | [
"MIT"
] | null | null | null | RtkServer/mainwindow.cpp | CORAL-CMU/Qt | 85f29279e70121d5108c6d9295b2ba09826fba85 | [
"MIT"
] | null | null | null | RtkServer/mainwindow.cpp | CORAL-CMU/Qt | 85f29279e70121d5108c6d9295b2ba09826fba85 | [
"MIT"
] | 2 | 2021-01-22T14:58:10.000Z | 2021-12-24T17:22:42.000Z | #include "mainwindow.h"
#include "ui_mainwindow.h"
#define GPGGASTR "$GPGGA,000637.10,4026.4183386,N,07956.1275614,W,5,06,1.0,308.021,M,-34.121,M,1.1,*7C"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
client = new QNtripClient();
client->addr="209.255.196.164";
client->port="2101";
client->user="CMU";
client->passwd="CMU";
client->loadCasterList();
connect(client,SIGNAL(signalRtkReceived(QByteArray)),this,SLOT(slotRtkReceived(QByteArray)));
server = new QNtripServer("CMU", "CMU");
connect(server,SIGNAL(signalNewConnection(QString)),this,SLOT(slotNewConnection(QString)));
connect(server,SIGNAL(signalUpdateGPGGA(QString)),this,SLOT(slotUpdateGPGGA(QString)));
connect(server,SIGNAL(signalClientDisconnect(QString)),this,SLOT(slotClientDisconnect(QString)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_setcaster_clicked()
{
QList<QString> casters;
for(int i=0;i<client->casterlist.size();i++)
{
casters.push_back(client->casterlist[i].identifier);
}
QString caster = QInputDialog::getItem(this,"Select Caster","Caster Identifier:", casters);
casterid = casters.indexOf(caster);
client->mntpnt = client->casterlist[casterid].mountpoint;
client->encodeNtripPath();
ui->casterinfo->setText(client->ntrippath);
server->caster = client->casterlist[casterid];
}
void MainWindow::on_triggerrtk_clicked()
{
if(ui->triggerrtk->text()==QString("Start RTK"))
{
client->startReceiveRtk(casterid, GPGGASTR);
ui->setcaster->setEnabled(false);
ui->triggerrtk->setText("Stop RTK");
}
else if(ui->triggerrtk->text()==QString("Stop RTK"))
{
client->stopReceiveRtk();
ui->setcaster->setEnabled(true);
ui->triggerrtk->setText("Start RTK");
}
}
void MainWindow::slotRtkReceived(QByteArray rtk)
{
if(ui->showrtk->isChecked())
{
QString content=QString("[%1]\n%2")
.arg(QTime::currentTime().toString("HH:mm:ss:zzz"))
.arg(QString(rtk));
ui->rtkview->append(content);
}
server->sendRtk(rtk);
}
void MainWindow::slotNewConnection(QString peer)
{
QString content=QString("[%1]\n%2 Connected")
.arg(QTime::currentTime().toString("HH:mm:ss:zzz"))
.arg(peer);
ui->serverlog->append(content);
}
void MainWindow::slotUpdateGPGGA(QString GPGGA)
{
client->stopReceiveRtk();
this->thread()->sleep(2);
client->startReceiveRtk(casterid, GPGGA);
QString content=QString("[%1]\n%2")
.arg(QTime::currentTime().toString("HH:mm:ss:zzz"))
.arg(GPGGA);
ui->serverlog->append(content);
}
void MainWindow::slotClientDisconnect(QString peer)
{
QString content=QString("[%1]\n%2 Disconnected")
.arg(QTime::currentTime().toString("HH:mm:ss:zzz"))
.arg(peer);
ui->serverlog->append(content);
}
void MainWindow::on_triggerserver_clicked()
{
if(ui->triggerserver->text()==QString("Open Server"))
{
server->openServer(QHostAddress::Any,12346);
ui->triggerserver->setText("Close Server");
}
else if(ui->triggerserver->text()==QString("Close Server"))
{
server->closeServer();
ui->triggerserver->setText("Open Server");
}
}
| 30.112069 | 104 | 0.6284 | CORAL-CMU |
0031dd4a87c00acaa7a66eeac4932568affff836 | 2,097 | cpp | C++ | savefinalmoviedialog.cpp | chennes/Stop_Motion_Animation | 282c65a38053202c4e35735a0bf0a53797dc1481 | [
"MIT"
] | 3 | 2015-09-28T13:14:06.000Z | 2019-11-28T13:23:10.000Z | savefinalmoviedialog.cpp | chennes/Stop_Motion_Animation | 282c65a38053202c4e35735a0bf0a53797dc1481 | [
"MIT"
] | 42 | 2017-03-26T15:22:37.000Z | 2019-04-05T13:42:00.000Z | savefinalmoviedialog.cpp | chennes/Stop_Motion_Animation | 282c65a38053202c4e35735a0bf0a53797dc1481 | [
"MIT"
] | null | null | null | #include "savefinalmoviedialog.h"
#include "ui_savefinalmoviedialog.h"
#include "settings.h"
#include <QFileDialog>
SaveFinalMovieDialog::SaveFinalMovieDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SaveFinalMovieDialog)
{
ui->setupUi(this);
}
SaveFinalMovieDialog::~SaveFinalMovieDialog()
{
delete ui;
}
void SaveFinalMovieDialog::reset(const QString &filename, const QString &title, const QString &credits)
{
Settings settings;
// Title duration
double titleScreenDuration = settings.Get("settings/titleScreenDuration").toDouble();
// Credits duration
double creditsDuration = settings.Get("settings/creditsDuration").toDouble();
ui->movieSaveLocationLabel->setText(filename);
if (titleScreenDuration > 0) {
if (title.length() > 0) {
ui->movieTitleLineEdit->setText(title);
} else {
ui->movieTitleLineEdit->clear();
ui->movieTitleLineEdit->setPlaceholderText("Enter a title here");
}
} else {
ui->movieTitleLineEdit->hide();
ui->movieTitleLabel->hide();
}
if (creditsDuration > 0) {
if (credits.length() > 0) {
ui->creditsPlainTextEdit->setPlainText(credits);
} else {
ui->creditsPlainTextEdit->clear();
ui->creditsPlainTextEdit->setPlaceholderText("Type your credits in here");
}
} else {
ui->creditsPlainTextEdit->hide();
ui->creditsLabel->hide();
}
adjustSize();
}
QString SaveFinalMovieDialog::filename() const
{
return ui->movieSaveLocationLabel->text();
}
QString SaveFinalMovieDialog::movieTitle() const
{
return ui->movieTitleLineEdit->text();
}
QString SaveFinalMovieDialog::credits() const
{
return ui->creditsPlainTextEdit->toPlainText();
}
void SaveFinalMovieDialog::on_changeLocationButton_clicked()
{
QString newFilename = QFileDialog::getSaveFileName(this, "Save movie to...", "", "Movie files (*.mp4);;All files (*.*)");
if (newFilename.length() > 0) {
ui->movieSaveLocationLabel->setText(newFilename);
}
}
| 26.544304 | 125 | 0.664759 | chennes |
004ccf2cd8b1955dfcdc018a74343e217ce5c42c | 3,603 | cpp | C++ | Raven.CppClient/AbstractIndexCreationTaskBase.cpp | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 3 | 2019-04-24T02:34:53.000Z | 2019-08-01T08:22:26.000Z | Raven.CppClient/AbstractIndexCreationTaskBase.cpp | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 2 | 2019-03-21T09:00:02.000Z | 2021-02-28T23:49:26.000Z | Raven.CppClient/AbstractIndexCreationTaskBase.cpp | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 3 | 2019-03-04T11:58:54.000Z | 2021-03-01T00:25:49.000Z | #include "stdafx.h"
#include "AbstractIndexCreationTaskBase.h"
#include "GetCppClassName.h"
#include "MaintenanceOperationExecutor.h"
#include "PutIndexesOperation.h"
namespace ravendb::client::documents::indexes
{
void AbstractIndexCreationTaskBase::throw_index_name_was_set()
{
throw std::runtime_error("The index name was already set");
}
void AbstractIndexCreationTaskBase::throw_index_name_was_not_set()
{
throw std::runtime_error("Index name was not set."
"Did you forget to call set_index_name() or set_default_index_name() ?");
}
void AbstractIndexCreationTaskBase::set_index_name(std::string index_name)
{
if(_index_name)
{
throw_index_name_was_set();
}
_index_name = std::move(index_name);
}
void AbstractIndexCreationTaskBase::set_default_index_name(std::type_index type)
{
if (_index_name)
{
throw_index_name_was_set();
}
auto&& index_name = impl::utils::GetCppClassName::get_simple_class_name(type);
for(auto& c : index_name)
{
if(c == '_')
c = '/';
}
_index_name = std::move(index_name);
}
AbstractIndexCreationTaskBase::~AbstractIndexCreationTaskBase() = default;
const std::optional<std::unordered_map<std::string, std::string>>&
AbstractIndexCreationTaskBase::get_additional_sources() const
{
return additional_sources;
}
void AbstractIndexCreationTaskBase::set_additional_sources(
std::optional<std::unordered_map<std::string, std::string>> additional_sources_param)
{
additional_sources = std::move(additional_sources_param);
}
bool AbstractIndexCreationTaskBase::is_map_reduce() const
{
return false;
}
std::string AbstractIndexCreationTaskBase::get_index_name() const
{
if(!_index_name)
{
throw_index_name_was_not_set();
}
return *_index_name;
}
std::shared_ptr<conventions::DocumentConventions> AbstractIndexCreationTaskBase::get_conventions() const
{
return conventions;
}
void AbstractIndexCreationTaskBase::set_conventions(
std::shared_ptr<conventions::DocumentConventions> conventions_param)
{
conventions = conventions_param;
}
std::optional<IndexPriority> AbstractIndexCreationTaskBase::get_priority() const
{
return priority;
}
void AbstractIndexCreationTaskBase::set_priority(std::optional<IndexPriority> priority_param)
{
priority = priority_param;
}
std::optional<IndexLockMode> AbstractIndexCreationTaskBase::get_lock_mode() const
{
return lock_mode;
}
void AbstractIndexCreationTaskBase::set_lock_mode(std::optional<IndexLockMode> lock_mode_param)
{
lock_mode = lock_mode_param;
}
void AbstractIndexCreationTaskBase::execute(std::shared_ptr<IDocumentStore> store,
std::shared_ptr<conventions::DocumentConventions> conventions_param,
std::optional<std::string> database)
{
struct OldConventionsRestore
{
AbstractIndexCreationTaskBase* outer_this;
std::shared_ptr<conventions::DocumentConventions> old_conventions;
~OldConventionsRestore(){ outer_this->set_conventions(old_conventions); }
} old_conventions_restore{this, get_conventions()};
if (conventions_param)
{
set_conventions(conventions_param);
}
else if(get_conventions())
{}
else
{
set_conventions(store->get_conventions());
}
auto index_definition = create_index_definition();
index_definition.name = get_index_name();
if(lock_mode)
{
index_definition.lock_mode = *lock_mode;
}
if(priority)
{
index_definition.priority = *priority;
}
store->maintenance()
->for_database(database ? *database : store->get_database())
->send(operations::indexes::PutIndexesOperation({ index_definition }));
}
}
| 25.020833 | 105 | 0.760755 | mlawsonca |
0059dd34aff2b4d2706c023af6cbe8af14f4b01e | 12,257 | cpp | C++ | src/tablestore/core/error.cpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | 2 | 2020-02-24T06:51:55.000Z | 2020-04-24T14:40:10.000Z | src/tablestore/core/error.cpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | null | null | null | src/tablestore/core/error.cpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | 1 | 2020-02-24T06:51:57.000Z | 2020-02-24T06:51:57.000Z | /*
BSD 3-Clause License
Copyright (c) 2017, Alibaba Cloud
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "tablestore/core/error.hpp"
#include "tablestore/util/mempiece.hpp"
#include "tablestore/util/prettyprint.hpp"
using namespace std;
using namespace aliyun::tablestore::util;
namespace aliyun {
namespace tablestore {
namespace core {
const string OTSError::kErrorCode_CouldntResolveHost("OTSCouldntResolveHost");
const string OTSError::kErrorCode_CouldntConnect("OTSCouldntConnect");
const string OTSError::kErrorCode_WriteRequestFail("OTSWriteRequestFail");
const string OTSError::kErrorCode_CorruptedResponse("OTSCorruptedResponse");
const string OTSError::kErrorCode_NoAvailableConnection("OTSNoAvailableConnection");
const string OTSError::kErrorCode_SslHandshakeFail("OTSSslHandshakeFail");
const string OTSError::kErrorCode_OTSOutOfColumnCountLimit("OTSOutOfColumnCountLimit");
const string OTSError::kErrorCode_OTSObjectNotExist("OTSObjectNotExist");
const string OTSError::kErrorCode_OTSServerBusy("OTSServerBusy");
const string OTSError::kErrorCode_OTSCapacityUnitExhausted("OTSCapacityUnitExhausted");
const string OTSError::kErrorCode_OTSTooFrequentReservedThroughputAdjustment(
"OTSTooFrequentReservedThroughputAdjustment");
const string OTSError::kErrorCode_OTSInternalServerError("OTSInternalServerError");
const string OTSError::kErrorCode_OTSQuotaExhausted("OTSQuotaExhausted");
const string OTSError::kErrorCode_OTSRequestBodyTooLarge("OTSRequestBodyTooLarge");
const string OTSError::kErrorCode_OTSTimeout("OTSTimeout");
const string OTSError::kErrorCode_OTSObjectAlreadyExist("OTSObjectAlreadyExist");
const string OTSError::kErrorCode_OTSTableNotReady("OTSTableNotReady");
const string OTSError::kErrorCode_OTSConditionCheckFail("OTSConditionCheckFail");
const string OTSError::kErrorCode_OTSOutOfRowSizeLimit("OTSOutOfRowSizeLimit");
const string OTSError::kErrorCode_OTSInvalidPK("OTSInvalidPK");
const string OTSError::kErrorCode_OTSRequestTimeout("OTSRequestTimeout");
const string OTSError::kErrorCode_OTSMethodNotAllowed("OTSMethodNotAllowed");
const string OTSError::kErrorCode_OTSAuthFailed("OTSAuthFailed");
const string OTSError::kErrorCode_OTSServerUnavailable("OTSServerUnavailable");
const string OTSError::kErrorCode_OTSParameterInvalid("OTSParameterInvalid");
const string OTSError::kErrorCode_OTSRowOperationConflict("OTSRowOperationConflict");
const string OTSError::kErrorCode_OTSPartitionUnavailable("OTSPartitionUnavailable");
OTSError::OTSError(Predefined def)
{
switch(def) {
case kPredefined_CouldntResoveHost:
init(kHttpStatus_CouldntResolveHost, kErrorCode_CouldntResolveHost);
break;
case kPredefined_CouldntConnect:
init(kHttpStatus_CouldntConnect, kErrorCode_CouldntConnect);
break;
case kPredefined_OperationTimeout:
init(kHttpStatus_OperationTimeout, kErrorCode_OTSRequestTimeout);
break;
case kPredefined_WriteRequestFail:
init(kHttpStatus_WriteRequestFail, kErrorCode_WriteRequestFail);
break;
case kPredefined_CorruptedResponse:
init(kHttpStatus_CorruptedResponse, kErrorCode_CorruptedResponse);
break;
case kPredefined_NoConnectionAvailable:
init(kHttpStatus_NoAvailableConnection, kErrorCode_NoAvailableConnection);
break;
case kPredefined_OTSOutOfColumnCountLimit:
init(400, kErrorCode_OTSOutOfColumnCountLimit);
break;
case kPredefined_OTSObjectNotExist:
init(404, kErrorCode_OTSObjectNotExist);
break;
case kPredefined_OTSServerBusy:
init(503, kErrorCode_OTSServerBusy);
break;
case kPredefined_OTSCapacityUnitExhausted:
init(403, kErrorCode_OTSCapacityUnitExhausted);
break;
case kPredefined_OTSTooFrequentReservedThroughputAdjustment:
init(403, kErrorCode_OTSTooFrequentReservedThroughputAdjustment);
break;
case kPredefined_OTSInternalServerError:
init(500, kErrorCode_OTSInternalServerError);
break;
case kPredefined_OTSQuotaExhausted:
init(403, kErrorCode_OTSQuotaExhausted);
break;
case kPredefined_OTSRequestBodyTooLarge:
init(413, kErrorCode_OTSRequestBodyTooLarge);
break;
case kPredefined_OTSTimeout:
init(503, kErrorCode_OTSTimeout);
break;
case kPredefined_OTSObjectAlreadyExist:
init(409, kErrorCode_OTSObjectAlreadyExist);
break;
case kPredefined_OTSTableNotReady:
init(404, kErrorCode_OTSTableNotReady);
break;
case kPredefined_OTSConditionCheckFail:
init(403, kErrorCode_OTSConditionCheckFail);
break;
case kPredefined_OTSOutOfRowSizeLimit:
init(400, kErrorCode_OTSOutOfRowSizeLimit);
break;
case kPredefined_OTSInvalidPK:
init(400, kErrorCode_OTSInvalidPK);
break;
case kPredefined_OTSMethodNotAllowed:
init(405, kErrorCode_OTSMethodNotAllowed);
break;
case kPredefined_OTSAuthFailed:
init(403, kErrorCode_OTSAuthFailed);
break;
case kPredefined_OTSServerUnavailable:
init(503, kErrorCode_OTSServerUnavailable);
break;
case kPredefined_OTSParameterInvalid:
init(400, kErrorCode_OTSParameterInvalid);
break;
case kPredefined_OTSRowOperationConflict:
init(409, kErrorCode_OTSRowOperationConflict);
break;
case kPredefined_OTSPartitionUnavailable:
init(503, kErrorCode_OTSPartitionUnavailable);
break;
case kPredefined_SslHandshakeFail:
init(kHttpStatus_SslHandshakeFail, kErrorCode_SslHandshakeFail);
break;
}
}
void OTSError::init(int64_t hs, const string& ec)
{
mHttpStatus = hs;
mErrorCode = ec;
}
void OTSError::prettyPrint(string& out) const
{
out.append("{\"HttpStatus\": ");
pp::prettyPrint(out, mHttpStatus);
out.append(", \"ErrorCode\": \"");
out.append(mErrorCode);
out.append("\", \"Message\": \"");
out.append(mMessage);
if (!mRequestId.empty()) {
out.append("\", \"RequestId\": \"");
out.append(mRequestId);
}
if (!mTraceId.empty()) {
out.append("\", \"TraceId\": \"");
out.append(mTraceId);
}
out.append("\"}");
}
void OTSError::setHttpStatusFromErrorCode(const string& _ec)
{
MemPiece ec = MemPiece::from(_ec);
if (ec == MemPiece::from(kErrorCode_CouldntResolveHost)) {
mHttpStatus = kHttpStatus_CouldntResolveHost;
} else if (ec == MemPiece::from(kErrorCode_CouldntConnect)) {
mHttpStatus = kHttpStatus_CouldntConnect;
} else if (ec == MemPiece::from(kErrorCode_OTSRequestTimeout)) {
mHttpStatus = kHttpStatus_OperationTimeout;
} else if (ec == MemPiece::from(kErrorCode_WriteRequestFail)) {
mHttpStatus = kHttpStatus_WriteRequestFail;
} else if (ec == MemPiece::from(kErrorCode_CorruptedResponse)) {
mHttpStatus = kHttpStatus_CorruptedResponse;
} else if (ec == MemPiece::from(kErrorCode_NoAvailableConnection)) {
mHttpStatus = kHttpStatus_NoAvailableConnection;
} else if (ec == MemPiece::from(kErrorCode_OTSOutOfColumnCountLimit)) {
mHttpStatus = 400;
} else if (ec == MemPiece::from(kErrorCode_OTSObjectNotExist)) {
mHttpStatus = 404;
} else if (ec == MemPiece::from(kErrorCode_OTSServerBusy)) {
mHttpStatus = 503;
} else if (ec == MemPiece::from(kErrorCode_OTSCapacityUnitExhausted)) {
mHttpStatus = 403;
} else if (ec == MemPiece::from(kErrorCode_OTSTooFrequentReservedThroughputAdjustment)) {
mHttpStatus = 403;
} else if (ec == MemPiece::from(kErrorCode_OTSInternalServerError)) {
mHttpStatus = 500;
} else if (ec == MemPiece::from(kErrorCode_OTSQuotaExhausted)) {
mHttpStatus = 403;
} else if (ec == MemPiece::from(kErrorCode_OTSRequestBodyTooLarge)) {
mHttpStatus = 413;
} else if (ec == MemPiece::from(kErrorCode_OTSTimeout)) {
mHttpStatus = 503;
} else if (ec == MemPiece::from(kErrorCode_OTSObjectAlreadyExist)) {
mHttpStatus = 409;
} else if (ec == MemPiece::from(kErrorCode_OTSTableNotReady)) {
mHttpStatus = 404;
} else if (ec == MemPiece::from(kErrorCode_OTSConditionCheckFail)) {
mHttpStatus = 403;
} else if (ec == MemPiece::from(kErrorCode_OTSOutOfRowSizeLimit)) {
mHttpStatus = 400;
} else if (ec == MemPiece::from(kErrorCode_OTSInvalidPK)) {
mHttpStatus = 400;
} else if (ec == MemPiece::from(kErrorCode_OTSMethodNotAllowed)) {
mHttpStatus = 405;
} else if (ec == MemPiece::from(kErrorCode_OTSAuthFailed)) {
mHttpStatus = 403;
} else if (ec == MemPiece::from(kErrorCode_OTSServerUnavailable)) {
mHttpStatus = 503;
} else if (ec == MemPiece::from(kErrorCode_OTSParameterInvalid)) {
mHttpStatus = 400;
} else if (ec == MemPiece::from(kErrorCode_OTSRowOperationConflict)) {
mHttpStatus = 409;
} else if (ec == MemPiece::from(kErrorCode_OTSPartitionUnavailable)) {
mHttpStatus = 503;
} else if (ec == MemPiece::from(kErrorCode_SslHandshakeFail)) {
mHttpStatus = kHttpStatus_SslHandshakeFail;
} else {
mHttpStatus = 400;
}
}
bool isCurlError(const OTSError& err)
{
return err.httpStatus() > 0 && err.httpStatus() <= 99;
}
bool isTemporary(const OTSError& err)
{
if (err.httpStatus() >= 500 && err.httpStatus() <= 599) {
return true;
}
if (err.httpStatus() >= 400 && err.httpStatus() <= 499) {
MemPiece code = MemPiece::from(err.errorCode());
MemPiece msg = MemPiece::from(err.message());
if (code == MemPiece::from("OTSQuotaExhausted") && msg == MemPiece::from("Too frequent table operations.")) {
return true;
} else if (code == MemPiece::from("OTSRowOperationConflict")) {
return true;
} else if (code == MemPiece::from("OTSTableNotReady")) {
return true;
} else if (code == MemPiece::from("OTSTooFrequentReservedThroughputAdjustment")) {
return true;
} else if (code == MemPiece::from("OTSCapacityUnitExhausted")) {
return true;
} else if (code == MemPiece::from("OTSRequestTimeout")) {
return true;
}
}
if (isCurlError(err)) {
switch(err.httpStatus()) {
case OTSError::kHttpStatus_CouldntResolveHost:
case OTSError::kHttpStatus_CouldntConnect:
case OTSError::kHttpStatus_OperationTimeout:
case OTSError::kHttpStatus_WriteRequestFail:
case OTSError::kHttpStatus_CorruptedResponse:
case OTSError::kHttpStatus_NoAvailableConnection:
return true;
default:
break;
}
}
return false;
}
} // namespace core
} // namespace tablestore
} // namespace aliyun
| 41.549153 | 117 | 0.725381 | TimeExceed |
005b04f990045526bc490b386efddb77e7654851 | 1,462 | hpp | C++ | include/pyplot_cpp/plt/pyplot.hpp | CalebCintary/pyplot_cpp | de33c3e921229e5efd72a7fc4fdb17212edc9aa9 | [
"MIT"
] | 1 | 2022-03-29T10:52:21.000Z | 2022-03-29T10:52:21.000Z | include/pyplot_cpp/plt/pyplot.hpp | CalebCintary/pyplot_cpp | de33c3e921229e5efd72a7fc4fdb17212edc9aa9 | [
"MIT"
] | 1 | 2022-03-20T12:17:11.000Z | 2022-03-20T17:50:12.000Z | include/pyplot_cpp/plt/pyplot.hpp | CalebCintary/pyplot_cpp | de33c3e921229e5efd72a7fc4fdb17212edc9aa9 | [
"MIT"
] | 1 | 2022-03-29T19:40:59.000Z | 2022-03-29T19:40:59.000Z | //
// Created by calebcintary on 3/15/22.
//
// NOTE: Might be connection point between Dynamic Script and Embedded Interpreter
//
#ifndef PYPLOT_CPP_PYPLOT_HPP
#define PYPLOT_CPP_PYPLOT_HPP
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include "Property.hpp"
#include "pyplot_cpp/converter/converter.hpp"
#define PYPLOT_PropertyArray const std::map<std::string, Property>&
namespace pyplot_cpp {
namespace plt {
// ----- < Show able objects > -----
std::string plot(const std::string& x, const std::string& y, PYPLOT_PropertyArray args = {});
std::string plot(const std::vector<double>& x, std::vector<double>& y, PYPLOT_PropertyArray args = {});
std::string bar(const std::string& x, const std::string& y, PYPLOT_PropertyArray args = {});
std::string hist(const std::string& x, PYPLOT_PropertyArray args = {});
std::string scatter(const std::string& x, const std::string& y, PYPLOT_PropertyArray args = {});
// ----- < Different functions > -----
std::string import();
std::string xlabel(const std::string& xlabel);
std::string ylabel(const std::string& ylabel);
std::string title(const std::string& title);
std::string tight_layout();
std::string show();
std::string savefig(const std::string& path);
std::string legend(std::string legend_array);
}
}
#endif //PYPLOT_CPP_PYPLOT_HPP | 24.779661 | 111 | 0.650479 | CalebCintary |
00611f8b4fb0a8cb06bebf72cff0fb151704ec8a | 4,449 | cpp | C++ | privatedns/src/v20201028/model/TldQuota.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | privatedns/src/v20201028/model/TldQuota.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | privatedns/src/v20201028/model/TldQuota.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* 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/privatedns/v20201028/model/TldQuota.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Privatedns::V20201028::Model;
using namespace std;
TldQuota::TldQuota() :
m_totalHasBeenSet(false),
m_usedHasBeenSet(false),
m_stockHasBeenSet(false),
m_quotaHasBeenSet(false)
{
}
CoreInternalOutcome TldQuota::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Total") && !value["Total"].IsNull())
{
if (!value["Total"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `TldQuota.Total` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_total = value["Total"].GetInt64();
m_totalHasBeenSet = true;
}
if (value.HasMember("Used") && !value["Used"].IsNull())
{
if (!value["Used"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `TldQuota.Used` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_used = value["Used"].GetInt64();
m_usedHasBeenSet = true;
}
if (value.HasMember("Stock") && !value["Stock"].IsNull())
{
if (!value["Stock"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `TldQuota.Stock` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_stock = value["Stock"].GetInt64();
m_stockHasBeenSet = true;
}
if (value.HasMember("Quota") && !value["Quota"].IsNull())
{
if (!value["Quota"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `TldQuota.Quota` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_quota = value["Quota"].GetInt64();
m_quotaHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void TldQuota::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_totalHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Total";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_total, allocator);
}
if (m_usedHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Used";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_used, allocator);
}
if (m_stockHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Stock";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_stock, allocator);
}
if (m_quotaHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Quota";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_quota, allocator);
}
}
int64_t TldQuota::GetTotal() const
{
return m_total;
}
void TldQuota::SetTotal(const int64_t& _total)
{
m_total = _total;
m_totalHasBeenSet = true;
}
bool TldQuota::TotalHasBeenSet() const
{
return m_totalHasBeenSet;
}
int64_t TldQuota::GetUsed() const
{
return m_used;
}
void TldQuota::SetUsed(const int64_t& _used)
{
m_used = _used;
m_usedHasBeenSet = true;
}
bool TldQuota::UsedHasBeenSet() const
{
return m_usedHasBeenSet;
}
int64_t TldQuota::GetStock() const
{
return m_stock;
}
void TldQuota::SetStock(const int64_t& _stock)
{
m_stock = _stock;
m_stockHasBeenSet = true;
}
bool TldQuota::StockHasBeenSet() const
{
return m_stockHasBeenSet;
}
int64_t TldQuota::GetQuota() const
{
return m_quota;
}
void TldQuota::SetQuota(const int64_t& _quota)
{
m_quota = _quota;
m_quotaHasBeenSet = true;
}
bool TldQuota::QuotaHasBeenSet() const
{
return m_quotaHasBeenSet;
}
| 24.445055 | 131 | 0.657901 | suluner |
00624f992da46ccb401186131cc5d4d2df6f1944 | 556 | cpp | C++ | Game/ZeldaDS/arm9/source/gslib/Hw/CpuClock.cpp | amaiorano/ZeldaDS | 78b093796a17ca0aaef4ff8b53a41fe59adc072e | [
"MIT"
] | 2 | 2018-02-18T19:11:39.000Z | 2020-08-16T18:16:35.000Z | Game/ZeldaDS/arm9/source/gslib/Hw/CpuClock.cpp | amaiorano/ZeldaDS | 78b093796a17ca0aaef4ff8b53a41fe59adc072e | [
"MIT"
] | null | null | null | Game/ZeldaDS/arm9/source/gslib/Hw/CpuClock.cpp | amaiorano/ZeldaDS | 78b093796a17ca0aaef4ff8b53a41fe59adc072e | [
"MIT"
] | null | null | null | #include "CpuClock.h"
#include <nds/timers.h>
namespace CpuClock
{
namespace
{
CpuTickType gLastFrameElapsedTicks = 0;
const uint32 gTimerChannel = 0;
}
void Update()
{
gLastFrameElapsedTicks = cpuEndTiming();
cpuStartTiming(gTimerChannel); // Restart timer for this frame
}
CpuTickType GetLastFrameElapsedTicks()
{
return gLastFrameElapsedTicks;
}
CpuTickType GetCurrFrameElapsedTicks()
{
//@TODO: Add cpuGetElapsed() that does the following...
return ( (TIMER_DATA(gTimerChannel) | (TIMER_DATA(gTimerChannel+1)<<16) ));
}
}
| 19.172414 | 77 | 0.730216 | amaiorano |
0064c2a0436cffecfcc6c0c09b31b80c8bc15810 | 1,885 | cpp | C++ | 2021/day20/main.cpp | bielskij/AOC-2019 | e98d660412037b3fdac4a6b49adcb9230f518c99 | [
"MIT"
] | null | null | null | 2021/day20/main.cpp | bielskij/AOC-2019 | e98d660412037b3fdac4a6b49adcb9230f518c99 | [
"MIT"
] | null | null | null | 2021/day20/main.cpp | bielskij/AOC-2019 | e98d660412037b3fdac4a6b49adcb9230f518c99 | [
"MIT"
] | null | null | null | #include "common/types.h"
#include "utils/file.h"
#include "utils/utils.h"
#define DEBUG_LEVEL 5
#include "common/debug.h"
int main(int argc, char *argv[]) {
std::string algorithm;
std::vector<std::string> image;
{
bool parseAlgorithm = true;
for (const auto &line : File::readAllLines(argv[1])) {
if (line.empty()) {
parseAlgorithm = false;
} else {
if (parseAlgorithm) {
algorithm = line;
} else {
image.push_back(line);
}
}
}
}
{
std::vector<std::string> srcImage = image;
std::vector<std::string> result;
int padding = 0;
int xMod[] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
int yMod[] = { -1, -1, -1, 0, 0, 0, 1, 1, 1 };
for (int i = 0; i < 50; i++) {
result.clear();
if (padding != 3) {
padding = 3;
} else {
padding = -1;
}
for (int row = 0; row < srcImage.size() + padding * 2; row++) {
std::string outRow;
for (int col = 0; col < srcImage[0].length() + padding * 2; col++) {
int padRow = row - padding;
int padCol = col - padding;
int index = 0;
for (int idx = 0; idx < 9; idx++) {
int cx = padCol + xMod[8 - idx];
int cy = padRow + yMod[8 - idx];
if (
(cy >= 0) && (cy < srcImage.size()) &&
(cx >= 0) && (cx < srcImage[0].length())
) {
index |= (((srcImage[cy][cx] == '#') ? 1 : 0) << idx);
}
}
outRow.push_back(algorithm[index]);
}
result.push_back(outRow);
}
if ((i == 1) || (i == 49)) {
int litNum = 0;
for (const auto &r : result) {
for (auto c : r) {
if (c == '#') {
litNum++;
}
}
}
PRINTF(("PART_%c: %d", i == 1 ? 'A' : 'B', litNum));
}
srcImage = result;
}
#if 0
for (const auto &r : result) {
for (auto c : r) {
printf("%c", c);
}
printf("\n");
}
printf("\n");
#endif
}
return 0;
}
| 17.616822 | 72 | 0.481698 | bielskij |
006579b4fa6323be66e30c61ffd782770a19917a | 608 | cpp | C++ | VideoPaletteExtraction/VideoPaletteExtraction/SystemParameter.cpp | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | d48f4fa942910b7e855eded4f1a2801db22050e4 | [
"MIT"
] | 10 | 2021-10-02T10:22:33.000Z | 2022-02-16T07:11:22.000Z | VideoPaletteExtraction/VideoPaletteExtraction/SystemParameter.cpp | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | d48f4fa942910b7e855eded4f1a2801db22050e4 | [
"MIT"
] | null | null | null | VideoPaletteExtraction/VideoPaletteExtraction/SystemParameter.cpp | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | d48f4fa942910b7e855eded4f1a2801db22050e4 | [
"MIT"
] | 5 | 2021-10-02T14:00:50.000Z | 2022-02-08T06:25:06.000Z | #include "SystemParameter.h"
int SysParameter::frmCnt = 0;
int SysParameter::sampFrmCnt = 0;
int SysParameter::sampFrmPixCnt = 0;
double SysParameter::frmRefineRlossWt = 0;
double SysParameter::frmRefineClossWt = 0;
double SysParameter::blockAlpha = 0;
double SysParameter::blockBeta = 0;
double SysParameter::blockRlossWt = 0;
double SysParameter::blockClossWt = 0;
double SysParameter::blockSlossWt = 0;
double SysParameter::blockTh = 0;
double SysParameter::simplifyRlossWt = 0;
double SysParameter::simplifyClossWt = 0;
double SysParameter::simplifySlossWt = 0;
double SysParameter::simplifyTh = 0;
| 28.952381 | 42 | 0.784539 | Zhengjun-Du |
0066bc0e3588ff1af61067c4f710fa505c4bb122 | 4,475 | cpp | C++ | src/examples/example3.cpp | mohistH/nanogui_from_dalerank | ae4b5e04b2d8e2e85ab63b737fd13f8882243526 | [
"MIT"
] | 2 | 2021-01-05T08:50:59.000Z | 2021-08-17T09:09:55.000Z | src/examples/example3.cpp | mohistH/nanogui_from_dalerank | ae4b5e04b2d8e2e85ab63b737fd13f8882243526 | [
"MIT"
] | null | null | null | src/examples/example3.cpp | mohistH/nanogui_from_dalerank | ae4b5e04b2d8e2e85ab63b737fd13f8882243526 | [
"MIT"
] | 1 | 2021-08-17T09:09:57.000Z | 2021-08-17T09:09:57.000Z | /*
src/example3.cpp -- C++ version of an example application that shows
how to use nanogui in an application with an already created and managed
glfw context.
NanoGUI was developed by Wenzel Jakob <[email protected]>.
The widget drawing code is based on the NanoVG demo application
by Mikko Mononen.
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE.txt file.
*/
// GLFW
//
#if defined(NANOGUI_GLAD)
#if defined(NANOGUI_SHARED) && !defined(GLAD_GLAPI_EXPORT)
#define GLAD_GLAPI_EXPORT
#endif
#include <glad/glad.h>
#else
#if defined(__APPLE__)
#define GLFW_INCLUDE_GLCOREARB
#else
#define GL_GLEXT_PROTOTYPES
#endif
#endif
#include <nanogui/screen.h>
#include <nanogui/window.h>
#include <nanogui/layout.h>
#include <nanogui/label.h>
#include <nanogui/checkbox.h>
#include <nanogui/dial.h>
#include <nanogui/button.h>
#include <nanogui/toolbutton.h>
#include <nanogui/popupbutton.h>
#include <nanogui/combobox.h>
#include <nanogui/progressbar.h>
#include <nanogui/entypo.h>
#include <nanogui/meter.h>
#include <nanogui/messagedialog.h>
#include <nanogui/textbox.h>
#include <nanogui/slider.h>
#include <nanogui/imagepanel.h>
#include <nanogui/imageview.h>
#include <nanogui/vscrollpanel.h>
#include <nanogui/colorwheel.h>
#include <nanogui/colorpicker.h>
#include <nanogui/table.h>
#include <nanogui/graph.h>
#include <nanogui/ledmatrix.h>
#include <nanogui/tabwidget.h>
#include <nanogui/switchbox.h>
#include <nanogui/spinner.h>
#include <nanogui/dropdownbox.h>
#include <nanogui/editworkspace.h>
#include <nanogui/editproperties.h>
#include <nanogui/scrollbar.h>
#include <nanogui/windowmenu.h>
#include <nanogui/perfchart.h>
#include <nanogui/common.h>
#include <nanogui/listbox.h>
#include <nanogui/themebuilder.h>
#include <nanogui/tolerancebar.h>
#include <nanogui/treeview.h>
#include <nanogui/treeviewitem.h>
#include <nanogui/picflow.h>
#include <nanogui/textarea.h>
#include <nanogui/searchbox.h>
#include <nanogui/editproperties.h>
#include <nanogui/formhelper.h>
#include <iostream>
using namespace nanogui;
enum test_enum {
Item1 = 0,
Item2,
Item3
};
bool bvar = true;
int ivar = 12345678;
double dvar = 3.1415926;
float fvar = (float)dvar;
std::string strval = "A string";
test_enum enumval = Item2;
Color colval(0.5f, 0.5f, 0.7f, 1.f);
int main(int /* argc */, char ** /* argv */) {
nanogui::init();
Vector2i size{ 1600, 900 };
auto window = nanogui::sample::create_window(size.x(), size.y(), "Example Nanogui", true, false, true);
nanogui::sample::create_context();
{
// Create a nanogui screen and pass the glfw pointer to initialize
Screen nscreen(size, "NanoGUI Test", false);
nanogui::sample::setup_window_params(window, &nscreen);
// Create nanogui gui
bool enabled = true;
FormHelper *gui = new FormHelper(&nscreen);
ref<Window> nanoguiWindow = gui->addWindow({ 10, 10 }, "Form helper example");
gui->addGroup("Basic types");
gui->addVariable("bool", bvar)->setTooltip("Test tooltip.");
gui->addVariable("string", strval);
gui->addGroup("Validating fields");
gui->addVariable("int", ivar)->setSpinnable(true);
gui->addVariable("float", fvar)->setTooltip("Test.");
gui->addVariable("double", dvar)->setSpinnable(true);
gui->addGroup("Complex types");
gui->addVariable("Enumeration", enumval, enabled)->setItems({ "Item 1", "Item 2", "Item 3" });
gui->addVariable("Color", colval)
->setFinalCallback([](const Color &c) {
std::cout << "ColorPicker Final Callback: ["
<< c.r() << ", "
<< c.g() << ", "
<< c.b() << ", "
<< c.w() << "]" << std::endl;
});
gui->addGroup("Other widgets");
gui->addButton("A button", []() { std::cout << "Button pressed." << std::endl; })->setTooltip("Testing a much longer tooltip, that will wrap around to new lines multiple times.");;
nscreen.setVisible(true);
nscreen.performLayout();
nscreen.drawAll();
nanogui::sample::run([&] {
nanogui::sample::clear_frame(nscreen.background());
nscreen.drawAll();
nanogui::sample::present_frame(window);
/* Wait for mouse/keyboard or empty refresh events */
nanogui::sample::wait_events();
});
nanogui::sample::poll_events();
}
nanogui::sample::destroy_window(window);
nanogui::shutdown();
return 0;
}
| 28.503185 | 184 | 0.679777 | mohistH |
006a814318fbd236ff070c9008cd1307032ee45f | 925 | cpp | C++ | message/pong.cpp | kagamikarasu/shaula | cbda881578669cbf407845e46a9a9f988a155aba | [
"MIT"
] | null | null | null | message/pong.cpp | kagamikarasu/shaula | cbda881578669cbf407845e46a9a9f988a155aba | [
"MIT"
] | 13 | 2021-08-09T10:25:28.000Z | 2021-08-12T07:39:05.000Z | message/pong.cpp | kagamikarasu/shaula | cbda881578669cbf407845e46a9a9f988a155aba | [
"MIT"
] | null | null | null | //
// Pong.cpp
//
// Copyright (c) 2021 Yuya Takeda (@kagamikarasu)
//
// MIT LICENSE
// See the following LICENSE file
// https://github.com/kagamikarasu/shaula/
//
#include "pong.h"
Pong::Pong(const std::vector<unsigned char> &bytes) {
setCommand(CommandDef.PONG);
setNonce(bytes);
}
void Pong::setNonce(const std::vector<unsigned char> &bytes) {
nonce_ = bytes;
}
std::vector<unsigned char> Pong::getMessage() {
std::vector<unsigned char> payload;
payload.insert(payload.end(), nonce_.begin(), nonce_.end());
Message::setPayload(payload);
return Message::getMessage();
}
void Pong::send(
boost::asio::ip::tcp::socket &socket,
const boost::asio::yield_context &yield,
LastSend& last_send,
const std::vector<unsigned char> &bytes) {
auto v = std::make_unique<Pong>(bytes);
v->sendMessage(socket, yield);
last_send.setHeader(v->getHeader());
} | 22.02381 | 64 | 0.656216 | kagamikarasu |
0075720f22d3e68212c06e73df62b3cd9ae10eac | 3,104 | cpp | C++ | source/Ch19/chapter/vector010_2.cpp | Fantasztikus21/UDProg-Introduction | 3828bf41bdfa483decd27aa1a9ab62b5d2633245 | [
"CC0-1.0"
] | 3 | 2021-11-02T08:30:53.000Z | 2022-02-28T07:32:25.000Z | source/Ch19/chapter/vector010_2.cpp | Fantasztikus21/UDProg-Introduction | 3828bf41bdfa483decd27aa1a9ab62b5d2633245 | [
"CC0-1.0"
] | 1 | 2020-11-10T15:58:17.000Z | 2020-11-10T15:58:17.000Z | source/Ch19/chapter/vector010_2.cpp | Fantasztikus21/UDProg-Introduction | 3828bf41bdfa483decd27aa1a9ab62b5d2633245 | [
"CC0-1.0"
] | 122 | 2020-09-12T08:29:45.000Z | 2022-03-04T10:22:46.000Z | #include "../std_lib_facilities.h"
class My_out_of_range{};
class My_vector {
int sz;
double* elem;
int space;
void debug(const string& s)
{
cerr << this << "->" << s << "; elem ptr: " << elem << '\n';
}
public:
My_vector(): sz{0}, elem{nullptr}, space{0} {}
explicit My_vector(int s): sz{s}, elem{new double[s]}, space{s}
{
for(int i = 0; i < sz; ++i) elem[i] = 0;
//debug("(int s) constructor");
}
My_vector(initializer_list<double> lst):
sz{lst.size()}, elem{new double[sz]}, space{sz}
{
copy(lst.begin(), lst.end(), elem);
//debug("(initializer_list<double> lst) constructor");
}
My_vector(const My_vector& arg):
sz{arg.sz}, elem{new double[arg.sz]}, space{arg.sz}
{
copy(arg.elem, arg.elem + arg.sz, elem);
//debug("copy constructor");
}
My_vector& operator=(const My_vector& arg)
{
if(this==&arg) return *this;
if(arg.sz <= space)
{
for(int i = 0; i < arg.sz; ++i) elem[i] = arg.elem[i];
sz = arg.sz;
return *this;
}
double* p = new double[arg.sz];
copy(arg.elem, arg.elem + arg.sz, p);
delete[] elem;
space = arg.sz;
sz = arg.sz;
elem = p;
//debug("copy assigment");
return *this;
}
My_vector(My_vector&& arg): sz{arg.sz}, elem{arg.elem}, space{arg.space}
{
arg.sz = 0;
arg.space = 0;
arg.elem = nullptr;
//debug("move constructor");
}
My_vector& operator=(My_vector&& arg)
{
delete[] elem;
elem = arg.elem;
sz = arg.sz;
space = arg.space;
arg.elem = nullptr;
arg.sz = 0;
arg.space = 0;
//debug("move assigment");
return *this;
}
~My_vector()
{
//debug("destructor");
delete[] elem;
}
double& operator[](int n) { return elem[n]; }
double operator[](int n) const { return elem[n]; }
//double get(int n) const { return elem[n]; }
//void set(int n, double d) { elem[n] = d; }
int size() const { return sz; }
int capacity() const { return space; }
void reserve(int newalloc)
{
if(newalloc <= space) return;
double* p = new double[newalloc];
for(int i = 0; i < sz; ++i) p[i] = elem[i];
delete[] elem;
elem = p;
space = newalloc;
}
void resize(int newsize)
{
reserve(newsize);
for(int i = sz; i < newsize; ++i) elem[i] = 0;
sz = newsize;
}
void push_back(double d)
{
if(sz == 0)
reserve(8);
else if(sz == space)
reserve(2 * space);
elem[sz] = d;
++sz;
}
double& at(int n)
{
if(n < 0 || sz <= n) throw My_out_of_range{};
return elem[n];
}
double at(int n) const
{
if(n < 0 || sz <= n) throw My_out_of_range{};
return elem[n];
}
};
My_vector* some_fct()
{
My_vector* myvec = new My_vector(10);
// fill vector
return myvec;
}
My_vector fill()
{
My_vector res = {12.2, 13.3, 14.4};
return res;
}
int main()
try {
My_vector v1;
cout << "\tsize: " << v1.size() << ' ';
cout << "\tspace: " << v1.capacity() << '\n';
for(int i = 0; i < 9; ++i)
{
v1.push_back(i);
cout << v1.at(i) << ' ';
cout << "\tsize: " << v1.size() << ' ';
cout << "\tspace: " << v1.capacity() << '\n';
}
cout << v1.at(-1) << '\n';
return 0;
} catch (My_out_of_range) {
cerr << "Out of range!\n";
return 1;
}
| 18.046512 | 73 | 0.568621 | Fantasztikus21 |
007bdb80aac3224dded2221d1ab1258e9ad9edb8 | 3,733 | cpp | C++ | Curses/WindowSystem.cpp | takeupcode/TUCUT | 17ef8064792b6b74e311d6438f43970cc97dba77 | [
"MIT"
] | 8 | 2018-10-29T02:42:52.000Z | 2021-02-04T17:37:14.000Z | Curses/WindowSystem.cpp | takeupcode/TUCUT | 17ef8064792b6b74e311d6438f43970cc97dba77 | [
"MIT"
] | null | null | null | Curses/WindowSystem.cpp | takeupcode/TUCUT | 17ef8064792b6b74e311d6438f43970cc97dba77 | [
"MIT"
] | 1 | 2019-11-07T02:18:23.000Z | 2019-11-07T02:18:23.000Z | //
// WindowSystem.cpp
// TUCUT (Take Up Code Utility)
//
// Created by Abdul Wahid Tanner on 10/26/17.
// Copyright © 2017 Take Up Code. All rights reserved.
//
#include "WindowSystem.h"
#include <curses.h>
#include "Colors.h"
#include "CursesUtil.h"
#include "ConsoleManager.h"
#include "Window.h"
namespace TUCUT {
namespace Curses {
const std::string WindowSystem::defaultToken = "WindowSystem";
std::shared_ptr<WindowSystem> WindowSystem::getSharedWindowSystem ()
{
return std::static_pointer_cast<WindowSystem>(shared_from_this());
}
WindowSystem::WindowSystem (const std::string & token, int identity)
: GameSystem(token, identity), mScreenMaxX(0), mScreenMaxY(0),
mMinScreenWidth(0), mMinScreenHeight(0), mMaxScreenWidth(80), mMaxScreenHeight(40),
mNextWindow(nullptr), mCurrentWindow(nullptr)
{ }
WindowSystem::~WindowSystem ()
{
deinitialize();
}
void WindowSystem::addWindow(const std::shared_ptr<Window> & window)
{
mWindows.push_back(window);
}
void WindowSystem::addWindow(std::shared_ptr<Window> && window)
{
mWindows.push_back(std::move(window));
}
void WindowSystem::selectNextWindow(const std::string & name)
{
for (auto & win: mWindows)
{
if (win->name() == name)
{
mNextWindow = win.get();
break;
}
}
}
int WindowSystem::screenWidth () const
{
return mScreenMaxX + 1;
}
int WindowSystem::screenHeight () const
{
return mScreenMaxY + 1;
}
int WindowSystem::minScreenWidth () const
{
return mMinScreenWidth;
}
int WindowSystem::minScreenHeight () const
{
return mMinScreenHeight;
}
void WindowSystem::setMinScreenDimensions (int height, int width)
{
mMinScreenHeight = height;
mMinScreenWidth = width;
}
int WindowSystem::maxScreenWidth () const
{
return mMaxScreenWidth;
}
int WindowSystem::maxScreenHeight () const
{
return mMaxScreenHeight;
}
void WindowSystem::setMaxScreenDimensions (int height, int width)
{
mMaxScreenHeight = height;
mMaxScreenWidth = width;
}
void WindowSystem::initialize ()
{
GameSystem::initialize();
initscr();
start_color();
raw();
noecho();
curs_set(0);
nodelay(stdscr, true);
keypad(stdscr, true);
mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, nullptr);
Colors::initializeColorPairs();
CursesUtil::getScreenMaxYX(mScreenMaxY, mScreenMaxX);
}
void WindowSystem::deinitialize ()
{
endwin();
}
void WindowSystem::handleInput ()
{
if (mNextWindow)
{
// Switch current window at the beginning of the loop.
mCurrentWindow = mNextWindow;
mNextWindow = nullptr;
}
if (!mCurrentWindow)
{
return;
}
mCurrentWindow->processInput(this);
}
void WindowSystem::update (Game::TimeResolution elapsedTime)
{
if (!mCurrentWindow)
{
return;
}
CursesUtil::getScreenMaxYX(mScreenMaxY, mScreenMaxX);
mCurrentWindow->resize(checkHeightBounds(screenHeight()), checkWidthBounds(screenWidth()));
mCurrentWindow->update();
}
void WindowSystem::render ()
{
if (!mCurrentWindow)
{
return;
}
mCurrentWindow->draw();
doupdate();
}
int WindowSystem::checkHeightBounds (int height) const
{
if (height < mMinScreenHeight)
{
return mMinScreenHeight;
}
if (height > mMaxScreenHeight)
{
return mMaxScreenHeight;
}
return height;
}
int WindowSystem::checkWidthBounds (int width) const
{
if (width < mMinScreenWidth)
{
return mMinScreenWidth;
}
if (width > mMaxScreenWidth)
{
return mMaxScreenWidth;
}
return width;
}
} // namespace Curses
} // namespace TUCUT
| 18.665 | 95 | 0.665149 | takeupcode |
008201a15e8f07132fd91304cfcdb2ad15982666 | 1,385 | cpp | C++ | graphics/Win32Adapter.cpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 26 | 2015-04-22T05:25:25.000Z | 2020-11-15T11:07:56.000Z | graphics/Win32Adapter.cpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 2 | 2015-01-05T10:41:27.000Z | 2015-01-06T20:46:11.000Z | graphics/Win32Adapter.cpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 5 | 2016-08-02T11:13:57.000Z | 2018-10-26T11:19:27.000Z | #include "Win32Adapter.hpp"
#include "Win32Monitor.hpp"
#include "../platform/Win32Window.hpp"
#include "../Strings.hpp"
BEGIN_INANITY_GRAPHICS
Win32Adapter::Win32Adapter(const DISPLAY_DEVICE& info)
: info(info), monitorsInitialized(false)
{
deviceName = Strings::Unicode2UTF8(info.DeviceName);
deviceString = Strings::Unicode2UTF8(info.DeviceString);
}
String Win32Adapter::GetId() const
{
return deviceName;
}
String Win32Adapter::GetName() const
{
return deviceString;
}
const Adapter::Monitors& Win32Adapter::GetMonitors()
{
if(!monitorsInitialized)
{
for(int i = 0; ; ++i)
{
DISPLAY_DEVICE monitorInfo;
monitorInfo.cb = sizeof(monitorInfo);
if(!EnumDisplayDevices(info.DeviceName, i, &monitorInfo, EDD_GET_DEVICE_INTERFACE_NAME))
break;
monitors.push_back(NEW(Win32Monitor(monitorInfo)));
}
monitorsInitialized = false;
}
return monitors;
}
void Win32Adapter::GetAdapters(Adapters& adapters)
{
for(int i = 0; ; ++i)
{
DISPLAY_DEVICE adapterInfo;
adapterInfo.cb = sizeof(adapterInfo);
if(!EnumDisplayDevices(NULL, i, &adapterInfo, 0))
break;
adapters.push_back(NEW(Win32Adapter(adapterInfo)));
}
}
ptr<Platform::Window> Win32Adapter::CreateOptimizedWindow(const String& title, int left, int top, int width, int height)
{
return Platform::Win32Window::CreateForOpenGL(title, left, top, width, height);
}
END_INANITY_GRAPHICS
| 22.33871 | 120 | 0.745848 | quyse |
0a5c7abc3c228f7abcd6a7cf3917a7d93b2104e8 | 3,246 | cpp | C++ | test/che/assembly.cpp | shze/biosim | e9e6d97de0ccf8067e1db15980eb600389fff6ca | [
"MIT"
] | null | null | null | test/che/assembly.cpp | shze/biosim | e9e6d97de0ccf8067e1db15980eb600389fff6ca | [
"MIT"
] | null | null | null | test/che/assembly.cpp | shze/biosim | e9e6d97de0ccf8067e1db15980eb600389fff6ca | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include "che/assembly.h" // header to test
using namespace biosim;
BOOST_AUTO_TEST_SUITE(suite_assembly)
BOOST_AUTO_TEST_CASE(assembly_ctor) {
che::assembly a;
BOOST_CHECK(a.get_chain_id_list().empty());
BOOST_CHECK(a.get_ensemble_size("A") == 0);
BOOST_CHECK(a.has_ensemble("A") == false);
BOOST_REQUIRE_THROW(a.get_ensemble("A"), std::out_of_range);
BOOST_REQUIRE_THROW(a.get_first_structure("A"), std::out_of_range);
BOOST_CHECK(a.get_first_structures().empty() == true);
std::string storage = "some_storage";
std::string id = "some_id";
che::structure s(storage, id);
a = che::assembly(s);
BOOST_CHECK(a.get_chain_id_list().size() == 1);
BOOST_CHECK(a.get_ensemble_size("A") == 1);
BOOST_CHECK(a.has_ensemble("A") == true);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1);
BOOST_CHECK(a.get_first_structure("A").get_identifier() == id);
BOOST_CHECK(a.get_first_structures().size() == 1);
std::list<che::structure> structures{s, che::structure()};
che::structure_ensemble e(structures.begin(), structures.end());
a = che::assembly(e);
BOOST_CHECK(a.get_chain_id_list().size() == 1);
BOOST_CHECK(a.get_ensemble_size("A") == 2);
BOOST_CHECK(a.has_ensemble("A") == true);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 2);
BOOST_CHECK(a.get_first_structure("A").get_identifier() == id);
BOOST_CHECK(a.get_first_structures().size() == 1);
}
BOOST_AUTO_TEST_CASE(assembly_add_set) {
std::string storage = "some_storage";
std::string id = "some_id";
che::structure s(storage, id);
che::assembly a;
BOOST_CHECK(a.get_chain_id_list().size() == 0);
BOOST_CHECK(a.add(s) == "A"); // check returned chain_id
BOOST_CHECK(a.get_chain_id_list().size() == 1);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1);
a.set("A", s);
BOOST_CHECK(a.get_chain_id_list().size() == 1);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1);
BOOST_CHECK(a.has_ensemble("B") == false);
a.set("C", s);
BOOST_CHECK(a.get_chain_id_list().size() == 2);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1);
BOOST_CHECK(a.get_ensemble("C").get_samples().size() == 1);
BOOST_CHECK(a.has_ensemble("B") == false);
BOOST_CHECK(a.has_ensemble("C") == true);
BOOST_CHECK(a.has_ensemble("D") == false);
std::list<che::structure> structures{s, che::structure()};
che::structure_ensemble e(structures.begin(), structures.end());
a = che::assembly();
BOOST_CHECK(a.get_chain_id_list().size() == 0);
BOOST_CHECK(a.add(e) == "A"); // check returned chain_id
BOOST_CHECK(a.get_chain_id_list().size() == 1);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 2);
a.set("A", s);
BOOST_CHECK(a.get_chain_id_list().size() == 1);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1);
BOOST_CHECK(a.has_ensemble("B") == false);
a.set("C", e);
BOOST_CHECK(a.get_chain_id_list().size() == 2);
BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1);
BOOST_CHECK(a.get_ensemble("C").get_samples().size() == 2);
BOOST_CHECK(a.has_ensemble("B") == false);
BOOST_CHECK(a.has_ensemble("C") == true);
BOOST_CHECK(a.has_ensemble("D") == false);
}
BOOST_AUTO_TEST_SUITE_END()
| 37.744186 | 69 | 0.679914 | shze |
0a5f0d8efe00fe669f0d8175bd00f244b03de745 | 1,330 | cpp | C++ | 3DRadSpace/3DRadSpaceDll/Quaternion.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 9 | 2017-01-10T11:47:06.000Z | 2021-11-27T14:32:55.000Z | 3DRadSpace/3DRadSpaceDll/Quaternion.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | null | null | null | 3DRadSpace/3DRadSpaceDll/Quaternion.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 6 | 2017-07-08T23:03:43.000Z | 2022-03-08T07:47:13.000Z | #include "Quaternion.hpp"
Engine3DRadSpace::Quaternion Engine3DRadSpace::Quaternion::CreateFromYawPitchRoll(float yaw, float pitch, float roll)
{
float halfRoll = roll * 0.5f;
float halfPitch = pitch * 0.5f;
float halfYaw = yaw * 0.5f;
float sinRoll = sin(halfRoll);
float cosRoll = cos(halfRoll);
float sinPitch = sin(halfPitch);
float cosPitch = cos(halfPitch);
float sinYaw = sin(halfYaw);
float cosYaw = cos(halfYaw);
return Quaternion((cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll),
(sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll),
(cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll),
(cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll));
}
Engine3DRadSpace::Quaternion Engine3DRadSpace::operator*(const Quaternion& q1, const Quaternion& q2)
{
float x = q1.X;
float y = q1.Y;
float z = q1.Z;
float w = q1.W;
float num4 = q2.X;
float num3 = q2.Y;
float num2 = q2.Z;
float num = q2.W;
float num12 = (y * num2) - (z * num3);
float num11 = (z * num4) - (x * num2);
float num10 = (x * num3) - (y * num4);
float num9 = ((x * num4) + (y * num3)) + (z * num2);
return Quaternion( ((x * num) + (num4 * w)) + num12, ((y * num) + (num3 * w)) + num11,((z * num) + (num2 * w)) + num10, (w * num) - num9);
}
| 34.102564 | 139 | 0.616541 | NicusorN5 |
0a610905dbf99cb1321d411431ceb988292c8cbb | 3,272 | hpp | C++ | src/gestion-fichiers/ifile.hpp | minijackson/IGI-3004 | 8354f40e296cce8735b188dd3ff7406e96d5878e | [
"MIT"
] | 1 | 2017-10-01T02:29:06.000Z | 2017-10-01T02:29:06.000Z | src/gestion-fichiers/ifile.hpp | minijackson/IGI-3004 | 8354f40e296cce8735b188dd3ff7406e96d5878e | [
"MIT"
] | null | null | null | src/gestion-fichiers/ifile.hpp | minijackson/IGI-3004 | 8354f40e296cce8735b188dd3ff7406e96d5878e | [
"MIT"
] | null | null | null | #pragma once
#include "utility.hpp"
/*! \brief Represents an input file.
*
* This class implements the RAII idiom.
*/
template <typename flag = unbuffered_flag>
class IFile : public DummyFile<flag, true> {
static_assert(std::is_same<flag, buffered_flag>::value ||
std::is_same<flag, unbuffered_flag>::value,
"An IFile must either be buffered or unbuffered.");
public:
/*! \brief Construct a dummy file reader.
*
* This object will not be associated with a file.
*/
IFile() noexcept;
/*! \brief IFile constructor with file descriptor.
*
* This constructor will not open the file nor will it close it on
* destruction.
*/
IFile(int const fd, size_t const bufSize) noexcept;
/*! \brief IFile constructor with file name.
*
* This constructor will open the file.
*/
IFile(char const* filename, size_t const bufSize);
/*! \brief IFile destructor.
*
* Will close the file if the object was constructed with the file name.
*/
~IFile();
// Non-copyable object
IFile(const IFile&) = delete;
IFile& operator=(const IFile&) = delete;
/*! \brief Move-construct the file reader.
*
* The previous reader will be transformed to a dummy IFile
*
* \param other the IFile to be moved.
*/
IFile(IFile&& other) noexcept;
/*! \brief Move-assign the file reader.
*
* The previous reader will be transformed to a dummy IFile
*
* \param other the IFile to be moved.
* \return the moved IFile
*/
IFile& operator=(IFile&& other) noexcept;
/*! \brief Read a line from the file.
*
* \param line the string to write the line to.
*
* \return the current object (for chaining operator>>).
*/
IFile& operator>>(char* line);
/*! \brief close the file associated with this object.
*/
void close();
/*! \brief Get the file's file descriptor.
*
* \return the file's file descriptor.
*/
int getFd() const;
/*! \brief Get the size of the buffer.
*
* \return the size of the buffer.
*/
size_t getBufSize() const;
/*! \brief Check if the end-of-file has been reached.
*
* \return `true` if the end-of-file has been reached.
*/
bool hasEnded() const;
/*! \brief Check if the object opened file.
*
* \return `true` if the object opened the file.
*/
bool hasOpenedTheFile() const;
protected:
/*! \brief Open the file in read-only mode.
*
* Will set the `openedTheFile` attribute to `true`.
*
* \param filename The name of the file to open.
*
* \return the opened file's file descriptor.
*/
int openFile(char const* filename) noexcept(false);
/*! \brief Read one line of the file.
*
* \param buf the buffer to write the line to.
*/
void getLine(char* buf) noexcept(false);
/*! \brief True if this object is a dummy reader.
*/
bool dummy = false;
/*! \brief The file descriptor of the current file.
*/
int fd;
/*! \brief The size of the buffer for reading.
*
* If a line in the file is longer than the buffer size, the whole line
* will not be returned.
*/
size_t bufSize;
/*! \brief `true` if the end-of-file has been reached, `false` otherwise.
*/
bool ended = false;
/*! \brief `true` if the current object is the one that opened the file.
*/
bool openedTheFile = false;
};
#include "ifile.tcc"
| 23.371429 | 74 | 0.661369 | minijackson |
0a6bc0065750fa6fc0ad16ec4c90ec157bd6c068 | 2,606 | cpp | C++ | ixperial/ixperial-main/lua-entity.cpp | aw-3/ixperial | 8406ac3265e572cf6a4fb4b53ae36936d550f4fe | [
"MIT"
] | 1 | 2019-07-14T04:01:42.000Z | 2019-07-14T04:01:42.000Z | ixperial/ixperial-main/lua-entity.cpp | aw-3/ixperial | 8406ac3265e572cf6a4fb4b53ae36936d550f4fe | [
"MIT"
] | null | null | null | ixperial/ixperial-main/lua-entity.cpp | aw-3/ixperial | 8406ac3265e572cf6a4fb4b53ae36936d550f4fe | [
"MIT"
] | null | null | null | #include "stdafx.h"
void* LuaEntity::GetEntityFromIndex(int i)
{
static void *listPtr = (int*)sigScan((int)CSGO::GetClientHandle(), "\xBB\x00\x00\x00\x00\x83\xFF\x01\x0F\x8C\x00\x00\x00\x00\x3B\xF8");
int list = *(int*)((char*)listPtr + 1);
return *(int**)(list + (i * 0x10));
}
RefCountedPtr<LuaEntity> LuaEntity::GetLocalPlayer()
{
static void* lpPtr = (int*)sigScan((int)CSGO::GetClientHandle(), "\xA3\x00\x00\x00\x00\xC7\x05\x00\x00\x00\x00\x00\x00\x00\x00\xE8\x00\x00\x00\x00\x59\xC3\x6A\x00");
int localEntPtr = *(*((int**)((int)lpPtr + 1)) + 4);
LuaEntity *localEnt = new LuaEntity(0);
localEnt->pEntity = localEntPtr;
return RefCountedPtr<LuaEntity>(localEnt);
}
void LuaEntity::UpdateEntity() const
{
if (!pEntity)
{
//pEntity = (int)GetEntityFromIndex(idx);
}
}
bool LuaEntity::IsDormant() const
{
UpdateEntity(); if (!pEntity) return true;
static int offset = g_pVars->GetOffset("BaseEntity", "m_bDormant");
return *(bool*)(pEntity + offset);
}
int LuaEntity::GetTeam() const
{
UpdateEntity(); if (!pEntity) return 0;
static int offset = g_pVars->GetOffset("DT_BaseEntity", "m_iTeamNum");
return *(int*)(pEntity + offset);
}
int LuaEntity::GetFlags() const
{
UpdateEntity(); if (!pEntity) return 0;
static int offset = g_pVars->GetOffset("DT_BasePlayer", "m_fFlags");
return *(int*)(pEntity + offset);
}
int LuaEntity::GetHealth() const
{
UpdateEntity(); if (!pEntity) return 0;
static int offset = g_pVars->GetOffset("DT_BasePlayer", "m_iHealth");
return *(int*)(pEntity + offset);
}
int LuaEntity::GetArmor() const
{
return 0;
}
RefCountedPtr<LuaVector3> LuaEntity::GetOrigin() const
{
UpdateEntity(); if (!pEntity) return 0;
static int offset = g_pVars->GetOffset("DT_BaseEntity", "m_vecOrigin");
float* pOrigin = (float*)(pEntity + offset); // is this safe? No.
return RefCountedPtr<LuaVector3>(new LuaVector3(pOrigin[0], pOrigin[1], pOrigin[2]));
}
int LuaEntity::GetShotsFired() const
{
UpdateEntity(); if (!pEntity) return 0;
static int offset = g_pVars->GetOffset("DT_CSPlayer", "m_iShotsFired");
return *(int*)(pEntity + offset);
}
RefCountedPtr<LuaVector3> LuaEntity::GetAimPunch() const
{
UpdateEntity(); if (!pEntity) return 0;
static int offset = g_pVars->GetOffset("DT_CSPlayer", "m_aimPunchAngle");
float* pAimpunch = (float*)(pEntity + offset);
return RefCountedPtr<LuaVector3>(new LuaVector3(pAimpunch[0], pAimpunch[1], pAimpunch[2]));
}
void LuaEntity::SetFlags(const int& fl)
{
UpdateEntity(); if (!pEntity) return;
static int offset = g_pVars->GetOffset("DT_BasePlayer", "m_fFlags");
*(int*)(pEntity + offset) = fl;
}
| 28.021505 | 166 | 0.699923 | aw-3 |
0a744784f40789357813ef53dcbcb261d9e2c20f | 2,720 | cpp | C++ | devtools/tmcdbg/tmcdbgW.cpp | flyingbluefish/tmc | 27cf82a3b1b5090fc81dfc82a453ccbc932896ec | [
"BSD-2-Clause"
] | null | null | null | devtools/tmcdbg/tmcdbgW.cpp | flyingbluefish/tmc | 27cf82a3b1b5090fc81dfc82a453ccbc932896ec | [
"BSD-2-Clause"
] | null | null | null | devtools/tmcdbg/tmcdbgW.cpp | flyingbluefish/tmc | 27cf82a3b1b5090fc81dfc82a453ccbc932896ec | [
"BSD-2-Clause"
] | null | null | null | // tmcdbgW.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "tmcdbgW.h"
#include "SplitWnd.h"
#include "tmcdbgWDlg.h"
/*
Copyright (C) Shmuel Safonov 2009-2012 All rights reserved.
Any usage of this file must be according to TMC License.
*/
#ifdef HAS_PLOT_DLL
#include "cplot.h"
#endif
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTmcdbgWApp
BEGIN_MESSAGE_MAP(CTmcdbgWApp, CWinApp)
//{{AFX_MSG_MAP(CTmcdbgWApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTmcdbgWApp construction
CTmcdbgWApp::CTmcdbgWApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CTmcdbgWApp object
CTmcdbgWApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CTmcdbgWApp initialization
BOOL CTmcdbgWApp::InitInstance()
{
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
//#ifdef _AFXDLL
// Enable3dControls(); // Call this when using MFC in a shared DLL
//#else
// Enable3dControlsStatic(); // Call this when linking to MFC statically
//#endif
// add doc template
//CDocTemplate* pDocTemplate;
//pDocTemplate = new CDocTemplate(IDR_TEXTTYPE,
// RUNTIME_CLASS(CPadDoc),
// RUNTIME_CLASS(CPadFrame),
// RUNTIME_CLASS(CPadView));
//pDocTemplate->SetServerInfo(
// IDR_TEXTTYPE_EMBEDDED, IDR_TEXTTYPE_INPLACE,
// RUNTIME_CLASS(CInPlaceFrame));
//AddDocTemplate(pDocTemplate);
InitTmc();
CTmcdbgWDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
FreeTmc();
}
//long CloseAll();
#ifdef HAS_PLOT_DLL
CloseAll();
#endif
// Since the dialog has been closed, return FALSE so that we exit the
// applicat ion, rather than start the application's message pump.
return FALSE;
}
| 25.904762 | 78 | 0.617279 | flyingbluefish |
0a7c03f1832f14af13c00529fff2506864848423 | 48 | hpp | C++ | src/boost_test_data_monomorphic_grid.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_test_data_monomorphic_grid.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_test_data_monomorphic_grid.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/test/data/monomorphic/grid.hpp>
| 24 | 47 | 0.791667 | miathedev |
0a897bad9835b03c71f3c9e79a3037c9510bdfd9 | 3,702 | hpp | C++ | boost/geometry/strategies/cartesian/densify.hpp | pranavgo/RRT | 87148c3ddb91600f4e74f00ffa8af14b54689aa4 | [
"MIT"
] | 326 | 2015-02-08T13:47:49.000Z | 2022-03-16T02:13:59.000Z | boost/geometry/strategies/cartesian/densify.hpp | pranavgo/RRT | 87148c3ddb91600f4e74f00ffa8af14b54689aa4 | [
"MIT"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | boost/geometry/strategies/cartesian/densify.hpp | pranavgo/RRT | 87148c3ddb91600f4e74f00ffa8af14b54689aa4 | [
"MIT"
] | 215 | 2015-01-14T15:50:38.000Z | 2022-02-23T03:58:36.000Z | // Boost.Geometry
// Copyright (c) 2017-2021, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP
#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP
#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>
#include <boost/geometry/algorithms/detail/signed_size_type.hpp>
#include <boost/geometry/arithmetic/arithmetic.hpp>
#include <boost/geometry/arithmetic/dot_product.hpp>
#include <boost/geometry/core/assert.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/strategies/densify.hpp>
#include <boost/geometry/util/algorithm.hpp>
#include <boost/geometry/util/math.hpp>
#include <boost/geometry/util/select_most_precise.hpp>
namespace boost { namespace geometry
{
namespace strategy { namespace densify
{
/*!
\brief Densification of cartesian segment.
\ingroup strategies
\tparam CalculationType \tparam_calculation
\qbk{
[heading See also]
[link geometry.reference.algorithms.densify.densify_4_with_strategy densify (with strategy)]
}
*/
template
<
typename CalculationType = void
>
class cartesian
{
public:
template <typename Point, typename AssignPolicy, typename T>
static inline void apply(Point const& p0, Point const& p1, AssignPolicy & policy, T const& length_threshold)
{
typedef typename AssignPolicy::point_type out_point_t;
typedef typename coordinate_type<out_point_t>::type out_coord_t;
typedef typename select_most_precise
<
typename coordinate_type<Point>::type, out_coord_t,
CalculationType
>::type calc_t;
typedef model::point<calc_t, geometry::dimension<Point>::value, cs::cartesian> calc_point_t;
assert_dimension_equal<calc_point_t, out_point_t>();
calc_point_t cp0, dir01;
// dir01 = p1 - p0
geometry::detail::for_each_dimension<calc_point_t>([&](auto index)
{
calc_t const coord0 = boost::numeric_cast<calc_t>(get<index>(p0));
calc_t const coord1 = boost::numeric_cast<calc_t>(get<index>(p1));
set<index>(cp0, coord0);
set<index>(dir01, coord1 - coord0);
});
calc_t const dot01 = geometry::dot_product(dir01, dir01);
calc_t const len = math::sqrt(dot01);
BOOST_GEOMETRY_ASSERT(length_threshold > T(0));
signed_size_type const n = signed_size_type(len / length_threshold);
if (n <= 0)
{
return;
}
calc_t const den = calc_t(n + 1);
for (signed_size_type i = 0 ; i < n ; ++i)
{
out_point_t out;
calc_t const num = calc_t(i + 1);
geometry::detail::for_each_dimension<out_point_t>([&](auto index)
{
// out = p0 + d * dir01
calc_t const coord = get<index>(cp0) + get<index>(dir01) * num / den;
set<index>(out, boost::numeric_cast<out_coord_t>(coord));
});
policy.apply(out);
}
}
};
#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace services
{
template <>
struct default_strategy<cartesian_tag>
{
typedef strategy::densify::cartesian<> type;
};
} // namespace services
#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
}} // namespace strategy::densify
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP
| 28.697674 | 112 | 0.680173 | pranavgo |
0a95ad0e93f390ce48b0c482da2f16a1bf6df28c | 8,359 | cpp | C++ | c++/src/util/itree.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/src/util/itree.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/src/util/itree.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: itree.cpp 103491 2007-05-04 17:18:18Z kazimird $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
* File Description:
* Implementation of interval search tree.
*
* ===========================================================================
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbistd.hpp>
#include <util/itree.hpp>
BEGIN_NCBI_SCOPE
inline
CIntervalTree::coordinate_type CIntervalTree::GetMaxRootCoordinate(void) const
{
coordinate_type max = m_Root.m_Key * 2;
if ( max <= 0 )
max = TTraits::GetMaxCoordinate();
return max;
}
inline
CIntervalTree::coordinate_type CIntervalTree::GetNextRootKey(void) const
{
coordinate_type nextKey = m_Root.m_Key * 2;
_ASSERT(nextKey > 0);
return nextKey;
}
void CIntervalTree::DoInsert(const interval_type& interval, TTreeMapI value)
{
_ASSERT(TTraits::IsNormal(interval));
// ensure our tree covers specified interval
if ( interval.GetTo() > GetMaxRootCoordinate() ) {
// insert one more level on top
if ( m_Root.m_Left || m_Root.m_Right || m_Root.m_NodeIntervals ) {
// non empty tree, insert new root node
do {
TTreeNode* newLeft = AllocNode();
// copy root node contents
*newLeft = m_Root;
// fill new root
m_Root.m_Key = GetNextRootKey();
m_Root.m_Left = newLeft;
m_Root.m_Right = 0;
m_Root.m_NodeIntervals = 0;
} while ( interval.GetTo() > GetMaxRootCoordinate() );
}
else {
// empty tree, just recalculate root
do {
m_Root.m_Key = GetNextRootKey();
} while ( interval.GetTo() > GetMaxRootCoordinate() );
}
}
TTreeNode* node = &m_Root;
coordinate_type nodeSize = m_Root.m_Key;
for ( ;; ) {
coordinate_type key = node->m_Key;
nodeSize = (nodeSize + 1) / 2;
TTreeNode** nextPtr;
coordinate_type nextKeyOffset;
if ( interval.GetFrom() > key ) {
nextPtr = &node->m_Right;
nextKeyOffset = nodeSize;
}
else if ( interval.GetTo() < key ) {
nextPtr = &node->m_Left;
nextKeyOffset = -nodeSize;
}
else {
// found our tile
TTreeNodeInts* nodeIntervals = node->m_NodeIntervals;
if ( !nodeIntervals )
node->m_NodeIntervals = nodeIntervals = CreateNodeIntervals();
nodeIntervals->Insert(interval, value);
return;
}
TTreeNode* next = *nextPtr;
if ( !next ) // create new node
(*nextPtr) = next = InitNode(AllocNode(), key + nextKeyOffset);
_ASSERT(next->m_Key == key + nextKeyOffset);
node = next;
}
}
bool CIntervalTree::DoDelete(TTreeNode* node, const interval_type& interval,
TTreeMapI value)
{
_ASSERT(node);
coordinate_type key = node->m_Key;
if ( interval.GetFrom() > key ) {
// left
return DoDelete(node->m_Right, interval, value) &&
!node->m_NodeIntervals && !node->m_Left;
}
else if ( interval.GetTo() < key ) {
// right
return DoDelete(node->m_Left, interval, value) &&
!node->m_NodeIntervals && !node->m_Right;
}
else {
// inside
TTreeNodeInts* nodeIntervals = node->m_NodeIntervals;
_ASSERT(nodeIntervals);
if ( !nodeIntervals->Delete(interval, value) )
return false; // node intervals non empty
// remove node intervals
DeleteNodeIntervals(nodeIntervals);
node->m_NodeIntervals = 0;
// delete node if it doesn't have leaves
return !node->m_Left && !node->m_Right;
}
}
void CIntervalTree::Destroy(void)
{
ClearNode(&m_Root);
m_ByX.clear();
}
CIntervalTree::iterator CIntervalTree::Insert(const interval_type& interval,
const mapped_type& value)
{
TTreeMapI iter = m_ByX.insert(TTreeMapValue(interval.GetFrom(),
interval.GetTo(),
value));
DoInsert(interval, iter);
return iterator(0, TTraits::GetMaxCoordinate(), &TTreeMap::get(iter));
}
CIntervalTree::const_iterator
CIntervalTree::IntervalsOverlapping(const interval_type& interval) const
{
coordinate_type x = interval.GetFrom();
coordinate_type y = interval.GetTo();
const_iterator it(x, TTraits::GetMaxCoordinate(), 0, &m_Root);
TTreeMapCI iter =
m_ByX.lower_bound(TTreeMapValue(x + 1, 0, mapped_type()));
if ( iter != m_ByX.end() && iter->GetKey() <= y ) {
it.m_SearchLimit = y;
it.m_CurrentMapValue = &*iter;
}
else {
it.NextLevel();
}
return it;
}
CIntervalTree::iterator
CIntervalTree::IntervalsOverlapping(const interval_type& interval)
{
coordinate_type x = interval.GetFrom();
coordinate_type y = interval.GetTo();
iterator it(x, TTraits::GetMaxCoordinate(), 0, &m_Root);
TTreeMapI iter =
m_ByX.lower_bound(TTreeMapValue(x + 1, 0, mapped_type()));
if ( iter != m_ByX.end() && iter->GetKey() <= y ) {
it.m_SearchLimit = y;
it.m_CurrentMapValue = &TTreeMap::get(iter);
}
else {
it.NextLevel();
}
return it;
}
CIntervalTree::TTreeNode* CIntervalTree::AllocNode(void)
{
return m_NodeAllocator.allocate(1, (TTreeNode*) 0);
}
void CIntervalTree::DeallocNode(TTreeNode* node)
{
m_NodeAllocator.deallocate(node, 1);
}
CIntervalTree::TTreeNodeInts* CIntervalTree::AllocNodeIntervals(void)
{
return m_NodeIntervalsAllocator.allocate(1, (TTreeNodeInts*) 0);
}
void CIntervalTree::DeallocNodeIntervals(TTreeNodeInts* ptr)
{
m_NodeIntervalsAllocator.deallocate(ptr, 1);
}
CIntervalTree::TTreeNodeInts* CIntervalTree::CreateNodeIntervals(void)
{
TTreeNodeInts* ints = new (AllocNodeIntervals())TTreeNodeInts();
#if defined(_RWSTD_VER) && !defined(_RWSTD_STRICT_ANSI)
ints->m_ByX.allocation_size(16);
ints->m_ByY.allocation_size(16);
#endif
return ints;
}
void CIntervalTree::DeleteNodeIntervals(TTreeNodeInts* ptr)
{
if ( ptr ) {
ptr->~TTreeNodeInts();
DeallocNodeIntervals(ptr);
}
}
void CIntervalTree::ClearNode(TTreeNode* node)
{
DeleteNodeIntervals(node->m_NodeIntervals);
DeleteNode(node->m_Left);
DeleteNode(node->m_Right);
node->m_Left = node->m_Right = 0;
}
pair<double, CIntervalTree::size_type> CIntervalTree::Stat(void) const
{
SStat stat;
stat.total = stat.count = stat.max = 0;
Stat(&m_Root, stat);
return make_pair(double(stat.total) / stat.count, stat.max);
}
void CIntervalTree::Stat(const TTreeNode* node, SStat& stat) const
{
if ( !node )
return;
if ( node->m_NodeIntervals ) {
size_type len = node->m_NodeIntervals->m_ByX.size();
++stat.count;
stat.total += len;
stat.max = max(stat.max, len);
}
Stat(node->m_Right, stat);
Stat(node->m_Left, stat);
}
END_NCBI_SCOPE
| 29.747331 | 78 | 0.609882 | OpenHero |
0a980d851f0981083c1bcde0b59a87844265920d | 1,719 | hpp | C++ | include/containers/range_view.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 44 | 2020-10-03T21:37:52.000Z | 2022-03-26T10:08:46.000Z | include/containers/range_view.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 1 | 2021-01-01T23:22:39.000Z | 2021-01-01T23:22:39.000Z | include/containers/range_view.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | null | null | null | // Copyright David Stone 2018.
// 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 <containers/begin_end.hpp>
#include <containers/is_range.hpp>
#include <containers/iter_difference_t.hpp>
#include <containers/iter_value_t.hpp>
#include <bounded/integer.hpp>
#include <operators/bracket.hpp>
#include <operators/forward.hpp>
#include <iterator>
#include <utility>
namespace containers {
template<typename Iterator, typename Sentinel = Iterator>
struct range_view {
using value_type = iter_value_t<Iterator>;
constexpr range_view(Iterator first, Sentinel last):
m_begin(std::move(first)),
m_end(std::move(last))
{
}
constexpr explicit range_view(std::pair<Iterator, Sentinel> pair):
range_view(std::move(pair).first, std::move(pair).second)
{
}
constexpr range_view(range auto && r):
range_view(containers::begin(OPERATORS_FORWARD(r)), containers::end(OPERATORS_FORWARD(r)))
{
}
constexpr auto begin() const {
return m_begin;
}
constexpr auto end() const {
return m_end;
}
OPERATORS_BRACKET_SEQUENCE_RANGE_DEFINITIONS
friend auto operator==(range_view, range_view) -> bool = default;
private:
[[no_unique_address]] Iterator m_begin;
[[no_unique_address]] Sentinel m_end;
};
template<typename Range>
range_view(Range &&) -> range_view<decltype(containers::begin(std::declval<Range &&>()), containers::end(std::declval<Range &&>()))>;
template<typename>
inline constexpr auto is_range_view = false;
template<typename Iterator, typename Sentinel>
inline constexpr auto is_range_view<range_view<Iterator, Sentinel>> = true;
} // namespace containers
| 25.656716 | 133 | 0.753345 | davidstone |
0a989e6bdbd9ec69c91af1f3073924420396ccb2 | 2,118 | cpp | C++ | src/core/src/scene/scene.cpp | zZnghialamZz/Ethan | e841b0a07f75022fab6634d53827c64dd1a466de | [
"Apache-2.0"
] | 2 | 2020-07-29T04:27:22.000Z | 2021-10-11T01:27:43.000Z | src/core/src/scene/scene.cpp | zZnghialamZz/Ethan | e841b0a07f75022fab6634d53827c64dd1a466de | [
"Apache-2.0"
] | null | null | null | src/core/src/scene/scene.cpp | zZnghialamZz/Ethan | e841b0a07f75022fab6634d53827c64dd1a466de | [
"Apache-2.0"
] | 2 | 2020-08-03T03:29:28.000Z | 2020-08-03T08:01:14.000Z | /**
* ==================================================
* _____
* __|___ |__ __ __ _ ____ ____ _
* | ___| | _| |_ | |_| || \ | \ | |
* | ___| ||_ _|| _ || \ | \| |
* |______| __| |__| |__| |_||__|\__\|__/\____|
* |_____|
*
* Game Engine
* ==================================================
*
* @file scene.cpp
* @author Nghia Lam <[email protected]>
*
* @brief
*
* @license Copyright 2020 Nghia Lam
*
* 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 "ethan/core/scene/scene.h"
#include "ethan/core/graphic/camera/camera_controller.h"
#include "ethan/core/graphic/renderer/renderer2D.h"
#include "ethan/ecs.h"
namespace Ethan {
Scene::Scene(const std::string& name) : name_(name) {
entity_manager_ = MakeScope<ECS::EntityManager>();
scene_camera_ = MakeShared<Camera>(CameraMode::CAMERA_2D);
camera_controller_.SetCurrentCamera(scene_camera_);
}
Scene::~Scene() {}
void Scene::Update() {
// Update
float dt = DeltaTime::GetSeconds();
camera_controller_.UpdateCamera(dt);
// Render
Renderer2D::Begin(*scene_camera_);
{
// NOTE(Nghia Lam): Draw Quads
auto group = entity_manager_->GetEntitiesWithTypes<ECS::TransformComponent, ECS::SpriteRenderComponent>();
for (auto entity : group) {
auto [transform, sprite] = group.get<ECS::TransformComponent, ECS::SpriteRenderComponent>(entity);
Renderer2D::DrawQuad(transform.Transform, sprite.Color);
}
}
Renderer2D::End();
}
}
| 29.830986 | 112 | 0.603872 | zZnghialamZz |
0a9b18fbbb21f8edf69284f4bdc7b83cd2f811b1 | 1,564 | hpp | C++ | NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/backtrace.hpp | bingmann/distributed-string-sorting | 238bdfd5f6139f2f14e33aed7b4d9bbffac5d295 | [
"BSD-2-Clause"
] | 284 | 2017-02-26T08:49:15.000Z | 2022-03-30T21:55:37.000Z | NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/backtrace.hpp | bingmann/distributed-string-sorting | 238bdfd5f6139f2f14e33aed7b4d9bbffac5d295 | [
"BSD-2-Clause"
] | 24 | 2017-09-05T21:02:41.000Z | 2022-03-07T10:09:59.000Z | NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/backtrace.hpp | bingmann/distributed-string-sorting | 238bdfd5f6139f2f14e33aed7b4d9bbffac5d295 | [
"BSD-2-Clause"
] | 62 | 2017-02-23T12:29:27.000Z | 2022-03-31T07:45:59.000Z | /*******************************************************************************
* tlx/backtrace.hpp
*
* Part of tlx - http://panthema.net/tlx
*
* Copyright (C) 2008-2017 Timo Bingmann <[email protected]>
*
* All rights reserved. Published under the Boost Software License, Version 1.0
******************************************************************************/
#ifndef TLX_BACKTRACE_HEADER
#define TLX_BACKTRACE_HEADER
#include <tlx/define/attribute_format_printf.hpp>
#include <cstdio>
namespace tlx {
//! \name Stack Backtrace Printing
//! \{
/*!
* Print a plain hex stack backtrace of the called function to FILE* out.
*/
void print_raw_backtrace(FILE* out = stderr, unsigned int max_frames = 63);
/*!
* Print a plain hex stack backtrace of the called function to FILE* out,
* prefixed with the given printf formatted output.
*/
void print_raw_backtrace(FILE* out, unsigned int max_frames,
const char* fmt, ...)
TLX_ATTRIBUTE_FORMAT_PRINTF(3, 4);
/*!
* Print a demangled stack backtrace of the caller function to FILE* out.
*
* \warning The binary has to be compiled with <tt>-rdynamic</tt> for meaningful
* output.
*/
void print_cxx_backtrace(FILE* out = stderr, unsigned int max_frames = 63);
/*!
* Install SIGSEGV signal handler and output backtrace on segmentation fault.
* Compile with `-rdynamic` for more useful output.
*/
void enable_segv_backtrace();
//! \}
} // namespace tlx
#endif // !TLX_BACKTRACE_HEADER
/******************************************************************************/
| 27.438596 | 80 | 0.602941 | bingmann |
0aa01a783110b5fae6238bbfc340dc6c3d9e4006 | 1,543 | hpp | C++ | include/thectci/factory.hpp | PeterHajdu/thectci | 7ffe4c7d8ccbf55490e155f93ef8637d6f9c4119 | [
"MIT"
] | null | null | null | include/thectci/factory.hpp | PeterHajdu/thectci | 7ffe4c7d8ccbf55490e155f93ef8637d6f9c4119 | [
"MIT"
] | null | null | null | include/thectci/factory.hpp | PeterHajdu/thectci | 7ffe4c7d8ccbf55490e155f93ef8637d6f9c4119 | [
"MIT"
] | null | null | null | #pragma once
#include <thectci/id.hpp>
#include <memory>
#include <cassert>
#include <functional>
#include <unordered_map>
namespace the
{
namespace ctci
{
template < typename Base >
class Creator
{
public:
typedef std::unique_ptr< Base > base_pointer;
virtual ~Creator() {}
virtual base_pointer create() = 0;
};
template < typename Base, typename Child >
class ExactCreator : public Creator< Base >
{
public:
typedef std::unique_ptr< Base > base_pointer;
base_pointer create() override
{
return std::unique_ptr< Base >( new Child() );
}
};
template < typename Base >
class Factory
{
public:
typedef std::unique_ptr< Base > base_pointer;
typedef Creator< Base > BaseCreator;
void register_creator( Id class_id, BaseCreator& base_creator )
{
assert( !is_registered( class_id ) );
m_creators.emplace( std::make_pair( class_id, std::ref( base_creator ) ) );
}
base_pointer create( Id class_id ) const
{
typename Creators::const_iterator creator_iterator( m_creators.find( class_id ) );
if ( creator_iterator == end( m_creators ) )
{
return base_pointer( nullptr );
}
return creator_iterator->second.get().create();
}
bool is_registered( Id class_id ) const
{
return m_creators.find( class_id ) != m_creators.end();
}
private:
typedef std::reference_wrapper< BaseCreator > CreatorReference;
typedef std::unordered_map< Id, CreatorReference > Creators;
Creators m_creators;
};
}
}
| 21.136986 | 88 | 0.668179 | PeterHajdu |
0aa42c79a0f46d9b2c1477582c12c3a27d66dff9 | 18,768 | cpp | C++ | src/DE_Scene.cpp | daher-alfawares/xr.desktop | 218a7cff7a9be5865cf786d7cad31da6072f7348 | [
"Apache-2.0"
] | 1 | 2018-09-20T10:01:30.000Z | 2018-09-20T10:01:30.000Z | src/DE_Scene.cpp | daher-alfawares/xr.desktop | 218a7cff7a9be5865cf786d7cad31da6072f7348 | [
"Apache-2.0"
] | null | null | null | src/DE_Scene.cpp | daher-alfawares/xr.desktop | 218a7cff7a9be5865cf786d7cad31da6072f7348 | [
"Apache-2.0"
] | null | null | null | //C++
/*
----------------------------------------------------
The Desktop Project
------------------
Copyright 2004 Daher Alfawares
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 "DE_Config.h"
#ifdef DE_SCENE
#undef DE_SCENE
#include "DShared.H"
#include "DSys.H"
#include "DGL.H"
#include "DUI_Main.H"
#include "Demo_Camera.h"
#include "Demo_Effect.h"
#include "Demo_Scene.h"
#include "Demo_Registery.h"
// Demos
#include "DE_IntroScene.h"
//////////////////////////////////////////
// Scene Objects
namespace objects
{
enum objects_e
{
no_object,
wall_bottom,
wall_front,
wall_left,
wall_right,
wall_back
};
}
#include "DE_Lighting_fx.h"
#include "DE_TerrainScene.h"
#include "DE_GetMrFrench.h"
//#include "DE_CG.h"
//////////////////////////////////////////
// Shared variables
DSys::Var_float gl_fov ("gl_Fov", "90");
DSys::Var_float gl_near ("gl_Near", "2");
DSys::Var_float gl_far ("gl_Far", "25");
DSys::Var_bool gl_drawFaces ("gl_drawfaces", "1");
DSys::Var_bool gl_avi ("gl_avi", "0");
DSys::Var_bool r_drawFPS ("r_drawFPS", "1");
DSys::Var_bool r_reflections ("r_reflections", "1");
DSys::Var_bool r_loopDemo ("r_loopDemo", "1");
DSys::Var_bool r_drawTimer ("r_drawTimer", "0");
DSys::Var_bool r_modelBounds ("r_modelBounds", "0");
DSys::Var_bool r_Lighting ("r_lighting", "0");
DSys::Var_bool r_VSync ("r_VSync", "1");
DSys::Var_int g_speed ("g_speed", "1");
DSys::Var_int g_cameraMotion ("g_cameraMotion", "0");
///////////////////////////////////////////
// User Interface Declerations
void UI_Init();
void UI_OnLeftClick(int button);
void UI_OnRightClick(int button);
void UI_Update(float msec);
void UI_OnKey(char key);
void UI_Render();
//////////////////////////////////////////
// Scene Mode
enum HScene_Mode {
MODE_PLAYBACK,
MODE_UI
} SceneMode;
//////////////////////////////////////////
// Macros
#define AT_KEY_DOWN(key) if(DSys::Input::KeyDown((key)))
#define AT_KEY_CHAR(key) if(DSys::Input::KeyChar((key)))
#define CHECK_QUIT { DSys::Input::Update();\
if(DSys::Input::KeyDown(DIK_ESCAPE)){\
DSys::SendConsoleCommand("quit");\
DMacro_TraceLeave();\
return false;}\
}
//////////////////////////////////////////
// Scene Objects
static DGL::LoadingScreen g_loadingScreen;
static DAudio::Sound2D g_bakmusic;
static DGL::ParticleEngine g_fireEngine;
static DGL::FadeScreen g_fadeOut;
static DGL::FadeScreen g_fadeIn;
static DGL::UserMessage g_userMessage;
static DGL::Font3D g_font3D;
static DGL::Font g_font;
static GLFT_Font g_fontft;
static DGL::Texture g_refMap;
static DGL::Texture g_menuBack;
static float g_timeCounter;
static DGL::Camera g_camera;
static DGL::Train g_train;
static bool g_trainUpdate;
static bool g_bQuitting;
static Horror::IntroScene *g_introScene;
static DGL::Lighting_fx *g_lightingScene;
static Horror::TerrainScene *g_terrainScene;
static GetMrFrench::Game *g_mrFrenchGame;
//static cg::cgDemo *g_cgDemo;
static Demo::Registery g_registery;
//////////////////////////////////////////
// Final Scene Functions
/* Add New Console Commands Here */
void AddConsoleCommands(){
}
bool Init(void){
DMacro_TraceEnter(Init);
//
// OpenGL
//
DGL::Font::Init();
// Texture
glEnable( GL_TEXTURE_2D);
g_loadingScreen.Init();
CHECK_QUIT;
g_loadingScreen.SetStage( 5, "Initializing OpenGL ...");
DGL::InitQuadrics();
DSys::Physics::Init();
DGL::Extensions::Init();
// g_userMessage.SetFont(g_font);
if(DGL::Extensions::IsEnabled_WGL_EXT_swap_control()){
DSys::Logger::Print("Setting monitor v-sync ...");
wglSwapIntervalEXT(r_VSync);
}
if(DGL::Extensions::IsEnabled_GL_EXT_clip_volume_hint()){
DSys::Logger::Print("Enabling volume clipping ...");
glHint( GL_CLIP_VOLUME_CLIPPING_HINT_EXT, GL_NICEST);
}
if(DGL::Extensions::IsEnabled_GL_EXT_point_parameters()){
DSys::Logger::Print("Setting point parameters ...");
// glPointSize(5);
// glPointParameterfEXT( GL_POINT_SIZE_MIN_EXT, 1);
// glPointParameterfEXT( GL_POINT_SIZE_MAX_EXT, 10);
// glPointParameterfEXT( GL_POINT_FADE_THRESHOLD_SIZE_EXT, 50);
// glPointParameterfEXT( GL_DISTANCE_ATTENUATION_EXT, 60);
}
// Depth buffer
glClearDepth( 20.0f);
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
#if 0
if(DGL::Extensions::IsEnabled_GL_NV_texgen_reflection()){
glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_NV);
glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_NV);
} else {
glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
}
#endif
// shade model
// glShadeModel(GL_SMOOTH);
// clear color
// glClearColor(0,0,0,1);
// hints
// glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
// glHint( GL_POINT_SMOOTH_HINT, GL_NICEST);
// glHint( GL_LINE_SMOOTH_HINT, GL_NICEST);
// glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST);
// polygon mode
// glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); // Back Face Is Solid
glEnable( GL_LIGHTING );
// glDisable( GL_CULL_FACE );
g_font.Create( "Font");
g_fontft.open("arial.ttf",16);
glLoadIdentity();
//
// Media
//
CHECK_QUIT;
g_loadingScreen.SetStage(10, "Loading Media...");
#ifndef _DEBUG
if(!DSys::sv_bDeveloper)
// g_bakmusic.Load( "sounds/music/The Prophecy.mp3");
// g_bakmusic.Load( "sounds/music/Lothlorien.mp3");
// g_bakmusic.Load( "sounds/music/Inshallah.mp3");
#endif
// User interface
CHECK_QUIT;
g_loadingScreen.SetStage(20, "Loading User Interface...");
UI_Init();
CHECK_QUIT;
g_loadingScreen.SetStage(30, "Building Particle Systems ...");
g_fireEngine.Init(
Vector(0,-5,-20),
Vector(0,2,0),
Vector(0,0,0),
DGL::Color::ColorYellow(),
DGL::Color::ColorRed(),
0.5f,
3,
0);
CHECK_QUIT;
g_loadingScreen.SetStage(50, "Building 3D Font...");
// g_font3D.Build("Gaze Bold", DSys::Window::GetDC());
/*/
CHECK_QUIT;
g_loadingScreen.SetStage(70, "Initializing MrFrench...");
g_mrFrenchGame = new GetMrFrench::Game;
g_registery.Register(g_mrFrenchGame, NULL);
//
CHECK_QUIT;
g_loadingScreen.SetStage(60, "Initializing Intro Scene ...");
g_introScene = new Horror::IntroScene;
g_registery.Register(g_introScene, NULL);
/**/
CHECK_QUIT;
g_loadingScreen.SetStage(75, "Initializing desktop ...");
g_lightingScene = new DGL::Lighting_fx;
g_registery.Register( g_lightingScene, DSys::sv_bDeveloper ? NULL : "lfx");
/*/
CHECK_QUIT;
g_loadingScreen.SetStage(80, "Initializing Terrain Scene ...");
g_terrainScene = new Horror::TerrainScene;
g_registery.Register(g_terrainScene, DSys::sv_bDeveloper ? NULL : "TerrainScene");
//
CHECK_QUIT;
g_loadingScreen.SetStage(93, "Initializing cg shaders demo...");
g_cgDemo = new cg::cgDemo;
g_registery.Register(g_cgDemo, NULL);
/**/
CHECK_QUIT;
g_loadingScreen.SetStage(95, "Initializing Effects...");
// fade effect
g_fadeIn.Init( DGL::Color(0.0f,0.0f,0.0f,1.0f), DGL::Color(0.0f,0.0f,0.0f,0.0f), 1000);
g_fadeOut.Init( DGL::Color(0.0f,0.0f,0.0f,0.0f), DGL::Color(0.0f,0.0f,0.0f,1.0f), 2000);
// g_refMap.Build("textures/ref.tga");
// g_menuBack.Build("textures/menuBack.jpg");
CHECK_QUIT;
// g_loadingScreen.SetStage(100, "Awaiting Snapshot...");
///////////////
// now start the back music
// g_bakmusic.Play();
///////////////
// setup initial camera location
g_camera.Set( g_camera.POSITION, Vector( 0, 4, -4 ) );
DMacro_TraceLeave();
return true;
}
void Update(float msec){
DMacro_TraceEnter(Update);
DSys::Input::Update();
DSys::Physics::Update(msec/1000.0f);
/*
AT_KEY_CHAR(DIK_F10) DSys::SendConsoleCommand("quit");
if( DSys::sv_bDeveloper )
{
AT_KEY_CHAR(DIK_ESCAPE)
(void ( SceneMode == MODE_UI ? SceneMode = MODE_PLAYBACK : SceneMode = MODE_UI ) );
}
else
{
AT_KEY_CHAR(DIK_ESCAPE) g_bQuitting = true;
}
*/
if(SceneMode == MODE_PLAYBACK) {
if(DSys::Input::KeyDown(DIK_LALT) || DSys::Input::KeyDown(DIK_RALT)){
////////////////
//************//
//* ALT KEYS *//
//************//
////////////////
if(DSys::sv_bDeveloper)
{
AT_KEY_CHAR(DIK_A){
Vector p,d;
g_camera.Get(g_camera.POSITION, p);
g_camera.Get(g_camera.DIRECTION, d);
g_train.PushNode(p,d);
}
AT_KEY_CHAR(DIK_Z){
DSys::Logger::Print("Turning camera train: %s", g_trainUpdate ? "OFF" : "ON");
g_trainUpdate = !g_trainUpdate;
}
AT_KEY_CHAR(DIK_S){
static int i;
g_train.Dump(va("autosave%d", i++));
}
AT_KEY_CHAR(DIK_C){
g_train.Destroy();
}
AT_KEY_CHAR(DIK_X){
g_train.RemoveLast();
}
}
} else {
///////////////////
//***************//
//* NORMAL KEYS *//
//***************//
///////////////////
if(!gl_avi){
AT_KEY_CHAR(DIK_F12) DSys::SendConsoleCommand("screenshot");
} else {
DSys::SendConsoleCommand("screenshot");
}
if(DGL::r_freeCam)
{
/////////////
// Camera movement
AT_KEY_DOWN(DIK_W) g_camera.MoveCameraFarward((DSys::Input::KeyValue(DIK_W)/10000.0f) * g_speed.floatval() * msec );
AT_KEY_DOWN(DIK_S) g_camera.MoveCameraFarward(-(DSys::Input::KeyValue(DIK_S)/10000.0f) * g_speed.floatval() * msec );
AT_KEY_DOWN(DIK_D) g_camera.MovePlaneRight((DSys::Input::KeyValue(DIK_D)/10000.0f) * g_speed.floatval() * msec );
AT_KEY_DOWN(DIK_A) g_camera.MovePlaneRight(-(DSys::Input::KeyValue(DIK_A)/10000.0f) * g_speed.floatval() * msec );
AT_KEY_DOWN(DIK_SPACE) g_camera.MovePlaneUp((DSys::Input::KeyValue(DIK_SPACE)/10000.0f) * g_speed.floatval() * msec );
AT_KEY_DOWN(DIK_C) g_camera.MovePlaneUp(-(DSys::Input::KeyValue(DIK_C)/10000.0f) * g_speed.floatval() * msec );
g_camera.RotateRight( DSys::Input::MouseXDelta() /200.0f );
g_camera.RotateUp( -DSys::Input::MouseYDelta() /200.0f );
}
}
g_registery.Update(msec);
/*
if(g_registery.Done())
DSys::SendConsoleCommand("quit");
if(DSys::sv_bDeveloper)
{
if(g_trainUpdate){
Vector p,d;
g_train.Update(msec,p,d);
g_camera.Set(g_camera.POSITION, p);
g_camera.Set(g_camera.DIRECTION, d);
}
}
*/
} else if( SceneMode == MODE_UI ){
// user interface should think now
UI_Update(msec);
}
///////////////////////
//*******************//
//* Non-Key Related *//
//*******************//
///////////////////////
// static float sceneTime;
// if(sceneTime>2){
// sceneTime += msec/1000.0f;
// g_userMessage.ShowMessage("Master Is Teh Tant = 6an6", 3,g_userMessage.STYLE_POPUP,6,DGL::Color::ColorGray());
// }
// g_fireEngine.Update(msec);
// g_userMessage.Update(msec);
// g_timeCounter += msec/50.0f;
// g_fadeIn.Update(msec);
// if(g_bQuitting)
// g_fadeOut.Update(msec);
DMacro_TraceLeave();
}
void Render3D(){
DMacro_TraceEnter(Render3D);
if( r_Lighting )
glEnable( GL_LIGHTING );
else
glDisable( GL_LIGHTING );
// render the scene
// if(DSys::sv_bDeveloper)
// g_camera.Setup();
g_registery.Render();
DSys::Physics::Render();
DMacro_TraceLeave();
}
void Render2D(float msec){ // all 2d drawings happens here
DMacro_TraceEnter(Render2D);
DGL::Color::ColorWhite().MakeCurrent();
DGL::MatrixOp::Ortho::Begin();
//==============================================================
if(r_drawFPS.intval())
{
g_font.SetStyle(g_font.STYLE_SHADOWS|g_font.STYLE_RIGHT);
g_font.SetColor(DGL::Color::ColorGray());
// g_font.Print(638,468, "%ifps", DGL::GetFPS(msec));
std::stringstream str;
str << DGL::GetFPS(msec) << " fps";
g_fontft.drawText(10,10, str.str() );
}
if(r_drawTimer.intval()){
static float totaltime;
static char *timer;
totaltime+= msec;
g_font.SetStyle(g_font.STYLE_SHADOWS|g_font.STYLE_RIGHT);
g_font.SetColor(DGL::Color::ColorGray());
g_font.Print(10, 20, "%s", D_Msec2String(totaltime));
}
// g_font.SetColor( DGL::Color::ColorCyan());
// g_font.SetStyle( g_font.STYLE_SHADOWS|g_font.STYLE_LEFT);
// g_font.Print( 20, 460, "Hello %s", DSys::sv_sUserName.strval());
// g_font.Print( 20, 470, "DaherEngine \"%s\"", SceneTitle.strval());
if(SceneMode == MODE_UI)
{
UI_Render();
}
else
{
// g_userMessage.Render();
// g_fadeIn.Render();
// if(g_bQuitting)
// if(!g_fadeOut.Render())
// DSys::SendConsoleCommand("quit");
}
//===========================================================
DGL::MatrixOp::Ortho::End();
DMacro_TraceLeave();
}
void Shutdown(){
g_registery.Destroy();
delete g_introScene;
delete g_terrainScene;
// delete g_cgDemo;
DUI::Destroy();
g_bakmusic.Destroy();
g_refMap.Delete();
g_menuBack.Delete();
}
//////////////////////////
// User Interface
/* Add UI Button ID Here */
enum UI_Button_e {
UIB_CONTINUE, // continues to the scene
UIB_RESTART_CURRENT,// restarts the current scene
UIB_RESTART_ALL, // restarts the whole demo
UIB_END_CURRENT, // ends the current scene (skip)
UIB_START_MUSIC, // starts music
UIB_CONSOLE, // show console
UIB_PUSH_CURRENT, // stores the current camera node
UIB_REMOVE_LAST, // remove the last node
UIB_TOGGLE_TRAIN, // toggles camera train
UIB_SAVE_TRAIN, // saves train data
UIB_CLEAR_TRAIN, // clears train data
UIB_EXIT, // exits scene
UIB_NUMBER
};
static DUI_MenuButton ui_buttons[ UIB_NUMBER];
#define MENU_Y 200
#define BUTTON_H 15
#define BUTTON_X 320
#define BUTTON_Y(id) MENU_Y - (id) * BUTTON_H
void UI_Init(){
DUI::Init();
DUI::CreateObject( &ui_buttons[UIB_CONTINUE], "Start Scene", BUTTON_X, BUTTON_Y(UIB_CONTINUE), 60, 30, "CONTINUE");
DUI::CreateObject( &ui_buttons[UIB_RESTART_CURRENT], "Restart Current", BUTTON_X, BUTTON_Y(UIB_RESTART_CURRENT), 60, 30, "RESTART CURRENT");
DUI::CreateObject( &ui_buttons[UIB_RESTART_ALL], "Restart Demo", BUTTON_X, BUTTON_Y(UIB_RESTART_ALL), 60, 30, "RESTART ALL");
DUI::CreateObject( &ui_buttons[UIB_END_CURRENT], "End Current", BUTTON_X, BUTTON_Y(UIB_END_CURRENT), 60, 30, "END CURRENT");
DUI::CreateObject( &ui_buttons[UIB_START_MUSIC], "Play", BUTTON_X, BUTTON_Y(UIB_START_MUSIC), 60, 30, "PLAY MUSIC");
DUI::CreateObject( &ui_buttons[UIB_CONSOLE], "Console", BUTTON_X, BUTTON_Y(UIB_CONSOLE), 60, 30, "TOGGLE CONSOLE");
DUI::CreateObject( &ui_buttons[UIB_EXIT], "Exit", BUTTON_X, BUTTON_Y(UIB_EXIT), 60, 30, "EXIT TO SYSTEM");
DUI::CreateObject( &ui_buttons[UIB_PUSH_CURRENT], "Push Current", BUTTON_X, BUTTON_Y(UIB_PUSH_CURRENT), 60, 30, "PUSH CURRENT", DSys::sv_bDeveloper);
DUI::CreateObject( &ui_buttons[UIB_REMOVE_LAST], "Remove Last", BUTTON_X, BUTTON_Y(UIB_REMOVE_LAST), 60, 30, "REMOVE LAST", DSys::sv_bDeveloper);
DUI::CreateObject( &ui_buttons[UIB_TOGGLE_TRAIN], "Toggle Train", BUTTON_X, BUTTON_Y(UIB_TOGGLE_TRAIN), 60, 30, "TOGGLE TRAIN", DSys::sv_bDeveloper);
DUI::CreateObject( &ui_buttons[UIB_SAVE_TRAIN], "Save Train", BUTTON_X, BUTTON_Y(UIB_SAVE_TRAIN), 60, 30, "SAVE TRAIN", DSys::sv_bDeveloper);
DUI::CreateObject( &ui_buttons[UIB_CLEAR_TRAIN], "Clear Train", BUTTON_X, BUTTON_Y(UIB_CLEAR_TRAIN), 60, 30, "CLEAR TRAIN", DSys::sv_bDeveloper);
}
void UI_OnLeftClick(int button){
switch (button) {
case UIB_CONTINUE:
SceneMode = MODE_PLAYBACK;
break;
case UIB_RESTART_CURRENT:
g_registery.RestartCurrent();
SceneMode = MODE_PLAYBACK;
break;
case UIB_RESTART_ALL:
g_registery.RestartAll();
SceneMode = MODE_PLAYBACK;
break;
case UIB_END_CURRENT:
g_registery.EndCurrent();
SceneMode = MODE_PLAYBACK;
break;
case UIB_START_MUSIC:
// Play(&g_bakmusic, 1);
break;
case UIB_CONSOLE:
DSys::SendConsoleCommand("toggle");
break;
case UIB_EXIT:
{
#ifdef _DEBUG
DSys::SendConsoleCommand("quit");
#endif
g_bQuitting = true;
SceneMode = MODE_PLAYBACK;
g_userMessage.ShowMessage("Good Bye",3,g_userMessage.STYLE_POPUP,3,DGL::Color::ColorGray());
}
break;
case UIB_PUSH_CURRENT:
{
g_userMessage.ShowMessage("Node Pushed", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan());
Vector p,d;
g_camera.Get(g_camera.POSITION, p);
g_camera.Get(g_camera.DIRECTION, d);
g_train.PushNode(p,d);
SceneMode = MODE_PLAYBACK;
}
break;
case UIB_REMOVE_LAST:
{
if(g_train.RemoveLast())
g_userMessage.ShowMessage("Last Removed", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan());
else
g_userMessage.ShowMessage("Error: No more nodes", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorRed());
SceneMode = MODE_PLAYBACK;
}
break;
case UIB_TOGGLE_TRAIN:
{
DSys::Logger::Print("Turning camera train: %s", g_trainUpdate ? "OFF" : "ON");
g_userMessage.ShowMessage("Train %s", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan(), g_trainUpdate? "OFF" : "ON");
g_trainUpdate = !g_trainUpdate;
SceneMode = MODE_PLAYBACK;
}
break;
case UIB_SAVE_TRAIN:
{
static int i;
g_train.Dump(va("autosave%d", i));
g_userMessage.ShowMessage("Saved to %s", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan(), va("autosave%d", i++));
SceneMode = MODE_PLAYBACK;
}
break;
case UIB_CLEAR_TRAIN:
{
g_userMessage.ShowMessage("Train Cleared", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan());
g_train.Destroy();
SceneMode = MODE_PLAYBACK;
}
break;
}
}
void UI_OnRightClick(int button){
}
void UI_Update(float msec) { static int i;
static bool MouseLeftClicked;
static bool MouseRightClicked;
MouseLeftClicked = DSys::Input::MouseChar(0);
MouseRightClicked= DSys::Input::MouseChar(1);
DUI::MouseMoved(DSys::Input::MouseXDelta(), DSys::Input::MouseYDelta());
for(i=0; i< UIB_NUMBER; i++){
DUI::SelectObject(&ui_buttons[i]);
DUI::CheckMouseOver(msec);
if(MouseLeftClicked)
if(DUI::OnMouseLeftClick())
UI_OnLeftClick(i);
if(MouseRightClicked)
if(DUI::OnMouseRightClick())
UI_OnRightClick(i);
}
}
void UI_OnKey(char key){ static int i;
for(i=0; i< UIB_NUMBER; i++){
DUI::SelectObject(&ui_buttons[i]);
DUI::OnKey(key);
}
}
void UI_Render(){ static int i;
for(i=0; i< UIB_NUMBER; i++){
DUI::SelectObject(&ui_buttons[i]);
DUI::RenderObject();
}
DUI::MouseRender();
for(i=0; i< UIB_NUMBER; i++){
DUI::SelectObject(&ui_buttons[i]);
DUI::RenderObjectToolTip();
}
}
#endif // DE_SCENE
| 25.85124 | 150 | 0.662671 | daher-alfawares |
0aa5fff6ca7ae472914aad4a22ac51badd3713c3 | 5,200 | cc | C++ | src/pub_key.cc | gladosconn/ecdsa- | 3b8d4b6df48843742fc33c931b9fadc225ae439b | [
"MIT"
] | 11 | 2019-11-20T21:38:22.000Z | 2022-03-18T08:45:25.000Z | src/pub_key.cc | gladosconn/ecdsa- | 3b8d4b6df48843742fc33c931b9fadc225ae439b | [
"MIT"
] | 1 | 2021-04-01T15:06:55.000Z | 2021-04-01T15:06:55.000Z | src/pub_key.cc | gladosconn/ecdsa- | 3b8d4b6df48843742fc33c931b9fadc225ae439b | [
"MIT"
] | 4 | 2017-11-03T17:34:27.000Z | 2022-03-21T18:40:49.000Z | #include "pub_key.h"
#include <cstring>
namespace ecdsa {
/** This function is taken from the libsecp256k1 distribution and implements
* DER parsing for ECDSA signatures, while supporting an arbitrary subset of
* format violations.
*
* Supported violations include negative integers, excessive padding, garbage
* at the end, and overly long length descriptors. This is safe to use in
* Bitcoin because since the activation of BIP66, signatures are verified to be
* strict DER before being passed to this module, and we know it supports all
* violations present in the blockchain before that point.
*/
static int ecdsa_signature_parse_der_lax(const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sig,
const unsigned char *input,
size_t inputlen) {
size_t rpos, rlen, spos, slen;
size_t pos = 0;
size_t lenbyte;
unsigned char tmpsig[64] = {0};
int overflow = 0;
/* Hack to initialize sig with a correctly-parsed but invalid signature. */
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
/* Sequence tag byte */
if (pos == inputlen || input[pos] != 0x30) {
return 0;
}
pos++;
/* Sequence length bytes */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
pos += lenbyte;
}
/* Integer tag byte for R */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for R */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
if (lenbyte >= sizeof(size_t)) {
return 0;
}
rlen = 0;
while (lenbyte > 0) {
rlen = (rlen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
rlen = lenbyte;
}
if (rlen > inputlen - pos) {
return 0;
}
rpos = pos;
pos += rlen;
/* Integer tag byte for S */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for S */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
if (lenbyte >= sizeof(size_t)) {
return 0;
}
slen = 0;
while (lenbyte > 0) {
slen = (slen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
slen = lenbyte;
}
if (slen > inputlen - pos) {
return 0;
}
spos = pos;
/* Ignore leading zeroes in R */
while (rlen > 0 && input[rpos] == 0) {
rlen--;
rpos++;
}
/* Copy R value */
if (rlen > 32) {
overflow = 1;
} else {
std::memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
}
/* Ignore leading zeroes in S */
while (slen > 0 && input[spos] == 0) {
slen--;
spos++;
}
/* Copy S value */
if (slen > 32) {
overflow = 1;
} else {
std::memcpy(tmpsig + 64 - slen, input + spos, slen);
}
if (!overflow) {
overflow = !secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
if (overflow) {
/* Overwrite the result again with a correctly-parsed but invalid
signature if parsing failed. */
std::memset(tmpsig, 0, 64);
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
return 1;
}
PubKey::PubKey(const std::vector<uint8_t> &pub_key_data)
: pub_key_data_(pub_key_data) {
// Create secp256k1 context.
ctx_ = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
}
PubKey::PubKey(PubKey &&rhs) {
pub_key_data_.assign(std::begin(rhs.pub_key_data_),
std::end(rhs.pub_key_data_));
ctx_ = rhs.ctx_;
rhs.pub_key_data_.clear();
rhs.ctx_ = nullptr;
}
PubKey &PubKey::operator=(PubKey &&rhs) {
if (this != &rhs) {
pub_key_data_.assign(std::begin(rhs.pub_key_data_),
std::end(rhs.pub_key_data_));
ctx_ = rhs.ctx_;
rhs.pub_key_data_.clear();
rhs.ctx_ = nullptr;
}
return *this;
}
PubKey::~PubKey() {
secp256k1_context_destroy(ctx_);
ctx_ = nullptr;
}
bool PubKey::Verify(const std::vector<uint8_t> &hash,
const std::vector<uint8_t> &sig_in) const {
// Parse public key.
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(ctx_, &pubkey, pub_key_data_.data(),
pub_key_data_.size())) {
return false;
}
// Parse signature.
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(ctx_, &sig, sig_in.data(),
sig_in.size())) {
return false;
}
/* libsecp256k1's ECDSA verification requires lower-S signatures, which have
* not historically been enforced in Bitcoin, so normalize them first. */
secp256k1_ecdsa_signature_normalize(ctx_, &sig, &sig);
return secp256k1_ecdsa_verify(ctx_, &sig, hash.data(), &pubkey);
}
} // namespace ecdsa
| 24.413146 | 80 | 0.587115 | gladosconn |
0aa66afae74665ada6a69df962f5c287155a7b93 | 772 | cpp | C++ | tests/job/test_co_generator.cpp | grandmaster789/bop | 909d4156503f83b66de3f7e3284e086bd98905eb | [
"MIT"
] | null | null | null | tests/job/test_co_generator.cpp | grandmaster789/bop | 909d4156503f83b66de3f7e3284e086bd98905eb | [
"MIT"
] | null | null | null | tests/job/test_co_generator.cpp | grandmaster789/bop | 909d4156503f83b66de3f7e3284e086bd98905eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include <array>
#include <algorithm>
#include "../../src/job/co_generator.h"
#include <catch2/catch.hpp>
namespace testing {
int test_iota() {
int sum = 0;
// derives to int
for (auto x : bop::job::iota(6))
sum += x;
return sum;
}
uint32_t test_generator_range_sum() {
uint32_t sum = 0;
// explicitly made uint32_t
for (auto x : bop::job::range<uint32_t>(5, 10))
sum += x;
return sum;
}
}
TEST_CASE("test_generator[iota]") {
REQUIRE(testing::test_iota() == (0 + 1 + 2 + 3 + 4 + 5)); // == 15
}
TEST_CASE("test_generator[range]") {
REQUIRE(testing::test_generator_range_sum() == (5 + 6 + 7 + 8 + 9)); // == 35
}
| 19.794872 | 81 | 0.546632 | grandmaster789 |
0aac1cb8984bd62f4179e4ad6dfc968d2fdab19d | 2,323 | cpp | C++ | Sources/ElkCraft/Sources/Utils/ItemsInfo.cpp | adriengivry/ElkCraft | 7147b1aae7183eee692f2691cac24505a61515c1 | [
"MIT"
] | 10 | 2018-11-09T03:38:30.000Z | 2022-01-31T11:46:10.000Z | Sources/ElkCraft/Sources/Utils/ItemsInfo.cpp | adriengivry/ElkCraft | 7147b1aae7183eee692f2691cac24505a61515c1 | [
"MIT"
] | null | null | null | Sources/ElkCraft/Sources/Utils/ItemsInfo.cpp | adriengivry/ElkCraft | 7147b1aae7183eee692f2691cac24505a61515c1 | [
"MIT"
] | 10 | 2018-09-30T05:07:35.000Z | 2021-12-22T04:41:38.000Z | #include "stdafx.h"
#include "ElkCraft/Utils/ItemsInfo.h"
using namespace ElkCraft::Utils;
using namespace ElkTools::Utils;
bool ItemsInfo::IsItem(uint8_t p_type)
{
return p_type >= 100;
}
bool ElkCraft::Utils::ItemsInfo::IsTool(uint8_t p_type)
{
return p_type >= 101 && p_type <= 106;
}
ItemsInfo::Quality ElkCraft::Utils::ItemsInfo::GetQuality(uint8_t p_type)
{
switch (GetItemType(p_type))
{
case ItemType::WOOD_AXE:
case ItemType::WOOD_PICKAXE:
case ItemType::WOOD_SHOVEL:
return Quality::WOOD;
case ItemType::STONE_AXE:
case ItemType::STONE_PICKAXE:
case ItemType::STONE_SHOVEL:
return Quality::STONE;
default:
return Quality::NONE;
}
}
ItemsInfo::ToolType ElkCraft::Utils::ItemsInfo::GetToolType(uint8_t p_type)
{
switch (GetItemType(p_type))
{
case ItemType::WOOD_AXE:
case ItemType::STONE_AXE:
return ToolType::AXE;
case ItemType::WOOD_PICKAXE:
case ItemType::STONE_PICKAXE:
return ToolType::PICKAXE;
case ItemType::WOOD_SHOVEL:
case ItemType::STONE_SHOVEL:
return ToolType::SHOVEL;
default:
return ToolType::NONE;
}
}
ItemsInfo::ItemType ElkCraft::Utils::ItemsInfo::GetItemType(uint8_t p_type)
{
return static_cast<ItemType>(p_type);
}
bool ElkCraft::Utils::ItemsInfo::IsEfficientOn(uint8_t p_tool, uint8_t p_block)
{
ToolType neededTool;
switch (static_cast<BlocksInfo::BlockType>(p_block))
{
case BlocksInfo::BlockType::GRASS:
neededTool = ToolType::SHOVEL;
break;
case BlocksInfo::BlockType::DIRT:
neededTool = ToolType::SHOVEL;
break;
case BlocksInfo::BlockType::GRAVEL:
neededTool = ToolType::SHOVEL;
break;
case BlocksInfo::BlockType::STONE:
neededTool = ToolType::PICKAXE;
break;
case BlocksInfo::BlockType::COBBLESTONE:
neededTool = ToolType::PICKAXE;
break;
case BlocksInfo::BlockType::WOOD:
neededTool = ToolType::AXE;
break;
case BlocksInfo::BlockType::WOODEN_PLANKS:
neededTool = ToolType::AXE;
break;
case BlocksInfo::BlockType::SAND:
neededTool = ToolType::SHOVEL;
break;
case BlocksInfo::BlockType::BRICK:
neededTool = ToolType::PICKAXE;
break;
case BlocksInfo::BlockType::STONE_BRICK:
neededTool = ToolType::PICKAXE;
break;
case BlocksInfo::BlockType::COAL_ORE:
neededTool = ToolType::PICKAXE;
break;
default:
return false;
}
return (GetToolType(p_tool) == neededTool);
}
| 19.521008 | 79 | 0.739991 | adriengivry |
0ab146c51d7c82f4c86242f7174fb169e42e3398 | 447 | cpp | C++ | solved/easy/1221. Split a String in Balanced Strings/main.cpp | SlaveWilson/leetcode | b762380594908ed44ae278ca1a14e9185eec2f0e | [
"MIT"
] | null | null | null | solved/easy/1221. Split a String in Balanced Strings/main.cpp | SlaveWilson/leetcode | b762380594908ed44ae278ca1a14e9185eec2f0e | [
"MIT"
] | null | null | null | solved/easy/1221. Split a String in Balanced Strings/main.cpp | SlaveWilson/leetcode | b762380594908ed44ae278ca1a14e9185eec2f0e | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
int balancedStringSplit(string s)
{
int count = 0, l = 0, r = 0;
for (char c : s)
{
if (c == 'R')
r++;
else
l++;
if (r == l)
count++;
}
return count;
}
};
int main()
{
string s = "RRLRRLRLLLRL";
Solution solution;
int output = solution.balancedStringSplit(s);
cout << output << endl;
} | 14.9 | 47 | 0.532438 | SlaveWilson |
0ab1ce011da3066e1e9019811eb1eed8170a10ce | 660 | cpp | C++ | snake/Food.cpp | kriss95/snake-game | cfd2121e6818f08b5275b16c03261c8ab538530e | [
"MIT"
] | null | null | null | snake/Food.cpp | kriss95/snake-game | cfd2121e6818f08b5275b16c03261c8ab538530e | [
"MIT"
] | null | null | null | snake/Food.cpp | kriss95/snake-game | cfd2121e6818f08b5275b16c03261c8ab538530e | [
"MIT"
] | null | null | null | #include "Food.h"
Food::Food(Boardd* board, Snake* snake)
{
int x, y;
srand(time(NULL));
do
{
x = rand() % board->GetM();
y = rand() % board->GetN();
}
while (!snake->SnakeMach(x,y));
foodPlace = make_pair(x, y);
outP = new GameOutput;
}
void Food::NewPlace(Boardd* board, Snake* snake)
{
int x, y;
srand(time(NULL));
do
{
x = rand() % board->GetM();
y = rand() % board->GetN();
} while (!snake->SnakeMach(x, y));
foodPlace = make_pair(x, y);
}
void Food::DisplayFood()
{
outP->gotoxy(foodPlace.first + 1, foodPlace.second + 1);
printf("*");
}
pair<int, int> Food::GetFoodPlace()
{
return foodPlace;
}
Food::~Food()
{
delete outP;
}
| 16.5 | 57 | 0.60303 | kriss95 |
0ab5f2c0b7b2e12ed3e705c7f050146f2aaecc2e | 2,405 | hpp | C++ | OptFrame/Experimental/NSIterators/IteratorNSSeqMultiRoute.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 2 | 2018-05-24T11:04:12.000Z | 2020-03-03T13:37:07.000Z | OptFrame/Experimental/NSIterators/IteratorNSSeqMultiRoute.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | null | null | null | OptFrame/Experimental/NSIterators/IteratorNSSeqMultiRoute.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 1 | 2019-06-06T16:57:49.000Z | 2019-06-06T16:57:49.000Z | // OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_ITERATORNSSEQMULTIROUTE_HPP_
#define OPTFRAME_ITERATORNSSEQMULTIROUTE_HPP_
// Framework includes
#include "../../Move.hpp"
#include "../../NSIterator.hpp"
using namespace std;
class NSSeqMultiRouteIteratorOutOfBound
{
public:
NSSeqMultiRouteIteratorOutOfBound()
{
}
};
template<class T, class DS = OPTFRAME_DEFAULT_EMEMORY, class MOVE = MoveMultiRoute<T, DS > >
class IteratorNSSeqMultiRoute: public NSIterator<vector<vector<T> > , DS >
{
typedef vector<T> Route;
typedef vector<vector<T> > MultiRoute;
private:
vector<NSIterator<Route, DS >*>& iterators;
int i;
public:
IteratorNSSeqMultiRoute(vector<NSIterator<Route, DS >*>& it) :
iterators(it)
{
i = 0;
}
virtual ~IteratorNSSeqMultiRoute()
{
for (int j = 0; j < iterators.size(); j++)
delete iterators[j];
delete &iterators;
}
void first()
{
for (int j = 0; j < iterators.size(); j++)
iterators[j]->first();
i = 0;
while (i < iterators.size())
if (!iterators[i]->isDone())
break;
else
i++;
}
void next()
{
iterators[i]->next();
while (i < iterators.size())
if (!iterators[i]->isDone())
break;
else
i++;
}
bool isDone()
{
for (int j = i; j < iterators.size(); j++)
if (!iterators[j]->isDone())
return false;
return true;
}
Move<MultiRoute, DS >& current()
{
if ((i < iterators.size()) && (!iterators[i]->isDone()))
return *new MOVE(i, iterators[i]->current());
else
throw NSSeqMultiRouteIteratorOutOfBound();
}
};
#endif /*OPTFRAME_ITERATORNSSEQMULTIROUTE_HPP_*/
| 22.904762 | 92 | 0.69106 | 216k155 |
0ab9fcba1b89f2f4da1d2146193717ef41bf6e71 | 3,551 | hpp | C++ | src/sdk/math.hpp | mov-rax-rax/gamesneeze | 09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1 | [
"MIT"
] | 1 | 2022-01-13T07:05:26.000Z | 2022-01-13T07:05:26.000Z | src/sdk/math.hpp | mov-rax-rax/gamesneeze | 09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1 | [
"MIT"
] | null | null | null | src/sdk/math.hpp | mov-rax-rax/gamesneeze | 09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1 | [
"MIT"
] | 1 | 2021-12-31T13:02:42.000Z | 2021-12-31T13:02:42.000Z | #pragma once
#include "sdk.hpp"
inline QAngle originalAngle{};
inline float originalForwardMove = 0.0f;
inline float originalSideMove = 0.0f;
inline void startMovementFix(Command* cmd) {
originalAngle = cmd->viewAngle;
originalForwardMove = cmd->move.x;
originalSideMove = cmd->move.y;
}
inline void endMovementFix(Command* cmd) {
// this was just taken from designer bc im lazy
// https://github.com/designer1337/csgo-cheat-base/blob/09fa2ba8de52eef482bbc82f682976e369191077/dependencies/math/math.cpp#L4
float deltaViewAngle;
float f1;
float f2;
if (originalAngle.y < 0.f)
f1 = 360.0f + originalAngle.y;
else
f1 = originalAngle.y;
if (cmd->viewAngle.y < 0.0f)
f2 = 360.0f + cmd->viewAngle.y;
else
f2 = cmd->viewAngle.y;
if (f2 < f1)
deltaViewAngle = abs(f2 - f1);
else
deltaViewAngle = 360.0f - abs(f1 - f2);
deltaViewAngle = 360.0f - deltaViewAngle;
cmd->move.x = cos(
sdk::to_radians(deltaViewAngle))
* originalForwardMove
+ cos(sdk::to_radians(deltaViewAngle + 90.f))
* originalSideMove;
cmd->move.y = sin(
sdk::to_radians(deltaViewAngle))
* originalForwardMove
+ sin(sdk::to_radians(deltaViewAngle + 90.f))
* originalSideMove;
// TODO: support upmove
}
inline void normalizePitch(float& pitch) {
pitch = std::clamp(pitch, -89.0f, 89.0f);
}
inline void normalizeYaw(float& yaw) {
while (yaw > 180.0f) {
yaw -= 360.0f;
}
while (yaw < -180.0f) {
yaw += 360.0f;
}
}
inline void normalizeAngle(QAngle& angle) {
normalizePitch(angle.x);
normalizeYaw(angle.y);
angle.z = 0.0f;
}
inline void clampAngle(QAngle& angle) {
angle.x = std::clamp(angle.x, -89.0f, 89.0f);
angle.y = std::clamp(angle.y, -180.0f, 180.0f);
angle.z = 0.0f;
}
inline QAngle calcAngle(const Vector& src, const Vector& dst) {
QAngle vAngle;
Vector delta((src.x - dst.x), (src.y - dst.y), (src.z - dst.z));
double hyp = sqrt(delta.x*delta.x + delta.y*delta.y);
vAngle.x = float(atanf(float(delta.z / hyp)) * 57.295779513082f);
vAngle.y = float(atanf(float(delta.y / delta.x)) * 57.295779513082f);
vAngle.z = 0.0f;
if (delta.x >= 0.0)
vAngle.y += 180.0f;
return vAngle;
}
inline void angleVectors(const QAngle &angles, Vector& forward) {
forward.x = cos(sdk::to_radians(angles.x)) * cos(sdk::to_radians(angles.y));
forward.y = cos(sdk::to_radians(angles.x)) * sin(sdk::to_radians(angles.y));
forward.z = -sin(sdk::to_radians(angles.x));
}
inline float getDistance(Vector pos1, Vector pos2) {
// Do 3d pythag
float a = abs(pos1.x-pos2.x);
float b = abs(pos1.y-pos2.y);
float c = abs(pos1.z-pos2.z);
return sqrt(pow(a, 2.f) + pow(b, 2.f) + pow(c, 2.f));
}
inline float getDistanceNoSqrt(Vector pos1, Vector pos2) {
// When you dont need an exact distance and just want to see if
// something is x further than something else for example theres no need to sqrt it
float a = abs(pos1.x-pos2.x);
float b = abs(pos1.y-pos2.y);
float c = abs(pos1.z-pos2.z);
return pow(a, 2.f) + pow(b, 2.f) + pow(c, 2.f);
}
inline Vector2D directionFromYawAndVelocity(float yaw, Vector velocity) {
auto cosYaw = std::cos(yaw / 180.0f * sdk::numeric_consts<float>::pi());
auto sinYaw = std::cos(yaw / 180.0f * sdk::numeric_consts<float>::pi());
return Vector2D {
(velocity.x * cosYaw) + (velocity.y * sinYaw),
(velocity.y * cosYaw) - (velocity.x * sinYaw),
};
}
bool worldToScreen(const Vector& origin, Vector& screen);
inline float randomFloat(float div) {
return static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX / div);
}
| 27.10687 | 130 | 0.672768 | mov-rax-rax |
0ac075f0ec84cebf2087c2465b308daef61587c9 | 4,632 | cpp | C++ | ModelViewer/ViewModels/TransformViewModel.cpp | seanisom/glTF-DXViewer | f1e7d88581e3598e397e563f529e7ee2bb4befd6 | [
"MIT"
] | 64 | 2018-05-25T06:18:42.000Z | 2019-04-15T17:27:38.000Z | ModelViewer/ViewModels/TransformViewModel.cpp | seanisom/glTF-DXViewer | f1e7d88581e3598e397e563f529e7ee2bb4befd6 | [
"MIT"
] | 4 | 2018-05-26T10:53:33.000Z | 2018-10-20T20:46:41.000Z | ModelViewer/ViewModels/TransformViewModel.cpp | seanisom/glTF-DXViewer | f1e7d88581e3598e397e563f529e7ee2bb4befd6 | [
"MIT"
] | 13 | 2019-09-19T00:50:07.000Z | 2022-03-22T13:39:52.000Z | #include "pch.h"
#include "TransformViewModel.h"
using namespace ViewModels;
float TransformViewModel::PositionX::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
return derived->GetTranslation().x;
}
return 0.0f;
}
void TransformViewModel::PositionX::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetTranslation(val, derived->GetTranslation().y, derived->GetTranslation().z);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::PositionY::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
return derived->GetTranslation().y;
}
return 0.0f;
}
void TransformViewModel::PositionY::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetTranslation(derived->GetTranslation().x, val, derived->GetTranslation().z);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::PositionZ::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
return derived->GetTranslation().z;
}
return 0.0f;
}
void TransformViewModel::PositionZ::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetTranslation(derived->GetTranslation().x, derived->GetTranslation().y, val);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::RotationX::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
//return derived->GetRotationX();
return derived->GetRotation().x;
}
return 0.0f;
}
void TransformViewModel::RotationX::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetRotationRoll(val);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::RotationY::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
//return derived->GetRotationY();
return derived->GetRotation().y;
}
return 0.0f;
}
void TransformViewModel::RotationY::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetRotationPitch(val);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::RotationZ::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
//return derived->GetRotationZ();
return derived->GetRotation().z;
}
return 0.0f;
}
void TransformViewModel::RotationZ::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetRotationYaw(val);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::ScaleX::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
return derived->GetScale().x;
}
return 0.0f;
}
void TransformViewModel::ScaleX::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetScale(val, derived->GetScale().y, derived->GetScale().z);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::ScaleY::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
return derived->GetScale().y;
}
return 0.0f;
}
void TransformViewModel::ScaleY::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetScale(derived->GetScale().x, val, derived->GetScale().z);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
float TransformViewModel::ScaleZ::get()
{
if (_selectedNode)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
return derived->GetScale().z;
}
return 0.0f;
}
void TransformViewModel::ScaleZ::set(float val)
{
shared_ptr<GraphContainerNode> derived =
dynamic_pointer_cast<GraphContainerNode>(_selectedNode);
derived->SetScale(derived->GetScale().x, derived->GetScale().y, val);
OnPropertyChanged(getCallerName(__FUNCTION__));
}
| 25.877095 | 88 | 0.778713 | seanisom |
0ac6d9dc3aa983684e889f76a0f91751dfd1e04d | 2,160 | cc | C++ | test/exprtest.cc | larskuhtz/MoCS | 8ea4aafb4a2036807af147efeac915876cf7390b | [
"BSD-3-Clause"
] | 1 | 2020-07-16T18:23:55.000Z | 2020-07-16T18:23:55.000Z | test/exprtest.cc | larskuhtz/MoCS | 8ea4aafb4a2036807af147efeac915876cf7390b | [
"BSD-3-Clause"
] | null | null | null | test/exprtest.cc | larskuhtz/MoCS | 8ea4aafb4a2036807af147efeac915876cf7390b | [
"BSD-3-Clause"
] | null | null | null | /* *** MOCS-COPYRIGHT-NOTICE-BEGIN ***
*
* This copyright notice is auto-generated by ./add-copyright-notice.
* Additional copyright notices must be added below the last line of this notice.
*
* MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/): "test/exprtest.cc".
* The content of this file is copyright of Saarland University -
* Copyright (C) 2009 Saarland University, Reactive Systems Group, Lars Kuhtz.
*
* This file is part of MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/).
*
* License: three-clause BSD style license.
* The license text can be found in the file LICENSE.
*
* *** MOCS-COPYRIGHT-NOTICE-END *** */
#include <fstream>
#include "expr.hh"
prop_t prop(int i)
{
return prop_t(1,i);
}
int main(int argsc, char ** args)
{
efac_ptr c = efac::newEfac();
expr_t p0 = c->mkProp(prop(0));
expr_t p1 = c->mkProp(prop(1));
expr_t p2 = c->mkProp(prop(2));
std::cerr << "check: " << "3 == " << c->size() << std::endl;
expr_t p0_ = c->mkProp(prop(0));
expr_t p1_ = c->mkProp(prop(1));
expr_t p2_ = c->mkProp(prop(2));
//p0.impl()->debug();
//p0_.impl()->debug();
std::cerr << "check: " << "3 == " << c->size() << std::endl;
expr_t ct = c->mkConst(true);
expr_t cf = c->mkConst(false);
std::cerr << "check: " << "5 == " << c->size() << std::endl;
expr_t ct_ = c->mkConst(true);
expr_t cf_ = c->mkConst(false);
std::cerr << "check: " << "5 == " << c->size() << std::endl;
expr_t np0 = c->mkNProp(prop(0));
expr_t np1 = c->mkNProp(prop(1));
expr_t np2 = c->mkNProp(prop(2));
std::cerr << "check: " << "8 == " << c->size() << std::endl;
expr_t np0_ = c->mkNProp(prop(0));
expr_t np1_ = c->mkNProp(prop(1));
expr_t np2_ = c->mkNProp(prop(2));
std::cerr << "check: " << "8 == " << c->size() << std::endl;
expr_t p0_and_p0 = p0 && p0;
std::cerr << "check: " << "8 == " << c->size() << std::endl;
expr_t a0 = p0 && p1;
std::cerr << "check: " << "9 == " << c->size() << std::endl;
expr_t a1 = p0 && p1 && p2;
std::cerr << "check: " << "10 == " << c->size() << std::endl;
return 0;
}
| 27 | 81 | 0.554167 | larskuhtz |
0ace65782b9a26fa77a5395599ce45034270e3e5 | 1,462 | cpp | C++ | cpp/src/exercise/e0100/e0004.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0100/e0004.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0100/e0004.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | #include "extern.h"
using namespace std;
class Solution {
public:
double findMedianSortedArrays_slow(vector<int>& nums1, vector<int>& nums2) {
auto v = vector<int>();
v.insert(v.end(), nums1.cbegin(), nums1.cend());
v.insert(v.end(), nums2.cbegin(), nums2.cend());
sort(v.begin(), v.end());
if (v.size() % 2 == 1) return v[v.size() / 2];
else return double(v[(v.size() + 1) / 2] + v[(v.size() - 1) / 2]) / 2;
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
size_t s = nums1.size() + nums2.size();
auto v = vector<int>(s, 0);
auto p1 = nums1.cbegin(); auto p2 = nums2.cbegin(); auto pt = v.begin();
size_t t = 0;
while (p1 != nums1.cend() && p2 != nums2.cend()) {
if (*p1 > *p2) { *pt = *p2; ++p2; }
else { *pt = *p1; ++p1; }
++pt;
}
while (p1 != nums1.cend()) { *pt = *p1; ++p1; ++pt; }
while (p2 != nums2.cend()) { *pt = *p2; ++p2; ++pt; }
if (s % 2 == 1) return v[s / 2];
else return double(v[(s + 1) / 2] + v[(s - 1) / 2]) / 2;
}
};
TEST(e0100, e0004) {
vector<int> n1{}, n2{};
n1 = str_to_vec<int>("[1, 3]");
n2 = str_to_vec<int>("[2]");
ASSERT_EQ(Solution().findMedianSortedArrays(n1, n2), 2);
n1 = str_to_vec<int>("[1, 2]");
n2 = str_to_vec<int>("[3, 4]");
ASSERT_EQ(Solution().findMedianSortedArrays(n1, n2), 2.5);
}
| 34.809524 | 80 | 0.497948 | ajz34 |
0ad0ed983b04fc8ec8b01da72acf293b22b292e9 | 679 | hpp | C++ | include/cjdb/iterator/reference.hpp | cjdb/clang-concepts-ranges | 7019754e97c8f3863035db74de62004ae3814954 | [
"Apache-2.0"
] | 4 | 2019-03-02T01:09:07.000Z | 2019-10-16T15:46:21.000Z | include/cjdb/iterator/reference.hpp | cjdb/cjdb-ranges | 7019754e97c8f3863035db74de62004ae3814954 | [
"Apache-2.0"
] | 5 | 2019-11-29T12:23:55.000Z | 2019-12-14T13:03:00.000Z | include/cjdb/iterator/reference.hpp | cjdb/clang-concepts-ranges | 7019754e97c8f3863035db74de62004ae3814954 | [
"Apache-2.0"
] | 3 | 2020-06-08T18:27:28.000Z | 2021-03-27T17:49:46.000Z | // Copyright (c) Christopher Di Bella.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
#ifndef CJDB_ITERATOR_REFERENCE_HPP
#define CJDB_ITERATOR_REFERENCE_HPP
#include "cjdb/detail/iterator/reference.hpp"
#include "cjdb/detail/iterator/iter_move.hpp"
#include "cjdb/type_traits/type_traits.hpp"
#include <utility>
namespace cjdb {
template<detail_iterator_reference::dereferenceable T>
using iter_reference_t = decltype(*std::declval<T&>());
template<typename T>
requires detail_iter_move::iter_move_can_reference<T>
using iter_rvalue_reference_t = decltype(ranges::iter_move(std::declval<T&>()));
} // namespace cjdb
#endif // CJDB_ITERATOR_REFERENCE_HPP
| 30.863636 | 81 | 0.792342 | cjdb |
bd598bc53274c46a279871c521f740e1329f5819 | 16,118 | cpp | C++ | flir_lepton_sensor/src/flir_lepton_hw_iface.cpp | angetria/flir_lepton_rpi2 | 46b1de815e2bfb752954fb2c3648d416f56e6c93 | [
"BSD-3-Clause"
] | 15 | 2015-11-10T10:39:53.000Z | 2022-03-29T07:07:53.000Z | flir_lepton_sensor/src/flir_lepton_hw_iface.cpp | angetria/flir_lepton | 46b1de815e2bfb752954fb2c3648d416f56e6c93 | [
"BSD-3-Clause"
] | 6 | 2015-10-23T12:18:45.000Z | 2019-07-02T09:55:46.000Z | flir_lepton_sensor/src/flir_lepton_hw_iface.cpp | angetria/flir_lepton_rpi2 | 46b1de815e2bfb752954fb2c3648d416f56e6c93 | [
"BSD-3-Clause"
] | 6 | 2017-04-13T12:28:38.000Z | 2019-07-03T21:58:51.000Z | /*********************************************************************
* *
* * Software License Agreement (BSD License)
* *
* * Copyright (c) 2015, P.A.N.D.O.R.A. Team.
* * All rights reserved.
* *
* * Redistribution and use in source and binary forms, with or without
* * modification, are permitted provided that the following conditions
* * are met:
* *
* * * Redistributions of source code must retain the above copyright
* * notice, this list of conditions and the following disclaimer.
* * * Redistributions in binary form must reproduce the above
* * copyright notice, this list of conditions and the following
* * disclaimer in the documentation and/or other materials provided
* * with the distribution.
* * * Neither the name of the P.A.N.D.O.R.A. Team nor the names of its
* * contributors may be used to endorse or promote products derived
* * from this software without specific prior written permission.
* *
* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* * POSSIBILITY OF SUCH DAMAGE.
* *
* * Author: Konstantinos Panayiotou, Angelos Triantafyllidis,
* * Tsirigotis Christos
* * Maintainer: Konstantinos Panayiotou
* * Email: [email protected]
* *
* *********************************************************************/
#include "flir_lepton_hw_iface.h"
#include "flir_lepton_utils.h"
/* ---< SPI interface related >--- */
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#include <ros/package.h>
/* ------------------------------- */
namespace flir_lepton
{
namespace flir_lepton_sensor
{
FlirLeptonHWIface::FlirLeptonHWIface(const std::string& ns):
nh_(ns),
vospiFps_(25)
{
loadParameters();
calibMap_ = Utils::loadThermalCalibMap(calibFileUri_);
flirSpi_.configSpiParams(nh_);
openDevice();
/* ----------------------- Publishers --------------------------------- */
temperPublisher_ = nh_.advertise<flir_lepton_msgs::TemperaturesMsg>(
temperTopic_, 1);
if(pubGray_)
{
grayPublisher_ = nh_.advertise<sensor_msgs::Image>(grayTopic_, 1);
}
if(pubRgb_)
{
rgbPublisher_ = nh_.advertise<sensor_msgs::Image>(rgbTopic_, 1);
rgbImage_.header.frame_id = frameId_;
rgbImage_.height = IMAGE_HEIGHT;
rgbImage_.width = IMAGE_WIDTH;
rgbImage_.encoding = "rgb8";
rgbImage_.is_bigendian = 0;
rgbImage_.step = IMAGE_WIDTH * sizeof(uint8_t) * 3;
}
batchPublisher_ = nh_.advertise<flir_lepton_msgs::FlirLeptonBatchMsg>(
batchTopic_, 1);
/* -------------------------------------------------------------------- */
flirDataFrame_.allocateBuffers();
allocateFrameData();
grayImage_.header.frame_id = frameId_;
grayImage_.height = IMAGE_HEIGHT;
grayImage_.width = IMAGE_WIDTH;
grayImage_.encoding = "mono8";
grayImage_.is_bigendian = 0;
grayImage_.step = IMAGE_WIDTH * sizeof(uint8_t);
temperMsg_.header.frame_id = frameId_;
temperMsg_.values.layout.dim.push_back(std_msgs::MultiArrayDimension());
temperMsg_.values.layout.dim[0].size = IMAGE_HEIGHT;
temperMsg_.values.layout.dim.push_back(std_msgs::MultiArrayDimension());
temperMsg_.values.layout.dim[1].size = IMAGE_WIDTH;
batchMsg_.header.frame_id = frameId_;
initThreadedIO();
/* -------------------------------------------------------------------- */
}
FlirLeptonHWIface::~FlirLeptonHWIface()
{
closeDevice();
ioThread_.interrupt();
ioThread_.join();
}
void FlirLeptonHWIface::loadParameters(void)
{
int param;
std::string calibFileName;
/* ----------- Load Parameters ------------ */
// Load calibration dataset file name. Datasets are stored under the
// flir_lepton_auxiliary package, into the datasets directory.
// (flir_lepton_auxiliary/datasets)
nh_.param<std::string>("dataset_file_name", calibFileName,
"dataset_spline");
// Search for flir_lepton_auxiliary package absolute path, using rospack.
std::string datasetPath = ros::package::getPath("flir_lepton_auxiliary") +
"/datasets/";
calibFileUri_ = datasetPath + calibFileName;
ROS_INFO("Temperature calibration dataset file: [%s]",
calibFileUri_.c_str());
nh_.param<std::string>("flir_urdf/camera_optical_frame", frameId_,
"/flir_optical_frame");
nh_.param<std::string>("published_topics/flir_gray_image_topic", grayTopic_,
"/flir_lepton/image/gray");
nh_.param<std::string>("published_topics/flir_rgb_image_topic", rgbTopic_,
"/flir_lepton/image/rgb");
nh_.param<std::string>("published_topics/flir_temper_topic",
temperTopic_, "flir_lepton/temperatures");
nh_.param<std::string>("published_topics/flir_batch_topic",
batchTopic_, "flir_lepton/batch");
nh_.param<bool>("gray_image", pubGray_, true);
nh_.param<bool>("rgb_image", pubRgb_, true);
/* ----------------------------------------- */
nh_.param<int32_t>("iface/packet_size", param, 164);
flirDataFrame_.packetSize = param;
flirDataFrame_.packetSize16 = param / 2;
nh_.param<int32_t>("iface/packets_per_frame", param, 60);
flirDataFrame_.packetsPerFrame = param;
}
void FlirLeptonHWIface::FlirSpi::configSpiParams(
const ros::NodeHandle& nh)
{
int param;
mode = SPI_MODE_3;
nh.param<int32_t>("iface/bits", param, 8);
bits = param;
nh.param<int32_t>("iface/speed", param, 16000000);
speed = param;
nh.param<int32_t>("iface/delay", param, 0);
delay = param;
nh.param<std::string>("iface/device_port", devicePort, "/dev/spidev0.0");
}
void FlirLeptonHWIface::initThreadedIO(void)
{
ioThread_ = boost::thread(&FlirLeptonHWIface::readFrame, this);
}
void FlirLeptonHWIface::FlirDataFrame::allocateBuffers(void)
{
frameBuffer = new uint8_t[packetSize * packetsPerFrame];
cleanDataBuffer = new uint16_t[IMAGE_HEIGHT * IMAGE_WIDTH];
frameData = new uint16_t[IMAGE_HEIGHT * IMAGE_WIDTH];
}
void FlirLeptonHWIface::allocateFrameData(void)
{
lastFrame_ = new uint16_t[IMAGE_HEIGHT * IMAGE_WIDTH];
}
void FlirLeptonHWIface::run(void)
{
//readFrame();;
//ROS_INFO("[Flir-Lepton]: VoSPI average fps: %f", vospiFps_);
now_ = ros::Time::now();
processFrame();
//Batch msg creation
fillBatchMsg();
/* --------< Publish Messages >-------- */
if(pubGray_)
{
grayPublisher_.publish(grayImage_);
}
if(pubRgb_)
{
rgbPublisher_.publish(rgbImage_);
}
temperPublisher_.publish(temperMsg_);
batchPublisher_.publish(batchMsg_);
/* ------------------------------------ */
}
void FlirLeptonHWIface::readFrame(void)
{
int packetNumber = -1;
int resets = 0;
int restarts = 0;
// Pointer to FlirDataFrame struct member buffer.
uint8_t* rawBuffer = flirDataFrame_.frameBuffer;
uint16_t* cleanData = flirDataFrame_.cleanDataBuffer;
uint16_t* frameData = flirDataFrame_.frameData;
uint16_t packetSize = flirDataFrame_.packetSize;
uint16_t packetsPerFrame = flirDataFrame_.packetsPerFrame;
uint16_t packetSize16 = packetSize / 2;
uint16_t frameSize16 = packetSize16 * packetsPerFrame;
uint16_t maxVal, minVal;
uint16_t value, temp;
boost::posix_time::ptime begin, end;
/* ------------------ Read raw frame data from spi -------------------- */
while(1)
{
begin = boost::posix_time::microsec_clock::local_time();
try
{
restarts = 0;
for (uint16_t i = 0; i < packetsPerFrame; i++)
{
read(flirSpi_.handler, &rawBuffer[packetSize * i],
sizeof(uint8_t) * packetSize);
// flir sends discard packets that we need to resolve
packetNumber = rawBuffer[i * packetSize + 1];
if (packetNumber != i)
{
// if it is a drop packet, reset i
i = -1;
resets += 1;
// sleep for 1ms
ros::Duration(0.01).sleep();
// If resets reach this value, we assume an error on communication with
// flir-lepton sensor. Perform communication restart
if (resets == MAX_RESETS_ERROR) //Reach 750 sometimes
{
restarts ++;
ROS_ERROR("[Flir-Lepton]: VoSPI packages are corrupted");
ROS_WARN("[Flir-Lepton]: SPI communication restarting...");
closeDevice();
boost::this_thread::sleep(boost::posix_time::milliseconds(25));
openDevice();
resets = 0;
}
// If true we assume an exit status.. Kill process and exit
if (restarts > MAX_RESTART_ATTEMPS_EXIT)
{
ROS_FATAL("[Flir-Lepton]: Sensor does not respond. Exiting...");
ros::shutdown();
exit(1);
}
}
}
/* -------------------------------------------------------------------- */
// Cast to uint16_t in (2 bytes).
uint16_t* rawBuffer16 = (uint16_t*) rawBuffer;
uint16_t cleanDataCount = 0;
maxVal = 0;
minVal = -1;
// Process this acquired from spi port, frame and create the data vector
for (int i = 0; i < frameSize16; i++)
{
//Discard the first 4 bytes. it is the header.
if (i % packetSize16 < 2) continue;
temp = rawBuffer[i * 2];
rawBuffer[i * 2] = rawBuffer[i * 2 + 1];
rawBuffer[i * 2 + 1] = temp;
value = rawBuffer16[i];
cleanData[cleanDataCount] = value;
cleanDataCount++;
if (value > maxVal) {maxVal = value;}
if (value < minVal) {minVal = value;}
}
mtxLock_.lock();
// Copy cleanData to class frameData buffer
memcpy(frameData, cleanData, IMAGE_HEIGHT * IMAGE_WIDTH * sizeof(uint16_t));
flirDataFrame_.minVal = minVal;
flirDataFrame_.maxVal = maxVal;
mtxLock_.unlock();
}
catch (boost::thread_interrupted&) {return;}
end = boost::posix_time::microsec_clock::local_time();
calcVoSPIfps(begin, end);
}
}
float FlirLeptonHWIface::calcVoSPIfps(
boost::posix_time::ptime& start, boost::posix_time::ptime& stop)
{
boost::posix_time::time_duration elapsedDur = stop - start;
vospiFps_ = (vospiFps_ +
static_cast<float>( 1000.0 / elapsedDur.total_milliseconds())) / 2;
return vospiFps_;
}
/*!
* @brief Process the last obtained from flir lepton VoSPI frame.
*
* @return Void.
*/
void FlirLeptonHWIface::processFrame(void)
{
uint8_t imageVal;
uint16_t temp;
float temperVal;
float temperSum = 0;
uint16_t minVal, maxVal;
uint8_t red = 0, green = 0, blue = 0;
/* -------------------------------------------------------------------- */
mtxLock_.lock();
memcpy(lastFrame_, flirDataFrame_.frameData,
IMAGE_HEIGHT * IMAGE_WIDTH * sizeof(uint16_t));
minVal = flirDataFrame_.minVal;
maxVal = flirDataFrame_.maxVal;
mtxLock_.unlock();
/* -------------------------------------------------------------------- */
// Clear previous acquired frame temperature values
temperMsg_.values.data.clear();
grayImage_.data.clear();
if(pubRgb_) {rgbImage_.data.clear();}
for (int i = 0; i < IMAGE_WIDTH; i++) {
for (int j = 0; j < IMAGE_HEIGHT; j++) {
// Thermal image creation
imageVal = Utils::signalToImageValue(
lastFrame_[i * IMAGE_HEIGHT + j], minVal, maxVal);
grayImage_.data.push_back(imageVal);
if(pubRgb_)
{
Utils::toColormap(imageVal, red, green, blue);
rgbImage_.data.push_back(red);
rgbImage_.data.push_back(green);
rgbImage_.data.push_back(blue);
}
// Scene frame Temperatures vector creation.
temperVal = Utils::signalToTemperature(
lastFrame_[i * IMAGE_HEIGHT + j], calibMap_);
temperMsg_.values.data.push_back(temperVal);
temperSum += temperVal;
}
}
grayImage_.header.stamp = now_;
rgbImage_.header.stamp = now_;
temperMsg_.header.stamp = now_;
frameAvgTemper_ = temperSum / (IMAGE_HEIGHT * IMAGE_WIDTH);
}
/*!
* @brief Fills batch topic msg.
*
* @return Void.
*/
void FlirLeptonHWIface::fillBatchMsg(void)
{
batchMsg_.header.stamp = now_;
batchMsg_.temperatures = temperMsg_;
batchMsg_.thermalImage = grayImage_;
}
void FlirLeptonHWIface::openDevice(void)
{
int statusVal;
flirSpi_.handler = open(flirSpi_.devicePort.c_str(), O_RDWR);
if (flirSpi_.handler < 0)
{
ROS_FATAL("[Flir-Lepton]: Can't open SPI device port --> %s",
flirSpi_.devicePort.c_str());
exit(1);
}
statusVal = ioctl(flirSpi_.handler, SPI_IOC_WR_MODE, &flirSpi_.mode);
if (statusVal < 0)
{
ROS_FATAL("[Flir-Lepton]: Can't set SPI-mode (WR)...ioctl failed");
exit(1);
}
statusVal = ioctl(flirSpi_.handler, SPI_IOC_RD_MODE, &flirSpi_.mode);
if (statusVal < 0)
{
ROS_FATAL("[Flir-Lepton]: Can't set SPI-mode (RD)...ioctl failed");
exit(1);
}
statusVal = ioctl(flirSpi_.handler, SPI_IOC_WR_BITS_PER_WORD, &flirSpi_.bits);
if (statusVal < 0)
{
ROS_FATAL("[Flir-Lepton]: Can't set SPI bitsperWord (WD)...ioctl failed");
exit(1);
}
statusVal = ioctl(flirSpi_.handler, SPI_IOC_RD_BITS_PER_WORD, &flirSpi_.bits);
if (statusVal < 0)
{
ROS_FATAL("[Flir-Lepton]: Can't set SPI bitsperWord (RD)...ioctl failed");
exit(1);
}
statusVal = ioctl(flirSpi_.handler, SPI_IOC_WR_MAX_SPEED_HZ, &flirSpi_.speed);
if (statusVal < 0)
{
ROS_FATAL("[Flir-Lepton]: Can't set SPI speed (WD)...ioctl failed");
exit(1);
}
statusVal = ioctl(flirSpi_.handler, SPI_IOC_RD_MAX_SPEED_HZ, &flirSpi_.speed);
if (statusVal < 0)
{
ROS_FATAL("[Flir-Lepton]: Can't set SPI speed (RD)...ioctl failed");
exit(1);
}
ROS_INFO("[Flir-Lepton]: Device SPI Port open.");
//ROS_INFO("[SPI Device information]:");
//std::cout << " * Device Port: " << flirSpi_.devicePort << std::endl;
}
void FlirLeptonHWIface::closeDevice(void)
{
int statusVal;
statusVal = close(flirSpi_.handler);
if (statusVal < 0)
{
ROS_FATAL("[Flir-Lepton]: Error while trying to close SPI device port");
exit(1);
}
ROS_INFO("[Flir-Lepton]: Closing device SPI Port");
}
} // namespace flir_lepton_sensor
} // namespace flir_lepton_rpi2
| 33.509356 | 86 | 0.585122 | angetria |
bd59e41984d0a6dcac40ad7e6ba9f4efe616a2b2 | 878 | hpp | C++ | src/gui/sprites/simple_world_sprite.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7 | 2015-01-28T09:17:08.000Z | 2020-04-21T13:51:16.000Z | src/gui/sprites/simple_world_sprite.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null | src/gui/sprites/simple_world_sprite.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1 | 2020-07-11T09:20:25.000Z | 2020-07-11T09:20:25.000Z | #ifndef SIMPLE_WORLD_SPRITE_HPP_INCLUDED
#define SIMPLE_WORLD_SPRITE_HPP_INCLUDED
#include <gui/sprites/world_sprite.hpp>
class SimpleWorldSprite: public WorldSprite
{
public:
SimpleWorldSprite(const Position& position, const sf::Sprite& sprite):
position(position),
sprite(sprite)
{}
~SimpleWorldSprite() = default;
Position get_world_pos() const
{
return this->position;
}
void draw(sf::RenderTarget& surface, const sf::RenderStates& states) const
{
surface.draw(this->sprite, states);
}
private:
const Position position;
const sf::Sprite& sprite;
SimpleWorldSprite(const SimpleWorldSprite&) = delete;
SimpleWorldSprite(SimpleWorldSprite&&) = delete;
SimpleWorldSprite& operator=(const SimpleWorldSprite&) = delete;
SimpleWorldSprite& operator=(SimpleWorldSprite&&) = delete;
};
#endif /* SIMPLE_WORLD_SPRITE_HPP_INCLUDED */
| 25.823529 | 76 | 0.753986 | louiz |
bd6105d0de0f2fc8b97c96312456888daa4a4a46 | 171,483 | cxx | C++ | osprey/be/cg/orc_intel/if_conv.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/cg/orc_intel/if_conv.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/cg/orc_intel/if_conv.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (C) 2000-2003, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
Neither the name of the owner 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 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.
*/
//-*-c++-*-
//*****************************************************************************
//
// Module: if_conv.cxx
// $Date: 2005/10/21 19:00:00 $
// $Author: marcel $
// $Source: /proj/osprey/CVS/open64/osprey1.0/be/cg/orc_intel/if_conv.cxx,v $
//
//
//
// Description: Implementation of Ipfec if-conversion.
// See if-conv.h for the description.
//
//*****************************************************************************
#include <vector>
#include <set>
#include <stdlib.h>
#include <stdio.h>
#include "bb.h"
#include "defs.h"
#include "mempool.h"
#include "error.h"
#include "bb_set.h"
#include "region.h"
#include "cgtarget.h"
#include "if_conv.h"
#include "timing.h"
#include "tracing.h"
#include "cg.h"
#include "profile_util.h"
#include "region_bb_util.h"
#include "ti_res_count.h"
#include "ti_latency.h"
#include "ipfec_defs.h"
#include "cg_dep_graph.h"
#include "dominate.h"
#include "vt_region.h"
#include "recovery.h"
#include <math.h>
#include "whirl2ops.h"
#include "tlog.h"
#include "glob.h"
#include "ipfec_options.h"
#include "be_util.h"
#include "freq.h"
#include "op.h"
#define MAX_NUM_PARA_CMP 2
#define COMP_TOP_NUM 32
#define PARA_COMP_TYPE_NUM 6
void fPrint_TN ( FILE *f, char *fmt, TN *tn);
BOOL CGTARG_Unconditional_Compare(OP *, TOP *);
void BB_SET_Calculate_Dominators(BB_SET *, BOOL, BOOL);
void Calculate_Dominators(void);
void Free_Dominators_Memory(void);
void Exp_True_False_Preds_For_Block(BB *, TN *&, TN *&);
void Exp_Pred_Set(TN *dest, TN *cdest, INT val, OPS *ops);
void Exp_Generic_Pred_Calc(TN*,TN *, COMPARE_TYPE, TN *, OPS*);
void draw_classic_BB_dependence_graph(BB *bb);
void Predicate_Block(BB* bb, TN *pred_tn, BB_SET*);
void Print_BB (BB *);
void Print_OPS(ops const *);
void Print_OP_No_SrcLine(const OP *op);
void GRA_LIVE_Compute_Liveness_For_BB(BB *bb);
BOOL FREQ_Match(float f1, float f2);
BOOL Is_In_Abnormal_Loop(REGION* r);
COMPARE_TYPE Compare_Type(TOP opcode);
hTN_MAPf frequency_of_predicates = 0;
TN_INFO_MEM info_mem;
hTN_MAP init_op_info = 0;
BOOL
Is_Para_Comp_May_Def(OP *op)
{
COMPARE_TYPE comp_type = Compare_Type(OP_code(op));
return ((comp_type != COMPARE_TYPE_unc)
&& (comp_type != COMPARE_TYPE_normal)
&& (comp_type != (COMPARE_TYPE)-1));
}
BOOL
Is_In_Infinite_Loop(REGION* region)
{
REGION* reg = region;
while (reg) {
if ( reg -> Region_Type() == LOOP
&& reg ->Exits().empty())
return TRUE;
reg = reg -> Parent();
}
return FALSE;
}
//*****************************************************************************
// Function: Is_Abnormal_Loop
// Input : region
// Output :
// a boolean value which indicates if the region is an abnormal loop.
// Here, an abnormal loop is a loop like :
// 1 <------|
// / \ |
// / \ |
// 2 3 |
// / \ / |
// / \ / |
// exit 4 --------|
// in such a loop, 1 dom 2 and 2 pdom 1, as a result, 1 and 2 are put into
// one control-equivalent-class. So some wrong results are caused in
// if-conversion and predicate analysis.
// Description :
// the conditions in which we judge if a region is an abnormal loop is :
// 1) region is a loop region;
// 2) the source of the back-edge is not an exit -node of the loop;
// 3) the exit is not the entry of the loop
//*****************************************************************************
BOOL
Is_Abnormal_Loop(REGION* region)
{
if ( region -> Region_Type() != LOOP)
return FALSE;
// find out the source node of back-edge
REGIONAL_CFG_NODE* loop_tail = NULL;
for (TOPOLOGICAL_REGIONAL_CFG_ITER iter( region -> Regional_Cfg());
iter!=0;
++iter)
{
REGIONAL_CFG_NODE *node = *iter;
if ( node -> Succ_Num() == 0)
{
if(loop_tail ||
(node -> Is_Region() && node->Region_Node()->Exits().size() >1 ) )
return TRUE;
loop_tail = node;
}
}
NODE_VECTOR exits = region -> Exits();
for (NODE_VECTOR_ITER iter1 = exits.begin();
iter1 != exits.end();
iter1++)
{
if ((*iter1) == loop_tail) {
return FALSE;
}
}
if ( region -> Entries().size() != 1) {
DevWarn("MEME region is illegal in Is_Abnormal_Loop!\n");
return FALSE;
}
if ( region -> Exits().size() == 1)
{
REGIONAL_CFG_NODE* entry = *(region -> Entries().begin());
REGIONAL_CFG_NODE* exit = *(region -> Exits().begin());
if (!entry->Is_Region() && entry == exit)
return FALSE;
}
return TRUE;
}
/* ====================================================================
*
* TN_Defined_At_Op
*
* This functions lookes for the definition of a given TN for
* a given OP.
*
* If the definition is conditional and garded by the same
* predicate as the given OP, then the pointer to this OP is returned.
* If this is not the case, then the pointer to this function is put
* into the OP list(ops) and it continues the search until it finds a
* definition which is not conditional or the predicates are the
* same.
* i.e The given values are tn=TN1, op=OP3, ops=<some valid pointer>
* TN1 TN2 OP1
* TN1 TN2 OP2 (TN3) cond.
* OP3 (TN1) cond.
*
* The function would in this case return the pointer to OP1, because
* this is the first OP which definitely defines TN1. In the OP list
* would be the pointers to OP2 and OP1.
*
* ====================================================================
*/
OP *
TN_Defined_At_Op (TN *tn, OP *op, std::vector<OP *> *ops) {
OP *value_op;
if (ops==NULL) {
FmtAssert(0, ("Parameter ops is NULL pointer!"));
}
if (TN_register(tn) != REGISTER_UNDEFINED) {
return NULL;
}
for (value_op=OP_prev(op); value_op!=NULL; value_op=OP_prev(value_op)) {
if (OP_Defs_TN(value_op, tn)) {
ops->push_back(value_op);
if (Is_OP_Cond(value_op)) {
if (OP_has_predicate(value_op) && OP_has_predicate(op)) {
TN *p1 = OP_opnd((OP*) value_op, OP_PREDICATE_OPND);
TN *p2 = OP_opnd((OP*) op, OP_PREDICATE_OPND);
if (p1 == p2) {
return value_op;
}
}
}
else {
return value_op;
}
}
}
return NULL;
}
//*****************************************************************************
// Function : Find_BB_Predicates
// Input :
// - bb : the bb contains branch and compare
// - first_pred: the first target of compare
// - second_pred: the second target of compare
// Output :
// < none >
// Description :
// if a bb has a conditional branch, and the guarding predicate of the
// branch is defined by a compare instructin , the function is to find out
// the first and the second predicate register of the compare instruction.
//*****************************************************************************
void
Find_BB_Predicates(BB* bb, TN*& first_pred,TN*& second_pred)
{
vector<OP *>::iterator op;
vector<OP *> ops;
OP *br = BB_branch_op(bb);
first_pred = NULL;
second_pred = NULL;
TN *pred_1;
TN *pred_2;
if (BB_succs_len(bb) != 2 || !br) {
return;
}
pred_1 = OP_opnd(br, OP_PREDICATE_OPND);
Is_True(pred_1, ("conditional branch has no guarded predicate!\n"));
OP *compare_op = TN_Defined_At_Op(pred_1, br, &ops);
if(!compare_op) {
return;
}
Is_True(compare_op,
(" the predicate of br has reaching definition!\n"));
Is_True(OP_results(compare_op),
(" compare_op must has result.\n"));
first_pred = OP_result(compare_op,0);
if (OP_results(compare_op) > 1)
{
second_pred = OP_result(compare_op,1);
}
// If we have more then one OP which defines the branch predicate,
// we have to check if all predicate pairs are the same.
// i.e
// TN1 TN2 op1
// TN2 TN1 op2
BOOL create_neg_of_br_pred = FALSE;
if (ops.size() < 2) {
return;
}
for (op = ops.begin(); op != ops.end(); op++) {
if (OP_results(*op) > 1) {
if ( !( (first_pred == OP_result(*op,0)) &&
(second_pred == OP_result(*op,1))
) &&
!( (first_pred == OP_result(*op,1)) &&
(second_pred == OP_result(*op,0))
)
)
{
// predicate pair is different
// we have to create and insert a predicate which is a
// negation of our branch predicate
create_neg_of_br_pred = TRUE;
break;
}
}
else {
// only one predicate
// we have to create and insert a predicate which is a
// negation of our branch predicate
create_neg_of_br_pred = TRUE;
break;
}
}
if (create_neg_of_br_pred) {
OP *neg_op;
// Lets check if we already have insert the negation op in a previous
// function call of Find_BB_Predictae()
neg_op = OP_prev(br);
if ( (OP_code(neg_op)==TOP_cmp_ne_unc) &&
(OP_Refs_TN(neg_op, pred_1)) &&
(OP_Refs_TN(neg_op, Zero_TN)) &&
(OP_Defs_TN(neg_op, True_TN)) )
{
pred_2 = OP_result(neg_op, 1);
}
else {
pred_2 = Gen_Predicate_TN();
neg_op = Mk_OP(TOP_cmp_ne_unc, True_TN, pred_2, True_TN, pred_1, Zero_TN);
OP_srcpos(neg_op) = OP_srcpos(br);
BB_Insert_Op(bb, br, neg_op, TRUE);
}
first_pred = pred_1;
second_pred = pred_2;
}
return;
}
//=============================================================================
// Part 1: implementation of the classes defined in this phase
//=============================================================================
//*****************************************************************************
// implementation for class IF_CONV_AREA
//*****************************************************************************
IF_CONV_AREA::IF_CONV_AREA(BB *bb, IF_CONVERTOR *convertor):
_included_blocks(BB_CONTAINER(&(convertor -> _m))),
_predecessors(IF_CONV_ALLOC(&(convertor -> _m))),
_successors(IF_CONV_ALLOC(&(convertor -> _m)))
{
_head = bb;
// add the present bb in _included_blocks
_included_blocks.push_back(bb);
// if the present basic block is not suitable for if-conversion,
// we set the mark
// if it is suitable, we compute the length of its critical path
AREA_TYPE type = convertor -> Suitable_For_If_Conv(bb);
_if_suitable = type;
_need_if_convert = NO_IF_CONV;
if (type != UNSUITABLE)
{
_cycled_critical_length = convertor ->
Compute_Critical_Path_Len(bb, true);
_critical_length = convertor ->
Compute_Critical_Path_Len(bb,false);
} else {
_cycled_critical_length = 0;
_critical_length = 0;
}
_control_deps = 0;
_pred_assign_info = 0;
}
void
IF_CONV_AREA::Combine_Blocks_With(IF_CONV_AREA *area, MEM_POOL *mem_pool)
{
BB_CONTAINER& set = area -> Blocks();
BB_CONTAINER::iterator iter;
for (iter = set.begin();
iter != set.end();
iter++)
{
_included_blocks.push_back(*iter);
}
}
void
IF_CONV_AREA::Init_Conversion_Info(MEM_POOL *mem_pool)
{
_control_deps = CXX_NEW(
CNTL_DEP(_head, _included_blocks, mem_pool), mem_pool);
_pred_assign_info = BB_MAP_Create();
BB_CONTAINER::iterator iter;
for (iter = _included_blocks.begin();
iter != _included_blocks.end();
iter++)
{
BB_PREDICATE_INFO* info =
CXX_NEW(BB_PREDICATE_INFO(mem_pool), mem_pool);
BB_MAP_Set(_pred_assign_info, *iter, info);
}
}
void
IF_CONV_AREA::Remove_BB(BB* bb)
{
BB_CONTAINER::iterator iter;
for (iter = _included_blocks.begin();
iter != _included_blocks.end();
iter++)
{
if ( *iter == bb)
{
_included_blocks.erase(iter);
return;
}
}
}
EXIT_TARGET_INFO*
IF_CONV_AREA::Exit_Target(BB* bb)
{
EXIT_CONTAINER::iterator iter;
for (iter = _exit_targets.begin();
iter != _exit_targets.end();
iter++)
{
if ( (*iter) -> Target() == bb) {
return *iter;
}
}
return NULL;
}
void
IF_CONV_AREA::Add_Exit_Target(BB* target, TN* predicate, MEM_POOL* mem_pool)
{
EXIT_TARGET_INFO* info =
CXX_NEW(EXIT_TARGET_INFO(target, mem_pool), mem_pool);
info -> Add_Main_Predicate(predicate);
_exit_targets.push_back(info);
}
BOOL
EXIT_TARGET_INFO::Is_Main_Predicate(TN* tn)
{
TN_CONTAINER::iterator iter;
for (iter = _main_predicates.begin();
iter != _main_predicates.end();
iter++)
{
if ( *iter == tn) return true;
}
return false;
}
void
EXIT_TARGET_INFO::Assign_Aux_Predicates(BB* bb, OP *br)
{
OPS ops = OPS_EMPTY;
if ( _aux_predicates.size() == 0 || _main_predicates.size() ==0 )
return;
Is_True(_main_predicates.size() == 1,
("Wrong number of main predicates!\n"));
TN *main_tn = *(_main_predicates.begin());
TN_CONTAINER::iterator iter;
for (iter = _aux_predicates.begin();
iter != _aux_predicates.end();
iter++)
{
Is_True(*iter, ("NULL predicate.\n"));
Build_OP(TOP_cmp_eq, main_tn, True_TN,
*iter,Zero_TN, Zero_TN, &ops);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
Print_OPS(&ops);
}
OP* new_op;
FOR_ALL_OPS_OPs_FWD((&ops),new_op){
Set_OP_cond_def_kind(new_op, OP_ALWAYS_COND_DEF);
}
BB_Insert_Ops_Before (bb, br, &ops);
}
void
EXIT_TARGET_INFO::Del_Main_Predicate(TN* tn){
TN_CONTAINER::iterator iter;
for (iter = _main_predicates.begin();
iter != _main_predicates.end();
iter++)
{
Is_True(*iter, ("NULL predicate.\n"));
if (*iter == tn)
{
_main_predicates.erase(iter);
break;
}
}
}
void
EXIT_TARGET_INFO::Update_Predicate(TN *old_tn, TN* new_tn)
{
if (old_tn == new_tn) return;
TN_CONTAINER::iterator iter;
for (iter = _main_predicates.begin();
iter != _main_predicates.end();
iter++)
{
Is_True(*iter, ("NULL predicate.\n"));
if (*iter == old_tn)
{
_main_predicates.erase(iter);
_main_predicates.push_back(new_tn);
break;
}
}
for (iter = _aux_predicates.begin();
iter != _aux_predicates.end();
iter++)
{
Is_True(*iter, ("NULL predicate.\n"));
if (*iter == old_tn)
{
_aux_predicates.erase(iter);
_aux_predicates.push_back(new_tn);
break;
}
}
return;
}
//*****************************************************************************
// implementation for class CNTL_DEP
//*****************************************************************************
//*****************************************************************************
// Function : CNTL::CNTL_DEP
// Input :
// - entry : the entry basic block of all BBs in set
// - set : a set of basic blocks. To use CNTL_DEP, the set must be:
// 1) all BBs in it are connected;
// 2) all BBs in it have a unique entry
// 3) there is no multiple-successor-bb in it
// 4) there is no such a case: a region is a predecessor of one bb
// in the set and, in the same time, it is a successor of another
// bb in the set
// Output :
// the control dependent tree of the input bb_set
// Description :
// it computes the control dependent information of a bb_set
//
//*****************************************************************************
CNTL_DEP::CNTL_DEP(BB *entry, BB_CONTAINER& bbs, MEM_POOL *mem_pool)
{
_entry = entry;
_bb_set = BB_SET_Create_Empty(PU_BB_Count, mem_pool);
BB_CONTAINER::iterator bb_iter;
BB *bb;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
_bb_set = BB_SET_Union1D(_bb_set, bb, mem_pool);
}
// Initialize control dependencies bit sets
_control_dependences = BB_MAP_Create();
_true_edges = BB_MAP_Create();
FOR_ALL_BB_SET_members(_bb_set, bb)
{
BB_SET *deps = BB_SET_Create_Empty(PU_BB_Count, mem_pool);
BB_SET *trues = BB_SET_Create_Empty(PU_BB_Count, mem_pool);
BB_MAP_Set(_control_dependences, bb, deps);
BB_MAP_Set(_true_edges, bb, trues);
}
// Find out the control dependences. Also, in this algorithms it's
// easy to set the true edges at the same time.
BBLIST *bl;
BB_SET *bb_to_add = BB_SET_Create_Empty(PU_BB_Count+2, mem_pool);
FOR_ALL_BB_SET_members(_bb_set, bb)
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " Computing BB%d:\n", BB_id(bb));
}
BB *fall_thru = BB_Fall_Thru_Successor(bb);
TN *second_pred = NULL;
TN *first_pred = NULL;
OP *br = NULL;
if ( BB_succs_len(bb) == 2)
{
br = BB_branch_op(bb);
Find_BB_Predicates(bb, first_pred, second_pred);
}
FOR_ALL_BB_SUCCS(bb, bl)
{
BB *bb_dep;
BB *bb_succ = BBLIST_item(bl);
BOOL true_edge = FALSE;
if ( br )
{
true_edge = (( first_pred == OP_opnd(br, OP_PREDICATE_OPND)
&& bb_succ != fall_thru)
|| ( second_pred == OP_opnd(br, OP_PREDICATE_OPND)
&& bb_succ == fall_thru));
}
//
// bb_to_add is set to (pdom(bb_succ) - pdom(bb)) & _bb_set.
// In other words, it is used to record what is in the bb_set
// post-dominates bb_succ (which will include bb_succ) and
// is not a post-dominator of bb. These are exactly the BB's which
// are control-dependent on bb. If the successor is not in the
// bb_set, we are safe to assume that nothing else in the bb_set
// post-dominates it, so we can ignore it. Also, if the successor
// is the bb_set entry, we have a loop and hence we must not
// consider this arc when computing the control dependence.
//
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " ===== succ BB%d:", BB_id(bb_succ));
}
if (BB_SET_MemberP(_bb_set, bb_succ) && (bb_succ != entry))
{
BB_SET_CopyD(bb_to_add, BB_pdom_set(bb_succ), mem_pool);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
BB* bb_tmp;
fprintf(TFile, " ** pdoms:");
FOR_ALL_BB_SET_members(bb_to_add, bb_tmp)
{
fprintf(TFile, " BB%d, ", BB_id(bb_tmp));
}
fprintf(TFile, "\n");
}
bb_to_add = BB_SET_DifferenceD(bb_to_add, BB_pdom_set(bb));
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
BB* bb_tmp;
fprintf(TFile, " ** after -pdoms(bb):");
FOR_ALL_BB_SET_members(bb_to_add, bb_tmp)
{
fprintf(TFile, " BB%d, ", BB_id(bb_tmp));
}
fprintf(TFile, "\n");
}
bb_to_add = BB_SET_IntersectionD(bb_to_add, _bb_set);
FOR_ALL_BB_SET_members(bb_to_add, bb_dep)
{
BB_SET *deps, *trues, *new_deps, *new_trues;
deps = (BB_SET*)BB_MAP_Get(_control_dependences, bb_dep);
Is_True(deps != NULL,
("Can't find cntl deps for BB%d.\n", BB_id(bb_dep)));
trues = (BB_SET*)BB_MAP_Get(_true_edges, bb_dep);
Is_True(trues != NULL,
("Can't find true edges for BB%d.\n", BB_id(bb_dep)));
new_deps = BB_SET_Union1D(deps, bb, mem_pool);
if ( deps != new_deps)
{
BB_MAP_Set(_control_dependences, bb_dep, new_deps);
}
if (true_edge)
{
new_trues = BB_SET_Union1D(trues, bb, mem_pool);
if ( trues != new_trues )
{
BB_MAP_Set( _true_edges, bb_dep, mem_pool);
}
}
}
}
}
}
}
BOOL
CNTL_DEP::Is_Cntl_Dep(BB *bb1, BB *bb2)
{
BB *bb;
if (bb1 == bb2) return true;
BB_SET *set = Cntl_Dep_Parents(bb2);
Is_True(set != NULL,
(" Can not find control dependent parents for BB%d", BB_id(bb2)));
FOR_ALL_BB_SET_members(set, bb)
{
if (Is_Cntl_Dep(bb1, bb))
return true;
}
return false;
}
void
CNTL_DEP::Cntl_Dep_Children(BB_SET*& result, BB *bb, MEM_POOL *mem_pool)
{
BB *block;
FOR_ALL_BB_SET_members(_bb_set, block)
{
BB_SET *cds = (BB_SET*)BB_MAP_Get(_control_dependences, block);
Is_True(cds != NULL,
(" Can not find control dependent parents for BB%d",
BB_id(block)));
if (BB_SET_MemberP(cds, bb))
{
result = BB_SET_Union1D( result, block, mem_pool);
}
}
}
void
CNTL_DEP::_Post_Order_Helper(BB_CONTAINER& result,
BB *bb,
IF_CONVERTOR* convertor)
{
BB *child;
BB_SET *child_set;
if (convertor -> Is_BB_Container_Member(result, bb))
return;
child_set = BB_SET_Create_Empty(PU_BB_Count, &(convertor -> _m));
Cntl_Dep_Children(child_set, bb, &(convertor -> _m));
FOR_ALL_BB_SET_members(child_set, child)
{
_Post_Order_Helper(result, child, convertor);
}
result.push_back(bb);
}
void
CNTL_DEP::Get_Post_Order(BB_CONTAINER& result,
IF_CONVERTOR* convertor)
{
BB *block;
FOR_ALL_BB_SET_members(_bb_set, block)
{
_Post_Order_Helper(result, block, convertor);
}
}
//=============================================================================
// Part2: some tool functions for IF_CONVERTOR
//=============================================================================
//*****************************************************************************
// Function : Suitable_For_If_Conv
// Input :
// - bb : a basic block
// Output :
// it indicate if it is legal to if_convert the bb
// Description :
// Determine if the block has some characteristics that make it
// undesirable or even illegal to be if-converted.
//
//*****************************************************************************
AREA_TYPE
IF_CONVERTOR::Suitable_For_If_Conv(BB *bb)
{
// except the basic block consisting of vargoto
if (BB_kind(bb) == BBKIND_VARGOTO || BB_kind(bb) == BBKIND_INDGOTO)
{
return UNSUITABLE;
}
if (BB_call(bb)) return UNSUITABLE;
// The bb with exception label can not be if-converted
if (BB_Has_Exc_Label(bb))
{
return UNSUITABLE;
}
// Blocks which have labels marked as address-taken cannot be if-converted.
if (BB_Has_Addr_Taken_Label(bb))
{
return UNSUITABLE;
}
AREA_TYPE ty = SUITABLE_FOR_IF_CONV;
OP* op;
FOR_ALL_BB_OPs_FWD(bb, op)
{
// if an op doesn't have qualifying predicate operands, it may be
// unsafe to employ predication. Exclude OP_xfer OPs as they
// will be eliminated as a by-product of doing if-conversion, so need
// to check for those OPs.
if (!OP_has_predicate(op) && !OP_xfer(op))
{
ty = (AREA_TYPE)((INT)ty & UPWARD_UNSUITABLE);
}
// For now, we do not plan to deal with blocks containing predicated
// instructions created by previous phases.
if (OP_has_predicate(op) &&
!TN_is_true_pred(OP_opnd(op, OP_PREDICATE_OPND)))
{
TN *pred_tn = OP_opnd(op, OP_PREDICATE_OPND);
if (TN_is_global_reg(pred_tn))
{
return UNSUITABLE;
}
vector<OP *> ops;
OP *def_op = TN_Defined_At_Op(pred_tn, op, &ops);
// If it's not defined in the block, we will give up.
if (!def_op)
{
DevWarn("Predicated instruction with no reaching def in BB%d "
"in Suitable_For_If_Conv.", BB_id(bb));
return UNSUITABLE;
}
// If its reaching defination is not in the bb, we will
// give up because it is very complicated.
if (OP_bb(def_op)!= bb)
{
DevWarn("An up-exposed predicate use stops if-converter BB%d "
"in Suitable_For_If_Conv.",BB_id(bb));
return UNSUITABLE;
}
}
// the following part is to protect the following case from being
// if-converted:
// p1, p2 = cmp a, b
// (p2) br
// / |
// / |
// p1, p2 = cmp a, b |
// \ |
// \ |
// (p2) br
// / \
// / \
// note: the 'cmp' is normal-type (non-unconditional)
// for the case,
// before if-convertion, if the condition of compare is false,
// both the two branches will all be taken; after if-convertion, it is
// changed to :
// p1, p2 = cmp a, b
// (p1) p1, p2 = cmp.unc a, b
// (p2) br
// note: the second cmp is changed to unconditional type. As a result,
// if the condition is false, the brance will not be taken.
// So, here, we skip the case.
COMPARE_TYPE ty = Compare_Type(OP_code(op));
if ( ty != (COMPARE_TYPE)-1) {
// compare type
Is_True(OP_results(op) <=2, ("too many results!\n"));
TN *pred_tn = OP_result(op, 0);
if (Is_Partial_Redundant_Def(bb, op, pred_tn)) {
return UNSUITABLE;
}
pred_tn = OP_result(op, 1);
if (Is_Partial_Redundant_Def(bb, op, pred_tn)) {
return UNSUITABLE;
}
}
}
return ty;
}
BOOL
IF_CONVERTOR::Is_Partial_Redundant_Def(BB* bb, OP* op, TN* tn)
{
// check all bb's ancestor in the region to see
// if tn is defined previously.
OP *def_op = NULL;
OP *def_bb = NULL;
vector<OP *> ops;
def_op = TN_Defined_At_Op(tn, op, &ops);
if (def_op)
{
BB *def_bb = OP_bb(def_op);
if ( def_bb != bb && !BB_SET_MemberP(BB_pdom_set(def_bb), bb))
{
return TRUE;
}
} else {
BB_SET* bb_queue = BB_SET_Create_Empty(PU_BB_Count, &_m);
bb_queue = BB_SET_Union1D(bb_queue, bb, &_m);
BB_SET* bb_processed = BB_SET_Create_Empty(PU_BB_Count, &_m);
while ( BB_SET_Size(bb_queue) )
{
BB* bb1 = BB_SET_Choose(bb_queue);
BS_Difference1D(bb_queue, BB_id(bb1));
BB_SET_Union1D(bb_processed, bb1, &_m);
REGIONAL_CFG_NODE* node = Regional_Cfg_Node(bb1);
for (CFG_PRED_NODE_ITER pred_iter(node);
pred_iter!=0;
++pred_iter)
{
REGIONAL_CFG_NODE *pred = *pred_iter;
if (pred -> Is_Region()) continue;
BB* pred_bb = pred -> BB_Node();
if ( GTN_SET_MemberP(BB_live_in(pred_bb),tn)
&& !BB_SET_MemberP(BB_pdom_set(pred_bb), bb))
{
return TRUE;
} else if (!BB_SET_MemberP(bb_processed, pred_bb)){
bb_queue = BB_SET_Union1D(bb_queue, pred_bb, &_m);
}
}
}
}
return FALSE;
}
//*****************************************************************************
// Function : Compute_Min_Cycle
// Input :
// - set : a set of basic blocks
// Output :
// a number to indicate the mininal executive time of the input bb
// Description :
// To compute the mininal execution cycle of the input BB_SET by only
// considering the resource usage.
//*****************************************************************************
void
IF_CONVERTOR::Compute_Min_Cycle(INT32& base, BB_CONTAINER& set)
{
TI_RES_COUNT *counter = TI_RES_COUNT_Alloc(&_m);
BB_CONTAINER::iterator iter;
for (iter = set.begin();
iter != set.end();
iter++)
{
OP *op;
FOR_ALL_BB_OPs_FWD(*iter, op)
{
TI_RES_COUNT_Add_Op_Resources(counter, OP_code(op));
}
}
base += (INT32)ceil(TI_RES_COUNT_Min_Cycles(counter));
}
//*****************************************************************************
// Function : Prob_Of_Area
// Description :
// To find out the probablity of two IF_CONV_AREAs according to the
// probablity of BBs.
//*****************************************************************************
float
IF_CONVERTOR::Prob_Of_Area(IF_CONV_AREA *area1,
IF_CONV_AREA *area2)
{
float freq = 0.0;
BB *head = area2 -> Entry_BB();
BB *bb;
BBLIST *bl;
FOR_ALL_BB_PREDS(head, bl)
{
BB *bb_pred = BBLIST_item(bl);
BB_CONTAINER& bbs = area1 -> Blocks();
if (Is_BB_Container_Member(bbs, bb_pred))
{
freq += Prob_Local(bb_pred, head) * BB_freq(bb_pred);
}
}
float result = BB_freq(area1 -> Entry_BB()) ?
freq / BB_freq(area1 -> Entry_BB()):0;
return result <1.0 ||FREQ_Match(result, 1.0) ? result: 1.0;
}
//*****************************************************************************
// Function : Compute_Critical_Path_Len
// Input :
// - bb : a basic block for which the function will figure out the length
// of its critical path
// - cycled : it indicates if we need consider the latency of ops. if it
// is false, we will look all ops as one-cycle-latency ops.
// Output :
// an INT value indicating the length of the critical path of the input
// Description :
// To compute the length of the critical path of the given basic block
//*****************************************************************************
INT32
IF_CONVERTOR::Compute_Critical_Path_Len(BB *bb,
BOOL cycled)
{
// to record the earliest start time of all ops
BB_OP_MAP earliest_time_table = BB_OP_MAP32_Create(bb, &_m);
INT32 critical_path_cycle = 0;
// build dag for current bb
if (CG_DEP_Has_Graph(bb))
{
CG_DEP_Delete_Graph(bb);
}
CG_DEP_Compute_Graph (
bb,
INCLUDE_ASSIGNED_REG_DEPS,
NON_CYCLIC,
NO_MEMREAD_ARCS,
INCLUDE_MEMIN_ARCS,
INCLUDE_CONTROL_ARCS,
NULL);
// search all ops of the bb and compute the earliest-start-time for them
OP *op;
FOR_ALL_BB_OPs_FWD(bb,op)
{
if ( OP_xfer(op))
break;
INT32 earliest_start_time = 0;
INT32 latency;
// the predecessors of an op are the ops, from which there are
// dependence edges pointing to the op;after the following loop,
// we can compute the earliest-start-time of an op;
for (ARC_LIST* arcs = OP_preds(op);
arcs != NULL;
arcs = ARC_LIST_rest(arcs))
{
ARC* arc = ARC_LIST_first(arcs);
OP* pred = ARC_pred(arc);
if (OP_bb(pred) != bb) continue;
INT32 start_time;
start_time = BB_OP_MAP32_Get(earliest_time_table, pred);
latency = cycled ? ARC_latency(arc):1;
start_time += latency;
if ( start_time > earliest_start_time)
earliest_start_time = start_time;
}
// in the following, we update the length of the longest path
// - critical_path_cycle
BB_OP_MAP32_Set(earliest_time_table, op, earliest_start_time);
latency = cycled ? TI_LATENCY_Result_Available_Cycle(OP_code(op),0):1;
INT32 path_time = earliest_start_time + latency;
if (critical_path_cycle < path_time)
{
critical_path_cycle = path_time;
}
}
CG_DEP_Delete_Graph(bb);
return critical_path_cycle;
}
//*****************************************************************************
// Function : Find_Area
// Description :
// Find out the position of an given IF_CONV_AREA from an AREA_CONTAINER
//*****************************************************************************
AREA_CONTAINER::iterator
IF_CONVERTOR::Find_Area(AREA_CONTAINER& areas,
IF_CONV_AREA* area)
{
AREA_CONTAINER::iterator iter;
for (iter = areas.begin();
iter!= areas.end();
iter++)
{
if ( area == *iter)
{
return iter;
}
}
return iter;
}
inline
void
IF_CONVERTOR::Add_Edge(IF_CONV_AREA *area1, IF_CONV_AREA *area2)
{
area1 -> Add_Succ(area2, this);
area2 -> Add_Pred(area1, this);
}
BOOL
IF_CONVERTOR::Is_BB_Container_Member(BB_CONTAINER& bbs, BB* bb)
{
BB *block;
BB_CONTAINER::iterator iter;
for (iter = bbs.begin();
iter != bbs.end();
iter++)
{
block = *iter;
if (block == bb) return true;
}
return false;
}
//=============================================================================
// Part 3: functions for if-conversion
//=============================================================================
//*****************************************************************************
// Function : If_Conversion_Init
// Input :
// - region: a regino to be if-converted
// - area_list : it is the result of the function. In area_list, there
// are several IF_CONV_AREAs, which are the candidates to
// be if-converted. After this function, there is only one
// block in each IF_CONV_AREA. Some properties of those
// IF_CONV_AREAs are fingured out.
// Output:
// < none>
// Description :
// The module will do something to initialize the data structure for
// if-conversion. The main steps of the module are shown as follows:
// 1) Construct an IF_CONV_AREA for each basis block in the input
// region.
// 2) Check if it is legal to if-convert each bb.
// 3) Compute some properties for each IF_CONV_AREA, such as critical
// path length and resource usage. Th step 2) and 3) are
// implemented in the constructor of the class IF_CONV_AREA.
// 4) Sort all IF_CONV_AREAs according to the post-DFS order.
//
//*****************************************************************************
void
IF_CONVERTOR::If_Conversion_Init(REGION *region,
AREA_CONTAINER& area_list)
{
// create an IF_CONV_AREA for each basic block
// area_table is used to record the map between basic blocks
// and IF_CONV_AREAs
BB_MAP area_table = BB_MAP_Create();
for (TOPOLOGICAL_REGIONAL_CFG_ITER iter( region -> Regional_Cfg());
iter!=0;
++iter)
{
REGIONAL_CFG_NODE *node = *iter;
BB *pred_bb;
IF_CONV_AREA *pred_area;
if (node -> Is_Region())
{
// if one area has a region successor, we do not
// if-convert it
for (CFG_PRED_NODE_ITER pred_iter(node);
pred_iter!=0;
++pred_iter)
{
REGIONAL_CFG_NODE *pred = *pred_iter;
if (pred -> Is_Region()) continue;
pred_bb = pred -> BB_Node();
pred_area = (IF_CONV_AREA*)BB_MAP_Get(area_table, pred_bb);
Is_True(pred_area != NULL,
("Can't find corresponding area for BB%d.\n",
BB_id(pred_bb)));
pred_area -> Area_Type(DOWNWARD_UNSUITABLE);
}
continue;
}
BB *bb = node -> BB_Node();
IF_CONV_AREA *area;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile,
" -- solving BB%d: \n", BB_id(bb));
}
// we do not generate IF_CONV_AREA for recovery block .
// instead, we add those blocks in the IF_CONV_AREA of their
// predecessors
if ( BB_recovery(bb))
{
Is_True(node -> Pred_Num() == 1,
("the basic block can only have one predecessor"));
REGIONAL_CFG_NODE *pred = node -> First_Pred() -> Src();
if (!pred -> Is_Region())
{
area = (IF_CONV_AREA*)BB_MAP_Get(area_table,
pred -> BB_Node());
Is_True(pred_area != NULL,
("Can't find corresponding area for BB%d.\n",
BB_id(pred_bb)));
area -> Blocks().push_back(bb);
BB_MAP_Set(area_table, bb, area);
continue;
}
}
// create an IF_CONV_AREA for the bb and add it into area_list
area = CXX_NEW(IF_CONV_AREA(bb, this), &_m);
area_list.push_back(area);
//record the relation of bb and area into area_table;
BB_MAP_Set(area_table, bb, area);
// add edge between IF_CONV_AREAs
for (CFG_PRED_NODE_ITER pred_iter(node);
pred_iter!=0;
++pred_iter)
{
REGIONAL_CFG_NODE *pred = *pred_iter;
if ( pred -> Is_Region())
{
area -> Area_Type(UPWARD_UNSUITABLE);
continue;
}
pred_bb = pred -> BB_Node();
pred_area = (IF_CONV_AREA*)BB_MAP_Get( area_table, pred_bb);
Is_True(pred_area != NULL,
("Can't find corresponding area for BB%d.\n",
BB_id(pred_bb)));
Add_Edge( pred_area,area );
}
if ( node -> Is_Exit())
{
area -> Area_Type(DOWNWARD_UNSUITABLE);
}
}
BB_MAP_Delete(area_table);
}
//*****************************************************************************
// Function : Detect_Type
// Input :
// - area : the head area
// - cand_list : a container of IF_CONV_AREAs. In fact, it is a part of the
// result. If the control flow pattern of the head area
// and its successors are suitable to be if-converted, the
// function will return the proper type of it, and add
// related IF_CONV_AREAs into cand_list.
// Here, for each CFLOW_TYPE, the order of areas in
// cand_list is fixed. It is:
// SERIAL_TYPE: area1 -- area;
// IF_THEN_TYPE: head -- then -- tail
// IF_THEN_ELSE_TYPE: head - then - else - tail
// or head - else - then - tail
// - forced : default is FALSE
// If TRUE a more aggresive pattern matching is used.
// This should be only used during forced/relaxed if conversion
// Output :
// the type of the control flow pattern of the head area and its successors
// Description :
// The function will look for the candidate areas, in which the control
// flow can be removed by if-converting them. Here, we only convert
// three kinds of control flow patterns. They are: serial type, if-then
// type, and if-then-else. The detail of those types is shown in if-conv.h.
//
//*****************************************************************************
CFLOW_TYPE
IF_CONVERTOR::Detect_Type(IF_CONV_AREA* area,
AREA_CONTAINER& cand_list,
BOOL forced)
{
if (area -> Area_Type() == UNSUITABLE
|| area -> Area_Type() == DOWNWARD_UNSUITABLE)
return NO_TYPE;
AREA_CONTAINER succs = area -> Succ_Set();
AREA_CONTAINER::iterator iter;
// check all its successor IF_CONV_AREAs
for ( iter = succs.begin();
iter != succs.end();
iter++)
{
IF_CONV_AREA *succ = *iter;
if (succ -> Area_Type() == UNSUITABLE
|| succ -> Area_Type() == UPWARD_UNSUITABLE)
return NO_TYPE;
}
// decide if it belongs to SERIAL_TYPE
if (area -> Succ_Num() == 1 )
{
IF_CONV_AREA *succ = *(succs.begin());
if (succ -> Pred_Num() == 1)
{
cand_list.push_back(area);
cand_list.push_back(succ);
return SERIAL_TYPE;
}
}
if ( area -> Succ_Num() == 2 )
{
IF_CONV_AREA *succ1, *succ2;
iter = succs.begin();
succ1 = *iter;
iter ++;
succ2 = *iter;
// decide if it is IF_THEN_TYPE
if (succ1 -> Pred_Num() == 1
&& Find_Area( succ1 -> Succ_Set(), succ2) != succ1->Succ_Set().end())
{
cand_list.push_back(area);
cand_list.push_back(succ1);
cand_list.push_back(succ2);
return IF_THEN_TYPE;
}
if (succ2 -> Pred_Num() == 1
&& Find_Area( succ2 -> Succ_Set(), succ1) != succ2->Succ_Set().end())
{
cand_list.push_back(area);
cand_list.push_back(succ2);
cand_list.push_back(succ1);
return IF_THEN_TYPE;
}
// decide if it is IF_THEN_ELSE_TYPE
if ( succ1 -> Pred_Num() == 1
&& succ2 -> Pred_Num() == 1)
{
IF_CONV_AREA* common_succ = NULL;
for ( iter = succ1 -> Succ_Set().begin();
iter != succ1 -> Succ_Set().end();
iter++)
{
IF_CONV_AREA* succ_of_succ1 = *iter;
if ( Find_Area( succ2 -> Succ_Set(), succ_of_succ1)
!= succ2 -> Succ_Set().end())
{
common_succ = succ_of_succ1;
break;
}
}
if ( common_succ)
{
cand_list.push_back(area);
cand_list.push_back(succ2);
cand_list.push_back(succ1);
cand_list.push_back(common_succ);
return IF_THEN_ELSE_TYPE;
}
}
}
if (forced && area -> Succ_Num() == 3) {
IF_CONV_AREA *area1, *area2, *area3;
IF_CONV_AREA *succ1, *succ2, *common_succ;
iter = succs.begin();
area1 = *iter;
iter++;
area2 = *iter;
iter++;
area3 = *iter;
if ( area1->Pred_Num() >= 3
&& area2->Pred_Num() == 1
&& area3->Pred_Num() == 1)
{
// area1 might be common successor
common_succ = area1;
succ1 = area2;
succ2 = area3;
}
else if ( area1->Pred_Num() == 1
&& area2->Pred_Num() >= 3
&& area3->Pred_Num() == 1)
{
// area2 might be common successor
common_succ = area2;
succ1 = area1;
succ2 = area3;
}
else if ( area1->Pred_Num() == 1
&& area2->Pred_Num() == 1
&& area3->Pred_Num() >= 3)
{
// area3 might be common successor
common_succ = area3;
succ1 = area1;
succ2 = area2;
}
else {
return NO_TYPE;
}
if (Find_Area (succ1->Succ_Set(), common_succ)
== succ1->Succ_Set().end())
{
return NO_TYPE;
}
if (Find_Area (succ2->Succ_Set(), common_succ)
== succ2->Succ_Set().end())
{
return NO_TYPE;
}
cand_list.push_back(area);
cand_list.push_back(succ1);
cand_list.push_back(succ2);
cand_list.push_back(common_succ);
return IF_THEN_ELSE_TYPE;
}
return NO_TYPE;
}
//*****************************************************************************
// Function : Worth_If_Convert
// Input :
// - cand_list : a list of candidate areas, which are candidates to be
// reduced to one bigger area if they can pass the
// test of this function
// - type : the type of the comming bigger area
// Output :
// a boolean value which indicates if the candidates have pass the test
// Description :
// The function will decide whether the recognized area is worth being
// if-converted. The criteria used here are mainly about: the length of
// critical path, the resource usage, the miss rate of branch predict,
// the miss-penalty of branch predict, the number of instructions.
//*****************************************************************************
BOOL
IF_CONVERTOR::Worth_If_Convert (AREA_CONTAINER& cand_list,
CFLOW_TYPE type,
BOOL forced)
{
if ( Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " \nConsider profitablity:");
}
// take out the head area and its successors
AREA_CONTAINER::iterator iter = cand_list.begin();
IF_CONV_AREA *head = *iter;
Is_True(head != NULL, (" All if-conv types have a head-BB.\n "));
iter++;
IF_CONV_AREA *succ1 = *iter;
IF_CONV_AREA *succ2 = NULL;
Is_True(succ1 != NULL,
(" All if-conv types have at least one successor.\n "));
if ( type == IF_THEN_ELSE_TYPE )
{
iter++;
succ2 = *iter;
}
// evaluate the execution time for unpredicated code
// here, we assume the latency of a call instruction is a big value
INT32 time = 0;
float exe_time = 0.0;
INT32 min_cycle_1 = 0;
Compute_Min_Cycle(min_cycle_1, succ1 -> Blocks());
INT32 min_cycle_2 = 0;
if ( succ2 )
Compute_Min_Cycle(min_cycle_2, succ2 -> Blocks());
if (succ1 -> Cycled_Critical_Len() > min_cycle_1)
{
time = succ1 -> Cycled_Critical_Len();
} else {
time = min_cycle_1;
}
float taken_rate_1 = Prob_Of_Area(head, succ1);
float taken_rate_2 = 1 - taken_rate_1;
exe_time += taken_rate_1 * time;
if (succ2)
{
if (succ2 -> Cycled_Critical_Len() > min_cycle_2)
{
time = succ2 -> Cycled_Critical_Len();
} else {
time = min_cycle_2;
}
exe_time += taken_rate_2 * time;
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " \n Prob : Area_%d ==> Area_%d: %f\n",
head -> Area_Label(),
succ1 -> Area_Label(),
taken_rate_1);
if ( succ2 )
{
fprintf(TFile, " Prob : Area_%d ==> Area_%d: %f\n",
head -> Area_Label(),
succ2 -> Area_Label(),
taken_rate_2);
}
fprintf(TFile, " min_cycle_1 : %d, min_cycle_2 : %d \n",
min_cycle_1, min_cycle_2);
fprintf(TFile, " critical_cycle_1 : %d ",
succ1 -> Cycled_Critical_Len());
if ( succ2 )
{
fprintf(TFile, ", critical_cycle_2 : %d \n",
succ2 -> Cycled_Critical_Len());
} else {
fprintf(TFile, "\n");
}
}
float branch_predict_miss_rate;
if ( taken_rate_1 > taken_rate_2)
{
branch_predict_miss_rate = taken_rate_2;
} else {
branch_predict_miss_rate = taken_rate_1;
}
INT32 branch_predict_miss_panelty, fixed, brtaken;
double factor;
CGTARG_Compute_Branch_Parameters(&branch_predict_miss_panelty,
&fixed, &brtaken, &factor);
float unpredicated_time;
unpredicated_time = exe_time +
branch_predict_miss_rate * branch_predict_miss_panelty;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile,
" unpredicated %f cycles vs", unpredicated_time);
}
// evaluate the execution time for predicated code
INT32 max_res_height = 0;
exe_time= 0.0;
if ( succ2 )
{
// compute execution time
if (succ1 -> Cycled_Critical_Len() > succ2 -> Critical_Len())
{
time = succ1 -> Cycled_Critical_Len();
} else {
time = succ2 -> Critical_Len();
}
exe_time += taken_rate_1* time;
if (succ2 -> Cycled_Critical_Len() > succ1 -> Critical_Len())
{
time = succ2 -> Cycled_Critical_Len();
} else {
time = succ1 -> Critical_Len();
}
exe_time += taken_rate_2* time;
// compute the minimal cycle only considering the resource usage
Compute_Min_Cycle(max_res_height, succ1 -> Blocks());
Compute_Min_Cycle(max_res_height, succ2 -> Blocks());
} else {
exe_time += succ1 -> Cycled_Critical_Len();
Compute_Min_Cycle(max_res_height, succ1 -> Blocks());
}
float predicated_time;
predicated_time = exe_time > max_res_height ? exe_time : max_res_height;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile,
" predicated %f cycles\n", predicated_time);
}
// decide if it is worth if-convertion
// here, if the execution time of predicated code is less then the
// execution time of unpredicated code, we think it should be if-converted
if (unpredicated_time > predicated_time) {
return TRUE;
}
else if (forced &&
((predicated_time*100) < (_loop_length*IF_CONV_BIASE_THRESHOLD)))
{
return TRUE;
}
else {
return FALSE;
}
}
//*****************************************************************************
// Function : Reduce_By_Type
// Input :
// -cand_list : a list of IF_CONV_AREAs, which are going to be reduced in
// one IF_CONV_AREA. And such a IF_CONV_AREA is a candidate
// area for if-conversion.
// -type : the type of the result IF_CONV_AREA.
// -area_list: the total IF_CONV_AREA list of the present region.
// Output :
// <none>
// Description :
// The function will reduce the selected areas into one IF_CONV_AREA.
// It mainly consists of three steps:
// 1) add all blocks in cand_list into the first area;
// 2) delete all areas except the first area from the area list;
// 3) maintain the predecessor and successor of the first area;
// 4) maintain the related properties of the first area,
// such as critical_path_length;
//
//*****************************************************************************
void
IF_CONVERTOR::Reduce_By_Type(AREA_CONTAINER& cand_list,
CFLOW_TYPE type,
AREA_CONTAINER& area_list)
{
AREA_CONTAINER::iterator iter= cand_list.begin();
IF_CONV_AREA *head = *iter;
Is_True(head != NULL,
(" All if-conv types have head-BB.\n "));
iter++;
INT32 max_length1 = 0;
INT32 max_length2 = 0;
IF_CONV_AREA *succ1 = NULL;
IF_CONV_AREA *succ2 = NULL;
IF_CONV_AREA *tail = NULL;
succ1 = *iter;
iter++;
Is_True(succ1 != NULL,
(" All if-conv types have at least one successor.\n "));
if (type == IF_THEN_ELSE_TYPE)
{
succ2 = *iter;
iter++;
Is_True(succ2 != NULL,
(" IF_THEN_ELSE_TYPE have at least two successor.\n "));
}
if (iter != cand_list.end())
{
tail = *iter;
}
// maintain the if-conversion type
if (type == SERIAL_TYPE)
{
if (head -> Conv_Type() == FULLY_IF_CONV
|| succ1 -> Conv_Type() == FULLY_IF_CONV)
{
head -> Conv_Type(FULLY_IF_CONV);
}
} else {
head -> Conv_Type(FULLY_IF_CONV);
}
if ( succ1 -> Area_Type() == DOWNWARD_UNSUITABLE
|| ( succ2 && succ2 -> Area_Type() == DOWNWARD_UNSUITABLE))
{
if ( head -> Area_Type() == UPWARD_UNSUITABLE)
{
head -> Area_Type(UNSUITABLE);
} else {
head -> Area_Type(DOWNWARD_UNSUITABLE);
}
}
// combine the included blocks into head
head -> Combine_Blocks_With(succ1, &_m);
if ( type == IF_THEN_ELSE_TYPE )
{
head -> Combine_Blocks_With(succ2, &_m);
}
// maintain the edges
AREA_CONTAINER successors = succ1 -> Succ_Set();
for (iter = successors.begin();
iter != successors.end();
iter++)
{
IF_CONV_AREA *succ_of_succ1 = *iter;
if (tail && succ_of_succ1 == tail) continue;
head -> Add_Succ(succ_of_succ1, this);
succ_of_succ1 -> Add_Pred(head, this);
succ_of_succ1 -> Del_Pred(succ1, this);
}
if (type == SERIAL_TYPE)
{
head -> Del_Succ(succ1, this);
}
if (type == IF_THEN_TYPE)
{
head -> Del_Succ(succ1, this);
tail -> Del_Pred(succ1, this);
}
if (type == IF_THEN_ELSE_TYPE)
{
AREA_CONTAINER successors = succ2 -> Succ_Set();
for (iter = successors.begin();
iter != successors.end();
iter++)
{
IF_CONV_AREA* succ_of_succ2 = *iter;
if (tail && succ_of_succ2 == tail)
continue;
head -> Add_Succ(succ_of_succ2, this);
succ_of_succ2 -> Add_Pred(head, this);
succ_of_succ2 -> Del_Pred(succ2, this);
}
head -> Del_Succ(succ1, this);
head -> Del_Succ(succ2, this);
head -> Add_Succ(tail, this);
tail -> Del_Pred(succ1, this);
tail -> Del_Pred(succ2, this);
tail -> Add_Pred(head, this);
}
// maintain some properties of head
if (type == IF_THEN_ELSE_TYPE)
{
max_length1 =
succ1 -> Cycled_Critical_Len() > succ2 -> Cycled_Critical_Len()?
succ1 -> Cycled_Critical_Len():succ2 -> Cycled_Critical_Len();
max_length2 =
succ1 -> Critical_Len() > succ2 -> Critical_Len()?
succ1 -> Critical_Len():succ2 -> Critical_Len();
} else {
max_length1 = succ1 -> Cycled_Critical_Len();
max_length2 = succ1 -> Critical_Len() ;
}
head -> Cycled_Critical_Len(head-> Cycled_Critical_Len() + max_length1);
head -> Critical_Len(head -> Critical_Len() + max_length2);
// delete unnecessary areas
area_list.erase(Find_Area(area_list, succ1));
CXX_DELETE(succ1, &_m);
if (type == IF_THEN_ELSE_TYPE)
{
area_list.erase( Find_Area(area_list, succ2));
CXX_DELETE(succ2, &_m);
}
}
//*****************************************************************************
// Function : Select_Candidates
// Input :
// - area_list : a list of IF_CONV_AREAs
// Output :
// <none>
// Description:
// The function is to find the candidates for if-conversion.
// Generally, the function will recognize the IF_CONV_AREAs which can not
// be if-converted and combine the IF_CONV_AREAs, which are suitable to be
// if converted, into larger ones. Before combination, we mainly do
// profitablity checking. The legality checking has been done in the
// process of initialization.
// Here, the partial if-conversion will be delayed to the second release.
// The function -- Worth_Partial_If_Convert will always return false.
//
//*****************************************************************************
void
IF_CONVERTOR::Select_Candidates (AREA_CONTAINER& area_list, BOOL forced)
{
IF_CONV_ALLOC temp_alloc(&_m);
AREA_CONTAINER cand_list(temp_alloc);
AREA_CONTAINER::iterator iter;
BOOL reduced = TRUE;
INT time = 0;
while (reduced)
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)){
fprintf(TFile," **** iteration %d ****\n", time);
}
reduced = FALSE;
for (iter = area_list.begin();
iter!= area_list.end();
iter++)
{
IF_CONV_AREA *area = *iter;
cand_list.clear();
if ( Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile,
" -- solving AREA%d: \n", area -> Area_Label());
}
// first, we try to find out an if-conversion area, whose head is
// the head of area, according to the control flow
CFLOW_TYPE type = Detect_Type (area, cand_list, forced);
if (type == NO_TYPE) continue;
if ( Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " Selected areas:");
AREA_CONTAINER::iterator it;
for (it = cand_list.begin();
it != cand_list.end();
it++)
{
fprintf(TFile, "%d ", (*it)->Area_Label());
}
fprintf(TFile,"\n");
}
// profitability checking
if (type == SERIAL_TYPE ||
Worth_If_Convert (cand_list, type, forced))
{
reduced = TRUE;
}
else {
continue;
}
Reduce_By_Type(cand_list, type, area_list);
}
time++;
}
}
//*****************************************************************************
// Function : Find_Start_Node
// Input :
// - area : a candidate IF_CONV_AREA
// - bb : the bb for which we will find starting node
// Output :
// <none>
// Description :
// To find starting-nodes for a bb.
//
// Here, If we decide to generate parallel compare for one node, the
// 'starting nodes' of it are the earliest nodes with which we can start to
// generate parallel compare.
// For example:
// 1
// / \
// 2
// / \
// 3
// / \
// 4
// if we decide to generate parallel compare for BB_4. The control condition
// of it can be (cond_2 && cond3) or (cond1 && cond2 && cond3) <cond_x mean
// the compare condition of BB_x>. Here, if we take (cond2 && cond3), we call
// start node of BB_4 is BB_2 and if we take (cond1 && cond2 && cond3), we
// call BB_1 the start_node.
//
// For multiple cntl-dep-parent node, we will look for multiple start-nodes
// for it corresponds to its all cntl-dep-parent.
//
// If there is no obstacle in BB2 and BB3 to block us to move generated
// parallel compare instruction up to BB1, we can move them to the start node
// and all generated parallel compare instruction can be guarded by the
// predicates of starting nodes. In such conditions, we call BB2 and BB3
// is transitional. That is :
// 'transitional' means a bb will not block generated parallel compare in the
// BB to be moved up.
//*****************************************************************************
void
IF_CONVERTOR::Find_Start_Node(IF_CONV_AREA* area,
BB* bb)
{
BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb);
Is_True( info != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb)));
CNTL_DEP *cntl_info = area -> Cntl_Dep_Info();
BB_SET *cds = cntl_info -> Cntl_Dep_Parents(bb);
// we do not generate parallel compare for the transitional node whose
// compare instruction will be deleted. Because that means there will
// be no instruction to be guarded by the qualifying predicates of it.
if (!IPFEC_Force_Para_Comp_Gen)
{
if (info -> Transitional() && BB_SET_Size(cds) == 1)
{
return;
}
}
BB *cd;
//look for the starting nodes from bottom to up
FOR_ALL_BB_SET_members(cds, cd)
{
BB *sn = cd;
if (!IPFEC_Force_Para_Comp_Gen && info -> Transitional())
{
// as above, for transitional node, we do not want to generate
// parallel compare for it. But for or-type node, we must
// generate parallel compare, so here, we just set the immediate
// cntl_dep_parents as its starting node.
info -> Start_Node(sn, cd);
continue;
}
INT n = 0;
while (n < MAX_NUM_PARA_CMP)
{
BB_PREDICATE_INFO *f = area -> Pred_Assign_Info(sn);
Is_True( f != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(sn)));
// a un-transitional node can stop us to go further to
// look for the starting node
if (!f -> Transitional()) break;
// the following conditions are to keep us from introducing
// too complicated conditions for parallel compare candidates
BB_SET *cds_of_sn = cntl_info -> Cntl_Dep_Parents(sn);
Is_True( cds_of_sn != NULL,
("Can't find cntl deps for BB%d.\n", BB_id(sn)));
// a multiple-cntl-dep-parent node can stop us to go further
// to look for the starting node
if (BB_SET_Size(cds_of_sn) != 1) break;
// when the present sn is not cntl-dep-parent of bb, the sn
// will stop us go further
// for example :
// 1
// / \
// 2
// / \
// 3
// / \
// / 4
// \ / \
// 5
// when we look for the starting node for 5, if we find 3 is
// start-node. the condition of 5 is cond3 || cond4. Then, we can
// generate parallel compare for it. But, if we find that 2 is
// the start-node corresponding to 3, the condition is
// ( cond2 && cond3) || cond4
// the condition is too complex to generate parallel compare.
if (BB_SET_Size(cds) > 1
&& !BB_SET_MemberP(cds, BB_SET_Choose(cds_of_sn)) )
break;
sn = BB_SET_Choose(cds_of_sn);
n ++;
}
info -> Start_Node(sn, cd);
}
}
BOOL
IF_CONVERTOR::Check_If_Gen_Useless_Predicate( BB_PREDICATE_INFO* info)
{
// check if there is any useful predicate generated here
if ( info -> True_TN() || info -> False_TN())
return false;
TN_CONTAINER set;
set = info -> Or_TNs();
if (!set.empty())
return false;
set = info -> And_TNs();
if (!set.empty())
return false;
set = info -> Orcm_TNs();
if (!set.empty())
return false;
set = info -> Andcm_TNs();
if (!set.empty())
return false;
return true;
}
//*****************************************************************************
// Function : Record_Para_Comp_Info
// Input :
// - area : the candidate IF_CONV_AREA
// - bb : the basic block to be solved
// Output :
// <none>
// Description :
// The following function will record some information for the predicate
// of the basic block. The information includes: in a basic block, how many
// predicate assignment instructions should be inserted into, what the type
// they are, what are their target predicates and so on.
//*****************************************************************************
void
IF_CONVERTOR::Record_Para_Comp_Info(IF_CONV_AREA *area,
BB *bb)
{
CNTL_DEP *cntl_info = area -> Cntl_Dep_Info();
BB_PREDICATE_INFO *pred_info = area -> Pred_Assign_Info(bb);
Is_True(pred_info != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb)));
TN *p = pred_info -> Predicate();
BB *entry = area -> Entry_BB();
BB_SET *cds = cntl_info -> Cntl_Dep_Parents(bb);
BB_SET *true_edges = cntl_info -> True_Cntl_Dep_Parents(bb);
// solve the non-parallel-compare-candidates
if (!pred_info -> Has_Start_Node())
{
Is_True(BB_SET_Size(cds) <=1,("non-parallel-comparea-candidate "
"can only has one control dependentor!\n"));
if (BB_SET_Size(cds) == 0) return;
TN *true_tn = NULL;
TN *false_tn = NULL;
BB *bb_cd = BB_SET_Choose(cds);
BB_PREDICATE_INFO *pred_info_of_cd = area -> Pred_Assign_Info(bb_cd);
Is_True(pred_info != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb_cd)));
if (BB_SET_MemberP(true_edges, bb_cd))
{
pred_info_of_cd -> True_TN(p);
} else {
pred_info_of_cd -> False_TN(p);
}
return;
}
if (Get_Trace(TP_PTRACE1, TP_PTRACE1_CG))
{
char tmp_string[6]="";
sprintf(tmp_string, "%d", BB_id(bb));
Generate_Tlog("AIC", "parallel_compare_generation", (SRCPOS)0,
tmp_string, "", "", "");
}
//solve the parallel compare candidates
if ( BB_SET_Size(cds) > 1)
{
// for or/orcm type
// insert an initialization instruction for the or-type predicate
OPS ops = OPS_EMPTY;
Exp_Pred_Set(p, True_TN, 0, &ops);
hTN_MAP_Set(init_op_info, p, ops.first);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
Print_OPS(&ops);
}
// Insert the predicate initialization code just before the branch
// (if it exists) or append it to the Entry block.
OP *xfer_op;
if (xfer_op = BB_xfer_op(entry))
{
BB_Insert_Ops_Before (entry, xfer_op, &ops);
} else {
BB_Append_Ops (entry, &ops);
}
// record the information about the predicates assignments in the
// corresponding start node
BB *cd;
FOR_ALL_BB_SET_members(cds, cd)
{
BB_PREDICATE_INFO* info_of_cd = area -> Pred_Assign_Info(cd);
Is_True(info_of_cd != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(cd)));
if (BB_SET_MemberP(true_edges, cd))
{
info_of_cd -> Add_Or_TNs(p);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile, "add or %s ", p);
fprintf(TFile,
" into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb));
}
} else {
info_of_cd -> Add_Orcm_TNs(p);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile, "add orcm %s ", p);
fprintf(TFile,
" into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb));
}
}
}
} else {
Is_True( BB_SET_Size(cds) == 1,
(" and-type node can only have one cd.\n"));
// for and/andcm type
// assign a new predicate for the and/andcm-type candidate
p = Gen_Predicate_TN();
pred_info -> Orig_Pred(pred_info -> Predicate());
pred_info -> Predicate(p);
BB *cd = BB_SET_Choose(cds);
// insert an initialization instruction for the or-type predicate
OPS ops = OPS_EMPTY;
Exp_Pred_Set(p, True_TN, 1, &ops);
hTN_MAP_Set(init_op_info, p, ops.first);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
Print_OPS(&ops);
}
BB* start_node = pred_info -> Start_Node(cd);
OP *xfer_op;
if (xfer_op = BB_xfer_op(start_node))
{
BB_Insert_Ops_Before (start_node, xfer_op, &ops);
} else {
BB_Append_Ops (start_node, &ops);
}
BB *sn = pred_info -> Start_Node(cd);
BB_PREDICATE_INFO *info_of_cd;
Is_True(info_of_cd != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(cd)));
BOOL is_start = false;
while (!is_start)
{
is_start = (cd == sn);
info_of_cd = area -> Pred_Assign_Info(cd);
if (BB_SET_MemberP(true_edges, cd))
{
info_of_cd -> Add_And_TNs(p);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile, "add and %s ", p);
fprintf(TFile,
" into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb));
}
} else {
info_of_cd -> Add_Andcm_TNs(p);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile, "add andcm %s ", p);
fprintf(TFile,
" into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb));
}
}
true_edges = cntl_info -> True_Cntl_Dep_Parents(cd);
cds = cntl_info -> Cntl_Dep_Parents(cd);
cd = BB_SET_Choose(cds);
}
}
}
//*****************************************************************************
// Function : Detect_Para_Comp
// Input :
// - area : a candidate IF_CONV_AREA
// Output :
// <none>
// Description :
// In the following two cases, we need to generate parallel compare:
// 1) when a basic block has multiple parents in the control dependent tree,
// we need to generate parallel compare for the basic block. In the case,
// the condition to invoke the basic block is the result of or-operation
// of all conditions of its control-dependence parents. So, we must
// generate parallel compare to predicate the block.
// 2) generating parallel compare can shorten the dependent height of a
// serial of compares. In the case, we generate parallel compare for
// optimizing code.
// The function is used to select the chance to generate parallel compare.
// 'Parallel compare candidates' indicate those basic blocks, whose
// qualifying predicate of which we decide to generate parallel compare.
// Besides, we call the instructions to assign to the predicate as related
// predicated assignments.
//
// In detail, the function will
// 1) select the parallel compare candidates;
// 2) compute the starting node for each parallel compare candidates.
// As a result, the starting node is saved in one member of
// BB_PREDICATE_INFO -- start_nodes. If its start_nodes is NULL, we will
// not generate parallel compare for the predicate of the node.
// Start_nodes is a BB_MAP. In the BB_MAP, we record the starting node
// for each control dependencer of the basic block.
// The conception of 'starting-node' is in the description of function
// 'Find_Start_Node'.
//
//*****************************************************************************
void
IF_CONVERTOR::Detect_Para_Comp(IF_CONV_AREA* area)
{
BB_CONTAINER& bbs = area -> Blocks();
CNTL_DEP *cntl_info = area -> Cntl_Dep_Info();
//
// step1: mark transitional nodes
//
// Here, we should generate parallel compare only when
// the action can lead performance improvement. So we need a cost model
// to select parallel compare candidates. In the first release, the cost
// model will be very simple. If there is not a downward-exposed definition
// in one basic block, we remark it and call it as a transitional node.
// That means, there is no obstacle for us to move the related predicate
// assignments up to the control dependent parent of it. If several
// predicate assignments can be moved to one place, they can run in
// one cycle and the performance will be better.
//
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " Start to decide transitional!\n");
}
BB_CONTAINER::iterator bb_iter;
BB *bb;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " -- solving BB%d:", BB_id(bb));
}
if (BB_recovery(bb)) continue;
OP *br_op = BB_branch_op(bb);
OP *cmp_op = NULL;
if (br_op && OP_has_predicate(br_op))
{
TN *pred_tn = OP_opnd(br_op, OP_PREDICATE_OPND);
vector<OP *> ops;
cmp_op = TN_Defined_At_Op(pred_tn, br_op, &ops);
}
OP *op;
BOOL is_transitional = TRUE;
BB_SET* cd_children = BB_SET_Create_Empty(PU_BB_Count, &_m);
cntl_info -> Cntl_Dep_Children(cd_children, bb, &_m);
if (BB_SET_Size(cntl_info -> Cntl_Dep_Parents(bb)) ==0
|| BB_SET_Size(cd_children) == 0)
{
is_transitional = FALSE;
} else if ( cmp_op && !Has_Para_Comp_Top(cmp_op)) {
is_transitional =FALSE;
} else {
if ( !br_op || !cmp_op ) {
is_transitional = FALSE;
} else {
FOR_ALL_BB_OPs_FWD(bb, op)
{
if ( op != br_op && op != cmp_op ) {
is_transitional = FALSE;
break;
}
}
}
}
if (IPFEC_Force_Para_Comp_Gen ||
(is_transitional && IPFEC_Para_Comp_Gen))
{
BB_PREDICATE_INFO *pred_info = area -> Pred_Assign_Info(bb);
Is_True(pred_info != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb)));
pred_info -> Set_Transitional();
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " transitional \n");
}
} else {
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " not transitional \n");
}
}
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile,
" Start to find starting node and collect info of pred! \n");
}
//step2: compute starting-nodes and collect information of predicates
BB_CONTAINER result;
cntl_info -> Get_Post_Order(result, this);
for (bb_iter = result.begin();
bb_iter != result.end();
bb_iter++)
{
bb = *bb_iter;
BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb);
Is_True(info != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb)));
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " -- solving BB%d:\n", BB_id(bb));
}
// we will ignore the recovery nodes during predicating
if ( BB_recovery(bb)) continue;
if (!info -> Eqv_Class_Head())
{
BB_PREDICATE_INFO *head_info =
area -> Pred_Assign_Info(info -> Eqv_Class_Head_BB());
info -> Orig_Pred( info -> Predicate() );
info -> Predicate(head_info -> Predicate());
continue;
}
// compute starting-nodes for parallel compare candidates
BB_SET* cds = cntl_info -> Cntl_Dep_Parents(bb);
Is_True( cds != NULL,
("Can't find cntl deps for BB%d.\n", BB_id(bb)));
BOOL cd_is_transitional = false;
if (BB_SET_Size(cds) == 1)
{
BB* cd = BB_SET_Choose(cds);
BB_PREDICATE_INFO *info_of_cd = area -> Pred_Assign_Info(cd);
cd_is_transitional = info_of_cd -> Transitional();
}
if ( BB_SET_Size(cds) >1 || cd_is_transitional)
Find_Start_Node(area,bb);
// collect the information of all predicates and their related
// assignments
Record_Para_Comp_Info(area, bb);
}
}
//*****************************************************************************
// Function : Gen_Para_Comp
// Input :
// - area : the candidate IF_CONV_AREA
// Output :
// <none>
// Description :
// In this function, we will generate the parallel compare for each basic
// block. Here, we will try to generate the instructions as few as possible.
// For example, we have an 'or' TN -- p and an 'andcm' TN - q, we will
// generate 'p,q = cmp. or. andcm cond (qp)' instead of
// 'p = cmp.or cond (qp) ; q = cmp.andcm cond (qp)'.
// Even though, after this phase, some useless predicate assignments will
// appear. In the first release, we depend on the dead-code- elimination
// to eliminate those assignments.
//*****************************************************************************
void
IF_CONVERTOR::Gen_Para_Comp (IF_CONV_AREA *area)
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
area -> Print(TFile);
}
BB_CONTAINER& bbs = area -> Blocks();
BB_CONTAINER::iterator bb_iter;
BB *bb;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " -- solving BB%d:\n", BB_id(bb));
}
BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb);
Is_True( info != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb)));
if (BB_recovery(bb)) continue;
// in the following steps, we try to combine the predicate assignments
// which fit the following conditions:
// 1) their qualifying predicates are identical; Here, the compare
// instructions to be inserted into one basic block will use the
// qualifying predicate of the basic block. So their guarding
// predicates are surely identical.
// 2) their types are compatible;
// here the compatible types are:
// and/and, or/or, andcm/andcm, orcm/orcm/, or/andcm, and/orcm
//
OPS op_list = OPS_EMPTY;
if (Check_If_Gen_Useless_Predicate(info)) continue;
OP *br_op = BB_branch_op(bb);
OP *cmp_op = NULL;
if (br_op && OP_has_predicate(br_op))
{
TN *pred_tn = OP_opnd(br_op, OP_PREDICATE_OPND);
vector<OP *> ops;
cmp_op = TN_Defined_At_Op(pred_tn, br_op, &ops);
}
//
// For example, if there is a compare instruction in the bb, such as:
// p, q = cmp_type, a>b (qp)
// now, we want to add assignment for two predicates: p1, q2, and they
// are or-type and they have the same quaulifing predicate
// -- qp_of_start. now , we have two approaches:
// Approach1: p, q = cmp_type a>b (qp)
// p1, q2 = cmp_or 0!=0 (p)
// Approach2: p , q = cmp_type a>b (qp)
// p1, q1 = cmp_or a>b (qp_of_start)
// here, we adopt approach2 if it is legal.
//
TN *p1, *p2, *start_qp;
TOP pred_top;
TN *qp;
COMPARE_TYPE type;
while (Get_2_Pred_And_Erase(p1, p2, type, bb, info))
{
TN *qp1 = Get_Start_Node_Pred(p1, bb, area);
TN* qp2 = NULL;
if (p2 != True_TN)
{
qp2 = Get_Start_Node_Pred(p2, bb, area);
}
if (p2 == True_TN || qp1 == qp2)
{
pred_top = Get_Para_Comp_Top(cmp_op, type);
qp = qp1;
} else {
pred_top = TOP_UNDEFINED;
}
if (pred_top == TOP_UNDEFINED)
{
TN *true_tn = NULL;
TN *false_tn = NULL;
Find_BB_Predicates(bb, true_tn, false_tn);
if (type == COMPARE_TYPE_or
|| type == COMPARE_TYPE_andcm
|| type == COMPARE_TYPE_or_andcm)
{
qp = true_tn ? true_tn : True_TN;
} else if (type == COMPARE_TYPE_orcm
|| type == COMPARE_TYPE_and
|| type == COMPARE_TYPE_and_orcm)
{
qp = false_tn ? false_tn: True_TN;
} else {
Is_True(0, ("wrong compare type!\n"));
}
}
Gen_Predicate_Assign(p1,p2, cmp_op, type, pred_top, qp,
&op_list);
}
OP* new_op;
FOR_ALL_OPS_OPs_FWD((&op_list),new_op){
Set_OP_cond_def_kind(new_op, OP_ALWAYS_COND_DEF);
}
// Insert these just before the ending branch
if (OPS_first(&op_list))
{
Is_True(br_op,
("parallel compare can only added into split bb.\n"));
BB_Insert_Ops(bb, br_op, &op_list, true);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
Print_OPS(&op_list);
}
}
}
}
TOP
cmp_top_index[COMP_TOP_NUM] =
{ TOP_cmp_ne, TOP_cmp_ne_unc,
TOP_cmp4_ne, TOP_cmp4_ne_unc,
TOP_cmp_i_ne, TOP_cmp_i_ne_unc,
TOP_cmp4_i_ne, TOP_cmp4_i_ne_unc,
TOP_cmp4_ge, TOP_cmp4_ge_unc,
TOP_cmp4_gt, TOP_cmp4_gt_unc,
TOP_cmp4_le, TOP_cmp4_le_unc,
TOP_cmp4_lt, TOP_cmp4_lt_unc,
TOP_cmp_ge, TOP_cmp_ge_unc,
TOP_cmp_gt, TOP_cmp_gt_unc,
TOP_cmp_le, TOP_cmp_le_unc,
TOP_cmp_lt, TOP_cmp_lt_unc,
TOP_cmp4_i_eq, TOP_cmp4_i_eq_unc,
TOP_cmp4_eq, TOP_cmp4_eq_unc,
TOP_cmp_i_eq, TOP_cmp_i_eq_unc,
TOP_cmp_eq, TOP_cmp_eq_unc
};
TOP
para_comp_top[COMP_TOP_NUM][PARA_COMP_TYPE_NUM] = {
{ TOP_cmp_ne_or, TOP_cmp_ne_orcm , TOP_cmp_ne_and,
TOP_cmp_ne_andcm, TOP_cmp_ne_or_andcm, TOP_cmp_ne_and_orcm }, // cmp_ne
{ TOP_cmp_ne_or, TOP_cmp_ne_orcm , TOP_cmp_ne_and,
TOP_cmp_ne_andcm, TOP_cmp_ne_or_andcm, TOP_cmp_ne_and_orcm }, // cmp_ne_unc
{ TOP_cmp4_ne_or, TOP_cmp4_ne_orcm, TOP_cmp4_ne_and,
TOP_cmp4_ne_andcm, TOP_cmp4_ne_or_andcm, TOP_cmp4_ne_and_orcm }, // cmp4_ne
{ TOP_cmp4_ne_or, TOP_cmp4_ne_orcm, TOP_cmp4_ne_and,
TOP_cmp4_ne_andcm, TOP_cmp4_ne_or_andcm, TOP_cmp4_ne_and_orcm }, // cmp4_ne_unc
{ TOP_cmp_i_ne_or, TOP_cmp_i_ne_orcm, TOP_cmp_i_ne_and,
TOP_cmp_i_ne_andcm, TOP_cmp_i_ne_or_andcm, TOP_cmp_i_ne_and_orcm }, // cmp_i_ne
{ TOP_cmp_i_ne_or, TOP_cmp_i_ne_orcm, TOP_cmp_i_ne_and,
TOP_cmp_i_ne_andcm, TOP_cmp_i_ne_or_andcm, TOP_cmp_i_ne_and_orcm }, // cmp_i_ne_unc
{ TOP_cmp4_i_ne_or, TOP_cmp4_i_ne_orcm, TOP_cmp4_i_ne_and,
TOP_cmp4_i_ne_andcm, TOP_cmp4_i_ne_or_andcm, TOP_cmp4_i_ne_and_orcm }, //cmp4_i_ne:
{ TOP_cmp4_i_ne_or, TOP_cmp4_i_ne_orcm, TOP_cmp4_i_ne_and,
TOP_cmp4_i_ne_andcm, TOP_cmp4_i_ne_or_andcm, TOP_cmp4_i_ne_and_orcm }, //cmp4_i_ne_unc
{ TOP_cmp4_ge_or, TOP_cmp4_ge_orcm, TOP_cmp4_ge_and,
TOP_cmp4_ge_andcm, TOP_cmp4_ge_or_andcm, TOP_cmp4_ge_and_orcm }, //cmp4_ge
{ TOP_cmp4_ge_or, TOP_cmp4_ge_orcm, TOP_cmp4_ge_and,
TOP_cmp4_ge_andcm, TOP_cmp4_ge_or_andcm, TOP_cmp4_ge_and_orcm }, //cmp4_ge_unc
{ TOP_cmp4_gt_or, TOP_cmp4_gt_orcm, TOP_cmp4_gt_and,
TOP_cmp4_gt_andcm, TOP_cmp4_gt_or_andcm, TOP_cmp4_gt_and_orcm }, //cmp4_gt
{ TOP_cmp4_gt_or, TOP_cmp4_gt_orcm, TOP_cmp4_gt_and,
TOP_cmp4_gt_andcm, TOP_cmp4_gt_or_andcm, TOP_cmp4_gt_and_orcm }, //cmp4_gt_unc
{ TOP_cmp4_le_or, TOP_cmp4_le_orcm, TOP_cmp4_le_and,
TOP_cmp4_le_andcm, TOP_cmp4_le_or_andcm, TOP_cmp4_le_and_orcm }, //cmp4_le
{ TOP_cmp4_le_or, TOP_cmp4_le_orcm, TOP_cmp4_le_and,
TOP_cmp4_le_andcm, TOP_cmp4_le_or_andcm, TOP_cmp4_le_and_orcm }, //cmp4_le_unc
{ TOP_cmp4_lt_or, TOP_cmp4_lt_orcm, TOP_cmp4_lt_and,
TOP_cmp4_lt_andcm, TOP_cmp4_lt_or_andcm, TOP_cmp4_lt_and_orcm }, //cmp4_lt
{ TOP_cmp4_lt_or, TOP_cmp4_lt_orcm, TOP_cmp4_lt_and,
TOP_cmp4_lt_andcm, TOP_cmp4_lt_or_andcm, TOP_cmp4_lt_and_orcm }, //cmp4_lt_unc
{ TOP_cmp_ge_or, TOP_cmp_ge_orcm, TOP_cmp_ge_and,
TOP_cmp_ge_andcm, TOP_cmp_ge_or_andcm, TOP_cmp_ge_and_orcm }, //cmp_ge
{ TOP_cmp_ge_or, TOP_cmp_ge_orcm, TOP_cmp_ge_and,
TOP_cmp_ge_andcm, TOP_cmp_ge_or_andcm, TOP_cmp_ge_and_orcm }, //cmp_ge_unc
{ TOP_cmp_gt_or, TOP_cmp_gt_orcm, TOP_cmp_gt_and,
TOP_cmp_gt_andcm, TOP_cmp_gt_or_andcm, TOP_cmp_gt_and_orcm }, //cmp_gt
{ TOP_cmp_gt_or, TOP_cmp_gt_orcm, TOP_cmp_gt_and,
TOP_cmp_gt_andcm, TOP_cmp_gt_or_andcm, TOP_cmp_gt_and_orcm }, //cmp_gt_unc
{ TOP_cmp_le_or, TOP_cmp_le_orcm, TOP_cmp_le_and,
TOP_cmp_le_andcm, TOP_cmp_le_or_andcm, TOP_cmp_le_and_orcm }, //cmp_le
{ TOP_cmp_le_or, TOP_cmp_le_orcm, TOP_cmp_le_and,
TOP_cmp_le_andcm, TOP_cmp_le_or_andcm, TOP_cmp_le_and_orcm }, //cmp_le_unc
{ TOP_cmp_lt_or, TOP_cmp_lt_orcm, TOP_cmp_lt_and,
TOP_cmp_lt_andcm, TOP_cmp_lt_or_andcm, TOP_cmp_lt_and_orcm }, //cmp_lt:
{ TOP_cmp_lt_or, TOP_cmp_lt_orcm, TOP_cmp_lt_and,
TOP_cmp_lt_andcm, TOP_cmp_lt_or_andcm, TOP_cmp_lt_and_orcm }, //cmp_lt_unc
{ TOP_cmp4_i_eq_or, TOP_cmp4_i_eq_orcm, TOP_cmp4_i_eq_and,
TOP_cmp4_i_eq_andcm, TOP_cmp4_i_eq_or_andcm, TOP_cmp4_i_eq_and_orcm }, //cmp4_i_eq
{ TOP_cmp4_i_eq_or, TOP_cmp4_i_eq_orcm, TOP_cmp4_i_eq_and,
TOP_cmp4_i_eq_andcm, TOP_cmp4_i_eq_or_andcm, TOP_cmp4_i_eq_and_orcm }, //cmp4_i_eq_unc
{ TOP_cmp4_eq_or, TOP_cmp4_eq_orcm, TOP_cmp4_eq_and,
TOP_cmp4_eq_andcm, TOP_cmp4_eq_or_andcm, TOP_cmp4_eq_and_orcm }, //cmp4_eq
{ TOP_cmp4_eq_or, TOP_cmp4_eq_orcm, TOP_cmp4_eq_and,
TOP_cmp4_eq_andcm, TOP_cmp4_eq_or_andcm, TOP_cmp4_eq_and_orcm }, //cmp4_eq_unc
{ TOP_cmp_i_eq_or, TOP_cmp_i_eq_orcm, TOP_cmp_i_eq_and,
TOP_cmp_i_eq_andcm, TOP_cmp_i_eq_or_andcm, TOP_cmp_i_eq_and_orcm }, //cmp_i_eq:
{ TOP_cmp_i_eq_or, TOP_cmp_i_eq_orcm, TOP_cmp_i_eq_and,
TOP_cmp_i_eq_andcm, TOP_cmp_i_eq_or_andcm, TOP_cmp_i_eq_and_orcm }, //cmp_i_eq_unc:
{ TOP_cmp_eq_or, TOP_cmp_eq_orcm, TOP_cmp_eq_and,
TOP_cmp_eq_andcm, TOP_cmp_eq_or_andcm, TOP_cmp_eq_and_orcm }, //cmp_eq
{ TOP_cmp_eq_or, TOP_cmp_eq_orcm, TOP_cmp_eq_and,
TOP_cmp_eq_andcm, TOP_cmp_eq_or_andcm, TOP_cmp_eq_and_orcm } //cmp_eq_unc
};
BOOL
IF_CONVERTOR::Has_Para_Comp_Top(OP* cmp_op) {
if (OP_flop(cmp_op)) {
return false;
}
TOP cmp_top = OP_code(cmp_op);
if (OP_opnd(cmp_op, 1) != Zero_TN && OP_opnd(cmp_op, 2) != Zero_TN)
{
switch (cmp_top)
{
case TOP_cmp_ne:
case TOP_cmp4_ne:
case TOP_cmp_i_ne:
case TOP_cmp4_i_ne:
case TOP_cmp4_i_eq:
case TOP_cmp4_eq:
case TOP_cmp_i_eq:
case TOP_cmp_eq:
case TOP_cmp_ne_unc:
case TOP_cmp4_ne_unc:
case TOP_cmp_i_ne_unc:
case TOP_cmp4_i_ne_unc:
case TOP_cmp4_i_eq_unc:
case TOP_cmp4_eq_unc:
case TOP_cmp_i_eq_unc:
case TOP_cmp_eq_unc:
break;
default:
return false;
}
}
return false;
}
TOP
IF_CONVERTOR::Get_Para_Comp_Top(OP* cmp_op, COMPARE_TYPE ctype)
{
if ( !Has_Para_Comp_Top(cmp_op) )
return TOP_UNDEFINED;
TOP cmp_top = OP_code(cmp_op);
INT index = 0;
while (index < COMP_TOP_NUM)
{
if ( cmp_top == cmp_top_index[index])
break;
index++;
}
if (index >= COMP_TOP_NUM)
return TOP_UNDEFINED;
INT id = (int)ctype;
Is_True( id>=1 && id <= PARA_COMP_TYPE_NUM, ("no such a ctype!"));
return para_comp_top[index][id-1];
}
TN*
IF_CONVERTOR::Get_1_Pred_And_Erase(TN_CONTAINER& tn_set)
{
TN_CONTAINER::iterator iter;
TN *p1; iter = tn_set.begin();
p1 = *iter;
tn_set.erase(iter);
return p1;
}
BOOL
IF_CONVERTOR::Get_2_Pred_And_Erase(TN*& p1,
TN*& p2,
COMPARE_TYPE& type,
BB* bb,
BB_PREDICATE_INFO *info)
{
// solve 'and_tns' and 'orcm_tns'
TN_CONTAINER& tn_set1 = info -> And_TNs();
TN_CONTAINER& tn_set2 = info -> Orcm_TNs();
if (tn_set1.size() >=2)
{
p1 = Get_1_Pred_And_Erase(tn_set1);
p2 = Get_1_Pred_And_Erase(tn_set1);
type = COMPARE_TYPE_and;
return true;
}
if ( tn_set1.size())
{
p1 = Get_1_Pred_And_Erase(tn_set1);
if (tn_set2.size())
{
p2 = Get_1_Pred_And_Erase(tn_set2);
type = COMPARE_TYPE_and_orcm;
return true;
} else {
p2 = True_TN;
type = COMPARE_TYPE_and;
return true;
}
}
if (tn_set2.size() >=1)
{
p1 = Get_1_Pred_And_Erase(tn_set2);
if (tn_set2.size())
{
p2 = Get_1_Pred_And_Erase(tn_set2);
} else {
p2 = True_TN;
}
type = COMPARE_TYPE_orcm;
return true;
}
// solve 'or_tns' and 'andcm_tns'
TN_CONTAINER& tn_set3 = info -> Or_TNs();
TN_CONTAINER& tn_set4 = info -> Andcm_TNs();
if (tn_set3.size() >=2)
{
p1 = Get_1_Pred_And_Erase(tn_set3);
p2 = Get_1_Pred_And_Erase(tn_set3);
type = COMPARE_TYPE_or;
return true;
}
if ( tn_set3.size())
{
p1 = Get_1_Pred_And_Erase(tn_set3);
if (tn_set4.size())
{
p2 = Get_1_Pred_And_Erase(tn_set4);
type = COMPARE_TYPE_or_andcm;
return true;
} else {
p2 = True_TN;
type = COMPARE_TYPE_or;
return true;
}
}
if ( tn_set4.size() >=1)
{
p1 = Get_1_Pred_And_Erase(tn_set4);
if ( tn_set4.size())
{
p2 = Get_1_Pred_And_Erase(tn_set4);
} else {
p2 = True_TN;
}
type = COMPARE_TYPE_andcm;
return true;
}
return false;
}
TN*
IF_CONVERTOR:: Get_Start_Node_Pred(TN *pred,
BB *present_solving_bb,
IF_CONV_AREA *area)
{
BB *bb_of_pred;
BB_PREDICATE_INFO *info = NULL;
BB_CONTAINER& bbs = area -> Blocks();
BB_CONTAINER::iterator bb_iter;
BB *bb;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
info = area -> Pred_Assign_Info(bb);
if ( pred == info -> Predicate())
{
bb_of_pred = bb;
break;
}
}
Is_True( info, (" Generate useless predicate assignment.\n"));
TN *result = NULL;
CNTL_DEP *cd_info = area -> Cntl_Dep_Info();
BB_SET *cds = cd_info -> Cntl_Dep_Parents(bb_of_pred);
if (BB_SET_Size(cds) == 1)
{
BB* cd = BB_SET_Choose(cds);
BB* start_node = info -> Start_Node(cd);
result = area -> Pred_Assign_Info(start_node) -> Predicate();
} else {
Is_True(BB_SET_MemberP(cds, present_solving_bb),
("predicate assign holder must in cds"));
BB* start_node = info -> Start_Node(present_solving_bb);
result = area -> Pred_Assign_Info(start_node) -> Predicate();
}
if ( !result )
result = True_TN;
return result;
}
void
IF_CONVERTOR::Gen_Predicate_Assign(TN* result1,
TN *result2,
OP* cmp_op,
COMPARE_TYPE ctype,
TOP pred_top,
TN *qual_pred,
OPS* ops)
{
if ( pred_top != TOP_UNDEFINED) {
Build_OP(pred_top,
result1,
result2,
qual_pred,
OP_opnd(cmp_op, OP_PREDICATE_OPND+1),
OP_opnd(cmp_op, OP_PREDICATE_OPND+2),
ops);
} else {
TOP top;
switch (ctype) {
case COMPARE_TYPE_or:
top = TOP_cmp_eq_or;
break;
case COMPARE_TYPE_andcm:
top = TOP_cmp_eq_andcm;
break;
case COMPARE_TYPE_or_andcm:
top = TOP_cmp_eq_or_andcm;
break;
case COMPARE_TYPE_and:
top = TOP_cmp_ne_and;
break;
case COMPARE_TYPE_orcm:
top = TOP_cmp_ne_orcm;
break;
case COMPARE_TYPE_and_orcm:
top = TOP_cmp_ne_and_orcm;
break;
default:
Is_True(0,("Illegal Compare Type.\n"));
}
Build_OP(top, result1, result2, qual_pred, Zero_TN, Zero_TN,
ops);
}
}
TN*
Predicate_Of_Succ(BB *bb, BB * succ, BB *fall_thru, BB_PREDICATE_INFO *info) {
TN *pp = NULL;
if ( BB_succs_len(bb) == 1 ) {
pp = info -> Predicate();
}
else if (BB_succs_len(bb) == 2) {
TN *first_pred = NULL;
TN *second_pred = NULL;
Find_BB_Predicates(bb, first_pred, second_pred);
Is_True(first_pred && second_pred,
(" lack of a predicate!\n"));
OP *br = BB_branch_op(bb);
Is_True(br, (" two-successor bb must have br\n"));
if (( first_pred == OP_opnd(br, OP_PREDICATE_OPND)
&& succ != fall_thru)
|| ( second_pred == OP_opnd(br, OP_PREDICATE_OPND)
&& succ == fall_thru))
{
pp = first_pred;
}
else {
pp = second_pred;
}
}
return pp;
}
//*****************************************************************************
// Function : Insert_Predicate
// Input :
// - area : the candidate
// Output :
// < none >
// Description :
// change the selected candidates to predicated code
//*****************************************************************************
BOOL
IF_CONVERTOR::Insert_Predicate(IF_CONV_AREA *area)
{
//
// step1: compute the equivalence classes and assign predicates for each
// equivalent class
// here, we use a BB_SET to represent equivalence class
// each bb in it represents a class of bbs who have the same control
// dependence
//
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, "\n Start to assign predicates!\n");
}
// we record the found information into BB_PREDICATE_INFO of each
// bb
BB_SET *equal_classes = BB_SET_Create_Empty(PU_BB_Count, &_m);
CNTL_DEP *cd_info = area -> Cntl_Dep_Info();
BB_CONTAINER& bbs = area -> Blocks();
BB_CONTAINER::iterator bb_iter;
BB *bb;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " -- solving BB%d: ", BB_id(bb));
}
if ( BB_recovery(bb))
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " it is a recovery bb.\n");
}
continue;
}
BB_PREDICATE_INFO *pred_info = area ->Pred_Assign_Info(bb);
BB_SET *cds_of_bb = cd_info -> Cntl_Dep_Parents(bb);
BB_SET *te_of_bb = cd_info -> True_Cntl_Dep_Parents(bb);
//
// Find out the equivalence class for bb. If there is no existing
// equivalent class, create a new one and insert bb into it.
//
BOOL find_ec = false;
BB *ec;
FOR_ALL_BB_SET_members(equal_classes, ec)
{
BB_SET *cds_of_ec = cd_info -> Cntl_Dep_Parents(ec);
Is_True( cds_of_ec != NULL,
("Can't find cntl deps for BB%d.\n", BB_id(ec)));
BB_SET *te_of_ec = cd_info -> True_Cntl_Dep_Parents(ec);
Is_True( te_of_ec != NULL,
("Can't find true edges for BB%d.\n", BB_id(ec)));
if (BB_SET_EqualP(cds_of_bb, cds_of_ec)
&&BB_SET_EqualP(te_of_bb, te_of_ec))
{
BB_PREDICATE_INFO *pred_of_ec =
area ->Pred_Assign_Info (ec);
Is_True(pred_of_ec != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n",
BB_id(bb)));
pred_info -> Predicate(pred_of_ec -> Predicate());
pred_info -> Eqv_Class_Head_BB(ec);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile,
" got(share): %s", pred_of_ec -> Predicate());
}
find_ec = true;
break;
}
}
if (!find_ec)
{
equal_classes = BB_SET_Union1D(equal_classes, bb, &_m);
pred_info -> Set_Eqv_Class_Head();
// set predicate TN for them
INT num_deps = BB_SET_Size(cds_of_bb);
if (num_deps == 1)
{
// if bb has single dependence, set up the TRUE
// and FALSE tns for the block.
TN *true_tn = NULL;
TN *false_tn = NULL;
BB *bb_cd = BB_SET_Choose(cds_of_bb);
Find_BB_Predicates(bb_cd, true_tn, false_tn);
// set the predicate for the equivalance class
if (BB_SET_MemberP(te_of_bb, bb_cd))
{
pred_info ->Predicate(true_tn);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile, " got: %s\n", true_tn);
}
} else {
pred_info ->Predicate(false_tn);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile, " got: %s\n", false_tn);
}
}
} else if (num_deps > 1)
{
// multiple dependencies. create a new predicate TN for them
TN *pred_tn;
pred_tn = Gen_Predicate_TN();
pred_info -> Predicate(pred_tn);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fPrint_TN(TFile, " got: %s\n", pred_tn);
}
}
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n");
}
}
// the following is to collect information of exits, including:
// 1. how many exits in the area
// 2. how many branches in the area
// 3. the information of the targets of all exits
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
BB* fall_thru = BB_Fall_Thru_Successor(bb);
BBLIST *succ_bl;
FOR_ALL_BB_SUCCS(bb, succ_bl)
{
BB* succ = BBLIST_item(succ_bl);
if (!Is_BB_Container_Member(bbs, succ)
|| Regional_Cfg_Node(bb) -> First_Succ() == NULL)
{
// record its information
EXIT_TARGET_INFO *tgt = area -> Exit_Target(succ);
BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb);
TN *pp = Predicate_Of_Succ(bb, succ, fall_thru, info);
if ( tgt != NULL)
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " BB%d target: BB%d ",
BB_id(bb), BB_id(succ));
fPrint_TN(TFile, " %s => main \n", pp);
}
if ( IPFEC_Combine_Exit )
{
Is_True(tgt -> Main_Predicate().size() == 1,
("Wrong number of main predicate!\n"));
TN *old_main = *(tgt -> Main_Predicate().begin());
tgt -> Add_Aux_Predicate(old_main);
tgt -> Del_Main_Predicate(old_main);
}
tgt -> Add_Main_Predicate(pp);
} else {
area -> Add_Exit_Target(succ, pp, &_m);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " BB%d target(new): BB%d ",
BB_id(bb), BB_id(succ));
fPrint_TN(TFile, " %s => main \n", pp);
}
}
}
}
}
// check whether if-conversion can really reduce the number of
// branches.
// if exit_num <= inner_br_num , the answer is yes.
INT exit_num = 0;
INT inner_br_num = 0;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
BOOL all_targets_hidden = TRUE;
BOOL has_inner_succ = FALSE;
BB* fall_thru = BB_Fall_Thru_Successor(bb);
BBLIST *succ_bl;
FOR_ALL_BB_SUCCS(bb, succ_bl)
{
BB* succ = BBLIST_item(succ_bl);
if (!Is_BB_Container_Member(bbs, succ)
|| Regional_Cfg_Node(bb) -> First_Succ() == NULL)
{
// record its information
EXIT_TARGET_INFO *tgt = area -> Exit_Target(succ);
BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb);
TN *pp = Predicate_Of_Succ(bb, succ, fall_thru, info);
Is_True(tgt, ("exit must have exit info.!\n"));
if ( tgt -> Is_Main_Predicate(pp))
{
all_targets_hidden = FALSE;
}
} else {
has_inner_succ = TRUE;
}
}
if (! all_targets_hidden) exit_num ++;
if ( has_inner_succ && BB_succs_len(bb) > 1 )
{
inner_br_num++;
}
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n Area_%d: exit_num : %d vs. br_num : %d\n",
area -> Area_Label(), exit_num, inner_br_num);
}
if ( (exit_num > inner_br_num) && !IPFEC_Force_If_Conv) return FALSE;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, "\n Start to detect parallel compare!\n");
}
//step2: find candidates for parallel compares
Detect_Para_Comp(area);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, "\n Start to generate parallel compare!\n");
}
//step3: generate predicate assignment, including parallel compare
Gen_Para_Comp(area);
return TRUE;
}
//*****************************************************************************
// Function : Merge_area
// Input :
// - area : the candicate IF_CONV_AREA
// Output :
// <none>
// Description :
// The function is to delete unnecessary branches and merge
// the one-exit-one-entry block pair into one basic block.
//*****************************************************************************
void
IF_CONVERTOR::Merge_Area(IF_CONV_AREA *area)
{
BB_SET *hold_bbs = BB_SET_Create_Empty(PU_BB_Count, &_m);
BB_SET *area_bb_set = BB_SET_Create_Empty(PU_BB_Count, &_m);
//
// Next, we will do the following jobs:
// 1. delete all unnecessary branches
// 2. add some necessary goto
// 3. maintain the profiling information
// 4. predicate all blocks in the area
// 5. merge blocks
//
BB_CONTAINER& bbs = area -> Blocks();
BB_CONTAINER::iterator bb_iter;
BB *bb;
BB *last_bb = NULL;
INT exit_num = 0;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
area_bb_set = BB_SET_Union1D(area_bb_set, bb, &_m);
BBLIST *succ_bl;
FOR_ALL_BB_SUCCS(bb, succ_bl)
{
BB* succ = BBLIST_item(succ_bl);
if (!Is_BB_Container_Member(bbs, succ))
{
exit_num++;
break;
}
}
last_bb =bb;
}
INT last_bb_type = 0;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile," -- solving BB%d:\n", BB_id(bb));
}
if ( BB_recovery(bb))
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " (recovery bb)");
}
continue;
}
CNTL_DEP *cntl_info = area -> Cntl_Dep_Info();
BB_SET *set = cntl_info -> Cntl_Dep_Parents(bb);
Is_True( cntl_info != NULL,
("Can't find cntl_info for BB%d.\n", BB_id(bb)));
BB_PREDICATE_INFO *pred_info = area -> Pred_Assign_Info (bb);
Is_True( pred_info != NULL,
("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb)));
TN *pred = pred_info -> Predicate();
TN *orig_pred = pred_info -> Orig_Pred()?pred_info -> Orig_Pred():pred;
if (IPFEC_Disable_Merge_BB)
{
Predicate_Block(bb, pred, area_bb_set);
continue;
}
// record the frequency of bb in its corresponding predicate TN
if (pred)
{
float f = BB_freq(bb);
hTN_MAPf_Set(frequency_of_predicates, pred, f);
}
BB_MERGE_TYPE bb_type = Classify_BB(bb, area);
BBLIST *bl;
BB *pred_bb = NULL;
if (bb == area -> Entry_BB())
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " (entry) ");
}
} else {
BOOL has_recovery_pred = false;
BBLIST *pred_bl;
FOR_ALL_BB_PREDS(bb, pred_bl)
{
if (BB_recovery(BBLIST_item(pred_bl)))
{
has_recovery_pred = true;
break;
}
}
// get out its predeccessor
if ( !has_recovery_pred) {
Is_True(BB_preds_len(bb) == 1,
("one bb only has one predecessor during merging!\n"));
bl = BB_preds(bb);
pred_bb = BBLIST_item(bl);
} else {
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " => it is successor of recovery bb.\n");
}
}
}
// when a block is solved, it and its predecessor will become straight
// line code; but the other successors of its predecessor have
// not been solved, so record them in the set 'bb_to_solve'
BB_SET* bb_to_solve = BB_SET_Create_Empty(PU_BB_Count, &_m);
BB *succ_bb_of_pred;
if (pred_bb && BB_succs_len(pred_bb) > 1)
{
FOR_ALL_BB_SUCCS(pred_bb, bl)
{
succ_bb_of_pred = BBLIST_item(bl);
if (succ_bb_of_pred != bb )
{
if (Is_BB_Container_Member(bbs, succ_bb_of_pred))
{
bb_to_solve = BB_SET_Union1D(bb_to_solve,
succ_bb_of_pred, &_m);
}
}
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
BB* bb_tmp;
fprintf(TFile, " (pred_bb:%d) ", BB_id(pred_bb));
fprintf(TFile, " (bb_to_solve:");
FOR_ALL_BB_SET_members(bb_to_solve, bb_tmp)
{
fprintf(TFile, " BB%d, ", BB_id(bb_tmp));
}
fprintf(TFile, ") ");
}
}
BOOL can_be_merged_into = FALSE;
BB *fall_thru = BB_Fall_Thru_Successor(bb);
BB *fall_thru_goto = NULL;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
Print_BB_Merge_Type(bb_type, TFile);
}
switch ( bb_type) {
case CASE_ALL_IN_AREA:
{
// Remove all the branches at the end of the block
BB_Remove_Branch(bb);
if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb))
{
hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m);
}
can_be_merged_into = TRUE;
break;
}
case CASE_CALL_IN:
{
break;
}
case CASE_CALL_OUT:
{
Is_True(BB_succs_len(bb) == 1,
("here call-inst can only have one succ!\n"));
bl = BB_succs(bb);
BB* exit_target = BBLIST_item(bl);
EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(exit_target);
BOOL is_main_exit = tgt_info -> Is_Main_Predicate(orig_pred);
tgt_info -> Update_Predicate(orig_pred, pred);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
if ( is_main_exit )
{
fprintf(TFile,
"\n exit-target(main): BB%d ",
BB_id(exit_target));
} else {
fprintf(TFile,
"\n exit-target(aux): BB%d ",
BB_id(exit_target));
}
}
// there are two situations in which a full_thru_goto need to
// be added:
// 1) it is a main exit and there are some BBs to be appended
// after it
// 2) it is a main exit and there are some auxiliary predicates
// need to be assigned there
if ( is_main_exit &&
(BB_SET_Size(bb_to_solve)
|| tgt_info -> Aux_Predicates().size()))
{
// add a new basic block and insert a goto into it
REGIONAL_CFG* cfg = Home_Region(bb) -> Regional_Cfg();
fall_thru = exit_target;
fall_thru_goto = RGN_Gen_And_Insert_BB(bb, fall_thru, cfg);
Add_Goto_Op(fall_thru_goto, fall_thru);
// update the prob of bb and its successors
Set_Prob(bb, fall_thru_goto, 1.0);
BB_freq(fall_thru_goto) = BB_freq(bb);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " fall-thru-succ: BB%d\n",
BB_id(fall_thru));
fprintf(TFile, " gen fall-thru-goto: BB%d.\n",
BB_id(fall_thru_goto));
}
Make_Branch_Conditional(fall_thru_goto);
Predicate_Block(fall_thru_goto, pred, area_bb_set);
Move_BB(fall_thru_goto, bb);
GRA_LIVE_Compute_Liveness_For_BB(fall_thru_goto);
if (tgt_info -> Aux_Predicates().size()){
OP *br = BB_branch_op(fall_thru_goto);
// assign auxiliary predicates
tgt_info -> Assign_Aux_Predicates(fall_thru_goto, br);
}
}
if (!is_main_exit) {
RGN_Unlink_Pred_Succ(bb, exit_target);
}
break;
}
case CASE_UNCOND_BR:
{
Is_True(BB_succs_len(bb) == 1,
("here uncond-br can only have one succ!\n"));
bl = BB_succs(bb);
BB* exit_target = BBLIST_item(bl);
EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(exit_target);
BOOL is_main_exit = tgt_info -> Is_Main_Predicate(orig_pred);
tgt_info -> Update_Predicate(orig_pred, pred);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
if ( is_main_exit )
{
fprintf(TFile,
"\n exit-target(main): BB%d ",
BB_id(exit_target));
} else {
fprintf(TFile,
"\n exit-target(aux): BB%d ",
BB_id(exit_target));
}
}
if (BB_SET_Size(set))
{
Make_Branch_Conditional(bb);
}
if ( is_main_exit)
{
OP* br = BB_branch_op(bb);
Is_True(br, ("uncond-br must has a br-op!\n"));
tgt_info -> Assign_Aux_Predicates(bb, br);
} else {
BB_Remove_Branch(bb);
if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb))
{
hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m);
}
can_be_merged_into = TRUE;
RGN_Unlink_Pred_Succ(bb, exit_target);
}
break;
}
case CASE_FALL_OUT:
{
Is_True(fall_thru, ("fall_thru can not be empty!\n"));
EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(fall_thru);
BOOL is_main_exit = tgt_info -> Is_Main_Predicate(orig_pred);
tgt_info -> Update_Predicate(orig_pred, pred);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
if ( is_main_exit )
{
fprintf(TFile,
"\n exit-target(main): BB%d \n",
BB_id(fall_thru));
} else {
fprintf(TFile,
"\n exit-target(aux): BB%d \n",
BB_id(fall_thru));
}
}
if ( is_main_exit)
{
if (tgt_info -> Aux_Predicates().size())
{
Add_Goto_Op(bb, fall_thru);
Make_Branch_Conditional(bb);
OP* br = BB_branch_op(bb);
tgt_info -> Assign_Aux_Predicates(bb, br);
// update the prob of bb and its fall-thru-succ
float pb1 = 1.0;
if (pred_bb)
{
BB *other_succ = NULL;
BBLIST *bl;
FOR_ALL_BB_SUCCS(bb, bl)
{
BB *tmp_bb = BBLIST_item(bl);
if (tmp_bb != bb)
{
other_succ = tmp_bb;
break;
}
}
if ( other_succ)
pb1 = 1.0 - Prob_Local(pred_bb,other_succ);
}
Set_Prob(bb, fall_thru, pb1);
} else {
if ( bb != last_bb)
{
Add_Goto_Op(bb, fall_thru);
Make_Branch_Conditional(bb);
}
}
} else {
if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb))
{
hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m);
}
can_be_merged_into = TRUE;
RGN_Unlink_Pred_Succ(bb, fall_thru);
}
break;
}
case CASE_IF_FALL_OUT:
{
Is_True(fall_thru, ("fall_thru can not be empty!\n"));
TN *first_pred = NULL;
TN *second_pred = NULL;
Find_BB_Predicates(bb, first_pred, second_pred);
Is_True(first_pred && second_pred,
(" lack of a predicate!\n"));
EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(fall_thru);
BOOL is_main_exit;
OP *br = BB_branch_op(bb);
Is_True(br, (" two-successor bb must have br\n"));
if (first_pred == OP_opnd(br, OP_PREDICATE_OPND))
{
is_main_exit = tgt_info -> Is_Main_Predicate(second_pred);
} else {
Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND),
("conditional br must have a predicate.\n"));
is_main_exit = tgt_info -> Is_Main_Predicate(first_pred);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
if ( is_main_exit )
{
fprintf(TFile,
"\n exit-target(main): BB%d \n",
BB_id(fall_thru));
} else {
fprintf(TFile,
"\n exit-target(aux): BB%d \n",
BB_id(fall_thru));
}
}
// Invert the branch to make the fall through the one
//in the area
BB_Remove_Branch(bb);
if (is_main_exit)
{
// add a new goto into it
Add_Goto_Op(bb, fall_thru);
RGN_Link_Pred_Succ_With_Prob(bb, fall_thru, 1.0);
Make_Branch_Conditional(bb);
OP* br = BB_branch_op(bb);
// update the prob of bb and its fall-thru-succ
float pb1 = pred_bb ? Prob_Local(pred_bb, bb):1;
float pb2 = Prob_Local(bb, fall_thru);
Set_Prob(bb, fall_thru, pb1 * pb2);
tgt_info -> Assign_Aux_Predicates(bb, br);
} else {
if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb))
{
hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m);
}
can_be_merged_into = TRUE;
BB* other_succ = BB_Other_Successor(bb, fall_thru);
RGN_Unlink_Pred_Succ(bb, other_succ);
}
break;
}
case CASE_IF_FALL_IN:
{
Is_True(fall_thru, ("fall_thru can not be empty!\n"));
BB* other_succ = BB_Other_Successor(bb, fall_thru);
Is_True(other_succ, ("fall_thru can not be empty!\n"));
EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(other_succ);
TN *first_pred = NULL;
TN *second_pred = NULL;
Find_BB_Predicates(bb, first_pred, second_pred);
Is_True(first_pred && second_pred,
(" lack of a predicate!\n"));
BOOL is_main_exit;
OP *br = BB_branch_op(bb);
Is_True(br, (" two-successor bb must have br\n"));
if (first_pred == OP_opnd(br, OP_PREDICATE_OPND))
{
is_main_exit = tgt_info -> Is_Main_Predicate(first_pred);
} else {
Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND),
("conditional br must have a predicate.\n"));
is_main_exit = tgt_info -> Is_Main_Predicate(second_pred);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n exit-target");
if ( is_main_exit )
{
fprintf(TFile, "(main)");
} else {
fprintf(TFile, "(aux)");
}
fprintf(TFile,": BB%d ", BB_id(other_succ));
}
if (is_main_exit)
{
OP* br = BB_branch_op(bb);
tgt_info -> Assign_Aux_Predicates(bb, br);
} else {
BB_Remove_Branch(bb);
if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb))
{
hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m);
}
can_be_merged_into = TRUE;
RGN_Unlink_Pred_Succ(bb, other_succ);
// Set_Prob(bb, fall_thru, 1.0);
}
break;
}
case CASE_IF_OUT:
{
Is_True(fall_thru, ("fall_thru can not be empty!\n"));
TN *first_pred = NULL;
TN *second_pred = NULL;
Find_BB_Predicates(bb, first_pred, second_pred);
Is_True(first_pred && second_pred,
(" lack of a predicate!\n"));
BOOL is_main_exit;
OP *br = BB_branch_op(bb);
Is_True(br, (" two-successor bb must have br\n"));
// solving target-successor(non-fall-thru successor)
TN *fall_thru_pred = NULL;
BB* other_succ = BB_Other_Successor(bb, fall_thru);
EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(other_succ);
if (first_pred == OP_opnd(br, OP_PREDICATE_OPND))
{
is_main_exit = tgt_info -> Is_Main_Predicate(first_pred);
fall_thru_pred = second_pred;
} else {
Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND),
("conditional br must have a predicate.\n"));
is_main_exit = tgt_info -> Is_Main_Predicate(second_pred);
fall_thru_pred = first_pred;
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n exit-target");
if ( is_main_exit )
{
fprintf(TFile, "(main)");
} else {
fprintf(TFile, "(aux)");
}
fprintf(TFile,": BB%d ", BB_id(other_succ));
}
BOOL need_add_fall_thru = TRUE;
if ( is_main_exit )
{
OP* br = BB_branch_op(bb);
tgt_info -> Assign_Aux_Predicates(bb, br);
} else {
BB_Remove_Branch(bb);
RGN_Unlink_Pred_Succ(bb, other_succ);
need_add_fall_thru = FALSE;
}
// solving fall through successor
tgt_info = area -> Exit_Target(fall_thru);
if (first_pred == OP_opnd(br, OP_PREDICATE_OPND))
{
is_main_exit = tgt_info -> Is_Main_Predicate(second_pred);
} else {
Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND),
("conditional br must have a predicate.\n"));
is_main_exit = tgt_info -> Is_Main_Predicate(first_pred);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n exit-target");
if ( is_main_exit )
{
fprintf(TFile, "(main)");
} else {
fprintf(TFile, "(aux)");
}
fprintf(TFile,": BB%d ", BB_id(fall_thru));
}
// Need to insert a fall-through goto, then conditionalize
// it with the inverse conditional
br = NULL;
if ( is_main_exit)
{
if ( need_add_fall_thru &&
(tgt_info -> Aux_Predicates().size() || bb != last_bb))
{
// add a new basic block and insert a goto into it
REGIONAL_CFG* cfg = BB_SET_Size(bb_to_solve) ?
Home_Region(bb) -> Regional_Cfg(): NULL;
fall_thru_goto = RGN_Gen_And_Insert_BB(bb, fall_thru, cfg);
Add_Goto_Op(fall_thru_goto, fall_thru);
if (fall_thru_pred && fall_thru_pred != True_TN)
{
Make_Branch_Conditional(fall_thru_goto);
Predicate_Block(fall_thru_goto,
fall_thru_pred, area_bb_set);
}
// assign auxiliary predicates
br = BB_branch_op(fall_thru_goto);
tgt_info -> Assign_Aux_Predicates(fall_thru_goto, br);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " fall-thru-succ: BB%d\n",
BB_id(fall_thru));
fprintf(TFile, " gen fall-thru-goto: BB%d.\n",
BB_id(fall_thru_goto));
}
Move_BB(fall_thru_goto, bb);
GRA_LIVE_Compute_Liveness_For_BB(fall_thru_goto);
float pb1 = Prob_Local(pred_bb, bb);
float pb2 = Prob_Local(bb, other_succ);
Set_Prob(bb, other_succ, pb1 * pb2);
Set_Prob(bb, fall_thru_goto, 1 - pb1 * pb2);
BB_freq(fall_thru_goto) =
BB_freq(pred_bb) * (1 -pb1 * pb2);
} else if (bb != last_bb ||
tgt_info -> Aux_Predicates().size())
{
Add_Goto_Op(bb, fall_thru);
Make_Branch_Conditional(bb);
br = BB_branch_op(bb);
if (fall_thru_pred && fall_thru_pred != True_TN)
{
Set_OP_opnd(br, OP_PREDICATE_OPND, fall_thru_pred);
}
// assign auxiliary predicates
tgt_info -> Assign_Aux_Predicates(bb, br);
}
} else {
RGN_Unlink_Pred_Succ(bb, fall_thru);
}
if (!need_add_fall_thru && !br)
{
if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb))
{
hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m);
}
can_be_merged_into = TRUE;
}
break;
}
case CASE_CHECK_IN:
case CASE_CHECK_OUT:
{
break;
}
default:
Is_True(0,("Unknown block classification"));
}
// predicate the current basic block
Predicate_Block(bb, pred, area_bb_set);
// merge it into its predecessor
// judge if it can be merged into its predecessor
if (pred_bb && BB_SET_MemberP(hold_bbs, pred_bb))
{
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " => merged.\n");
}
if (pred)
{
if (!pred_info -> Eqv_Class_Head()
&& pred_info -> Eqv_Class_Head_BB() != pred_bb)
{
Set_TN_is_global_reg(pred);
Set_BB_has_globals(bb);
Set_BB_has_globals(pred_info -> Eqv_Class_Head_BB());
} else if (pred_info -> Has_Start_Node())
{
BB* st_n = pred_info -> Start_Node(BB_SET_Choose(set));
if (st_n != pred_bb)
{
Set_TN_is_global_reg(pred);
Set_BB_has_globals(bb);
Set_BB_has_globals(st_n);
}
}
}
BB *succ_of_goto = NULL;
if (fall_thru_goto)
{
Is_True(BB_succs_len(fall_thru_goto) == 1,
("here fall-thru-goto can only have one succ!\n"));
bl = BB_succs(fall_thru_goto);
succ_of_goto = BBLIST_item(bl);
}
FOR_ALL_BB_SET_members(bb_to_solve, succ_bb_of_pred)
{
if (fall_thru_goto)
{
// add succ_bb_of_pred as the fall-thru-successor of
// fall_thru_goto
float pb = Prob_Local(pred_bb, succ_bb_of_pred);
RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred);
RGN_Link_Pred_Succ_With_Prob(fall_thru_goto,
succ_bb_of_pred, pb);
Set_Fall_Thru(fall_thru_goto, succ_bb_of_pred);
Set_Prob(fall_thru_goto, succ_of_goto, 1 - pb);
} else {
// add succ_bb_of_pred as a successor of bb
float pb = Prob_Local(pred_bb, succ_bb_of_pred);
RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred);
RGN_Link_Pred_Succ_With_Prob(bb, succ_bb_of_pred, pb);
}
}
if ( BB_call(bb) )
{
BB_Transfer_Callinfo( bb, pred_bb);
}
Merge_Blocks(pred_bb, bb);
if (!can_be_merged_into)
{
BB_SET_Difference1D(hold_bbs, pred_bb);
}
}else if (pred_bb){
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " => appended .\n");
}
// maintain localization information of registers
if (pred &&
(!pred_info -> Eqv_Class_Head()|| pred_info -> Has_Start_Node()))
{
Set_TN_is_global_reg(pred);
Set_BB_has_globals(bb);
if (!pred_info -> Eqv_Class_Head())
Set_BB_has_globals(pred_info -> Eqv_Class_Head_BB());
}
if ( BB_SET_Size(bb_to_solve) )
{
BB *succ_of_goto = NULL;
if (fall_thru_goto)
{
Is_True(BB_succs_len(fall_thru_goto) == 1,
("here fall-thru-goto can only have one succ!\n"));
bl = BB_succs(fall_thru_goto);
succ_of_goto = BBLIST_item(bl);
}
FOR_ALL_BB_SET_members(bb_to_solve, succ_bb_of_pred)
{
if (fall_thru_goto)
{
// add succ_bb_of_pred as the fall-thru-successor of
// fall_thru_goto
float pb = Prob_Local(pred_bb, succ_bb_of_pred);
RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred);
RGN_Link_Pred_Succ_With_Prob(fall_thru_goto,
succ_bb_of_pred, pb);
Set_Fall_Thru(fall_thru_goto, succ_bb_of_pred);
Set_Prob(fall_thru_goto, succ_of_goto, 1 - pb);
} else {
// add succ_bb_of_pred as a successor of bb
float pb = Prob_Local(pred_bb, succ_bb_of_pred);
RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred);
RGN_Link_Pred_Succ_With_Prob(bb, succ_bb_of_pred, pb);
}
}
}
if (last_bb_type == CASE_CALL_OUT)
{
Set_Fall_Thru(pred_bb, bb);
}
float out_pb = 0.0;
// update fall thru successor
if (pred_bb && BB_succs_len(pred_bb) > 1)
{
Is_True(BB_succs_len(pred_bb) == 2,
("a bb can not have more than 2 succs!\n"));
// for a bb, one succ is out of the area, the other succ(bb)
// should be fall-thru-succ
FOR_ALL_BB_SUCCS(pred_bb, bl)
{
succ_bb_of_pred = BBLIST_item(bl);
if (succ_bb_of_pred != bb
&& !Is_BB_Container_Member(bbs, succ_bb_of_pred))
{
out_pb = Prob_Local(pred_bb, succ_bb_of_pred);
Set_Fall_Thru(pred_bb, bb);
}
}
}
// maintain frequency information
BB_freq(bb) = BB_freq(pred_bb) * ( 1- out_pb);
Set_Prob(pred_bb, bb, 1.0 - out_pb);
} else {
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n");
}
}
last_bb_type = bb_type;
}
// get rid of useless 'br'. Sometime, after if-conversion, a bb with
// a conditional 'br' will only has one successor. In this case, the
// 'br' should be deleted.
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
OP *br = BB_branch_op(bb);
if ( !br ) continue;
if ( OP_cond(br) && BB_succs_len(bb) == 1 )
{
BB *fall_thru = BB_Fall_Thru_Successor(bb);
if ( fall_thru && fall_thru == BB_next(bb) && OP_bb(br) )
{
BB_Remove_Op(bb, br);
} else if (!fall_thru ) {
//OSP_265
//Here means the branch will always be taken.
//Instead of using True_TN as predicate, we just revert br.cond back to br.
//CGTARG_Predicate_OP(bb, br, True_TN);
TOP new_top;
switch (OP_code(br)) {
case TOP_br_cond:
new_top = TOP_br;
break;
case TOP_br_r_cond:
new_top = TOP_br_r;
break;
default:
FmtAssert(0, ("Weird branch instruction!"));
break;
}
OP* new_br = Mk_OP(new_top,
Gen_Enum_TN(ECV_ph_few),
Gen_Enum_TN(ECV_dh),
OP_opnd(br,4));
OP_srcpos(new_br) = OP_srcpos(br);
BB_Insert_Op_After(bb, br, new_br);
BB_Remove_Op(bb, br);
}
}
}
}
BB_MERGE_TYPE
IF_CONVERTOR::Classify_BB(BB *bb,
IF_CONV_AREA *area)
{
BB_MERGE_TYPE result;
BB *entry = area -> Entry_BB();
BB *fall_thru;
BB *other_succ;
fall_thru = BB_Fall_Thru_Successor(bb);
other_succ = NULL;
BBLIST *bl;
FOR_ALL_BB_SUCCS(bb, bl)
{
other_succ = BBLIST_item(bl);
if (other_succ != fall_thru) break;
}
// check for easy case, to see if all succs are in the area
BOOL fall_thru_out = false;
BOOL other_out = false;
BB_CONTAINER& bbs_1 = area -> Blocks();
if (fall_thru &&
(!Is_BB_Container_Member(bbs_1, fall_thru) ||fall_thru == entry))
{
fall_thru_out = TRUE;
}
if (other_succ &&
(!Is_BB_Container_Member(bbs_1, other_succ) || other_succ == entry))
{
other_out = TRUE;
}
if (!other_out && !fall_thru_out)
{
if (BB_exit(bb) || BB_call(bb))
{
result = CASE_CALL_IN;
} else if (BB_chk_op(bb))
{
result = CASE_CHECK_IN;
} else {
result = CASE_ALL_IN_AREA;
}
return result;
}
// In the case, at least one block is out of the area.
if (BB_exit(bb) || BB_call(bb))
{
result = CASE_CALL_OUT;
return result;
}
if (BB_chk_op(bb))
{
result = CASE_CHECK_OUT;
return result;
}
OP *br = BB_branch_op(bb);
if (!br)
{
// No branch, just fall_thru.
result = CASE_FALL_OUT;
return result;
}
if (!OP_cond(br))
{
// Unconditional branch
result = CASE_UNCOND_BR;
return result;
}
if (fall_thru_out && other_out)
{
result = CASE_IF_OUT;
} else if (fall_thru_out && !other_out) {
result = CASE_IF_FALL_OUT;
} else {
result = CASE_IF_FALL_IN;
}
return result;
}
void
IF_CONVERTOR::Set_Fall_Thru(BB* bb, BB* fall_thru)
{
BB* before_bb = bb;
while (fall_thru) {
BB* next = BB_next(fall_thru);
// if the target of the branch of 'fall_thru' is the fall_thru_bb
// of 'fall_thru', stop iteration.
BOOL stop_iter = FALSE;
OP *br_op = BB_branch_op(fall_thru);
if (next && br_op) {
INT tfirst, tcount;
CGTARG_Branch_Info(br_op, &tfirst, &tcount);
if (tcount != 0) {
TN *dest = OP_opnd(br_op, tfirst);
Is_True(tcount == 1,
("%d branch targets, expected 1", tcount));
Is_True(TN_is_label(dest), ("expected label"));
if (Is_Label_For_BB(TN_label(dest), next)) {
stop_iter = TRUE;
}
}
}
if (stop_iter || next != BB_Fall_Thru_Successor(fall_thru))
{
next = NULL;
}
Move_BB(fall_thru, before_bb);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n => move BB:%d after BB:%d\n",
BB_id(fall_thru), BB_id(before_bb));
}
before_bb = fall_thru;
fall_thru = next;
}
}
void
IF_CONVERTOR::Merge_Blocks(BB *bb_first,
BB *bb_second)
{
// step 0: maintain fall-thrugh-information
BOOL need_maintain = TRUE;
OP *br_op = BB_branch_op(bb_second);
BB* next = BB_next(bb_second);
if (next && br_op) {
INT tfirst, tcount;
CGTARG_Branch_Info(br_op, &tfirst, &tcount);
if (tcount != 0) {
TN *dest = OP_opnd(br_op, tfirst);
Is_True(tcount == 1, ("%d branch targets, expected 1", tcount));
Is_True(TN_is_label(dest), ("expected label"));
if (Is_Label_For_BB(TN_label(dest), next)) {
need_maintain = FALSE;
}
}
}
if ( need_maintain && bb_second != BB_next(bb_first))
{
BB* fall_thru = BB_Fall_Thru_Successor(bb_second);
Set_Fall_Thru(bb_first, fall_thru);
}
// step1: Move all ops of bb_second to bb_first.
OP *op;
OP *op_next;
OP *last = BB_last_op(bb_first);
for (op = BB_first_op(bb_second);
op;
op = op_next)
{
op_next = OP_next(op);
if (last)
{
BB_Move_Op(bb_first, last, bb_second, op, FALSE);
} else {
BB_Append_Op (bb_first, op);
}
last = op;
}
// step2: Clean up the first pred-succ list
RGN_Unlink_Pred_Succ(bb_first, bb_second);
// step3: move bb_second's successor arcs to bb_first.
BB *succ;
BBLIST *bl;
while (bl = BB_succs(bb_second))
{
succ = BBLIST_item(bl);
float pb = Prob_Local(bb_second, succ);
RGN_Unlink_Pred_Succ(bb_second, succ);
RGN_Link_Pred_Succ_With_Prob(bb_first, succ, pb);
}
//step4: take bb_second out of the list.
RGN_Remove_BB_And_Edges(bb_second);
// step5: maintain the call and exit infomation
// If bb_second is an exit, move the relevant info to the
// merged block.
if (BB_exit(bb_second))
{
BB_Transfer_Exitinfo(bb_second, bb_first);
Exit_BB_Head = BB_LIST_Delete(bb_second, Exit_BB_Head);
Exit_BB_Head = BB_LIST_Push(bb_first, Exit_BB_Head, &MEM_pu_pool);
}
// Transfer call info if merged block will now contain a call.
if (BB_call(bb_second))
{
BB_Copy_Annotations(bb_first, bb_second, ANNOT_CALLINFO);
}
}
//*****************************************************************************
// Function : Convert_Candidates
// Input :
// - areas : a list of IF_CONV_AREAs. On them, there are obvious flags to
// indicate if the IF_CONV_AREA should be if-converted.
// Output :
// <none>
// Description :
// apply if-conversion on the selected candidates to predicated code.
//
//*****************************************************************************
BOOL
IF_CONVERTOR::Convert_Candidates(AREA_CONTAINER& areas)
{
AREA_CONTAINER:: iterator iter;
BOOL converted = FALSE;
for ( iter = areas.begin();
iter != areas.end();
iter++)
{
IF_CONV_AREA* area = *iter;
BB_CONTAINER& bbs = area -> Blocks();
if (IPFEC_Query_Skiplist(if_conv_skip_area, area -> Area_Label()))
continue;
if ( area -> Conv_Type() != FULLY_IF_CONV)
continue;
converted = TRUE;
char if_conversion_key[6] = "";
char input_string[100] = "";
char output_string[60] = "";
if (Get_Trace(TP_PTRACE1, TP_PTRACE1_CG))
{
BB_CONTAINER::iterator bb_iter;
BB *bb;
sprintf(if_conversion_key, "%d", area -> Area_Label());
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
char tmp_string[6];
sprintf(tmp_string, "%d", BB_id(bb));
strcat(input_string, tmp_string);
strcat(input_string, "||");
}
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, "\n IF_CONV_AREA %d:\n", area -> Area_Label());
}
// caculate control dependence and initialize the predicate info
area -> Init_Conversion_Info(&_m);
if ( !Insert_Predicate(area)) {
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n too many exits, give up!!\n");
}
continue;
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, "\n Start to merge basic blocks!\n");
}
Merge_Area(area);
if (Get_Trace(TP_PTRACE1, TP_PTRACE1_CG))
{
BB_CONTAINER& bbs = area -> Blocks();
BB_CONTAINER::iterator bb_iter;
BB *bb;
sprintf(if_conversion_key, "%d", area -> Area_Label());
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb = *bb_iter;
if (Regional_Cfg_Node(bb))
{
char tmp_string[6];
sprintf(tmp_string, "%d", BB_id(bb));
strcat(output_string, tmp_string);
strcat(output_string, "||");
}
}
Generate_Tlog("AIC", "if_conversion", (SRCPOS)0,
if_conversion_key, input_string, output_string, "");
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, "\n after merging basic blocks:\n");
area -> Print_IR(TFile);
}
}
return converted;
}
//*****************************************************************************
// Function : If_Conversion
// Input :
// - region_tree : a region tree
// Output :
// < none >
// Description :
// the driver of if-conversion phase
//*****************************************************************************
IF_CONVERTOR::IF_CONVERTOR(REGION_TREE *region_tree)
{
Start_Timer(T_Ipfec_If_Conv_CU);
//trace before IF_CONV
if (Get_Trace(TKIND_IR, TP_A_IFCONV, REGION_First_BB))
Trace_IR(TP_A_IFCONV, "IF_CONV", NULL, FALSE);
if (!frequency_of_predicates)
{
frequency_of_predicates = hTN_MAPf_Create(&(info_mem._m));
}
if (!init_op_info)
{
init_op_info = hTN_MAP_Create(&(info_mem._m));
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC))
{
draw_global_cfg();
}
BOOL changed = TRUE;
for (INNERMOST_REGION_FIRST_ITER iter(region_tree);
iter != 0;
++iter)
{
REGION* region = *iter;
if (IPFEC_Query_Skiplist(if_conv_skip_rgn, region -> Id(), Current_PU_Count()))
continue;
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC))
{
draw_regional_cfg(region);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " \nIF CONVERSION -- region %d\n", region -> Id());
}
if ( Is_In_Infinite_Loop(region) )
continue;
if (Is_In_Abnormal_Loop(region))
continue;
if (region->Region_Type () == IMPROPER)
continue;
// Calculate_Dominators is time comsumption, only recalculate
// when the cfg changed
if( changed )
Calculate_Dominators();
// do something to initialize
IF_CONV_ALLOC temp_alloc(&_m);
AREA_CONTAINER areas(temp_alloc);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " \n Start to initialize!\n");
}
If_Conversion_Init(region,areas);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " IF_CONV_AREAs after initialization:\n\n");
Print_All_Areas(areas, TFile);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " \n Start to select proper areas!\n");
}
// select the if-conversion candidates
Select_Candidates(areas);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " IF_CONV_AREAs after selection:\n\n");
Print_All_Areas(areas, TFile);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " \n Start to convert candidates!\n");
}
//convert the if-conversion candidates to predicated code
changed = Convert_Candidates(areas);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC))
{
draw_regional_cfg(region);
}
CXX_DELETE(&areas, &_m);
if( changed )
Free_Dominators_Memory();
}
if(!changed)
Free_Dominators_Memory();
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC))
{
draw_global_cfg();
}
//trace after IF_CONV
if (Get_Trace(TKIND_IR, TP_A_IFCONV, REGION_First_BB))
Trace_IR(TP_A_IFCONV, "IF_CONV", NULL);
Stop_Timer(T_Ipfec_If_Conv_CU);
}
IF_CONVERTOR::IF_CONVERTOR()
{
if (!frequency_of_predicates)
{
frequency_of_predicates = hTN_MAPf_Create(&(info_mem._m));
}
if (!init_op_info)
{
init_op_info = hTN_MAP_Create(&(info_mem._m));
}
_loop_length = 0;
}
//*****************************************************************************
// Function : Force_If_Conversion
// Input :
// - loop : a descriptor of a loop. here, we assume the loop is a SEME and
// innermost loop.
// - allow_muti_bb : a boolean value to indicate if multiple bb in a loop is
// allowed
// Output :
// - a basic block : If allow_multi_bb, it will always be converted if
// possible. If not possible, return NULL.
// Description :
// in swp phase, a loop without control flow in it is suitable to apply
// swp. It is a driver to if-convert a loop body
//*****************************************************************************
BB *
IF_CONVERTOR::Force_If_Convert(LOOP_DESCR *loop, BOOL allow_multi_bb)
{
BB *bb_entry = LOOP_DESCR_loophead(loop);
// possible quick exit if there is already only one block in the region
if (BB_SET_Size(LOOP_DESCR_bbset(loop)) == 1) {
return bb_entry;
}
// check if it is safe to if-convert the loop
IF_CONV_ALLOC temp_alloc(&_m);
AREA_CONTAINER areas(temp_alloc);
REGION* region = Home_Region(bb_entry);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC))
{
draw_regional_cfg(region);
}
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " ======start to force_if_convert\n\n");
}
if ( Is_In_Infinite_Loop(region) )
{
return NULL;
}
If_Conversion_Init(region,areas);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " IF_CONV_AREAs after initialization:\n\n");
Print_All_Areas(areas, TFile);
}
// check if it can be merged into one basic block
BOOL is_legal = Can_Merge_Into_One_Area(areas);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY))
{
fprintf(TFile, " is_legal: %d\n", (int)is_legal);
}
if (!is_legal)
{
return NULL;
}
// When relaxed if conversion is used, we don't blindly merge all areas to
// one singel area and apply if conversion. Instead we use a similar approch
// as the normal if conversion does, but the heuristics to calculate the
// profitability is more relaxed because we might gain additional performance
// through SWP.
if (IPFEC_Relaxed_If_Conv) {
if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_SUMMARY)) {
fprintf(TFile, " ======use relaxed_if_conv\n\n");
}
// Calculate a rough estimate of the critical path of the loop
INT32 loop_length1, loop_length2;
loop_length1 = Calculate_Loop_Critical_Length (areas[0]);
loop_length2 = Calculate_Loop_Cycled_Critical_Length (areas[0]);
_loop_length = loop_length1 > loop_length2 ? loop_length1 : loop_length2;
if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_DETAILED)) {
fprintf (TFile,
" Loop Length: %i\n",
_loop_length);
}
Select_Candidates (areas, /*forced=*/TRUE);
if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_DETAILED)) {
fprintf (TFile, " IF_CONV_AREAs after selection:\n\n");
Print_All_Areas (areas, TFile);
}
// Check if the loop has been reduced to one area.
// If not we will not If Convert the loop
if (areas.size()!=1) {
return NULL;
}
}
else {
// merge all areas
AREA_CONTAINER::iterator area_iter;
area_iter = areas.begin();
IF_CONV_AREA *head_area = *area_iter;
area_iter++;
for (; area_iter != areas.end(); area_iter++) {
head_area -> Combine_Blocks_With (*area_iter, &_m);
}
// We can now delete all areas except the first one,
// because all the other areas have been merged into
// the first area
areas.erase (areas.begin()+1,areas.end());
head_area -> Conv_Type(FULLY_IF_CONV);
}
BOOL can_one_bb = Can_Merge_Into_One_BB (*(areas.begin()));
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) {
fprintf (TFile, " can_one_bb: %d\n", (int) can_one_bb);
}
// Do the if-conversion
if (can_one_bb || allow_multi_bb) {
if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_SUMMARY)) {
fprintf (TFile, " \n Start to convert candidates!\n");
}
Convert_Candidates(areas);
// Update the loop descriptor
BB* fall_thru_bb = NULL;
BB* bb;
IF_CONV_AREA* area = *(areas.begin());
BB_CONTAINER del_blks(&_m);
BB_CONTAINER::iterator bb_iter;
for (bb_iter = area -> Blocks().begin();
bb_iter != area -> Blocks().end();
bb_iter++)
{
bb = *bb_iter;
REGIONAL_CFG_NODE* node = Regional_Cfg_Node(bb);
REGION* home_region = node ? node -> Home_Region() : NULL;
// home_region == NULL means the bb has been deleted
if (!home_region) {
// get rid of all the old blocks from the loop descriptors
// Due to some bugs, when BB set in LOOP_DESCR is changed,
// the "delete" operations should be performed after "add"
// is done.
// LOOP_DESCR_Delete_BB(loop, bb);
del_blks.push_back (bb);
}
else if (home_region != region) {
FmtAssert (fall_thru_bb == NULL,
(" can only have one fall_thru_bb\n"));
fall_thru_bb = bb;
// Add the fall_thru_block to the loop descriptors
// for all the enclosing loops
LOOP_DESCR *enc_loop = LOOP_DESCR_Next_Enclosing_Loop(loop);
if (enc_loop) {
LOOP_DESCR_Add_BB (enc_loop, fall_thru_bb);
}
}
}
for (BB_CONTAINER::iterator iter = del_blks.begin();
iter != del_blks.end ();
iter++)
{
LOOP_DESCR_Delete_BB (loop, *iter);
}
BB* single_bb = NULL;
if (can_one_bb) {
FmtAssert (areas.size() ==1, (" loop should be shrinked to one bb"));
IF_CONV_AREA* area = *(areas.begin());
if (BB_SET_Size(LOOP_DESCR_bbset(loop)) == 1) {
single_bb = area -> Entry_BB();
}
}
if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_GRAPHIC)) {
draw_regional_cfg(region);
}
return single_bb;
}
return NULL;
}
BOOL
IF_CONVERTOR::Can_Merge_Into_One_Area(AREA_CONTAINER& areas)
{
INT break_num = 0;
AREA_CONTAINER::iterator iter;
for ( iter = areas.begin();
iter != areas.end();
iter++)
{
IF_CONV_AREA* area = *iter;
if (area -> Area_Type() == UNSUITABLE)
{
return false;
}
if (area -> Area_Type() == UPWARD_UNSUITABLE
&& area -> Pred_Num())
{
return false;
}
if (area -> Area_Type() == DOWNWARD_UNSUITABLE
&& area -> Succ_Num())
{
return false;
}
}
return true;
}
BOOL
IF_CONVERTOR::Can_Merge_Into_One_BB(IF_CONV_AREA* area)
{
BB_CONTAINER& bbs = area -> Blocks();
BB_CONTAINER::iterator bb_iter;
BB *bb;
BOOL break_num = FALSE;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
bb =*bb_iter;
BB_MERGE_TYPE merge_type = Classify_BB(bb, area);
if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED))
{
fprintf(TFile, " => BB_%d is",BB_id(bb));
Print_BB_Merge_Type(merge_type,TFile);
fprintf(TFile,"type.\n");
}
switch ( merge_type) {
case CASE_ALL_IN_AREA:
{
break;
}
case CASE_CALL_IN:
case CASE_IF_FALL_OUT:
case CASE_IF_FALL_IN:
case CASE_CHECK_IN:
{
return false;
}
case CASE_CALL_OUT:
case CASE_UNCOND_BR:
case CASE_FALL_OUT:
case CASE_IF_OUT:
case CASE_CHECK_OUT:
{
if (!break_num) {
break_num= TRUE;
break;
} else
return false;
}
default:
Is_True(0,("Unknown block classification"));
}
}
return true;
}
//=============================================================================
// Print functions
//=============================================================================
void
IF_CONVERTOR::Print_BB_Merge_Type(BB_MERGE_TYPE merge_type,FILE* file)
{
switch ( merge_type) {
case CASE_ALL_IN_AREA:
{
fprintf(file, "CASE_ALL_IN_AREA");
break;
}
case CASE_CALL_IN:
{
fprintf(file, "CASE_CALL_IN");
break;
}
case CASE_CALL_OUT:
{
fprintf(file, "CASE_CALL_OUT");
break;
}
case CASE_UNCOND_BR:
{
fprintf(file, "CASE_UNCOND_BR");
break;
}
case CASE_FALL_OUT:
{
fprintf(file, "CASE_FALL_OUT");
break;
}
case CASE_IF_FALL_OUT:
{
fprintf(file, "CASE_IF_FALL_OUT");
break;
}
case CASE_IF_FALL_IN:
{
fprintf(file, "CASE_IF_FALL_IN");
break;
}
case CASE_IF_OUT:
{
fprintf(file, "CASE_IF_OUT");
break;
}
case CASE_CHECK_IN:
{
fprintf(file, "CASE_CHECK_IN");
break;
}
case CASE_CHECK_OUT:
{
fprintf(file, "CASE_CHECK_OUT");
break;
}
default:
{
Is_True(0,("Unknown block classification"));
}
}
}
void
IF_CONVERTOR::Print_All_Areas(AREA_CONTAINER& areas, FILE* file)
{
AREA_CONTAINER::iterator iter;
for (iter = areas.begin();
iter != areas.end();
iter++)
{
IF_CONV_AREA* area = *iter;
area -> Print(TFile);
}
}
// This function calculates a rough estimate of the loop critical path
INT32
IF_CONVERTOR::Calculate_Loop_Critical_Length (IF_CONV_AREA* area) {
INT32 critical_length = 0;
INT32 length1, length2;
AREA_CONTAINER::iterator area_succs;
FmtAssert(area!=NULL, ("Parameter area is NULL pointer!"));
critical_length += area->Critical_Len ();
area_succs = area->Succ_Set().begin();
switch (area->Succ_Num ()) {
case 0: break;
case 1: critical_length +=
Calculate_Loop_Critical_Length (*area_succs);
break;
case 2: length1 =
Calculate_Loop_Critical_Length (*area_succs);
area_succs++;
length2 =
Calculate_Loop_Critical_Length (*area_succs);
if (length1 > length2 ) {
critical_length += length1;
}
else {
critical_length += length2;
}
break;
default: FmtAssert (0, ("Unexpected number of successors!"));
break;
}
return critical_length;
}
// This function calculates a rough estimate of the loop critical path under
// the assumption that one instruction takes one cycle
INT32
IF_CONVERTOR::Calculate_Loop_Cycled_Critical_Length (IF_CONV_AREA* area) {
INT32 cycled_critical_length = 0;
INT32 length1, length2;
AREA_CONTAINER::iterator area_succs;
FmtAssert(area!=NULL, ("Parameter area is NULL pointer!"));
cycled_critical_length += area->Cycled_Critical_Len ();
area_succs = area->Succ_Set().begin();
switch (area->Succ_Num ()) {
case 0: break;
case 1: cycled_critical_length +=
Calculate_Loop_Cycled_Critical_Length (*area_succs);
break;
case 2: length1 =
Calculate_Loop_Cycled_Critical_Length (*area_succs);
area_succs++;
length2 =
Calculate_Loop_Cycled_Critical_Length (*area_succs);
if (length1 > length2 ) {
cycled_critical_length += length1;
}
else {
cycled_critical_length += length2;
}
break;
default: FmtAssert (0, ("Unexpected number of successors!"));
break;
}
return cycled_critical_length;
}
void
IF_CONV_AREA::Print(FILE* file)
{
fprintf(file,
"\nIF_CONV_AREA_%d: (",
Area_Label());
fprintf(file, " suitable type : ");
switch (_if_suitable) {
case UPWARD_UNSUITABLE:
{
fprintf(file, " UPWARD_UNSUITABLE; ");
break;
}
case DOWNWARD_UNSUITABLE:
{
fprintf(file, " DOWNWARD_UNSUITABLE; ");
break;
}
case UNSUITABLE:
{
fprintf(file, " UNSUITABLE; ");
break;
}
case SUITABLE_FOR_IF_CONV:
{
fprintf(file, " SUITABLE_FOR_IF_CONV; ");
break;
}
default:
{
Is_True(0, (" Illegal AREA_TYPE.\n"));
}
}
fprintf(file, " if-conv type : ");
switch (_need_if_convert ) {
case NO_IF_CONV:
{
fprintf(file, " NO_IF_CONV;");
break;
}
case PARTIAL_IF_CONV:
{
fprintf(file, " PARTIAL_IF_CONV;");
break;
}
case FULLY_IF_CONV:
{
fprintf(file, " FULLY_IF_CONV;");
break;
}
default:
{
Is_True(0, (" Illegal IF_CONV_TYPE.\n"));
}
}
fprintf(file, " length(cycled): %d; ",_cycled_critical_length);
fprintf(file, " length : %d ", _critical_length);
fprintf(file,")\n -- included blocks : ");
BB_CONTAINER& bbs = _included_blocks;
BB_CONTAINER::iterator bb_iter;
BB *block;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
block = *bb_iter;
fprintf(file,"BB%d, ", block -> id);
}
fprintf(file,"\n");
AREA_CONTAINER::iterator iter;
fprintf(file, " -- predecessors : ");
for ( iter = _predecessors.begin();
iter!=_predecessors.end();
iter++)
{
IF_CONV_AREA* pred = *iter;
fprintf(file,"AREA_%d, ", pred->Area_Label());
}
fprintf(file, "\n -- successors : ");
for ( iter = _successors.begin();
iter!= _successors.end();
iter++)
{
IF_CONV_AREA* succ = *iter;
fprintf(file,"AREA_%d, ", succ->Area_Label());
}
fprintf(file, "\n");
if (_control_deps)
{
Is_True(_pred_assign_info, (" _pred_true_edges must be initialized!"));
_control_deps -> Print(file);
fprintf(file, " -- more detailed information for each bb : \n");
BB_CONTAINER::iterator bb_iter;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
block = *bb_iter;
BB_SET *set;
BB *bb;
BB_PREDICATE_INFO *info;
fprintf(file, " \n** BB%d : ", BB_id(block));
info = (BB_PREDICATE_INFO*)BB_MAP_Get( _pred_assign_info, block);
fPrint_TN(file,
" predicate: %s ; ",
info -> Predicate());
fprintf(file,
" transitional: %c ;",
info -> Transitional()?'y':'n');
fPrint_TN(file,
" true pred: %s ;",
info -> True_TN());
fPrint_TN(file,
" false pred: %s\n",
info -> False_TN());
TN_CONTAINER::iterator iter;
TN_CONTAINER tn_set;
fprintf(file," # or preds:");
tn_set = info ->Or_TNs();
for (iter = tn_set.begin();
iter != tn_set.end();
iter++)
{
fPrint_TN(file, " %s,", *iter);
}
fprintf(file," # orcm preds:");
tn_set = info -> Orcm_TNs();
for (iter = tn_set.begin();
iter != tn_set.end();
iter++)
{
fPrint_TN(file, " %s,", *iter);
}
fprintf(file," # and preds:\n");
tn_set = info -> And_TNs();
for (iter = tn_set.begin();
iter != tn_set.end();
iter++)
{
fPrint_TN(file, " %s,", *iter);
}
fprintf(file," # andcm preds:");
tn_set = info -> Andcm_TNs();
for (iter = tn_set.begin();
iter != tn_set.end();
iter++)
{
fPrint_TN(file, " %s,", *iter);
}
fprintf(file, "\n");
if ( !info -> Has_Start_Node()) continue;
fprintf(file,
" # starting nodes for each control dependentor:\n");
BB_SET* cds = _control_deps -> Cntl_Dep_Parents(block);
BB* cd;
FOR_ALL_BB_SET_members(cds, cd)
{
BB* sn = info -> Start_Node(cd);
if (sn)
{
fprintf(file, " BB%d ==> BB%d ; ",
BB_id(cd), BB_id(sn));
}
}
fprintf(file, "\n");
}
}
}
void
IF_CONV_AREA::Print_IR(FILE *file)
{
fprintf(file,
"\nIF_CONV_AREA_%d:========================\n",
Area_Label());
BB_CONTAINER& bbs = _included_blocks;
BB_CONTAINER::iterator bb_iter;
BB *block;
for (bb_iter = bbs.begin();
bb_iter != bbs.end();
bb_iter++)
{
block = *bb_iter;
Print_BB (block);
}
fprintf(file,"\n");
}
void
CNTL_DEP::Print(FILE* file)
{
BB *block;
fprintf(file, "\n -- control dependence information \n");
FOR_ALL_BB_SET_members(_bb_set, block)
{
BB_SET *set;
BB *bb;
fprintf(file, " ** BB_%d: cds : ", block -> id);
set = (BB_SET*)BB_MAP_Get(_control_dependences, block);
FOR_ALL_BB_SET_members(set, bb)
{
fprintf(file, " BB%d, ", BB_id(bb));
}
fprintf(file, " true edges : ");
set = (BB_SET*)BB_MAP_Get(_true_edges, block);
FOR_ALL_BB_SET_members(set, bb)
{
fprintf(file, " BB%d, ", BB_id(bb));
}
fprintf(file, "\n");
}
}
| 33.104826 | 99 | 0.510645 | sharugupta |
bd669e7b9abd96dc688d8060947ff6c18765c7c6 | 2,271 | hh | C++ | src/opbox/ops/OpHelpers.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-01-25T21:21:07.000Z | 2021-04-29T17:24:00.000Z | src/opbox/ops/OpHelpers.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 8 | 2018-10-09T14:35:30.000Z | 2020-09-30T20:09:42.000Z | src/opbox/ops/OpHelpers.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-04-23T19:01:36.000Z | 2021-05-11T07:44:55.000Z | // Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#ifndef OPBOX_OPHELPERS_HH
#define OPBOX_OPHELPERS_HH
#include "opbox/common/Types.hh"
#include "opbox/common/Message.hh"
#include "opbox/OpBox.hh"
namespace opbox {
/**
* @brief Designate that network should only notify Op about errors
*/
class ErrorOnlyCallback {
private:
Op *op;
public:
explicit ErrorOnlyCallback(Op *op) : op(op) {}
WaitingType operator()(OpArgs *args) {
if ((args->type >= UpdateType::send_error) && (args->type <= UpdateType::atomic_error)) {
opbox::internal::UpdateOp(op, args);
}
return WaitingType::done_and_destroy;
}
};
/**
* @brief Designate that network should only notify Op about successful events
*/
class SuccessOnlyCallback {
private:
Op *op;
public:
explicit SuccessOnlyCallback(Op *op) : op(op) {}
WaitingType operator()(OpArgs *args) {
if (args->type < UpdateType::timeout) {
opbox::internal::UpdateOp(op, args);
}
return WaitingType::done_and_destroy;
}
};
/**
* @brief Designate that network should only notify Op about unsuccessful events
*/
class UnsuccessfulOnlyCallback {
private:
Op *op;
public:
explicit UnsuccessfulOnlyCallback(Op *op) : op(op) {}
WaitingType operator()(OpArgs *args){
if (args->type >= UpdateType::timeout) {
opbox::internal::UpdateOp(op, args);
}
return WaitingType::done_and_destroy;
}
};
/**
* @brief Designate that network should only notify Op about timeout events
*/
class TimeoutOnlyCallback {
private:
Op *op;
public:
explicit TimeoutOnlyCallback(Op *op) : op(op) {}
WaitingType operator()(OpArgs *args) {
if (args->type == UpdateType::timeout) {
opbox::internal::UpdateOp(op, args);
}
return WaitingType::done_and_destroy;
}
};
/**
* @brief Designate that network should notify Op about all events
*/
class AllEventsCallback {
private:
Op *op;
public:
explicit AllEventsCallback(Op *op) : op(op) {}
WaitingType operator()(OpArgs *args) {
opbox::internal::UpdateOp(op, args);
return WaitingType::done_and_destroy;
}
};
}
#endif // OPBOX_OPHELPERS_HH
| 23.65625 | 93 | 0.696169 | faodel |
bd6cbb970402b0aee3778775d4503e5743662c84 | 2,065 | cpp | C++ | stat01.cpp | DTL2020/stat01 | 5c9ec775071f234f062d23d6434649a0a48d92f5 | [
"MIT"
] | null | null | null | stat01.cpp | DTL2020/stat01 | 5c9ec775071f234f062d23d6434649a0a48d92f5 | [
"MIT"
] | null | null | null | stat01.cpp | DTL2020/stat01 | 5c9ec775071f234f062d23d6434649a0a48d92f5 | [
"MIT"
] | null | null | null | // stat01.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include "math.h"
int ArrSamples[10] = { 52, 46, 54, 20, 50, 48, 51, 53, 45, 50 };
int ArrSADs[10][10] = {};
int ArrOut[10] = {};
int VectMinSumSADs[10] = {};
int iVectIncludedSamples[10] = {};
int thSAD = 5;
int main()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
ArrSADs[i][j] = abs(ArrSamples[i] - ArrSamples[j]);
}
}
//calc vect min sums sads
for (int i = 0; i < 10; i++)
{
int minsunsads = 0;
for (int j = 0; j < 10; j++)
{
minsunsads += ArrSADs[i][j];
}
VectMinSumSADs[i] = minsunsads;
}
int idx_minsad = 0;
int minsumsads = 10e10;
for (int i = 0; i < 10; i++)
{
if (VectMinSumSADs[i] < minsumsads)
{
minsumsads = VectMinSumSADs[i];
idx_minsad = i;
}
}
for (int i = 0; i < 10; i++)
{
if (ArrSADs[idx_minsad][i] < thSAD )
{
iVectIncludedSamples[i] = 1;
}
else
{
iVectIncludedSamples[i] = 0;
}
}
//calc output
for (int i = 0; i < 10; i++)
{
float fMidval2 = 0;
int cnt = 0;
if (iVectIncludedSamples[i] == 0) // skip proc
{
ArrOut[i] = ArrSamples[i];
continue;
}
for (int j = 0; j < 10; j++)
{
if ((iVectIncludedSamples[j] != 0) || (ArrSADs[i][j] < thSAD))
{
fMidval2 += ArrSamples[j];
cnt++;
}
else
if (j == i)
{
fMidval2 += ArrSamples[j];
cnt++;
}
/* if (ArrSADs[i][j] < thSAD)
{
fMidval2 += ArrSamples[j];
cnt++;
}*/
}
fMidval2 /= cnt;
ArrOut[i] = round(fMidval2);
}
// calc psnr
float fMid_val = 0;
for (int i = 0; i < 10; i++)
{
fMid_val += ArrSamples[i];
}
fMid_val /= 10;
float fNoise = 0;
for(int i=0; i<10; i++)
{
fNoise += (ArrOut[i] - fMid_val)*(ArrOut[i] - fMid_val);
}
fNoise /= 10;
float fpsnr = 10e10;
if (fNoise != 0)
{
fpsnr = fMid_val* fMid_val / fNoise;
}
int idbr = 0;
}
| 15.884615 | 97 | 0.498789 | DTL2020 |
bd71aae4ecfcdd068a0e2da125a0653a56d85402 | 1,592 | cpp | C++ | Windows/IniReader.cpp | cas-nctu/multispec | 0bc840bdb073b5feaeec650c2da762cfa34ee37d | [
"Apache-2.0"
] | 11 | 2020-03-10T02:06:00.000Z | 2022-02-17T19:59:50.000Z | Windows/IniReader.cpp | cas-nctu/multispec | 0bc840bdb073b5feaeec650c2da762cfa34ee37d | [
"Apache-2.0"
] | null | null | null | Windows/IniReader.cpp | cas-nctu/multispec | 0bc840bdb073b5feaeec650c2da762cfa34ee37d | [
"Apache-2.0"
] | 5 | 2020-05-30T00:59:22.000Z | 2021-12-06T01:37:05.000Z | #include "IniReader.h"
#include <iostream>
#include <Windows.h>
CIniReader::CIniReader(char* szFileName)
{
memset(m_szFileName, 0x00, 255);
memcpy(m_szFileName, szFileName, strlen(szFileName));
}
int CIniReader::ReadInteger(char* szSection, char* szKey, int iDefaultValue)
{
int iResult = GetPrivateProfileInt((LPCWSTR)szSection, (LPCWSTR)szKey, iDefaultValue, (LPCWSTR)m_szFileName);
return iResult;
}
float CIniReader::ReadFloat(char* szSection, char* szKey, float fltDefaultValue)
{
char szResult[255];
char szDefault[255];
float fltResult;
sprintf_s(szDefault, "%f",fltDefaultValue);
GetPrivateProfileString((LPCWSTR)szSection, (LPCWSTR)szKey, (LPCWSTR)szDefault, (LPWSTR)szResult, 255, (LPCWSTR)m_szFileName);
fltResult = (float)atof(szResult);
return fltResult;
}
bool CIniReader::ReadBoolean(char* szSection, char* szKey, bool bolDefaultValue)
{
char szResult[255];
char szDefault[255];
bool bolResult;
sprintf_s(szDefault, "%s", bolDefaultValue? "True" : "False");
GetPrivateProfileString((LPCWSTR)szSection, (LPCWSTR)szKey, (LPCWSTR)szDefault, (LPWSTR)szResult, 255, (LPCWSTR)m_szFileName);
bolResult = (strcmp(szResult, "True") == 0 ||
strcmp(szResult, "true") == 0) ? true : false;
return bolResult;
}
char* CIniReader::ReadString(char* szSection, char* szKey, const char* szDefaultValue)
{
char* szResult = new char[255];
memset(szResult, 0x00, 255);
GetPrivateProfileString((LPCWSTR)szSection, (LPCWSTR)szKey,
(LPCWSTR)szDefaultValue, (LPWSTR)szResult, 255, (LPCWSTR)m_szFileName);
return szResult;
} | 37.023256 | 130 | 0.731784 | cas-nctu |
bd76eaf5676f3498c1a498bc055beb34dee5bac1 | 7,252 | cpp | C++ | test/range/test-element_types.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | test/range/test-element_types.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | test/range/test-element_types.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2014, 2015 Rogier van Dalen.
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.
*/
#define BOOST_TEST_MODULE test_range_element_types
#include "utility/test/boost_unit_test.hpp"
#include "range/element_types.hpp"
#include <type_traits>
#include <list>
#include <tuple>
#include "meta/vector.hpp"
#include "range/std.hpp"
#include "range/take.hpp"
BOOST_AUTO_TEST_SUITE(test_range_element_types)
BOOST_AUTO_TEST_CASE (test_element_types_contents) {
{
typedef std::tuple<> tuple;
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple>>::type,
meta::vector<>>::value, "");
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple &>>::type,
meta::vector<>>::value, "");
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple const &>>::type,
meta::vector<>>::value, "");
}
{
typedef std::tuple <int> tuple;
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple>>::type,
meta::vector <int &&>>::value, "");
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple &>>::type,
meta::vector <int &>>::value, "");
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple const &>>::type,
meta::vector <int const &>>::value, "");
}
{
typedef std::tuple <int, int, int const &, float> tuple;
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple>>::type,
meta::vector <int &&, int &&, int const &, float &&>
>::value, "");
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple &>>::type,
meta::vector <int &, int &, int const &, float &>
>::value, "");
static_assert (std::is_same <
meta::as_vector <range::element_types <tuple const &>>::type,
meta::vector <
int const &, int const &, int const &, float const &>
>::value, "");
}
}
BOOST_AUTO_TEST_CASE (test_element_types_behaviour) {
{
typedef meta::as_vector <range::element_types <std::tuple<>>>::type
types;
static_assert (meta::empty <types>::value, "");
static_assert (meta::size <types>::value == 0, "");
static_assert (meta::empty <direction::front, types>::value, "");
static_assert (meta::size <direction::front, types>::value == 0, "");
static_assert (meta::empty <direction::back, types>::value, "");
static_assert (meta::size <direction::back, types>::value == 0, "");
}
{
typedef range::element_types <std::tuple <float>> types;
static_assert (!meta::empty <types>::value, "");
static_assert (meta::size <types>::value == 1, "");
static_assert (!meta::empty <direction::front, types>::value, "");
static_assert (meta::size <direction::front, types>::value == 1, "");
static_assert (!meta::empty <direction::back, types>::value, "");
static_assert (meta::size <direction::back, types>::value == 1, "");
static_assert (std::is_same <
meta::first <types>::type, float &&>::value, "");
static_assert (std::is_same <
meta::first <direction::front, types>::type, float &&>::value, "");
static_assert (std::is_same <
meta::first <direction::back, types>::type, float &&>::value, "");
static_assert (meta::empty <meta::drop <types>::type>::value, "");
static_assert (meta::empty <
meta::drop <direction::front, types>::type>::value, "");
static_assert (meta::empty <
meta::drop <direction::back, types>::type>::value, "");
}
{
typedef range::element_types <std::tuple <float, bool, int>> types;
static_assert (!meta::empty <types>::value, "");
static_assert (meta::size <types>::value == 3, "");
static_assert (!meta::empty <direction::front, types>::value, "");
static_assert (meta::size <direction::front, types>::value == 3, "");
static_assert (!meta::empty <direction::back, types>::value, "");
static_assert (meta::size <direction::back, types>::value == 3, "");
static_assert (std::is_same <
meta::first <types>::type, float &&>::value, "");
static_assert (std::is_same <
meta::first <direction::front, types>::type, float &&>::value, "");
static_assert (std::is_same <
meta::first <direction::back, types>::type, int &&>::value, "");
static_assert (!meta::empty <meta::drop <types>::type>::value, "");
static_assert (meta::empty <meta::drop <
direction::front, rime::size_t <3>, types>::type>::value, "");
static_assert (std::is_same <
meta::first <meta::drop <types>::type>::type, bool &&>::value, "");
}
}
template <class ... Types> struct show_types;
// Used on a homogeneous type, element_types becomes an infinite meta-range.
BOOST_AUTO_TEST_CASE (test_element_types_homogeneous) {
{
typedef range::element_types <std::vector <int> &> types;
static_assert (std::is_same <
meta::first <types>::type, int &>::value, "");
static_assert (std::is_same <
meta::first <meta::drop <types>::type>::type, int &>::value, "");
static_assert (std::is_same <
meta::first <meta::drop <rime::size_t <34>, types>::type>::type,
int &>::value, "");
// After one call to "drop", the range is turned into a view.
typedef meta::drop <types>::type view;
static_assert (std::is_same <meta::drop <view>::type, view>::value, "");
// It then becomes heterogeneous.
static_assert (std::is_same <
meta::drop <view>::type, view>::value, "");
static_assert (std::is_same <
meta::drop <rime::size_t <3>, view>::type, view>::value, "");
}
{
std::list <int> l;
auto v = range::take (l, rime::size_t <2>());
typedef range::element_types <decltype (v)> types;
static_assert (std::is_same <
meta::first <types>::type, int &>::value, "");
static_assert (std::is_same <
meta::first <meta::drop <types>::type>::type, int &>::value, "");
static_assert (!meta::empty <types>::value, "");
static_assert (!meta::empty <meta::drop <types>::type>::value, "");
static_assert (meta::empty <
meta::drop <meta::drop <types>::type>::type>::value, "");
}
}
BOOST_AUTO_TEST_SUITE_END()
| 37.381443 | 80 | 0.58246 | rogiervd |
bd79d91c0558c2941b64895d1855dc3838658d2c | 6,650 | cpp | C++ | 4 course/info_protection/lab07/Widget.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 4 course/info_protection/lab07/Widget.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 4 course/info_protection/lab07/Widget.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | #include "Widget.h"
#include "./ui_Widget.h"
#include <cmath>
#include <algorithm>
#include <random>
#include <QFileDialog>
#include <QMessageBox>
using namespace std;
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->prepareProbabilityTable();
this->prepareKeys();
}
Widget::~Widget()
{
delete ui;
}
void Widget::prepareKeys()
{
// Генерируем массив из 1000 чисел.
const uint16_t numberSize = 1000;
vector<uint16_t> numbers(numberSize);
iota(numbers.begin(), numbers.end(), 0);
// Перемешиваем его.
mt19937 mt (mt19937::result_type(time(nullptr)));
shuffle(numbers.begin(), numbers.end(), mt);
// Настраиваем таблицу.
ui->tableWidget->horizontalHeader()->setMinimumSectionSize(headerSectionWidth);
ui->tableWidget->horizontalHeader()->setDefaultSectionSize(headerSectionWidth);
ui->tableWidget->setRowCount(maxRowCount);
auto numberIt = numbers.begin();
// Для каждой буквы алфавита сгенерируем числа.
auto columnCount = ALPHABET.length();
for (int i = 0; i < columnCount; ++i)
{
QChar c = ALPHABET[i];
ui->tableWidget->insertColumn(i);
ui->tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(QString(c)));
// Список строк в соответствии с вероятностью появления символа c.
auto rowCount = probabilityTable[c];
for (int j = 0; j < rowCount; ++j)
{
// Сохраняем омофон в таблицу.
auto homophone = QString::number(*numberIt++).rightJustified(3, '0');
ui->tableWidget->setItem(j, i, new QTableWidgetItem(homophone));
// Сохраним в специальных контейнерах соответствие между буквой и омофоном.
// Омофоны по букве.
homophonesBySymbol[c].push_back(homophone);
// И буква по омофону.
symbolByHomophone[homophone] = c;
}
}
}
void Widget::prepareProbabilityTable()
{
probabilityTable[' '] = 146;
probabilityTable[L'О'] = 94;
probabilityTable[L'Е'] = 71;
probabilityTable[L'А'] = 69;
probabilityTable[L'И'] = 64;
probabilityTable[L'Н'] = 57;
probabilityTable[L'Т'] = 54;
probabilityTable[L'С'] = 46;
probabilityTable[L'Р'] = 42;
probabilityTable[L'В'] = 38;
probabilityTable[L'Л'] = 39;
probabilityTable[L'К'] = 29;
probabilityTable[L'М'] = 27;
probabilityTable[L'Д'] = 24;
probabilityTable[L'П'] = 26;
probabilityTable[L'У'] = 23;
probabilityTable[L'Я'] = 17;
probabilityTable[L'Ы'] = 15;
probabilityTable[L'З'] = 16;
probabilityTable[L'Ъ'] = 1;
probabilityTable[L'Ь'] = 13;
probabilityTable[L'Б'] = 13;
probabilityTable[L'Г'] = 14;
probabilityTable[L'Ч'] = 12;
probabilityTable[L'Й'] = 10;
probabilityTable[L'Х'] = 8;
probabilityTable[L'Ж'] = 7;
probabilityTable[L'Ю'] = 5;
probabilityTable[L'Ш'] = 6;
probabilityTable[L'Ц'] = 5;
probabilityTable[L'Щ'] = 4;
probabilityTable[L'Э'] = 2;
probabilityTable[L'Ф'] = 3;
}
Widget::Text Widget::readFromFile(const QString &filename)
{
Text text;
QFile file(filename);
if (file.open(QIODevice::ReadOnly))
{
while (!file.atEnd())
{
QString buffer = file.readLine();
text.push_back(buffer);
}
}
else
{
QMessageBox::warning(this, "Ошибка!", "Не удалось открыть файл " + filename);
}
file.close();
return text;
}
void Widget::saveToFile(const Text &text, const QString &filename)
{
if (filename.length() <= 0)
{
return;
}
QFile file(filename);
if (file.open(QIODevice::WriteOnly))
{
for (auto &line : text)
{
file.write(line.toUtf8());
file.write("\n");
}
}
else
{
QMessageBox::warning(this, "Ошибка!", "Не удалось сохранить файл " + filename);
}
file.close();
}
void Widget::openFileOnSystem(const QString &filename) const
{
#ifdef WIN32
std::wstring s = L"start \"\" \"" + filename.toStdWString() + L"\"";
_wsystem(s.c_str());
#else
auto s = "open \"" + filename.toStdString() + "\"";
system(s.c_str());
#endif
}
Widget::Text Widget::crypt(const Text &text) const
{
mt19937 mt (mt19937::result_type(time(nullptr)));
Text res;
res.reserve(text.size());
for (const auto &origLine : text)
{
QString newLine;
newLine.reserve(origLine.length() * 3);
for (QChar c : origLine)
{
auto homophones = homophonesBySymbol[ c.isUpper() ? c : c.toUpper() ];
uniform_int_distribution<uint16_t> dist(0, uint16_t(homophones.size()-1));
newLine.push_back( homophones[dist(mt)] );
}
res.push_back( newLine );
}
return res;
}
Widget::Text Widget::decrypt(const Text &text) const
{
Text res;
res.reserve(text.size());
for (const auto &origLine : text)
{
QString newLine;
newLine.reserve(origLine.length() / 3);
auto len = origLine.length();
for (qsizetype i = 0; i < len; i += 3)
{
auto homophone = origLine.mid(i, 3);
auto decryptedChar = symbolByHomophone[homophone];
newLine.push_back( decryptedChar );
}
res.push_back( newLine );
}
return res;
}
void Widget::on_pushButton_openOrigFile_clicked()
{
this->origFileName = QFileDialog::getOpenFileName(this, "Открыть файл", "");
if (this->origFileName.length() > 0)
{
ui->lineEdit_origFilePath->setText(this->origFileName);
}
}
void Widget::on_pushButton_saveOutFile_clicked()
{
this->outFileName = QFileDialog::getSaveFileName(this, "Сохранить файл", "");
if (this->outFileName.length() > 0)
{
// указываем путь
ui->lineEdit_outFilePath->setText(this->outFileName);
}
}
void Widget::on_pushButton_crypt_clicked()
{
const auto text = this->readFromFile(this->origFileName);
if (text.length())
{
this->saveToFile(this->crypt(text), this->outFileName);
this->openFileOnSystem(this->outFileName);
}
}
void Widget::on_pushButton_decrypt_clicked()
{
const auto text = this->readFromFile(this->origFileName);
if (text.length())
{
this->saveToFile(this->decrypt(text), this->outFileName);
this->openFileOnSystem(this->outFileName);
}
}
void Widget::on_lineEdit_outFilePath_textEdited(const QString &arg1)
{
this->outFileName = arg1;
}
void Widget::on_lineEdit_origFilePath_textEdited(const QString &arg1)
{
this->origFileName = arg1;
}
| 24.906367 | 87 | 0.614586 | SgAkErRu |
bd7c798477d19239b38f3ba1e89147f3289c6ad2 | 1,963 | cpp | C++ | sem/4ex/work1/4ex2Pp.cpp | ruska112/infTasks | db3bf563376dac435f5fed74e03bc3592d67c46f | [
"MIT"
] | null | null | null | sem/4ex/work1/4ex2Pp.cpp | ruska112/infTasks | db3bf563376dac435f5fed74e03bc3592d67c46f | [
"MIT"
] | 1 | 2021-11-16T11:17:37.000Z | 2021-11-16T11:44:54.000Z | sem/4ex/work1/4ex2Pp.cpp | ruska112/infTasks | db3bf563376dac435f5fed74e03bc3592d67c46f | [
"MIT"
] | null | null | null | #include <iostream>
const int maxRow = 128;
const int maxCol = 128;
int matrixRepacer (double *a, int n, int m) {
int result = 0;
int i, j;
int negColCount = 0;
int posRowCount = 0;
double rowSum = 0;
if ( n > 0 && n < maxRow && m > 0 && m < maxCol ) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (a[j*8 + i] < 0) {
negColCount++;
}
rowSum += a[i*8 + j];
}
if (rowSum > 0) {
posRowCount++;
}
rowSum = 0;
}
if (negColCount > posRowCount) {
result = 1;
} else if (posRowCount > negColCount) {
result = 2;
} else {
result = 3;
}
}
return result;
}
int main() {
int n, m;
int i, j;
int funcRes;
do {
system("clear");
printf("Enter count of row: ");
scanf("%d", &n);
} while (n <= 0 || n > maxRow);
do {
system("clear");
printf("Enter count of column: ");
scanf("%d", &m);
} while (m <= 0 || m > maxCol);
double* a = new double [n * m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("[%d][%d]", i, j);
scanf("%lf", &a[i*8 + j]);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("%3.1lf ", a[i*8 + j]);
}
printf("\n");
}
funcRes = matrixRepacer(a, n, m);
if (funcRes == 1) {
printf("Column with negative element greater than row with positive sum\n");
} else if (funcRes == 2) {
printf("Column with negative element less than row with positive sum\n");
} else if (funcRes) {
printf("Column with negative element equal with row with positive sum\n");
} else {
printf("\nError\n");
}
delete[] a;
return 0;
}
| 20.882979 | 84 | 0.417219 | ruska112 |
bd7fbf79e4f67ceb44f81e36a7a4aa0edcc97f06 | 1,037 | cpp | C++ | RLSimion/Lib/actor-cacla.cpp | xcillero001/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | 1 | 2019-02-21T10:40:28.000Z | 2019-02-21T10:40:28.000Z | RLSimion/Lib/actor-cacla.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | RLSimion/Lib/actor-cacla.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | #include "actor.h"
#include "vfa.h"
#include "policy.h"
#include "policy-learner.h"
#include "../Common/named-var-set.h"
#include "features.h"
#include "etraces.h"
#include "config.h"
#include "parameters-numeric.h"
#include "app.h"
CACLALearner::CACLALearner(ConfigNode* pConfigNode): PolicyLearner(pConfigNode)
{
m_pStateFeatures = new FeatureList("Actor/s");
m_pAlpha = CHILD_OBJECT_FACTORY<NumericValue>(pConfigNode, "Alpha", "Learning gain [0..1]");
}
CACLALearner::~CACLALearner()
{
delete m_pStateFeatures;
}
void CACLALearner::update(const State *s, const Action *a, const State *s_p, double r, double td)
{
double lastNoise;
double alpha;
//CACLA (van Hasselt)
//if delta>0: theta= theta + alpha*(lastNoise)*phi_pi(s)
if (td > 0.0)
{
alpha = m_pAlpha->get();
if (alpha != 0.0)
{
m_pPolicy->getFeatures(s, m_pStateFeatures);
lastNoise = a->get(m_pPolicy->getOutputAction()) - m_pPolicy->getDeterministicOutput(m_pStateFeatures);
m_pPolicy->addFeatures(m_pStateFeatures, alpha*lastNoise);
}
}
}
| 23.044444 | 106 | 0.714561 | xcillero001 |
bd8095816328e10b87f8d4df9e155e24214d5ad3 | 1,178 | cc | C++ | glacier/channel.cc | iceice/Glacier | 779082cc197f753fb2feff63ac8fbe3f5512828c | [
"MIT"
] | 2 | 2020-02-05T04:08:07.000Z | 2020-08-15T01:57:41.000Z | glacier/channel.cc | iceice/Glacier | 779082cc197f753fb2feff63ac8fbe3f5512828c | [
"MIT"
] | null | null | null | glacier/channel.cc | iceice/Glacier | 779082cc197f753fb2feff63ac8fbe3f5512828c | [
"MIT"
] | null | null | null | #include "glacier/channel.h"
#include <sys/epoll.h>
#include "glacier/base/logging.h"
Channel::Channel(EventLoop *loop)
: loop_(loop), fd_(0), events_(0), revents_(0), lastevents_(0) {}
Channel::Channel(EventLoop *loop, int fd)
: loop_(loop), fd_(fd), events_(0), revents_(0), lastevents_(0) {}
Channel::~Channel() {}
void Channel::handleEvents() {
events_ = 0;
if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) {
// 文件描述符被挂断,并且文件描述符不可读
return;
}
if (revents_ & EPOLLERR) {
// 文件描述符发生错误
try {
errorCallback_();
} catch (const std::bad_function_call &e) {
LOG_ERROR << "errorCallback_";
}
return;
}
if (revents_ & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) {
// 文件描述符可读,或有紧急的数据可读,或对端断开连接
try {
readCallback_();
} catch (const std::bad_function_call &e) {
LOG_ERROR << "errorCallback_";
}
}
if (revents_ & EPOLLOUT) {
// 文件描述符可写
try {
writeCallback_();
} catch (const std::bad_function_call &e) {
LOG_ERROR << "errorCallback_";
}
}
// 更新events
try {
connCallback_();
} catch (const std::bad_function_call &e) {
LOG_ERROR << "errorCallback_";
}
} | 24.040816 | 70 | 0.60781 | iceice |
bd8111c165e2e9957726dbc6a112caae08e73659 | 1,324 | cpp | C++ | aws-cpp-sdk-ecr/source/model/ReplicationDestination.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-ecr/source/model/ReplicationDestination.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ecr/source/model/ReplicationDestination.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ecr/model/ReplicationDestination.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ECR
{
namespace Model
{
ReplicationDestination::ReplicationDestination() :
m_regionHasBeenSet(false),
m_registryIdHasBeenSet(false)
{
}
ReplicationDestination::ReplicationDestination(JsonView jsonValue) :
m_regionHasBeenSet(false),
m_registryIdHasBeenSet(false)
{
*this = jsonValue;
}
ReplicationDestination& ReplicationDestination::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("region"))
{
m_region = jsonValue.GetString("region");
m_regionHasBeenSet = true;
}
if(jsonValue.ValueExists("registryId"))
{
m_registryId = jsonValue.GetString("registryId");
m_registryIdHasBeenSet = true;
}
return *this;
}
JsonValue ReplicationDestination::Jsonize() const
{
JsonValue payload;
if(m_regionHasBeenSet)
{
payload.WithString("region", m_region);
}
if(m_registryIdHasBeenSet)
{
payload.WithString("registryId", m_registryId);
}
return payload;
}
} // namespace Model
} // namespace ECR
} // namespace Aws
| 17.653333 | 78 | 0.726586 | perfectrecall |
bd831a3528c2092c4cd2450efb5bba7e57838dac | 700 | cpp | C++ | Source/Core/FileFormat/TIFF/Tag.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 42 | 2015-07-24T23:05:07.000Z | 2022-03-16T01:31:04.000Z | Source/Core/FileFormat/TIFF/Tag.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 4 | 2015-03-17T05:42:49.000Z | 2020-08-09T15:21:45.000Z | Source/Core/FileFormat/TIFF/Tag.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 29 | 2015-01-03T05:56:32.000Z | 2021-10-05T15:28:33.000Z | /****************************************************************************/
/**
* @file Tag.cpp
* @author Naohisa Sakamoto
*/
/****************************************************************************/
#include "Tag.h"
#include <kvs/Type>
#include <string>
namespace kvs
{
namespace tiff
{
Tag::Tag():
m_id( 0 ),
m_name( "" )
{
}
Tag::Tag( const kvs::UInt16 id, const std::string& name ):
m_id( id ),
m_name( name )
{
}
Tag::Tag( const Tag& tag ):
m_id( tag.m_id ),
m_name( tag.m_name )
{
}
Tag& Tag::operator = ( const Tag& tag )
{
m_id = tag.m_id;
m_name = tag.m_name;
return *this;
}
} // end of namespace tiff
} // end of namespace kvs
| 15.217391 | 78 | 0.437143 | X1aoyueyue |
bd8cb4c8d122a1aebe81e79a9f19b7fe39a5a6a8 | 8,467 | cpp | C++ | src/apps/ojph_expand/ojph_expand.cpp | jpambrun/OpenJPH | 9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030 | [
"BSD-2-Clause"
] | null | null | null | src/apps/ojph_expand/ojph_expand.cpp | jpambrun/OpenJPH | 9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030 | [
"BSD-2-Clause"
] | null | null | null | src/apps/ojph_expand/ojph_expand.cpp | jpambrun/OpenJPH | 9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030 | [
"BSD-2-Clause"
] | null | null | null | /****************************************************************************/
// This software is released under the 2-Clause BSD license, included
// below.
//
// Copyright (c) 2019, Aous Naman
// Copyright (c) 2019, Kakadu Software Pty Ltd, Australia
// Copyright (c) 2019, The University of New South Wales, Australia
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/****************************************************************************/
// This file is part of the OpenJPH software implementation.
// File: ojph_expand.cpp
// Author: Aous Naman
// Date: 28 August 2019
/****************************************************************************/
#include <ctime>
#include <iostream>
#include <cstdlib>
#include "ojph_arg.h"
#include "ojph_mem.h"
#include "ojph_img_io.h"
#include "ojph_file.h"
#include "ojph_codestream.h"
#include "ojph_params.h"
#include "ojph_message.h"
//////////////////////////////////////////////////////////////////////////////
bool get_arguments(int argc, char *argv[],
char *&input_filename, char *&output_filename)
{
ojph::cli_interpreter interpreter;
interpreter.init(argc, argv);
interpreter.reinterpret("-i", input_filename);
interpreter.reinterpret("-o", output_filename);
if (interpreter.is_exhausted() == false) {
printf("The following arguments were not interpreted:\n");
ojph::argument t = interpreter.get_argument_zero();
t = interpreter.get_next_avail_argument(t);
while (t.is_valid()) {
printf("%s\n", t.arg);
t = interpreter.get_next_avail_argument(t);
}
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
const char *get_file_extension(const char *filename)
{
size_t len = strlen(filename);
return filename + ojph_max(0, len - 4);
}
/////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
char *input_filename = NULL;
char *output_filename = NULL;
if (argc <= 1) {
std::cout <<
"\nThe following arguments are necessary:\n"
" -i input file name\n"
" -o output file name (either pgm, ppm, or yuv)\n\n"
;
return -1;
}
if (!get_arguments(argc, argv, input_filename, output_filename))
{
return -1;
}
clock_t begin = clock();
try {
ojph::j2c_infile j2c_file;
j2c_file.open(input_filename);
ojph::codestream codestream;
ojph::ppm_out ppm;
ojph::yuv_out yuv;
ojph::image_out_base *base = NULL;
const char *v = get_file_extension(output_filename);
if (v)
{
codestream.read_headers(&j2c_file);
ojph::param_siz_t siz = codestream.access_siz();
if (strncmp(".pgm", v, 4) == 0)
{
if (siz.get_num_components() != 1)
OJPH_ERROR(0x020000001,
"The file has more than one color component, but .pgm can "
"contain only on color component\n");
ppm.configure(siz.get_image_extent().x - siz.get_image_offset().x,
siz.get_image_extent().y - siz.get_image_offset().y,
siz.get_num_components(), siz.get_bit_depth(0));
ppm.open(output_filename);
base = &ppm;
}
else if (strncmp(".ppm", v, 4) == 0)
{
codestream.set_planar(false);
ojph::param_siz_t siz = codestream.access_siz();
if (siz.get_num_components() != 3)
OJPH_ERROR(0x020000002,
"The file has %d color components; this cannot be saved to"
" a .ppm file\n", siz.get_num_components());
bool all_same = true;
ojph::point p = siz.get_downsampling(0);
for (int i = 1; i < siz.get_num_components(); ++i)
{
ojph::point p1 = siz.get_downsampling(i);
all_same = all_same && (p1.x == p.x) && (p1.y == p.y);
}
if (!all_same)
OJPH_ERROR(0x020000003,
"To save an image to ppm, all the components must have the "
"downsampling ratio\n");
ppm.configure(siz.get_image_extent().x - siz.get_image_offset().x,
siz.get_image_extent().y - siz.get_image_offset().y,
siz.get_num_components(), siz.get_bit_depth(0));
ppm.open(output_filename);
base = &ppm;
}
else if (strncmp(".yuv", v, 4) == 0)
{
codestream.set_planar(true);
ojph::param_siz_t siz = codestream.access_siz();
if (siz.get_num_components() != 3 && siz.get_num_components() != 1)
OJPH_ERROR(0x020000004,
"The file has %d color components; this cannot be saved to"
" a .yuv file\n", siz.get_num_components());
ojph::param_cod_t cod = codestream.access_cod();
if (cod.is_using_color_transform())
OJPH_ERROR(0x020000005,
"The current implementation of yuv file object does not "
"support saving a file when conversion from yuv to rgb is needed; "
"In any case, this is not the normal usage of a yuv file");
ojph::point points[3];
int max_bit_depth = 0;
for (int i = 0; i < siz.get_num_components(); ++i)
{
points[i] = siz.get_downsampling(i);
max_bit_depth = ojph_max(max_bit_depth, siz.get_bit_depth(i));
}
codestream.set_planar(true);
yuv.configure(siz.get_image_extent().x, siz.get_image_offset().x,
max_bit_depth, siz.get_num_components(), points);
yuv.open(output_filename);
base = &yuv;
}
else
OJPH_ERROR(0x020000006,
"unknown output file extension; only (pgm, ppm, and yuv) are"
" suppoted\n");
}
else
OJPH_ERROR(0x020000007,
"Please supply a proper output filename with a proper three-letter"
" extension\n");
codestream.create();
if (codestream.is_planar())
{
ojph::param_siz_t siz = codestream.access_siz();
for (int c = 0; c < siz.get_num_components(); ++c)
{
ojph::point p = siz.get_downsampling(c);
int height = ojph_div_ceil(siz.get_image_extent().y, p.y)
- ojph_div_ceil(siz.get_image_offset().y, p.y);
for (int i = height; i > 0; --i)
{
int comp_num;
ojph::line_buf *line = codestream.pull(comp_num);
assert(comp_num == c);
base->write(line, comp_num);
}
}
}
else
{
ojph::param_siz_t siz = codestream.access_siz();
int height = siz.get_image_extent().y - siz.get_image_offset().y;
for (int i = 0; i < height; ++i)
{
for (int c = 0; c < siz.get_num_components(); ++c)
{
int comp_num;
ojph::line_buf *line = codestream.pull(comp_num);
assert(comp_num == c);
base->write(line, comp_num);
}
}
}
base->close();
codestream.close();
}
catch (const std::exception& e)
{
const char *p = e.what();
if (strncmp(p, "ojph error", 10) != 0)
printf("%s\n", p);
exit(-1);
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
printf("Elapsed time = %f\n", elapsed_secs);
return 0;
}
| 34.70082 | 79 | 0.590292 | jpambrun |
bd922daaccc417ac15d3a99e42e68c33da917872 | 5,404 | cpp | C++ | Libs/Widgets/Testing/Cpp/ctkMenuComboBoxEventTranslatorPlayerTest1.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 515 | 2015-01-13T05:42:10.000Z | 2022-03-29T03:10:01.000Z | Libs/Widgets/Testing/Cpp/ctkMenuComboBoxEventTranslatorPlayerTest1.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 425 | 2015-01-06T05:28:38.000Z | 2022-03-08T19:42:18.000Z | Libs/Widgets/Testing/Cpp/ctkMenuComboBoxEventTranslatorPlayerTest1.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 341 | 2015-01-08T06:18:17.000Z | 2022-03-29T21:47:49.000Z | /*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
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.
=========================================================================*/
// Qt includes
#include <QAction>
#include <QApplication>
#include <QDebug>
#include <QSignalSpy>
#include <QStandardItemModel>
#include <QTimer>
#include <QTreeView>
// CTK includes
#include "ctkCallback.h"
#include "ctkConfig.h"
#include "ctkMenuComboBox.h"
#include "ctkMenuComboBoxEventPlayer.h"
#include "ctkMenuComboBoxEventTranslator.h"
#include "ctkEventTranslatorPlayerWidget.h"
// QtTesting includes
#include "pqTestUtility.h"
// STD includes
#include <cstdlib>
#include <iostream>
namespace
{
QSignalSpy* Spy1;
QSignalSpy* Spy2;
QSignalSpy* Spy3;
QSignalSpy* Spy4;
QSignalSpy* Spy5;
QSignalSpy* Spy6;
QSignalSpy* Spy7;
QSignalSpy* Spy8;
//-----------------------------------------------------------------------------
void checkFinalWidgetState(void* data)
{
ctkMenuComboBox* widget = reinterpret_cast<ctkMenuComboBox*>(data);
Q_UNUSED(widget);
CTKCOMPARE(Spy1->count(), 2);
CTKCOMPARE(Spy2->count(), 2);
CTKCOMPARE(Spy3->count(), 2);
CTKCOMPARE(Spy4->count(), 2);
}
//-----------------------------------------------------------------------------
void checkFinalWidgetState2(void* data)
{
ctkMenuComboBox* widget = reinterpret_cast<ctkMenuComboBox*>(data);
Q_UNUSED(widget);
CTKCOMPARE(Spy5->count(), 1);
CTKCOMPARE(Spy6->count(), 1);
CTKCOMPARE(Spy7->count(), 1);
CTKCOMPARE(Spy8->count(), 1);
}
}
//-----------------------------------------------------------------------------
int ctkMenuComboBoxEventTranslatorPlayerTest1(int argc, char * argv [] )
{
QApplication app(argc, argv);
QString xmlDirectory = CTK_SOURCE_DIR "/Libs/Widgets/Testing/Cpp/";
// ------------------------
ctkEventTranslatorPlayerWidget etpWidget;
pqTestUtility* testUtility = new pqTestUtility(&etpWidget);
etpWidget.setTestUtility(testUtility);
etpWidget.addWidgetEventPlayer(new ctkMenuComboBoxEventPlayer);
etpWidget.addWidgetEventTranslator(new ctkMenuComboBoxEventTranslator);
// Test case 1 - default behavior - Test Completer
QWidget* widget = new QWidget(0);
QMenu* menu = new QMenu("File", widget);
QAction* action1 = new QAction("first", widget);
menu->addAction(action1);
QMenu* wizards = new QMenu("Wizards", menu);
menu->addMenu(wizards);
QMenu*informatics = new QMenu("Informatics", menu);
menu->addMenu(informatics);
QAction* action2 = new QAction("extra choice 1", widget);
QAction* action3 = new QAction("extra choice 2", widget);
QAction* action4 = new QAction("extra choice 3", widget);
menu->addAction(action2);
menu->addAction(wizards->menuAction());
menu->addAction(informatics->menuAction());
wizards->addAction(action3);
informatics->addAction(action4);
QSignalSpy spy1(action1, SIGNAL(triggered()));
QSignalSpy spy2(action2, SIGNAL(triggered()));
QSignalSpy spy3(action3, SIGNAL(triggered()));
QSignalSpy spy4(action4, SIGNAL(triggered()));
Spy1 = &spy1;
Spy2 = &spy2;
Spy3 = &spy3;
Spy4 = &spy4;
ctkMenuComboBox* menuComboBox = new ctkMenuComboBox(widget);
menuComboBox->setMenu(menu);
etpWidget.addTestCase(widget,
xmlDirectory + "ctkMenuComboBoxEventTranslatorPlayerTest1.xml",
&checkFinalWidgetState);
// Test case 2 - default behavior - test Menu
QWidget* widget2 = new QWidget(0);
ctkMenuComboBox* menuComboBox2 = new ctkMenuComboBox(widget2);
QMenu* menu2 = new QMenu("File", menuComboBox2);
QAction* action5 = new QAction("first", menu2);
menu2->addAction(action5);
QMenu* wizards2 = new QMenu("Wizards", menu2);
menu2->addMenu(wizards2);
QMenu*informatics2 = new QMenu("Informatics", menu2);
menu2->addMenu(informatics2);
QAction* action6 = new QAction("extra choice 1", menu2);
QAction* action7 = new QAction("extra choice 2", menu2);
QAction* action8 = new QAction("extra choice 3", menu2);
menu2->addAction(action6);
// menu2->addAction(wizards2->menuAction());
// menu2->addAction(informatics2->menuAction());
wizards2->addAction(action7);
informatics2->addAction(action8);
QSignalSpy spy5(action5, SIGNAL(triggered()));
QSignalSpy spy6(action6, SIGNAL(triggered()));
QSignalSpy spy7(action7, SIGNAL(triggered()));
QSignalSpy spy8(action8, SIGNAL(triggered()));
Spy5 = &spy5;
Spy6 = &spy6;
Spy7 = &spy7;
Spy8 = &spy8;
menuComboBox2->setMenu(menu2);
etpWidget.addTestCase(widget2,
xmlDirectory + "ctkMenuComboBoxEventTranslatorPlayerTest2.xml",
&checkFinalWidgetState2);
// ------------------------
if (argc < 2 || QString(argv[1]) != "-I")
{
QTimer::singleShot(0, &etpWidget, SLOT(play()));
}
etpWidget.show();
return app.exec();
}
| 30.531073 | 87 | 0.6547 | kraehlit |
bd940e7c4b6d7610e3e7bab80961b0b6adbb6e7f | 85 | cpp | C++ | src/Luddite/ECS/Reflection.cpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | 1 | 2021-06-03T05:46:46.000Z | 2021-06-03T05:46:46.000Z | src/Luddite/ECS/Reflection.cpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | null | null | null | src/Luddite/ECS/Reflection.cpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | null | null | null | #include "Luddite/ECS/Reflection.hpp"
#include "Luddite/ECS/Modules/Transform3D.hpp"
| 28.333333 | 46 | 0.8 | Aquaticholic |
bd95838fa9cb565302869384616a7dd0189fb56a | 11,570 | cpp | C++ | WinUSBFTDI/WinUSBFTDI-C/EnOceanSample/main.cpp | ahidaka/WinUSB_Collection | 4a8362707272444a11aacb7d869da32a63baa5e8 | [
"Apache-2.0"
] | null | null | null | WinUSBFTDI/WinUSBFTDI-C/EnOceanSample/main.cpp | ahidaka/WinUSB_Collection | 4a8362707272444a11aacb7d869da32a63baa5e8 | [
"Apache-2.0"
] | null | null | null | WinUSBFTDI/WinUSBFTDI-C/EnOceanSample/main.cpp | ahidaka/WinUSB_Collection | 4a8362707272444a11aacb7d869da32a63baa5e8 | [
"Apache-2.0"
] | 4 | 2020-12-13T07:28:40.000Z | 2022-01-18T05:55:05.000Z | #include "pch.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct _eep_data
{
UCHAR ROrg;
UCHAR Func;
UCHAR Type;
USHORT ManID;
}
EEP_DATA, *PEEP_DATA;
enum PacketType
{
Radio = 0x01,
Response = 0x02,
RadioSubTel = 0x03,
Event = 0x04,
CommonCommand = 0x05,
SmartAckCommand = 0x06,
RmoteManCommand = 0x07,
RadioMessage = 0x09,
RadioAdvanced = 0x0A
};
UCHAR Crc8(PUCHAR Data, INT Count);
UCHAR Crc8Ex(PUCHAR Data, INT Offset, INT Count);
//
// Globals
//
BOOL UseFilter;
ULONG SwitchID;
ULONG TempID;
//
//
//
VOID BufferFilter(PUCHAR Buffer, ULONG Id)
{
Buffer[0] = 0x55; // Sync Byte
Buffer[1] = 0; // Data Length[0]
Buffer[2] = 7; // Data Length[1]
Buffer[3] = 0; // Optional Length
Buffer[4] = 5; // Packet Type = CO (5)
Buffer[5] = Crc8Ex(Buffer, 1, 4); // CRC8H
Buffer[6] = 11; // Command Code = CO_WR_FILTER_ADD (11)
Buffer[7] = 0; // FilterType = Device ID (0)
Buffer[8] = (UCHAR)((Id >> 24) & 0xFF); // ID[0]
Buffer[9] = (UCHAR)((Id >> 16) & 0xFF); // ID[1]
Buffer[10] = (UCHAR)((Id >> 8) & 0xFF); // ID[2]
Buffer[11] = (UCHAR)(Id & 0xFF); // ID[3]
Buffer[12] = 0x80; // Filter Kind = apply (0x80)
Buffer[13] = Crc8Ex(Buffer, 6, 7); // CRC8D
}
//
//
//UsbDeviceWrite(
// _In_ PDEVICE_DATA DeviceData,
// _In_ UCHAR* Buffer,
// _In_ ULONG Length,
// _Out_opt_ ULONG* pcbWritten
//);
BOOL PreparationFilter(
_In_ PDEVICE_DATA DeviceData,
_In_ BOOL Enable
)
{
BOOL clearFilter = true;
BOOL writeFilter = Enable;
ULONG wroteLength = 0;
UCHAR buffer[16];
#define CHECK_RESULT(len) \
if (wroteLength != (len)) \
{ \
printf("FILTER: length error=%d(%d)", wroteLength, len); \
return FALSE; \
}
if (clearFilter)
{
if (true)
{
//printf("FILTER: Clear all Filters\n");
buffer[0] = 0x55; // Sync Byte
buffer[1] = 0; // Data Length[0]
buffer[2] = 1; // Data Length[1]
buffer[3] = 0; // Optional Length
buffer[4] = 5; // Packet Type = CO (5)
buffer[5] = Crc8Ex(buffer, 1, 4); // CRC8H
buffer[6] = 13; // Command Code = CO_WR_FILTER_DEL (13)
buffer[7] = Crc8Ex(buffer, 6, 1); // CRC8D
UsbDeviceWrite(DeviceData, buffer, 8, &wroteLength);
CHECK_RESULT(8);
Sleep(100);
//GetResponse();
}
if (writeFilter && SwitchID != 0)
{
printf("FILTER: SwitchID Add Filter=%08X\n", SwitchID);
BufferFilter(buffer, SwitchID);
UsbDeviceWrite(DeviceData, buffer, 14, &wroteLength);
CHECK_RESULT(14);
Sleep(100);
}
if (writeFilter && TempID != 0)
{
printf("FILTER: TempID Add Filter=%08X\n", TempID);
BufferFilter(buffer, TempID);
UsbDeviceWrite(DeviceData, buffer, 14, &wroteLength);
CHECK_RESULT(14);
Sleep(100);
//GetResponse();
}
}
if (writeFilter)
{
printf("Enable Filters\n");
buffer[0] = 0x55; // Sync Byte
buffer[1] = 0; // Data Length[0]
buffer[2] = 3; // Data Length[1]
buffer[3] = 0; // Optional Length
buffer[4] = 5; // Packet Type = CO (5)
buffer[5] = Crc8Ex(buffer, 1, 4); // CRC8H
buffer[6] = 14; // Command Code = CO_WR_FILTER_ENABLE (14)
buffer[7] = 1; // Filter Enable = ON (1)
buffer[8] = 0; // Filter Operator = OR (0)
//buffer[8] = 1; // Filter Operator = AND (1)
buffer[9] = Crc8Ex(buffer, 6, 3); // CRC8D
UsbDeviceWrite(DeviceData, buffer, 10, &wroteLength);
CHECK_RESULT(10);
Sleep(100);
//GetResponse();
}
return TRUE;
#undef CHECK_RESULT
}
BOOL MainLoop(PDEVICE_DATA DeviceData)
{
const int BUFFER_SIZE = 64;
UCHAR buffer[BUFFER_SIZE];
ULONG length;
BOOL result;
BOOL gotHeader;
USHORT dataLength;
USHORT optionalLength;
ULONG readLength;
UCHAR packetType = 0;
UCHAR crc8h;
UCHAR crc8d;
UCHAR rOrg;
UCHAR dataOffset;
UCHAR dataSize;
UCHAR id[4];
UCHAR data[4];
UCHAR nu;
// printf("Enter MainLoop\n");
do
{
dataLength = optionalLength = 0;
gotHeader = FALSE;
result = UsbDeviceRead(DeviceData, buffer, 1, &length);
if (!result)
{
printf("ERROR: !result\n");
return FALSE;
}
else if (length == 0)
{
Sleep(1);
continue;
}
else if (buffer[0] != 0x55)
{
continue;
}
result = UsbDeviceRead(DeviceData, buffer, 5, &length);
if (!result)
{
printf("ERROR: !result\n");
return FALSE;
}
else if (length != 5)
{
Sleep(1);
printf("TRY: length != 5\n"); ////
continue;
}
dataLength = buffer[0] << 8 | buffer[1];
optionalLength = buffer[2];
packetType = buffer[3];
crc8h = buffer[4];
gotHeader = crc8h == Crc8(buffer, 4);
// printf("CRC8H: crc8h=%02X Calc=%02X\n", crc8h, Crc8(buffer, 4)); ////
}
while(!gotHeader);
// printf("Got Header!\n"); ////
readLength = dataLength + optionalLength + 1;
if (readLength > BUFFER_SIZE)
{
// mayne something error but have to keep buffer size
readLength = BUFFER_SIZE;
}
UsbDeviceRead(DeviceData, buffer, readLength, &length);
if (!result)
{
printf("ERROR: !result\n");
return FALSE;
}
else if (length != readLength)
{
Sleep(1);
return FALSE;
}
crc8d = buffer[readLength - 1];
if (crc8d != Crc8(buffer, readLength - 1))
{
printf("CRC8D error!\n");
}
else
{
// printf("CRC8D OK!\n");
}
//printf("CRC8D: crc8d=%02X Calc=%02X\n", crc8d, Crc8(buffer, readLength - 1));
if (packetType == RadioAdvanced)
{
rOrg = buffer[0];
switch (rOrg)
{
case 0x62: //Teach-In
dataOffset = 2;
dataSize = 0;
break;
case 0x20: //RPS
dataOffset = 0;
dataSize = 1;
break;
case 0x22: //4BS
dataOffset = 0;
dataSize = 4;
break;
default: // not used
dataOffset = 0;
dataSize = 0;
break;
}
id[3] = buffer[1 + dataOffset];
id[2] = buffer[2 + dataOffset];
id[1] = buffer[3 + dataOffset];
id[0] = buffer[4 + dataOffset];
switch (rOrg)
{
case 0x62: //Teach-In
case 0x22: //4BS
data[0] = buffer[5 + dataOffset];
data[1] = buffer[6 + dataOffset];
data[2] = buffer[7 + dataOffset];
data[3] = buffer[8 + dataOffset];
break;
case 0x20: //RPS
nu = (buffer[5 + dataOffset] >> 7) & 0x01;
data[0] = buffer[5 + dataOffset] & 0x0F;
data[1] = 0; // not used
data[2] = 0; // not used
data[3] = 0; // not used
break;
default: // not used
break;
}
}
return TRUE;
}
static UCHAR crc8Table[] =
{
0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d,
0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65,
0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d,
0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5,
0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd,
0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85,
0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd,
0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2,
0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea,
0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2,
0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a,
0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32,
0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a,
0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42,
0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a,
0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c,
0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4,
0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec,
0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4,
0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c,
0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44,
0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c,
0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34,
0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b,
0x76, 0x71, 0x78, 0x7f, 0x6A, 0x6d, 0x64, 0x63,
0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b,
0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13,
0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb,
0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8D, 0x84, 0x83,
0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb,
0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3
};
UCHAR Crc8Ex(PUCHAR Data, INT Offset, INT Count)
{
UCHAR crc = 0;
Count += Offset;
for (int i = Offset; i < Count; i++)
crc = crc8Table[crc ^ Data[i]];
return crc;
}
UCHAR Crc8(PUCHAR Data, INT Count)
{
return Crc8Ex(Data, 0, Count);
}
VOID Usage(_In_ LPTSTR MyName)
{
printf("Usage: %ws [-f] [Switch-ID] [TempSensor-ID]\n\n", MyName);
printf(" -f Use ID Filters for switch and sensors.\n");
printf(" Switch-ID EnOcean Locker Switch ID. '0' is not existing.\n");
printf(" TempSensor-ID EnOcean Temperature sensor ID. '0' is not existing.\n\n");
}
LONG __cdecl
_tmain(
LONG Argc,
LPTSTR * Argv
)
{
DEVICE_DATA deviceData;
HRESULT hr;
BOOL result;
BOOL noDevice;
INT argIndex = 0;
if (Argc > 1)
{
if (Argv[1][0] == '-')
{
if (Argv[1][1] == 'f')
{
UseFilter = TRUE;
argIndex++;
}
else
{
Usage(Argv[0]);
return 0;
}
}
}
if (Argc > (1 + argIndex))
{
SwitchID = wcstoul(Argv[1 + argIndex], NULL, 16);
printf("SwitchID=%08X(%ws)\n", SwitchID, Argv[1 + argIndex]);
}
if (Argc > (2 + argIndex))
{
TempID = wcstoul(Argv[2 + argIndex], NULL, 16);
printf("TempID=%08X(%ws)\n", TempID, Argv[2 + argIndex]);
}
//
// Find a device connected to the system that has WinUSB installed using our
// INF
//
hr = UsbDeviceOpen(&deviceData, &noDevice);
if (FAILED(hr)) {
if (noDevice) {
wprintf(L"Device not connected or driver not installed\n");
} else {
wprintf(L"Failed looking for device, HRESULT 0x%x\n", hr);
}
UsbDeviceClose(&deviceData);
return 0;
}
result = UsbDeviceInitialize(&deviceData, 57600);
if (!result)
{
printf("Error !result\n");
UsbDeviceClose(&deviceData);
return 0;
}
if (!PreparationFilter(&deviceData, UseFilter))
{
printf("Error\n");
return 0;
}
do
{
result = MainLoop(&deviceData);
}
while (result);
UsbDeviceClose(&deviceData);
return 0;
}
| 26.235828 | 86 | 0.51599 | ahidaka |
bd97657c4e1e7d4a0033b492126f2609bd309c34 | 639 | cc | C++ | src/core/imap/MCIMAPMessagePart.cc | zhanleewo/mailcore2 | a6c2d0465b25351689a1b4761f191201275f2b52 | [
"BSD-3-Clause"
] | 1 | 2020-10-14T21:44:57.000Z | 2020-10-14T21:44:57.000Z | src/core/imap/MCIMAPMessagePart.cc | zhanleewo/mailcore2 | a6c2d0465b25351689a1b4761f191201275f2b52 | [
"BSD-3-Clause"
] | null | null | null | src/core/imap/MCIMAPMessagePart.cc | zhanleewo/mailcore2 | a6c2d0465b25351689a1b4761f191201275f2b52 | [
"BSD-3-Clause"
] | null | null | null | #include "MCIMAPMessagePart.h"
using namespace mailcore;
IMAPMessagePart::IMAPMessagePart()
{
init();
}
IMAPMessagePart::IMAPMessagePart(IMAPMessagePart * other) : AbstractMessagePart(other)
{
init();
MC_SAFE_REPLACE_COPY(String, mPartID, other->mPartID);
}
IMAPMessagePart::~IMAPMessagePart()
{
MC_SAFE_RELEASE(mPartID);
}
Object * IMAPMessagePart::copy()
{
return new IMAPMessagePart(this);
}
void IMAPMessagePart::init()
{
mPartID = NULL;
}
void IMAPMessagePart::setPartID(String * partID)
{
MC_SAFE_REPLACE_COPY(String, mPartID, partID);
}
String * IMAPMessagePart::partID()
{
return mPartID;
}
| 15.975 | 86 | 0.723005 | zhanleewo |
bd97fd78f6dce58444152e74d0fc4c93d312b2b5 | 4,120 | cpp | C++ | firmware/modules/core/cSound.cpp | klaus-liebler/sensact | b8fc05eff67f23cf58c4fdf53e0026aab0966f6b | [
"Apache-2.0"
] | 2 | 2021-02-09T16:17:43.000Z | 2021-08-09T04:02:44.000Z | firmware/modules/core/cSound.cpp | klaus-liebler/sensact | b8fc05eff67f23cf58c4fdf53e0026aab0966f6b | [
"Apache-2.0"
] | 2 | 2016-05-17T20:45:10.000Z | 2020-03-10T07:03:39.000Z | firmware/modules/core/cSound.cpp | klaus-liebler/sensact | b8fc05eff67f23cf58c4fdf53e0026aab0966f6b | [
"Apache-2.0"
] | 1 | 2020-05-24T13:37:55.000Z | 2020-05-24T13:37:55.000Z | #include "cMaster.h"
#include "cModel.h"
#include "cSound.h"
#include <chrono>
#define LOGLEVEL LEVEL_DEBUG
#define LOGNAME "SOUND"
#include "cLog.h"
namespace sensact {
static uint8_t send_buf[10] = {0x7E, 0xFF,0x06,0,0,0,0,0,0,0xEF};
//static bool is_reply = false;
//
static void fill_uint16_bigend (uint8_t *thebuf, uint16_t data)
{
*thebuf = (uint8_t)(data>>8);
*(thebuf+1) = (uint8_t)data;
}
//calc checksum (1~6 byte)
static uint16_t mp3_get_checksum (uint8_t *thebuf)
{
uint16_t sum = 0;
for (int i=1; i<7; i++)
{
sum += thebuf[i];
}
return -sum;
}
//fill checksum to send_buf (7~8 byte)
static void mp3_fill_checksum ()
{
uint16_t checksum = mp3_get_checksum (send_buf);
fill_uint16_bigend (send_buf+7, checksum);
}
static void send_func ()
{
HAL_UART_Transmit(&BSP::BELL, send_buf, 10, 1000);
}
static void mp3_send_cmd (uint8_t cmd, uint16_t arg)
{
send_buf[3] = cmd;
fill_uint16_bigend ((send_buf+5), arg);
mp3_fill_checksum ();
send_func();
}
//play mp3 file in mp3 folder in your tf card
static void mp3_play (uint16_t num) {
mp3_send_cmd (0x12, num);
}
static void mp3_set_volume (uint16_t volume)
{
mp3_send_cmd (0x06, volume);
}
/*
static void mp3_send_cmd (uint8_t cmd)
{
send_buf[3] = cmd;
fill_uint16_bigend ((send_buf+5), 0);
mp3_fill_checksum ();
send_func();
}
static void mp3_set_reply (bool state)
{
is_reply = state;
send_buf[4] = is_reply;
}
static void mp3_play ()
{
mp3_send_cmd (0x0d);
}
//
static void mp3_play_physical (uint16_t num)
{
mp3_send_cmd (0x03, num);
}
//
static void mp3_play_physical ()
{
mp3_send_cmd (0x03);
}
//
static void mp3_next ()
{
mp3_send_cmd (0x01);
}
//
static void mp3_prev ()
{
mp3_send_cmd (0x02);
}
//0x06 set volume 0-30
//0x07 set EQ0/1/2/3/4/5 Normal/Pop/Rock/Jazz/Classic/Bass
static void mp3_set_EQ (uint16_t eq)
{
mp3_send_cmd (0x07, eq);
}
//0x09 set device 1/2/3/4/5 U/SD/AUX/SLEEP/FLASH
static void mp3_set_device (uint16_t device)
{
mp3_send_cmd (0x09, device);
}
//
static void mp3_sleep ()
{
mp3_send_cmd (0x0a);
}
//
static void mp3_reset ()
{
mp3_send_cmd (0x0c);
}
//
//
static void mp3_pause ()
{
mp3_send_cmd (0x0e);
}
//
static void mp3_stop () {
mp3_send_cmd (0x16);
}
//
static void mp3_get_state () {
mp3_send_cmd (0x42);
}
//
static void mp3_get_volume () {
mp3_send_cmd (0x43);
}
//
static void mp3_get_u_sum () {
mp3_send_cmd (0x47);
}
//
static void mp3_get_tf_sum () {
mp3_send_cmd (0x48);
}
//
static void mp3_get_flash_sum () {
mp3_send_cmd (0x49);
}
//
static void mp3_get_tf_current () {
mp3_send_cmd (0x4c);
}
//
static void mp3_get_u_current () {
mp3_send_cmd (0x4b);
}
//
static void mp3_get_flash_current () {
mp3_send_cmd (0x4d);
}
//
static void mp3_single_loop (bool state) {
mp3_send_cmd (0x19, !state);
}
//add
static void mp3_single_play (uint16_t num) {
mp3_play (num);
HAL_Delay(10);
mp3_single_loop (true);
//mp3_send_cmd (0x19, !state);
}
//
static void mp3_DAC (bool state) {
mp3_send_cmd (0x1a, !state);
}
//
static void mp3_random_play () {
mp3_send_cmd (0x18);
}
*/
eAppCallResult cSound::Setup() {
mp3_set_volume(this->lastSetVolume);
return BSP::SetDigitalOutput(this->output, BSP::INACTIVE)?eAppCallResult::OK:eAppCallResult::BUS_ERROR;
}
eAppType cSound::GetAppType()
{
return eAppType::SOUND;
}
void cSound::OnSET_SIGNALCommand(uint16_t signal, Time_t now)
{
uint32_t vol = lastSetVolume;
if(this->volumeSchedule!=NULL)
{
vol = volumeSchedule->GetCurrentValue();
}
BSP::SetDigitalOutput(this->output, BSP::ACTIVE);
this->autoOffTimeMs=now+30000;
if(vol!=lastSetVolume)
{
mp3_set_volume(vol);
HAL_Delay(20);
this->lastSetVolume=vol;
}
mp3_play(signal);
}
void cSound::OnSTARTCommand(Time_t now)
{
LOGD("%s OnSTARTCommand called", this->Id);
OnSET_SIGNALCommand(1, now);
}
eAppCallResult cSound::DoEachCycle(Time_t now, uint8_t *statusBuffer, size_t *statusBufferLength)
{
if(now>this->autoOffTimeMs)
{
BSP::SetDigitalOutput(this->output, BSP::INACTIVE);
this->autoOffTimeMs=TIME_MAX;
}
UNUSED(statusBuffer);
*statusBufferLength=0;
return eAppCallResult::OK;
}
}
| 15.147059 | 104 | 0.699757 | klaus-liebler |
bd990bd8964c2c1c933f7886b7adf94fe51bc1b1 | 1,384 | cpp | C++ | src/EPI/ch4/bit_swap.cpp | j-haj/interview-prep | 7d9f0ca4c321cf1d2393aea17bcd375119005e5d | [
"MIT"
] | null | null | null | src/EPI/ch4/bit_swap.cpp | j-haj/interview-prep | 7d9f0ca4c321cf1d2393aea17bcd375119005e5d | [
"MIT"
] | null | null | null | src/EPI/ch4/bit_swap.cpp | j-haj/interview-prep | 7d9f0ca4c321cf1d2393aea17bcd375119005e5d | [
"MIT"
] | null | null | null | #include <bitset>
#include <iostream>
#include <random>
/**
* Returns a random integer from the interval [low, high]
*
* @param low left end of the range (inclusive)
* @param high right end of the range (inclusive)
*
* @return random integer from specified interval [low, high]
*/
int random_int(const int low, const int high) {
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(low, high);
return dist(gen);
}
/**
* Swaps bits at indices i and j, assuming index 0 is the least significant bit,
* for the given value
*
* @param value number whose bits will be swapped
* @param i index of bit
* @param j index of bit
*
* @return the result of swapping bits i and j within a given number
*/
int swap_bits(int value, const int i, const int j) {
if (((value >> i) & 1) != ((value >> j) & 1)) {
auto bit_mask = (1 << i) | (1 << j);
value ^= bit_mask;
}
return value;
}
int main(int argc, char* argv[]) {
int val = random_int(1, 1000);
std::bitset<16> bit_rep(val);
int i = random_int(1, 15);
int j = random_int(1, 15);
int res = swap_bits(val, i, j);
std::bitset<16> new_bit_rep(res);
std::cout << "Swapping bits i = " << i << ", j = " << j
<< " in " << val << ":\n"
<< "\told: " << bit_rep << '\n'
<< "\tnew: " << new_bit_rep << '\n';
return 0;
}
| 27.137255 | 80 | 0.601879 | j-haj |
bda81d8e98e07b3227e819c1b0ba88bf7e7d2064 | 1,713 | cpp | C++ | sleepy_discord/asio_udp.cpp | qualk/sleepy-discord | 1a4045326c15b3e3a7461043e29769f8ccb8a2a9 | [
"MIT"
] | 830 | 2017-05-29T21:00:17.000Z | 2022-03-26T16:07:28.000Z | sleepy_discord/asio_udp.cpp | qualk/sleepy-discord | 1a4045326c15b3e3a7461043e29769f8ccb8a2a9 | [
"MIT"
] | 200 | 2017-06-27T20:08:49.000Z | 2022-03-05T14:37:59.000Z | sleepy_discord/asio_udp.cpp | qualk/sleepy-discord | 1a4045326c15b3e3a7461043e29769f8ccb8a2a9 | [
"MIT"
] | 212 | 2017-06-27T00:16:27.000Z | 2022-03-13T15:48:42.000Z | #include "asio_udp.h"
#ifndef NONEXISTENT_ASIO
#include "client.h"
namespace SleepyDiscord {
//Note: you need to be using a ASIOBasedScheduleHandler for this to work
ASIOUDPClient::ASIOUDPClient(BaseDiscordClient& client) :
ASIOUDPClient(static_cast<ASIOBasedScheduleHandler&>(client.getScheduleHandler()).getIOService())
{}
ASIOUDPClient::ASIOUDPClient(asio::io_service& service) :
iOService(&service),
uDPSocket(*iOService, asio::ip::udp::endpoint(asio::ip::udp::v4(), 0)),
resolver (*iOService)
{
}
bool ASIOUDPClient::connect(const std::string & to, const uint16_t port) {
if (iOService == nullptr) return false;
endpoint = *resolver.resolve({ asio::ip::udp::v4(), to, std::to_string(port) });
return true;
}
void handle_send(
const std::error_code& /*error*/,
std::size_t /*bytes_transferred*/,
GenericUDPClient::SendHandler handler
) {
handler();
}
void ASIOUDPClient::send(
const uint8_t* _buffer,
size_t bufferLength,
SendHandler handler
) {
if (iOService == nullptr) return;
uDPSocket.async_send_to(asio::buffer(_buffer, bufferLength), endpoint,
std::bind(&handle_send, std::placeholders::_1, std::placeholders::_2, handler)
);
}
void ASIOUDPClient::receive(ReceiveHandler handler) {
if (iOService == nullptr) return;
uDPSocket.async_receive_from(asio::buffer(buffer, bufferSize), endpoint, 0,
std::bind(
&ASIOUDPClient::handle_receive, this, std::placeholders::_1,
std::placeholders::_2, handler
)
);
}
void ASIOUDPClient::handle_receive(
const std::error_code& /*error*/,
std::size_t bytes_transferred,
ReceiveHandler handler
) {
handler(std::vector<uint8_t>(buffer, buffer + bytes_transferred));
}
};
#endif | 26.765625 | 99 | 0.718622 | qualk |
bdb42deba85d26844a6075972a4d8444b1decc59 | 13,716 | cpp | C++ | tests/HandwrittenRuntime/Test_Database2.cpp | ankurvdev/stencil | b6429f8b92947273a5e66d5f10210b960616a89d | [
"BSD-3-Clause"
] | null | null | null | tests/HandwrittenRuntime/Test_Database2.cpp | ankurvdev/stencil | b6429f8b92947273a5e66d5f10210b960616a89d | [
"BSD-3-Clause"
] | null | null | null | tests/HandwrittenRuntime/Test_Database2.cpp | ankurvdev/stencil | b6429f8b92947273a5e66d5f10210b960616a89d | [
"BSD-3-Clause"
] | null | null | null | #include "Test_Database2.h"
#include "TestUtils.h"
#include <thread>
using namespace std::string_literals;
using namespace std::chrono_literals;
namespace Catch
{
template <> struct StringMaker<std::filesystem::file_time_type>
{
static std::string convert(std::filesystem::file_time_type const& ftime) { return std::to_string(ftime.time_since_epoch().count()); }
};
} // namespace Catch
using DB = TestData::DataStore;
template <size_t N, typename T> constexpr uuids::uuid TestUuid();
template <> constexpr uuids::uuid TestUuid<0, TestData::Simple>()
{
return uuids::uuid::from_string("{00000000-0000-0000-0000-000000000001}").value();
}
template <> constexpr uuids::uuid TestUuid<1, TestData::Simple>()
{
return uuids::uuid::from_string("{00000000-0000-0000-0000-000000000002}").value();
}
template <> constexpr uuids::uuid TestUuid<0, TestData::Shared>()
{
return uuids::uuid::from_string("{00000001-0001-0001-0001-000000000000}").value();
}
template <> constexpr uuids::uuid TestUuid<1, TestData::Shared>()
{
return uuids::uuid::from_string("{00000001-0001-0001-0001-000000000001}").value();
}
template <> constexpr uuids::uuid TestUuid<0, TestData::Encrypted>()
{
return uuids::uuid::from_string("{00000002-0002-0002-0002-000000000000}").value();
}
template <> constexpr uuids::uuid TestUuid<1, TestData::Encrypted>()
{
return uuids::uuid::from_string("{00000002-0002-0002-0002-000000000001}").value();
}
template <> constexpr uuids::uuid TestUuid<0, TestData::EncryptedAndShared>()
{
return uuids::uuid::from_string("{00000003-0003-0003-0003-000000000000}").value();
}
template <> constexpr uuids::uuid TestUuid<1, TestData::EncryptedAndShared>()
{
return uuids::uuid::from_string("{00000003-0003-0003-0003-000000000001}").value();
}
template <> constexpr uuids::uuid TestUuid<0, TestData::WithSimpleRef>()
{
return uuids::uuid::from_string("{00000004-0004-0004-0004-000000000000}").value();
}
template <> constexpr uuids::uuid TestUuid<1, TestData::WithSimpleRef>()
{
return uuids::uuid::from_string("{00000004-0004-0004-0004-000000000001}").value();
}
#if TODO_OBJREF
template <> constexpr uuids::uuid TestUuid<TestData::WithString>()
{
return uuids::uuid("{00000005-0005-0005-0005-000000000000}");
};
template <> constexpr uuids::uuid TestUuid<TestData::WithSharedString>()
{
return uuids::uuid("{00000006-0006-0006-0006-000000000000}");
};
template <> constexpr uuids::uuid TestUuid<TestData::WithSharedData>()
{
return uuids::uuid("{00000007-0007-0007-0007-000000000000}");
};
template <> constexpr uuids::uuid TestUuid<TestData::WithEncryptedString>()
{
return uuids::uuid("{00000008-0008-0008-0008-000000000000}");
};
template <> constexpr uuids::uuid TestUuid<TestData::WithEncryptedSharedString>()
{
return uuids::uuid("{00000009-0009-0009-0009-000000000000}");
};
#endif
template <size_t N, typename T> constexpr std::string_view TestValue();
template <> constexpr std::string_view TestValue<0, TestData::Simple>()
{
return "Simple_0";
}
template <> constexpr std::string_view TestValue<1, TestData::Simple>()
{
return "Simple_1";
}
template <> constexpr std::string_view TestValue<0, TestData::Shared>()
{
return "Shared_0";
}
template <> constexpr std::string_view TestValue<1, TestData::Shared>()
{
return "Shared_1";
}
template <> constexpr std::string_view TestValue<0, TestData::Encrypted>()
{
return "Encrypted_0";
}
template <> constexpr std::string_view TestValue<1, TestData::Encrypted>()
{
return "Encrypted_1";
}
template <> constexpr std::string_view TestValue<0, TestData::EncryptedAndShared>()
{
return "EncryptedAndShared_0";
}
template <> constexpr std::string_view TestValue<1, TestData::EncryptedAndShared>()
{
return "EncryptedAndShared_1";
}
template <> constexpr std::string_view TestValue<0, TestData::WithSimpleRef>()
{
return "WithSimpleRef_0";
}
template <> constexpr std::string_view TestValue<1, TestData::WithSimpleRef>()
{
return "WithSimpleRef_1";
}
template <> constexpr std::string_view TestValue<0, Database2::ByteString>()
{
return "Database2::ByteString_0";
}
template <> constexpr std::string_view TestValue<1, Database2::ByteString>()
{
return "Database2::ByteString_1";
}
#if TODO_OBJREF
template <> constexpr std::string_view TestValue<TestData::WithString>()
{
return "WithString";
};
template <> constexpr std::string_view TestValue<TestData::WithSharedString>()
{
return "WithSharedString";
};
template <> constexpr std::string_view TestValue<TestData::WithSharedData>()
{
return "WithSharedData";
};
template <> constexpr std::string_view TestValue<TestData::WithEncryptedString>()
{
return "WithEncryptedString";
};
template <> constexpr std::string_view TestValue<TestData::WithEncryptedSharedString>()
{
return "WithEncryptedSharedString";
};
#endif
template <size_t N, typename TObj> struct ObjTester;
template <size_t N, typename... TObjs> auto CreateObjects(DB& db)
{
auto lock = db.LockForEdit();
using Tuple = std::tuple<ObjTester<N, TObjs>...>;
std::vector<std::unique_ptr<Tuple>> arrayoftuples(1000);
for (size_t i = 0; i < 1000; i++)
{
arrayoftuples[i].reset(new Tuple(ObjTester<N, TObjs>{i, {}}...));
std::apply([&](auto&... x) { [[maybe_unused]] auto tmp = std::make_tuple(x.CreateObj(lock, db)...); }, *arrayoftuples[i].get());
}
return arrayoftuples;
}
template <size_t N, typename T> void VerifyObjects(T const& arrayoftuples, DB& db)
{
auto lock = db.LockForRead();
for (auto& t : arrayoftuples)
{
std::apply([&](auto&... x) { [[maybe_unused]] auto tmp = std::make_tuple(x.VerifyObj(lock, db)...); }, *t.get());
}
}
template <size_t N> struct ObjTester<N, Database2::ByteString>
{
template <typename TLock> bool CreateObj(TLock const& lock, DB& db)
{
auto [ref1, obj] = db.Create<Database2::ByteString>(lock, TestValue<N, Database2::ByteString>());
ref = ref1;
auto obj1 = db.Get(lock, ref);
REQUIRE(obj == TestValue<N, Database2::ByteString>());
REQUIRE(obj1 == TestValue<N, Database2::ByteString>());
return true;
}
template <typename TLock> bool VerifyObj(TLock const& lock, DB& db)
{
auto obj = db.Get(lock, ref);
REQUIRE(obj == TestValue<N, Database2::ByteString>());
return true;
}
size_t iteration;
Database2::Ref<DB, Database2::ByteString> ref{};
};
template <size_t N> struct ObjTester<N, TestData::WithSimpleRef>
{
using Type = TestData::WithSimpleRef;
template <typename TLock> bool CreateObj(TLock const& lock, DB& db)
{
auto [ref1, obj] = db.Create<TestData::WithSimpleRef>(lock,
TestUuid<N, TestData::Simple>(),
TestUuid<N, TestData::WithSimpleRef>(),
TestUuid<N, TestData::Simple>(),
TestValue<N, Database2::ByteString>());
ref = ref1;
auto obj1 = db.Get(lock, ref);
REQUIRE(obj.uuid == TestUuid<N, Type>());
REQUIRE(obj1.uuid == TestUuid<N, Type>());
return true;
}
template <typename TLock> bool VerifyObj(TLock const& lock, DB& db)
{
auto obj = db.Get(lock, ref);
REQUIRE(obj.uuid == TestUuid<N, Type>());
// auto subobj = obj.ref1.Get(lock.shared(), db, obj);
// REQUIRE(subobj.uuid == TestUuid<TestData::Simple>());
return true;
}
size_t iteration;
Database2::Ref<DB, Type> ref;
};
template <typename TObj> void TestCaseForObj()
{
auto dbFileName = std::to_string(typeid(TObj).hash_code()) + ".bin"s;
std::filesystem::remove(dbFileName);
{
DB db{dbFileName};
ObjTester<0, TObj> tester{0, {}};
tester.CreateObj(db.LockForEdit(), db);
tester.VerifyObj(db.LockForRead(), db);
}
std::filesystem::remove(dbFileName);
}
#define TEST_CASE_FOR_OBJTYPE(type) \
TEST_CASE("CodeGen::Database2::" #type, "[Unit]") { TestCaseForObj<type>(); }
//#define TEST_CASE_FOR_(type, ...) TEST_CASE_FOR_OBJTYPE(type) TEST_CASE_FOR_(__VA_ARGS__)
//#define TEST_CASE_FOR__(arg) TEST_CASE_FOR_ arg
//#define TEST_CASE_FOR(args) TEST_CASE_FOR__((args))
#define ALL_TESTED_TYPES Database2::ByteString, TestData::WithSimpleRef
TEST_CASE_FOR_OBJTYPE(Database2::ByteString)
TEST_CASE_FOR_OBJTYPE(TestData::WithSimpleRef)
// TEST_CASE_FOR(ALL_TESTED_TYPES);
TEST_CASE("CodeGen::Database2::SaveAndLoadFile", "[Database2]")
{
auto dbFileName = "SaveAndLoadFile.bin"s;
if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName);
// Constructor With Path Creates New File and Writes Header
{
{
DB datastore{dbFileName};
}
REQUIRE(std::filesystem::exists(dbFileName));
REQUIRE(std::filesystem::file_size(dbFileName) == (8192 * 2 + 80));
}
// Constructor With Path Reads Existing File but doesnt touch it
{
auto time = std::filesystem::file_time_type::clock::now();
{
DB datastore{dbFileName};
}
if (std::filesystem::last_write_time(dbFileName).time_since_epoch().count() > time.time_since_epoch().count())
{
FAIL("Failed. Database was modified");
}
}
// Constructor With IStream reads file
{
auto time = std::filesystem::file_time_type::clock::now();
{
DB datastore{std::ifstream(dbFileName)};
CreateObjects<0, ALL_TESTED_TYPES>(datastore);
}
if (std::filesystem::last_write_time(dbFileName).time_since_epoch().count() > time.time_since_epoch().count())
{
FAIL("Database changed");
}
}
// Empty Constructor for in-memory datastore
{
{
DB datastore{DB::InMemory};
CreateObjects<0, ALL_TESTED_TYPES>(datastore);
}
{
// TODO : Verify nothing written
}
}
}
TEST_CASE("CodeGen::Database2::SaveAndLoadObjects", "[Database2]")
{
auto dbFileName = "SaveAndLoadObjects.bin"s;
SECTION("Check Objects Write and Read")
{
if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName);
auto state = [&]() {
DB datastore{dbFileName};
return CreateObjects<0, ALL_TESTED_TYPES>(datastore);
}();
{
DB datastore{dbFileName};
VerifyObjects<0>(state, datastore);
}
// AvailableSlot Initialized to right value on reload
{
DB datastore{dbFileName};
VerifyObjects<0>(state, datastore);
VerifyObjects<1>(CreateObjects<1, ALL_TESTED_TYPES>(datastore), datastore);
VerifyObjects<0>(state, datastore);
}
}
SECTION("ChildRef Release marks dirty and saves and reloads")
{
if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName);
auto objs = [&]() {
DB datastore{dbFileName};
return CreateObjects<0, TestData::WithSimpleRef>(datastore);
}();
auto time = std::filesystem::last_write_time(dbFileName);
std::this_thread::sleep_for(10ms); // Looks like the below code is too quick for appreciable difference in modified time
{
DB datastore{dbFileName};
auto lock = datastore.LockForEdit();
auto& editObj = datastore.Get(lock, std::get<0>(*objs[0]).ref);
REQUIRE(editObj.ref1.ref.Valid());
editObj.ref1.Release(lock, datastore);
REQUIRE(!editObj.ref1.ref.Valid());
}
if (std::filesystem::last_write_time(dbFileName).time_since_epoch().count() < time.time_since_epoch().count())
{
FAIL("Database not changed");
}
{
DB datastore{dbFileName};
auto lock = datastore.LockForRead();
auto& editObj = datastore.Get(lock, std::get<0>(*objs[0]).ref);
REQUIRE(!editObj.ref1.ref.Valid());
}
}
SECTION("Get Edit ref marks the object as dirty")
{ // FAIL("TODO");
}
}
TEST_CASE("CodeGen::Database2::UniqueSharedAndSelf", "[Database2]")
{
auto dbFileName = "UniqueSharedAndSelf.bin"s;
if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName);
SECTION("Self")
{
DB store{dbFileName};
{
auto lock = store.LockForEdit();
auto [ref, objstr1] = store.Create<Database2::ByteString>(lock, TestValue<0, Database2::ByteString>());
REQUIRE(ref.page > 0);
REQUIRE(ref.slot >= 0);
REQUIRE(objstr1 == TestValue<0, Database2::ByteString>());
}
{
auto lock = store.LockForRead();
size_t count = 0;
for ([[maybe_unused]] auto const [ref, obj] : store.Objects<Database2::ByteString>(lock)) { count++; }
REQUIRE(count == 1);
}
{
auto lock = store.LockForEdit();
for (auto const [ref, obj] : store.Objects<Database2::ByteString>(lock)) { store.Delete(lock, ref); }
size_t count = 0;
for ([[maybe_unused]] auto const [ref, obj] : store.Objects<Database2::ByteString>(lock)) { count++; }
// TODO : REQUIRE(count == 0);
// TODO : TEst case for verifying that editlock causes a page dirty
}
}
}
| 32.657143 | 137 | 0.63014 | ankurvdev |
bdc9f53a41d25d29c68ac43c89e298c78de3f1cc | 13,138 | cpp | C++ | Antario/Features/Aimbot.cpp | NoelWriter/mirrorcsgo | bb527561df68cff5283472d5fed0492c58c2a078 | [
"MIT"
] | 1 | 2020-02-23T17:35:51.000Z | 2020-02-23T17:35:51.000Z | Antario/Features/Aimbot.cpp | NoelWriter/mirrorcsgo | bb527561df68cff5283472d5fed0492c58c2a078 | [
"MIT"
] | null | null | null | Antario/Features/Aimbot.cpp | NoelWriter/mirrorcsgo | bb527561df68cff5283472d5fed0492c58c2a078 | [
"MIT"
] | null | null | null | #include "Aimbot.h"
#include <Windows.h>
#include "..\Utils\Utils.h"
#include "..\Utils\GlobalVars.h"
#include "..\Hooks.h"
#include "..\SDK\Studio.hpp"
#include "..\Utils\Interfaces.h"
#include "Backtrack.h"
#include "Ragewall.h"
#include "..\SDK\CGlobalVarsBase.h"
// Declare classes
Aimbot g_Aimbot;
// Movefix variables
float m_oldforward, m_oldsidemove;
QAngle m_oldangle;
// Aimbot variables
C_BaseEntity *target;
void Aimbot::DoAimbot(CUserCmd* pCmd)
{
if (g_Settings.bAimbotEnable && g_Settings.bRagebotEnable)
return;
if (g_Settings.bRagebotEnable)
{
DoRageAimbot(pCmd);
return;
}
if (g_Settings.bAimbotEnable)
{
DoLegitAimbot(pCmd);
return;
}
}
void Aimbot::DoRageAimbot(CUserCmd* pCmd) {
// Check if player is in game
if (!g::pLocalEntity || !g_pEngine->IsInGame())
return;
// Check if player is alive
if (!g::pLocalEntity
|| g::pLocalEntity->IsDormant()
|| !g::pLocalEntity->IsAlive())
return;
// Get some other variables
auto weapon = g::pActiveWeapon;
if (!weapon)
return;
int bestHitbox = 8;
bool isAttacking = (pCmd->buttons & IN_ATTACK || g_Settings.bRagebotAutoFire);
if (!isAttacking)
return;
// Dont aimbot when we have a knife or grenade in our hands
if (weapon->isGrenade() || weapon->GetCSWpnData()->weapon_type() == 0)
return;
g_RageWall.TargetEntities(pCmd);
}
void Aimbot::DoLegitAimbot(CUserCmd* pCmd) {
// Check if player is in game
if (!g::pLocalEntity || !g_pEngine->IsInGame())
return;
// Check if player is alive
if (!g::pLocalEntity
|| g::pLocalEntity->IsDormant()
|| !g::pLocalEntity->IsAlive())
return;
// Get some other variables
auto weapon = g::pActiveWeapon;
if (!weapon)
return;
int bestHitbox = 7;
bool isAttacking = (pCmd->buttons & IN_ATTACK);
if (!isAttacking)
return;
if (weapon->isGrenade() || weapon->GetCSWpnData()->weapon_type() == 0)
return;
// Get a new target
Vector targetHitbox;
C_BaseEntity *target = GetBestTarget(targetHitbox);
// Check if target is Null
if (!target)
return;
// Check if target is behind smoke
if (target->IsBehindSmoke(target))//&& g_Settings.bSmokeCheck)
return;
// TODO: Custom hitbox selection
bestHitbox = getHitbox(weapon);
// Let's check if wee can see the player, if we can, we aim.
CGameTrace tr;
g_RageWall.traceIt(g::pLocalEntity->GetEyePosition(), target->GetBonePos(bestHitbox), MASK_SHOT | CONTENTS_GRATE, g::pLocalEntity, &tr);
if (tr.fraction > 0.97f && tr.fraction != 1.f)
AimAt(pCmd, target, bestHitbox);
}
bool isLocked = false;
C_BaseEntity* Aimbot::GetBestTarget(Vector& outBestPos)
{
// Init some variables
C_BaseEntity* target = nullptr;
int curBestTarget;
float currentFov;
float weaponFov;
float bestFov = 360;
float bestDistance = 8128.f;
// Variables we need later
auto weapon = g::pActiveWeapon;
if (!weapon)
return nullptr;
auto localTeam = g::pLocalEntity->GetTeam();
if (!isLocked && g::bestTarget == 0)
{
// Itterate through all the players in the server
for (int i = 1; i <= g_pEngine->GetMaxClients(); ++i)
{
// Get the entity from the player we are currently itterating on
C_BaseEntity* pPlayerEntity = g_pEntityList->GetClientEntity(i);
// Various checks
if (!pPlayerEntity
|| !pPlayerEntity->IsAlive()
|| pPlayerEntity->IsDormant()
|| pPlayerEntity == g::pLocalEntity
|| pPlayerEntity->GetTeam() == localTeam)
continue;
// Get Fov for each weapon
if (g_Settings.bAimbotEnable)
weaponFov = getFov(weapon);
else
weaponFov = g_Settings.bRagebotFov;
// Get positions from me and target
Vector myPos = g::pLocalEntity->GetBonePos(8);
Vector pEntPos = pPlayerEntity->GetBonePos(8);
// Calculate angle between me and target
QAngle aimAngle = Utils::CalcAngle(myPos, pEntPos);
// Calculate recoil values to compensate aimbot
currentFov = get_fov(g::pCmd->viewangles + g::pLocalEntity->GetPunchAngles() * 2, aimAngle);
// Get Distance between me and target
auto currentDistance = Get3D_Distance(myPos, pEntPos);
// Check if the target is closer to the crosshair and if the target is in range of FOV
if (currentFov < weaponFov && (bestFov == NULL || currentFov < bestFov))
{
bestFov = currentFov;
curBestTarget = i;
target = pPlayerEntity;
}
// Check for distance also
if (currentFov <= weaponFov && currentDistance < bestDistance && (currentFov < bestFov || bestFov == NULL))
{
bestFov = currentFov;
curBestTarget = i;
target = pPlayerEntity;
bestDistance = currentDistance;
}
}
if (g::bestTarget > 0)
{
isLocked = true;
g::bestTarget = curBestTarget;
}
}
if (g::bestTarget > 0)
return g_pEntityList->GetClientEntity(g::bestTarget);
else
return target;
}
bool Aimbot::AutoShoot(CUserCmd* pCmd, C_BaseEntity* BestTarget)
{
C_BaseCombatWeapon* pWeapon = g::pActiveWeapon;
if (!pWeapon)
return false;
float flServerTime = g::pLocalEntity->GetTickBase() * g_pGlobalVars->intervalPerTick;
bool canShoot = !(pWeapon->GetNextPrimaryAttack() > flServerTime) && !(pCmd->buttons & IN_RELOAD);
if (Hitchance(pWeapon, 20) > 20 && !(pCmd->buttons & IN_ATTACK) && canShoot)
pCmd->buttons |= IN_ATTACK;
else
return false;
return true;
}
float Aimbot::Hitchance(C_BaseCombatWeapon* pWeapon, float hitChance)
{
float hitchance = 101;
if (!pWeapon) return 0;
if (hitChance > 0)
{
float inaccuracy = pWeapon->GetInaccuracy();
if (inaccuracy == 0) inaccuracy = 0.0000001f;
inaccuracy = 1 / inaccuracy;
hitchance = inaccuracy;
}
return hitchance;
}
/*
bool Aimbot::CanHitTarget(C_BaseEntity* pTarget)
{
Vector newShittyDistance;
bool hasPenetratedWall = false;
Vector bestHitboxPos;
auto pEnt = pTarget;
Vector hitboxPos;
studiohdr_t* pStudioHdr = g_pMdlInfo->GetStudiomodel2(pEnt->GetModel());
std::vector<int> hitboxes;
if (!pStudioHdr)
return false;
Vector vParent, vChild, sParent, sChild;
for (int j = 0; j < pStudioHdr->numbones; j++)
{
mstudiobone_t* pBone = pStudioHdr->GetBone(j);
if (pBone && (pBone->flags & BONE_USED_BY_HITBOX) && (pBone->parent != -1))
{
hitboxes.push_back(j);
hitboxes.push_back(pBone->parent);
}
}
for (const int &hitbox : hitboxes)
{
Vector pTargetPos = pTarget->GetBonePos(hitbox);
if (g_RageWall.CanHit(pTargetPos))
return true;
}
return false;
}*/
float Aimbot::getFov(C_BaseCombatWeapon* weapon) {
if (weapon->isSniper())
return g_Settings.bAimbotFovSniper;
if (weapon->isRifle())
return g_Settings.bAimbotFovRifle;
if (weapon->isPistol())
return g_Settings.bAimbotFovPistol;
return g_Settings.bAimbotFovRifle;
}
float Aimbot::getSmooth(C_BaseCombatWeapon* weapon) {
if (weapon->isSniper())
return g_Settings.bAimbotSmoothSniper;
if (weapon->isRifle())
return g_Settings.bAimbotSmoothRifle;
if (weapon->isPistol())
return g_Settings.bAimbotSmoothPistol;
return g_Settings.bAimbotFovRifle;
}
int Aimbot::getHitbox(C_BaseCombatWeapon* weapon) {
int curSelected = 3;
if (weapon->isSniper())
curSelected = g_Settings.bAimbotHitboxSniper;
if (weapon->isRifle())
curSelected = g_Settings.bAimbotHitboxRifle;
if (weapon->isPistol())
curSelected = g_Settings.bAimbotHitboxPistol;
switch (curSelected)
{
case 0: return 8;
case 1: return 4;
case 2: return 6;
default: return 8;
}
}
void Aimbot::AimAtVec(CUserCmd* pCmd, C_BaseEntity* pEnt, Vector hitbox)
{
if (!g::pLocalEntity || !g_pEngine->IsInGame())
return;
auto weapon = g::pActiveWeapon;
if (!weapon)
return;
if (weapon->GetAmmo() == 0 || pCmd->buttons & IN_RELOAD)
return;
auto localTeam = g::pLocalEntity->GetTeam();
if (!pEnt
|| !pEnt->IsAlive()
|| pEnt->IsDormant()
|| pEnt == g::pLocalEntity
|| pEnt->GetTeam() == localTeam
|| pEnt->IsImmune())
return;
Vector pHitboxServerDistance;
bool doBacktrack = false;
QAngle tempAimAngle = Utils::CalcAngle(g::pLocalEntity->GetBonePos(8), pEnt->GetBonePos(8));
float bestFov = get_fov(pCmd->viewangles, tempAimAngle);
float curWeaponFov = getFov(g::pActiveWeapon);
Vector actualHitBox = hitbox;
Vector myPos = g::pLocalEntity->GetEyePosition();
// If we have a better tick to aim at, move our target to that tick
if (doBacktrack)
actualHitBox -= pHitboxServerDistance;
Vector pEntPos = actualHitBox;
// Velocity Compensation
pEntPos += pEnt->GetVelocity() * g_pGlobalVars->intervalPerTick;
// Get angle we are supposed to aim at
QAngle aimAngle = Utils::CalcAngle(myPos, pEntPos);
if (g::pLocalEntity->GetPunchAngles().Length() > 0)
aimAngle -= g::pLocalEntity->GetPunchAngles() * 2;
// Make sure we dont aim out of bounds otherwise we'll get untrusted
Utils::ClampViewAngles(aimAngle);
// Get the difference between aim angle and your viewangle
QAngle deltaAngle = pCmd->viewangles - aimAngle;
// Make sure we dont aim out of bounds otherwise we'll get untrusted
Utils::ClampViewAngles(deltaAngle);
// Get the fov
auto fov = get_fov(pCmd->viewangles + g::pLocalEntity->GetPunchAngles() * 2, aimAngle);
QAngle finalAngle;
finalAngle = pCmd->viewangles - deltaAngle;
Utils::ClampViewAngles(finalAngle);
float currentFov;
currentFov = g_Settings.bRagebotFov;
if (fov <= currentFov)
{
if (!g_Settings.bRagebotSilent)
{
g_pEngine->SetViewAngles(finalAngle);
}
pCmd->viewangles = finalAngle;
}
}
void Aimbot::AimAt(CUserCmd* pCmd, C_BaseEntity* pEnt, int hitbox)
{
if (!g::pLocalEntity || !g_pEngine->IsInGame())
return;
auto weapon = g::pActiveWeapon;
if (!weapon)
return;
if (weapon->GetAmmo() == 0 || pCmd->buttons & IN_RELOAD)
return;
auto localTeam = g::pLocalEntity->GetTeam();
if (!pEnt
|| !pEnt->IsAlive()
|| pEnt->IsDormant()
|| pEnt == g::pLocalEntity
|| pEnt->GetTeam() == localTeam
|| pEnt->IsImmune())
return;
Vector pHitboxServerDistance;
bool doBacktrack = false;
QAngle tempAimAngle = Utils::CalcAngle(g::pLocalEntity->GetBonePos(8), pEnt->GetBonePos(8));
float bestFov = get_fov(pCmd->viewangles, tempAimAngle);
float curWeaponFov = getFov(g::pActiveWeapon);
if (g_Settings.bAimbotBacktrack && g_Settings.bAimbotEnable)
{
// Loop through backtracking ticks
for (int i = 0; i < g_Settings.bAimbotBacktrackTicks; i++)
{
Vector pHitboxPos = l_SavedTicks[pEnt->EntIndex()][i].hitboxPos;
QAngle pHitboxAngle = Utils::CalcAngle(g::pLocalEntity->GetBonePos(8), pHitboxPos);
auto newFov = g_Aimbot.get_fov(pCmd->viewangles, pHitboxAngle);
if (l_SavedTicks[pEnt->EntIndex()][i].simtime <= g::pLocalEntity->GetSimulationTime() - 1)
continue;
// Is our fov closer to the tick we are currently itterating on?
if (newFov < curWeaponFov && newFov < bestFov)
{
bestFov = newFov;
doBacktrack = true;
pHitboxServerDistance = Vector(sqrt((pHitboxPos.x - pEnt->GetBonePos(8).x) * (pHitboxPos.x - pEnt->GetBonePos(8).x)), sqrt((pHitboxPos.y - pEnt->GetBonePos(8).y) * (pHitboxPos.y - pEnt->GetBonePos(8).y)), 0);
}
}
}
Vector actualHitBox = pEnt->GetBonePos(hitbox);
Vector myPos = g::pLocalEntity->GetEyePosition();
// If we have a better tick to aim at, move our target to that tick
if (doBacktrack)
actualHitBox -= pHitboxServerDistance;
Vector pEntPos = actualHitBox;
// Velocity Compensation
pEntPos += pEnt->GetVelocity() * g_pGlobalVars->intervalPerTick;
// Get angle we are supposed to aim at
QAngle aimAngle = Utils::CalcAngle(myPos, pEntPos);
if (g::pLocalEntity->GetPunchAngles().Length() > 0)
aimAngle -= g::pLocalEntity->GetPunchAngles() * 2;
// Make sure we dont aim out of bounds otherwise we'll get untrusted
Utils::ClampViewAngles(aimAngle);
// Get the difference between aim angle and your viewangle
QAngle deltaAngle = pCmd->viewangles - aimAngle;
// Make sure we dont aim out of bounds otherwise we'll get untrusted
Utils::ClampViewAngles(deltaAngle);
// Get the fov
auto fov = get_fov(pCmd->viewangles + g::pLocalEntity->GetPunchAngles() * 2, aimAngle);
QAngle finalAngle;
// TODO: Custom smoothing based on settings / weapon here
float currentSmooth;
if (g_Settings.bAimbotEnable)
currentSmooth = getSmooth(weapon);
else
currentSmooth = 1.f;
finalAngle = pCmd->viewangles - deltaAngle / currentSmooth;
Utils::ClampViewAngles(finalAngle);
float currentFov;
if (g_Settings.bAimbotEnable)
currentFov = getFov(weapon);
else
currentFov = g_Settings.bRagebotFov;
if (fov <= currentFov)
{
if (!g_Settings.bRagebotSilent)
{
g_pEngine->SetViewAngles(finalAngle);
}
pCmd->viewangles = finalAngle;
}
}
float Aimbot::Get3D_Distance(Vector src, Vector dst) {
return sqrt(powf(src[0] - dst[0], 2.f) + powf(src[1] - dst[1], 2.f) + powf(src[2] - dst[2], 2.f));
}
void Aimbot::MakeVector(QAngle angle, Vector& vector)
{
float pitch = float(angle[0] * PI / 180);
float yaw = float(angle[1] * PI / 180);
float tmp = float(cos(pitch));
vector[0] = float(-tmp * -cos(yaw));
vector[1] = float(sin(yaw)*tmp);
vector[2] = float(-sin(pitch));
}
float Aimbot::get_fov(const QAngle &viewAngles, const QAngle &aimAngles)
{
Vector ang, aim;
MakeVector(viewAngles, aim);
MakeVector(aimAngles, ang);
return RAD2DEG(acos(aim.Dot(ang) / aim.LengthSqr()));
}
| 25.560311 | 212 | 0.702923 | NoelWriter |
bdcf0f01282935ff7d2ab422e5bd939e63177e61 | 168 | hpp | C++ | samples/dependency/mod1.hpp | tlammi/rtfw | 7a993e83b4d4e6ba7179219fd3667f42a2ae07e6 | [
"MIT"
] | null | null | null | samples/dependency/mod1.hpp | tlammi/rtfw | 7a993e83b4d4e6ba7179219fd3667f42a2ae07e6 | [
"MIT"
] | null | null | null | samples/dependency/mod1.hpp | tlammi/rtfw | 7a993e83b4d4e6ba7179219fd3667f42a2ae07e6 | [
"MIT"
] | null | null | null | #pragma once
#include "rtfw/module.hpp"
struct Mod1{
static rtfw::Config config(){
return {};
}
Mod1(const rtfw::Config& conf);
~Mod1();
int foo() const;
};
| 11.2 | 32 | 0.630952 | tlammi |
bdcf8103512a939066841b0b34a20d00468ab4d8 | 426 | cpp | C++ | Codigos de ejercicios en cpp/Programa 7.cpp | EulisesBrazon/ejercicios-c- | 700235bced91bc6f508ca6d203ea7ee7c241006c | [
"Apache-2.0"
] | null | null | null | Codigos de ejercicios en cpp/Programa 7.cpp | EulisesBrazon/ejercicios-c- | 700235bced91bc6f508ca6d203ea7ee7c241006c | [
"Apache-2.0"
] | null | null | null | Codigos de ejercicios en cpp/Programa 7.cpp | EulisesBrazon/ejercicios-c- | 700235bced91bc6f508ca6d203ea7ee7c241006c | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int numi,i=0,j,d=1;
double numf;
cout<<"introdusca el numero con decimales"<<endl;
cin>>numf;
numi=numf;
cout<<"los decimales son: "<<numf-numi<<endl;
while(numi!=numf)
{
numf=numf*10;
numi=numf;
i++;
}
for(j=0;j<i;j++)
{
d=d*10;
}
numi=numi/d;
numf=numf-(numi*d);
cout<<"pasados a enteros: "<<numf<<endl;
getch();
return 0;
}
| 14.689655 | 50 | 0.617371 | EulisesBrazon |
bdcfb0daf2af74f715cf7c4e3cc6754f2282e048 | 2,578 | cpp | C++ | src/test/scalar/functions/nonsmooth_functions/fmax_test.cpp | stan-dev/nomad | a21149ef9f4d53a198e6fdb06cfd0363d3df69e7 | [
"BSD-3-Clause"
] | 23 | 2015-12-11T20:06:57.000Z | 2021-01-15T18:59:58.000Z | src/test/scalar/functions/nonsmooth_functions/fmax_test.cpp | stan-dev/nomad | a21149ef9f4d53a198e6fdb06cfd0363d3df69e7 | [
"BSD-3-Clause"
] | 2 | 2015-12-15T08:12:01.000Z | 2016-07-17T01:36:56.000Z | src/test/scalar/functions/nonsmooth_functions/fmax_test.cpp | stan-dev/nomad | a21149ef9f4d53a198e6fdb06cfd0363d3df69e7 | [
"BSD-3-Clause"
] | 2 | 2017-10-13T17:40:34.000Z | 2021-03-08T19:17:51.000Z | #include <gtest/gtest.h>
#include <math.h>
#include <string>
#include <src/autodiff/base_functor.hpp>
#include <src/scalar/functions.hpp>
#include <src/test/io_validation.hpp>
#include <src/test/finite_difference.hpp>
template <typename T>
class fmax_vv_eval_func: public nomad::base_functor<T> {
public:
T operator()(const Eigen::VectorXd& x) const {
return fmax(nomad::tests::construct_unsafe_var<T>(x[0]),
nomad::tests::construct_unsafe_var<T>(x[1]));
}
static std::string name() { return "fmax_vv"; }
};
template <typename T>
class fmax_vd_eval_func: public nomad::base_functor<T> {
public:
T operator()(const Eigen::VectorXd& x) const {
return fmax(nomad::tests::construct_unsafe_var<T>(x[0]),
x[1]);
}
static std::string name() { return "fmax_vd"; }
};
template <typename T>
class fmax_dv_eval_func: public nomad::base_functor<T> {
public:
T operator()(const Eigen::VectorXd& x) const {
return fmax(x[0],
nomad::tests::construct_unsafe_var<T>(x[1]));
}
static std::string name() { return "fmax_dv"; }
};
template <typename T>
class fmax_vv_grad_func: public nomad::base_functor<T> {
public:
T operator()(const Eigen::VectorXd& x) const {
T v1 = x[0];
T v2 = x[1];
return fmax(exp(v1), exp(v2));
}
static std::string name() { return "fmax_vv"; }
};
template <typename T>
class fmax_vd_grad_func: public nomad::base_functor<T> {
public:
T operator()(const Eigen::VectorXd& x) const {
return fmax(exp(T(x[0])), exp(0.5));
}
static std::string name() { return "fmax_vd"; }
};
template <typename T>
class fmax_dv_grad_func: public nomad::base_functor<T> {
public:
T operator()(const Eigen::VectorXd& x) const {
return fmax(exp(0.5), exp(T(x[0])));
}
static std::string name() { return "fmax_dv"; }
};
TEST(ScalarNonSmoothFunctions, Fmax) {
nomad::eigen_idx_t d = 2;
Eigen::VectorXd x1(d);
x1[0] = 0.75;
x1[1] = 0.25;
nomad::tests::test_validation<fmax_vv_eval_func>(x1);
nomad::tests::test_validation<fmax_vd_eval_func>(x1);
nomad::tests::test_validation<fmax_dv_eval_func>(x1);
nomad::tests::test_derivatives<fmax_vv_grad_func>(x1);
x1 *= -1;
nomad::tests::test_derivatives<fmax_vv_grad_func>(x1);
Eigen::VectorXd x2 = Eigen::VectorXd::Ones(1);
x2[0] = 0.75;
nomad::tests::test_derivatives<fmax_vd_grad_func>(x2);
nomad::tests::test_derivatives<fmax_dv_grad_func>(x2);
x2[0] = 0.25;
nomad::tests::test_derivatives<fmax_vd_grad_func>(x2);
nomad::tests::test_derivatives<fmax_dv_grad_func>(x2);
}
| 26.57732 | 61 | 0.674166 | stan-dev |
7524e0acb600b2a45b765da97e5fdbbbe1ba34c3 | 780 | hpp | C++ | OracleSolaris_OpenJDK_Builder/patches-17/patch-src_hotspot_os__cpu_solaris__x86_prefetch__solaris__x86.inline.hpp | gco/oraclesolaris-contrib | f9905a8758a50a44720f5500e19b5f2528c6b6c8 | [
"UPL-1.0"
] | null | null | null | OracleSolaris_OpenJDK_Builder/patches-17/patch-src_hotspot_os__cpu_solaris__x86_prefetch__solaris__x86.inline.hpp | gco/oraclesolaris-contrib | f9905a8758a50a44720f5500e19b5f2528c6b6c8 | [
"UPL-1.0"
] | null | null | null | OracleSolaris_OpenJDK_Builder/patches-17/patch-src_hotspot_os__cpu_solaris__x86_prefetch__solaris__x86.inline.hpp | gco/oraclesolaris-contrib | f9905a8758a50a44720f5500e19b5f2528c6b6c8 | [
"UPL-1.0"
] | null | null | null | $NetBSD$
Support SunOS/gcc.
--- src/hotspot/os_cpu/solaris_x86/prefetch_solaris_x86.inline.hpp.orig 2019-01-08 12:44:56.000000000 +0000
+++ src/hotspot/os_cpu/solaris_x86/prefetch_solaris_x86.inline.hpp
@@ -34,14 +34,22 @@ extern "C" {
inline void Prefetch::read (void *loc, intx interval) {
#ifdef AMD64
+# ifdef SPARC_WORKS
_Prefetch_read(loc, interval);
+# else
+ __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));
+# endif
#endif // AMD64
}
// Use of this method should be gated by VM_Version::has_prefetchw.
inline void Prefetch::write(void *loc, intx interval) {
#ifdef AMD64
+# ifdef SPARC_WORKS
_Prefetch_write(loc, interval);
+# else
+ __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));
+# endif
#endif // AMD64
}
| 26 | 107 | 0.669231 | gco |
7525cd500fbb8b24fd11dcd145610a42237a65ea | 602 | cpp | C++ | 1518_num_water_bottles/num_water_bottles.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | 1518_num_water_bottles/num_water_bottles.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | 1518_num_water_bottles/num_water_bottles.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | /*
* @Date: 2021-12-17 08:27:08
* @Author: Mengsen Wang
* @LastEditors: Mengsen Wang
* @LastEditTime: 2021-12-17 08:28:14
*/
#include <cassert>
class Solution {
public:
int numWaterBottles(int numBottles, int numExchange) {
return numBottles >= numExchange
? (numBottles - numExchange) / (numExchange - 1) + 1 + numBottles
: numBottles;
}
};
int main() {
assert(Solution().numWaterBottles(9, 3) == 13);
assert(Solution().numWaterBottles(15, 4) == 19);
assert(Solution().numWaterBottles(5, 5) == 6);
assert(Solution().numWaterBottles(2, 3) == 2);
} | 25.083333 | 80 | 0.631229 | Mengsen-W |
7525f6edd892f2295f908348079655f1af062b87 | 3,904 | cpp | C++ | unittests/test_description_t.cpp | lysevi/solidarity | c4febebce2247b5ab628bea226aa5e7e4805a1e5 | [
"Apache-2.0"
] | 1 | 2019-08-16T06:52:10.000Z | 2019-08-16T06:52:10.000Z | unittests/test_description_t.cpp | lysevi/solidarity | c4febebce2247b5ab628bea226aa5e7e4805a1e5 | [
"Apache-2.0"
] | 10 | 2019-05-14T13:25:41.000Z | 2019-08-19T07:05:07.000Z | unittests/test_description_t.cpp | lysevi/solidarity | c4febebce2247b5ab628bea226aa5e7e4805a1e5 | [
"Apache-2.0"
] | null | null | null | #include "test_description_t.h"
void test_description_t::init(size_t cluster_size, bool add_listener_handler) {
std::vector<unsigned short> ports(cluster_size);
std::iota(ports.begin(), ports.end(), (unsigned short)(8000));
std::cerr << "start nodes" << std::endl;
unsigned short client_port = 10000;
for (auto p : ports) {
std::vector<unsigned short> out_ports;
out_ports.reserve(ports.size() - 1);
std::copy_if(ports.begin(),
ports.end(),
std::back_inserter(out_ports),
[p](const auto v) { return v != p; });
EXPECT_EQ(out_ports.size(), ports.size() - 1);
std::vector<std::string> out_addrs;
out_addrs.reserve(out_ports.size());
std::transform(out_ports.begin(),
out_ports.end(),
std::back_inserter(out_addrs),
[](const auto prt) {
return solidarity::utils::strings::to_string("localhost:", prt);
});
solidarity::node::params_t params;
params.port = p;
params.client_port = client_port++;
params.thread_count = 1;
params.cluster = out_addrs;
params.name = solidarity::utils::strings::to_string("node_", p);
std::cerr << params.name << " starting..." << std::endl;
auto log_prefix = solidarity::utils::strings::to_string(params.name, "> ");
auto node_logger = std::make_shared<solidarity::utils::logging::prefix_logger>(
solidarity::utils::logging::logger_manager::instance()->get_shared_logger(),
log_prefix);
auto state_machines = get_state_machines();
std::unordered_map<uint32_t, solidarity::abstract_state_machine *> for_ctor(
state_machines.size());
for (auto &sms_kv : state_machines) {
for_ctor.insert({sms_kv.first, sms_kv.second.get()});
}
auto n = std::make_shared<solidarity::node>(node_logger, params, for_ctor);
n->start();
if (add_listener_handler) {
n->add_event_handler([](const solidarity::client_event_t &ev) {
if (ev.kind == solidarity::client_event_t::event_kind::COMMAND_STATUS) {
std::stringstream ss;
ss << "command " << solidarity::to_string(ev);
std::cerr << ss.str() << std::endl;
}
});
}
solidarity::client::params_t cpar(
solidarity::utils::strings::to_string("client_", params.name));
cpar.threads_count = 1;
cpar.host = "localhost";
cpar.port = params.client_port;
auto c = std::make_shared<solidarity::client>(cpar);
c->connect();
while (!c->is_connected()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
EXPECT_EQ(n->connections_count(), size_t(1));
consumers[params.name] = state_machines;
nodes[params.name] = n;
clients[params.name] = c;
}
}
std::unordered_set<solidarity::node_name> test_description_t::wait_election() {
std::cerr << "wait election" << std::endl;
std::unordered_set<solidarity::node_name> leaders;
while (true) {
leaders.clear();
for (auto &kv : nodes) {
if (kv.second->state().node_kind == solidarity::NODE_KIND::LEADER) {
leaders.insert(kv.second->self_name());
}
}
if (leaders.size() == 1) {
auto leader_name = *leaders.begin();
bool election_complete = true;
for (auto &kv : nodes) {
auto state = kv.second->state();
auto nkind = state.node_kind;
if (nkind != solidarity::NODE_KIND::LEADER
&& nkind != solidarity::NODE_KIND::FOLLOWER) {
election_complete = false;
break;
}
if ((nkind == solidarity::NODE_KIND::LEADER
|| nkind == solidarity::NODE_KIND::FOLLOWER)
&& state.leader != leader_name) {
election_complete = false;
break;
}
}
if (election_complete) {
break;
}
}
}
return leaders;
} | 34.245614 | 85 | 0.605533 | lysevi |
752c533e5117d7424a117759df77b30c9b5487e8 | 14,123 | hpp | C++ | Tools/bjs.u/External/include/stratosphere/ipc/ipc_service_session.hpp | BrewJS/HAC.js | 998f82cbfe5ed245825b0ad8252f09691788dc6c | [
"MIT"
] | 103 | 2018-07-10T10:51:36.000Z | 2022-03-24T15:55:35.000Z | Tools/bjs.u/External/include/stratosphere/ipc/ipc_service_session.hpp | BrewJS/HAC.js | 998f82cbfe5ed245825b0ad8252f09691788dc6c | [
"MIT"
] | 5 | 2018-07-10T10:55:24.000Z | 2019-04-12T13:04:46.000Z | Tools/bjs.u/External/include/stratosphere/ipc/ipc_service_session.hpp | BrewJS/HAC.js | 998f82cbfe5ed245825b0ad8252f09691788dc6c | [
"MIT"
] | 15 | 2018-07-10T10:16:25.000Z | 2022-03-31T12:50:12.000Z | /*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include "../iwaitable.hpp"
#include "ipc_service_object.hpp"
#include "ipc_serialization.hpp"
enum HipcControlCommand : u32 {
HipcControlCommand_ConvertCurrentObjectToDomain = 0,
HipcControlCommand_CopyFromCurrentDomain = 1,
HipcControlCommand_CloneCurrentObject = 2,
HipcControlCommand_QueryPointerBufferSize = 3,
HipcControlCommand_CloneCurrentObjectEx = 4
};
#define RESULT_DEFER_SESSION (0x6580A)
class ServiceSession : public IWaitable
{
protected:
Handle session_handle;
std::vector<unsigned char> pointer_buffer;
ServiceObjectHolder obj_holder;
ServiceObjectHolder control_holder = ServiceObjectHolder(std::make_shared<IHipcControlService>(this));
u8 backup_tls[0x100];
ServiceSession(Handle s_h) : session_handle(s_h) { }
public:
template<typename T>
ServiceSession(Handle s_h, size_t pbs) : session_handle(s_h), pointer_buffer(pbs), obj_holder(std::make_shared<T>()) { }
ServiceSession(Handle s_h, size_t pbs, ServiceObjectHolder &&h) : session_handle(s_h), pointer_buffer(pbs), obj_holder(std::move(h)) { }
virtual ~ServiceSession() override {
svcCloseHandle(this->session_handle);
}
SessionManagerBase *GetSessionManager() {
return static_cast<SessionManagerBase *>(this->GetManager());
}
DomainManager *GetDomainManager() {
return static_cast<DomainManager *>(this->GetSessionManager());
}
Result Receive() {
int handle_index;
/* Prepare pointer buffer... */
IpcCommand c;
ipcInitialize(&c);
if (this->pointer_buffer.size() > 0) {
ipcAddRecvStatic(&c, this->pointer_buffer.data(), this->pointer_buffer.size(), 0);
ipcPrepareHeader(&c, 0);
/* Fix libnx bug in serverside C descriptor handling. */
((u32 *)armGetTls())[1] &= 0xFFFFC3FF;
((u32 *)armGetTls())[1] |= (2) << 10;
} else {
ipcPrepareHeader(&c, 0);
}
/* Receive. */
Result rc = svcReplyAndReceive(&handle_index, &this->session_handle, 1, 0, U64_MAX);
if (R_SUCCEEDED(rc)) {
std::memcpy(this->backup_tls, armGetTls(), sizeof(this->backup_tls));
}
return rc;
}
Result Reply() {
int handle_index;
return svcReplyAndReceive(&handle_index, &this->session_handle, 0, this->session_handle, 0);
}
/* For preparing basic replies. */
Result PrepareBasicResponse(IpcResponseContext *ctx, Result rc) {
ipcInitialize(&ctx->reply);
struct {
u64 magic;
u64 result;
} *raw = (decltype(raw))ipcPrepareHeader(&ctx->reply, sizeof(*raw));
raw->magic = SFCO_MAGIC;
raw->result = rc;
return raw->result;
}
Result PrepareBasicDomainResponse(IpcResponseContext *ctx, Result rc) {
ipcInitialize(&ctx->reply);
struct {
DomainResponseHeader hdr;
u64 magic;
u64 result;
} *raw = (decltype(raw))ipcPrepareHeader(&ctx->reply, sizeof(*raw));
raw->hdr = (DomainResponseHeader){0};
raw->magic = SFCO_MAGIC;
raw->result = rc;
return raw->result;
}
/* For making a new response context. */
void InitializeResponseContext(IpcResponseContext *ctx) {
std::memset(ctx, 0, sizeof(*ctx));
ctx->manager = this->GetSessionManager();
ctx->obj_holder = &this->obj_holder;
ctx->pb = this->pointer_buffer.data();
ctx->pb_size = this->pointer_buffer.size();
}
/* IWaitable */
virtual Handle GetHandle() {
return this->session_handle;
}
virtual Result GetResponse(IpcResponseContext *ctx) {
Result rc = 0xF601;
FirmwareVersion fw = GetRuntimeFirmwareVersion();
const ServiceCommandMeta *dispatch_table = ctx->obj_holder->GetDispatchTable();
size_t entry_count = ctx->obj_holder->GetDispatchTableEntryCount();
if (IsDomainObject(ctx->obj_holder)) {
switch (ctx->request.InMessageType) {
case DomainMessageType_Invalid:
return 0xF601;
case DomainMessageType_Close:
return PrepareBasicDomainResponse(ctx, ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->request.InThisObjectId));
case DomainMessageType_SendMessage:
{
auto sub_obj = ctx->obj_holder->GetServiceObject<IDomainObject>()->GetObject(ctx->request.InThisObjectId);
if (sub_obj == nullptr) {
return PrepareBasicDomainResponse(ctx, 0x3D80B);
}
dispatch_table = sub_obj->GetDispatchTable();
entry_count = sub_obj->GetDispatchTableEntryCount();
}
}
}
for (size_t i = 0; i < entry_count; i++) {
if (ctx->cmd_id == dispatch_table[i].cmd_id && dispatch_table[i].fw_low <= fw && fw <= dispatch_table[i].fw_high) {
rc = dispatch_table[i].handler(ctx);
break;
}
}
return rc;
}
virtual Result HandleReceived() {
IpcResponseContext ctx;
this->InitializeResponseContext(&ctx);
ctx.cmd_type = (IpcCommandType)(*(u16 *)(armGetTls()));
ctx.rc = 0;
/* Parse based on command type. */
switch (ctx.cmd_type) {
case IpcCommandType_Invalid:
case IpcCommandType_LegacyRequest:
case IpcCommandType_LegacyControl:
return 0xF601;
case IpcCommandType_Close:
{
/* Clean up gracefully. */
PrepareBasicResponse(&ctx, 0);
this->Reply();
}
return 0xF601;
case IpcCommandType_Control:
case IpcCommandType_ControlWithContext:
ctx.rc = ipcParse(&ctx.request);
ctx.obj_holder = &this->control_holder;
break;
case IpcCommandType_Request:
case IpcCommandType_RequestWithContext:
if (IsDomainObject(&this->obj_holder)) {
ctx.rc = ipcParseDomainRequest(&ctx.request);
} else {
ctx.rc = ipcParse(&ctx.request);
}
break;
default:
return 0xF601;
}
if (R_SUCCEEDED(ctx.rc)) {
ctx.cmd_id = ((u32 *)ctx.request.Raw)[2];
this->PreProcessRequest(&ctx);
ctx.rc = this->GetResponse(&ctx);
}
if (ctx.rc == RESULT_DEFER_SESSION) {
/* Session defer. */
this->SetDeferred(true);
} else if (ctx.rc == 0xF601) {
/* Session close, nothing to do. */
} else {
if (R_SUCCEEDED(ctx.rc)) {
this->PostProcessResponse(&ctx);
}
ctx.rc = this->Reply();
if (ctx.rc == 0xEA01) {
ctx.rc = 0x0;
}
this->CleanupResponse(&ctx);
}
return ctx.rc;
}
virtual Result HandleDeferred() override {
memcpy(armGetTls(), this->backup_tls, sizeof(this->backup_tls));
Result rc = this->HandleReceived();
if (rc != RESULT_DEFER_SESSION) {
this->SetDeferred(false);
}
return rc;
}
virtual Result HandleSignaled(u64 timeout) {
Result rc;
if (R_SUCCEEDED(rc = this->Receive())) {
rc = this->HandleReceived();
}
return rc;
}
virtual void PreProcessRequest(IpcResponseContext *ctx) {
/* ... */
(void)(ctx);
}
virtual void PostProcessResponse(IpcResponseContext *ctx) {
/* ... */
(void)(ctx);
}
virtual void CleanupResponse(IpcResponseContext *ctx) {
std::memset(this->backup_tls, 0, sizeof(this->backup_tls));
}
public:
class IHipcControlService : public IServiceObject {
private:
ServiceSession *session;
public:
explicit IHipcControlService(ServiceSession *s) : session(s) {
}
virtual ~IHipcControlService() override { }
Result ConvertCurrentObjectToDomain(Out<u32> object_id) {
/* Allocate new domain. */
auto new_domain = this->session->GetDomainManager()->AllocateDomain();
if (new_domain == nullptr) {
return 0x1900B;
}
/* Reserve an object in the domain for our session. */
u32 reserved_id;
Result rc = new_domain->ReserveObject(&reserved_id);
if (R_FAILED(rc)) {
return rc;
}
new_domain->SetObject(reserved_id, std::move(this->session->obj_holder));
this->session->obj_holder = std::move(ServiceObjectHolder(std::move(new_domain)));
/* Return the object id. */
object_id.SetValue(reserved_id);
return 0;
}
Result CopyFromCurrentDomain(Out<MovedHandle> out_h, u32 id) {
auto domain = this->session->obj_holder.GetServiceObject<IDomainObject>();
if (domain == nullptr) {
return 0x3D60B;
}
auto object = domain->GetObject(id);
if (object == nullptr) {
return 0x3D80B;
}
Handle server_h, client_h;
if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) {
/* N aborts here. Should we error code? */
std::abort();
}
this->session->GetSessionManager()->AddSession(server_h, std::move(object->Clone()));
out_h.SetValue(client_h);
return 0;
}
void CloneCurrentObject(Out<MovedHandle> out_h) {
Handle server_h, client_h;
if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) {
/* N aborts here. Should we error code? */
std::abort();
}
this->session->GetSessionManager()->AddSession(server_h, std::move(this->session->obj_holder.Clone()));
out_h.SetValue(client_h);
}
void QueryPointerBufferSize(Out<u16> size) {
size.SetValue(this->session->pointer_buffer.size());
}
void CloneCurrentObjectEx(Out<MovedHandle> out_h, u32 which) {
/* TODO: Figure out what this u32 controls. */
return CloneCurrentObject(out_h);
}
public:
DEFINE_SERVICE_DISPATCH_TABLE {
MakeServiceCommandMeta<HipcControlCommand_ConvertCurrentObjectToDomain, &ServiceSession::IHipcControlService::ConvertCurrentObjectToDomain>(),
MakeServiceCommandMeta<HipcControlCommand_CopyFromCurrentDomain, &ServiceSession::IHipcControlService::CopyFromCurrentDomain>(),
MakeServiceCommandMeta<HipcControlCommand_CloneCurrentObject, &ServiceSession::IHipcControlService::CloneCurrentObject>(),
MakeServiceCommandMeta<HipcControlCommand_QueryPointerBufferSize, &ServiceSession::IHipcControlService::QueryPointerBufferSize>(),
MakeServiceCommandMeta<HipcControlCommand_CloneCurrentObjectEx, &ServiceSession::IHipcControlService::CloneCurrentObjectEx>(),
};
};
};
| 39.560224 | 162 | 0.509311 | BrewJS |
752eaa39f006be3d52a790b98bde796b2ff5940c | 1,074 | cpp | C++ | src/output_files.cpp | KevinBoxuGao/temperatureTimeAdjustor | 2e8941bf7217d21afdc21c9ce217cd30d6b85238 | [
"MIT"
] | null | null | null | src/output_files.cpp | KevinBoxuGao/temperatureTimeAdjustor | 2e8941bf7217d21afdc21c9ce217cd30d6b85238 | [
"MIT"
] | null | null | null | src/output_files.cpp | KevinBoxuGao/temperatureTimeAdjustor | 2e8941bf7217d21afdc21c9ce217cd30d6b85238 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include "output_files.h"
OutputFiles::OutputFiles(std::vector<std::string> base_data) {
base_data_template = base_data;
}
void OutputFiles::Adjust(const std::string file_name) {
std::ofstream output("output/"+file_name+".txt");
std::ifstream temperature_file;
std::string file_line;
temperature_file.open("input/TemperatureChanges/" + file_name + ".csv");
if(temperature_file.is_open()) {
for(int i = 0; i < 9; i++) {
getline(temperature_file, file_line);
}
for(unsigned int x = 0; x < base_data_template.size(); x++) {
std::string substr;
getline(temperature_file, file_line);
std::istringstream iss(file_line);
for(int x = 0; x < 4; x++) {
getline(iss, substr, ',');
}
output << base_data_template[x] << substr << std::endl;
}
}
else{
std::cout << "missing temperature file" << std::endl;
}
}
| 29.027027 | 76 | 0.588454 | KevinBoxuGao |
7530917c3844fce27baf17f6adea6b26be9d4b49 | 711 | hh | C++ | pes.timed/utilities.hh | petercfontana/TimeSolver | fb3bc660af90f58255e2526bee9a36fc9357deb0 | [
"MIT"
] | 4 | 2018-12-19T14:30:27.000Z | 2022-03-20T20:19:20.000Z | pes.timed/utilities.hh | petercfontana/TimeSolver | fb3bc660af90f58255e2526bee9a36fc9357deb0 | [
"MIT"
] | null | null | null | pes.timed/utilities.hh | petercfontana/TimeSolver | fb3bc660af90f58255e2526bee9a36fc9357deb0 | [
"MIT"
] | 2 | 2019-04-24T03:18:20.000Z | 2019-09-13T07:49:00.000Z | /**
* Utility functions.
*
* @author Jeroen Keiren
* @copyright MIT Licence, see the accompanying LICENCE.txt.
*/
#ifndef UTILITIES_HH
#define UTILITIES_HH
#include <algorithm>
#include <vector>
inline bool is_power_of_two(std::size_t n) {
if (n == 0) {
return false;
} else {
return (n & (n - 1)) == 0;
}
}
template<typename T>
void delete_vector_elements(std::vector<T*>& vec)
{
std::for_each(vec.begin(), vec.end(), [](T* t) { delete t; });
}
template<typename T>
void deep_copy(std::vector<T*>& out, const std::vector<T*>& in)
{
out.reserve(out.size()+in.size());
std::for_each(in.begin(), in.end(), [&](T* t) { out.emplace_back(new T(*t)); });
}
#endif // UTILITIES_HH
| 19.216216 | 82 | 0.625879 | petercfontana |
75322367403aaca015a42f6e39d6753e1577dc63 | 523 | cpp | C++ | cf/1076-A.cpp | PIPIKAI/ACM | b8e4416a29c0619946c9b73b0fe5699b6e96e782 | [
"MIT"
] | null | null | null | cf/1076-A.cpp | PIPIKAI/ACM | b8e4416a29c0619946c9b73b0fe5699b6e96e782 | [
"MIT"
] | null | null | null | cf/1076-A.cpp | PIPIKAI/ACM | b8e4416a29c0619946c9b73b0fe5699b6e96e782 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f
#define mem(a,b) memset( a,b,sizeof a)
int main()
{
std::ios::sync_with_stdio(false);
int n;
cin>>n;
{
string s;
int flag=0;
cin>>s;
for(int i=1;i<n;i++)
{
if(s[i]<s[i-1])
{
s.erase(i-1,1);
flag=1;
break;
}
}
if(!flag)
s.erase(n-1,1);
cout<<s<<endl;
}
return 0;
}
| 16.870968 | 39 | 0.422562 | PIPIKAI |
753fa5393f2d98fc97880bd2303ab884c682b90e | 14,527 | cc | C++ | test/rebuild_graphs.cc | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 40 | 2015-03-10T07:55:39.000Z | 2021-06-11T10:13:56.000Z | test/rebuild_graphs.cc | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 297 | 2015-04-30T10:02:04.000Z | 2022-03-09T13:31:54.000Z | test/rebuild_graphs.cc | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 29 | 2015-08-03T10:04:15.000Z | 2021-11-25T12:21:00.000Z | /*
** Copyright 2013-2015 Centreon
**
** 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.
**
** For more information : [email protected]
*/
#include <sys/stat.h>
#include <QDateTime>
#include <QFileInfo>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include "com/centreon/broker/exceptions/msg.hh"
#include "test/config.hh"
#include "test/engine.hh"
#include "test/generate.hh"
#include "test/misc.hh"
#include "test/rrd_file.hh"
#include "test/vars.hh"
using namespace com::centreon::broker;
#define DB_NAME "broker_rebuild_graphs"
#define HOST_COUNT 2
#define SERVICES_BY_HOST 6
// Local structure.
struct metric_info {
time_t first_entry;
bool is_infinity;
};
/**
* Check that graphs can be properly rebuild.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Error flag.
bool error(true);
// Variables that need cleaning.
std::list<command> commands;
std::list<host> hosts;
std::list<service> services;
std::string cbmod_config_path(tmpnam(NULL));
std::string engine_config_path(tmpnam(NULL));
std::string metrics_path(tmpnam(NULL));
std::string status_path(tmpnam(NULL));
engine daemon;
test_db db;
// Log.
std::clog << "status directory: " << status_path << "\n"
<< "metrics directory: " << metrics_path << std::endl;
try {
// Prepare database.
db.open(DB_NAME);
// Create RRD paths.
mkdir(metrics_path.c_str(), S_IRWXU);
mkdir(status_path.c_str(), S_IRWXU);
// Write cbmod configuration file.
{
std::ofstream ofs;
ofs.open(cbmod_config_path.c_str(),
std::ios_base::out | std::ios_base::trunc);
if (ofs.fail())
throw(exceptions::msg() << "cannot open cbmod configuration file '"
<< cbmod_config_path.c_str() << "'");
ofs << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
<< "<centreonbroker>\n"
<< " <include>" PROJECT_SOURCE_DIR
"/test/cfg/broker_modules.xml</include>\n"
<< " <instance>42</instance>\n"
<< " <instance_name>MyBroker</instance_name>\n"
<< " <!--\n"
<< " <logger>\n"
<< " <type>file</type>\n"
<< " <name>cbmod.log</name>\n"
<< " <config>1</config>\n"
<< " <debug>1</debug>\n"
<< " <error>1</error>\n"
<< " <info>1</info>\n"
<< " <level>3</level>\n"
<< " </logger>\n"
<< " -->\n"
<< " <output>\n"
<< " <name>EngineToStorageUnitTest</name>\n"
<< " <type>storage</type>\n"
<< " <db_type>" DB_TYPE "</db_type>\n"
<< " <db_host>" DB_HOST "</db_host>\n"
<< " <db_port>" DB_PORT "</db_port>\n"
<< " <db_user>" DB_USER "</db_user>\n"
<< " <db_password>" DB_PASSWORD "</db_password>\n"
<< " <db_name>" DB_NAME "</db_name>\n"
<< " <queries_per_transaction>0</queries_per_transaction>\n"
<< " <length>2592000</length>\n"
<< " "
"<rebuild_check_interval>" MONITORING_ENGINE_INTERVAL_LENGTH_STR
"</rebuild_check_interval>\n"
<< " </output>\n"
<< " <output>\n"
<< " <name>StorageToRRDUnitTest</name>\n"
<< " <type>rrd</type>\n"
<< " <metrics_path>" << metrics_path << "</metrics_path>\n"
<< " <status_path>" << status_path << "</status_path>\n"
<< " </output>\n"
<< "</centreonbroker>\n";
ofs.close();
}
// Prepare monitoring engine configuration parameters.
generate_commands(commands, 2);
{
command* cmd(&commands.front());
char const* cmdline;
cmdline = MY_PLUGIN_PATH " 0 \"output1|metric=100\"";
cmd->command_line = new char[strlen(cmdline) + 1];
strcpy(cmd->command_line, cmdline);
cmd = &*(++commands.begin());
cmdline = MY_PLUGIN_PATH " 0 \"output2|metric=inf\"";
cmd->command_line = new char[strlen(cmdline) + 1];
strcpy(cmd->command_line, cmdline);
}
int i(0);
generate_hosts(hosts, HOST_COUNT);
for (std::list<host>::iterator it(hosts.begin()), end(hosts.end());
it != end; ++it) {
it->host_check_command = new char[2];
strcpy(it->host_check_command, (++i % 2 ? "1" : "2"));
}
i = 0;
generate_services(services, hosts, SERVICES_BY_HOST);
for (std::list<service>::iterator it(services.begin()), end(services.end());
it != end; ++it) {
it->service_check_command = new char[2];
strcpy(it->service_check_command, (++i % 2 ? "1" : "2"));
}
std::string engine_additional;
{
std::ostringstream oss;
oss << "broker_module=" << CBMOD_PATH << " " << cbmod_config_path;
engine_additional = oss.str();
}
// Insert entries in index_data.
{
QSqlQuery q(*db.centreon_db());
for (uint32_t i(1); i <= HOST_COUNT * SERVICES_BY_HOST; ++i) {
std::ostringstream query;
query << "INSERT INTO rt_index_data (host_id, service_id)"
<< " VALUES(" << (i - 1) / SERVICES_BY_HOST + 1 << ", " << i
<< ")";
if (!q.exec(query.str().c_str()))
throw(exceptions::msg()
<< "cannot create index of service ("
<< (i - 1) / SERVICES_BY_HOST + 1 << ", " << i << ")");
}
}
// Generate monitoring engine configuration files.
config_write(engine_config_path.c_str(), engine_additional.c_str(), &hosts,
&services, &commands);
// Start monitoring engine.
std::string engine_config_file(engine_config_path);
engine_config_file.append("/nagios.cfg");
daemon.set_config_file(engine_config_file);
daemon.start();
sleep_for(30);
// Get index list.
std::map<uint32_t, time_t> indexes;
{
QSqlQuery q(*db.centreon_db());
if (!q.exec("SELECT index_id FROM rt_index_data"))
throw(exceptions::msg()
<< "cannot get index list: " << qPrintable(q.lastError().text()));
while (q.next())
indexes[q.value(0).toUInt()];
if (indexes.size() != HOST_COUNT * SERVICES_BY_HOST)
throw(exceptions::msg()
<< "not enough entries in rt_index_data: got " << indexes.size()
<< ", expected " << HOST_COUNT * SERVICES_BY_HOST);
}
// For each index, get the first entry time.
for (std::map<uint32_t, time_t>::iterator it(indexes.begin()),
end(indexes.end());
it != end; ++it) {
std::ostringstream file_path;
file_path << status_path << "/" << it->first << ".rrd";
rrd_file graph;
graph.load(file_path.str().c_str());
if (graph.get_rras().empty() || graph.get_rras().front().empty())
throw(exceptions::msg() << "not enough data in status graph '"
<< file_path.str().c_str() << "'");
it->second = graph.get_rras().front().begin()->first;
}
// Get metrics list.
std::map<uint32_t, metric_info> metrics;
{
std::ostringstream query;
query << "SELECT m.metric_id"
<< " FROM rt_metrics AS m LEFT JOIN rt_index_data AS i"
<< " ON m.index_id = i.index_id"
<< " ORDER BY i.host_id, i.service_id";
QSqlQuery q(*db.centreon_db());
if (!q.exec(query.str().c_str()))
throw(exceptions::msg() << "cannot get metric list: "
<< qPrintable(q.lastError().text()));
i = 0;
while (q.next())
metrics[q.value(0).toUInt()].is_infinity = !(++i % 2);
if (metrics.size() != HOST_COUNT * SERVICES_BY_HOST)
throw(exceptions::msg()
<< "not enough entries in rt_metrics: got " << metrics.size()
<< ", expected " << HOST_COUNT * SERVICES_BY_HOST);
}
// For each metric, get the first entry time.
for (std::map<uint32_t, metric_info>::iterator it(metrics.begin()),
end(metrics.end());
it != end; ++it) {
std::ostringstream file_path;
file_path << metrics_path << "/" << it->first << ".rrd";
rrd_file graph;
graph.load(file_path.str().c_str());
if (graph.get_rras().empty() || graph.get_rras().front().empty())
throw(exceptions::msg() << "not enough data in metrics graph '"
<< file_path.str().c_str() << "'");
it->second.first_entry = graph.get_rras().front().begin()->first;
}
// Graphs must have been recreated from this time.
time_t recreated_limit(time(NULL));
std::clog << "recreation limit: " << recreated_limit << std::endl;
// Launch rebuild.
{
QSqlQuery q(*db.centreon_db());
if (!q.exec("UPDATE rt_index_data SET must_be_rebuild=1"))
throw(exceptions::msg() << "cannot launch rebuild from DB: "
<< qPrintable(q.lastError().text()));
sleep_for(15);
}
// Check that rebuild successfully executed.
{
QSqlQuery q(*db.centreon_db());
if (!q.exec("SELECT COUNT(*)"
" FROM rt_index_data"
" WHERE must_be_rebuild!=0") ||
!q.next())
throw(exceptions::msg()
<< "cannot check that rebuild successfully executed");
if (q.value(0).toUInt())
throw(exceptions::msg()
<< "rebuild did not succeed, " << q.value(0).toUInt()
<< " indexes are still waiting/being rebuild");
}
// Check status graphs.
for (std::map<uint32_t, time_t>::iterator it(indexes.begin()),
end(indexes.end());
it != end; ++it) {
// Check file properties.
std::ostringstream file_path;
file_path << status_path << "/" << it->first << ".rrd";
QFileInfo info(file_path.str().c_str());
if (!info.exists())
throw(exceptions::msg() << "status file '" << file_path.str().c_str()
<< "' does not exist");
else if (static_cast<time_t>(info.created().toTime_t()) < recreated_limit)
throw(exceptions::msg()
<< "status file '" << file_path.str().c_str()
<< "' was created at " << info.created().toTime_t()
<< " whereas recreation limit is " << recreated_limit);
// Check file content.
time_t data_low(it->second -
2592000 / 5 / MONITORING_ENGINE_INTERVAL_LENGTH);
time_t data_high(it->second +
2592000 * 5 * MONITORING_ENGINE_INTERVAL_LENGTH);
rrd_file graph;
graph.load(file_path.str().c_str());
if (graph.get_rras().empty() || graph.get_rras().front().empty())
throw(exceptions::msg() << "status file '" << file_path.str().c_str()
<< "' does not have any data after rebuild");
else if ((graph.get_rras().front().begin()->first < data_low) ||
(graph.get_rras().front().begin()->first > data_high))
throw(exceptions::msg()
<< "data time mismatch in status file '"
<< file_path.str().c_str() << "': got "
<< graph.get_rras().front().begin()->first << ", expected "
<< data_low << ":" << data_high);
}
// Check metrics graphs.
for (std::map<uint32_t, metric_info>::iterator it(metrics.begin()),
end(metrics.end());
it != end; ++it) {
// Check file properties.
std::ostringstream file_path;
file_path << metrics_path << "/" << it->first << ".rrd";
QFileInfo info(file_path.str().c_str());
if (!info.exists())
throw(exceptions::msg() << "metric file '" << file_path.str().c_str()
<< "' does not exist");
else if (static_cast<time_t>(info.created().toTime_t()) < recreated_limit)
throw(exceptions::msg()
<< "metric file '" << file_path.str().c_str()
<< "' was created at " << info.created().toTime_t()
<< " whereas recreation limit is " << recreated_limit);
// Check file content.
time_t data_low(it->second.first_entry -
2592000 / 5 / MONITORING_ENGINE_INTERVAL_LENGTH);
time_t data_high(it->second.first_entry +
2592000 * 5 * MONITORING_ENGINE_INTERVAL_LENGTH);
rrd_file graph;
graph.load(file_path.str().c_str());
if (graph.get_rras().empty() || graph.get_rras().front().empty())
throw(exceptions::msg() << "metric file '" << file_path.str().c_str()
<< "' does not have any data after rebuild");
else if ((graph.get_rras().front().begin()->first < data_low) ||
(graph.get_rras().front().end()->first > data_high))
throw(exceptions::msg()
<< "data time mismatch in metric file '"
<< file_path.str().c_str() << "': got "
<< graph.get_rras().front().begin()->first << ", expected "
<< data_low << ":" << data_high);
else if (it->second.is_infinity &&
!isinf(graph.get_rras().front().begin()->second))
throw(exceptions::msg()
<< "graph rebuild does not handle infinity of file '"
<< file_path.str().c_str() << "' ("
<< graph.get_rras().front().begin()->second << ")");
}
// Success.
error = false;
} catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "unknown exception" << std::endl;
}
// Cleanup.
daemon.stop();
config_remove(engine_config_path.c_str());
::remove(cbmod_config_path.c_str());
free_hosts(hosts);
free_services(services);
recursive_remove(metrics_path);
recursive_remove(status_path);
// Return check result.
return (error ? EXIT_FAILURE : EXIT_SUCCESS);
}
| 37.634715 | 80 | 0.560129 | centreon-lab |
7548b8d28cfaf93f262dc4fb920fd71abdd5f27c | 72,073 | cpp | C++ | libnd4j/tests_cpu/layers_tests/DeclarableOpsTests8.cpp | DongJiHui/deeplearning4j | bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854 | [
"Apache-2.0"
] | null | null | null | libnd4j/tests_cpu/layers_tests/DeclarableOpsTests8.cpp | DongJiHui/deeplearning4j | bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854 | [
"Apache-2.0"
] | null | null | null | libnd4j/tests_cpu/layers_tests/DeclarableOpsTests8.cpp | DongJiHui/deeplearning4j | bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854 | [
"Apache-2.0"
] | null | null | null | //
// @author Yurii Shyrma ([email protected]), created on 10.06.2018
//
#include "testlayers.h"
#include <ops/declarable/CustomOperations.h>
#include <NDArray.h>
// #include <array/NDArrayList.h>
using namespace nd4j;
class DeclarableOpsTests8 : public testing::Test {
public:
DeclarableOpsTests8() {
printf("\n");
fflush(stdout);
}
};
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVariance_test1) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f});
NDArray<float> exp('c', {4}, {602.2222f, 727.13885f, 993.5555f, 755.8889f});
nd4j::ops::reduce_variance<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVariance_test2) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f});
NDArray<float> exp('c', {1,1,4}, {602.2222f, 727.13885f, 993.5555f, 755.8889f});
nd4j::ops::reduce_variance<float> op;
auto result = op.execute({&x}, {1.}, {0,1});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVariance_test3) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f});
NDArray<float> exp('c', {3}, {900.9375f, 969.8594f, 424.1875f});
nd4j::ops::reduce_variance<float> op;
auto result = op.execute({&x}, {}, {0,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVariance_test4) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f});
NDArray<float> exp('c', {1,3,1}, {900.9375f, 969.8594f, 424.1875f});
nd4j::ops::reduce_variance<float> op;
auto result = op.execute({&x}, {1.}, {0,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVariance_test5) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f});
NDArray<float> exp(788.6927f);
nd4j::ops::reduce_variance<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVariance_test6) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp(788.6927f);
nd4j::ops::reduce_variance<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVariance_test7) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp('c', {1,1,1}, {788.6927f});
nd4j::ops::reduce_variance<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test1) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp('c', {4}, {24.54022f, 26.96551f, 31.52072f, 27.49343f});
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test2) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp('c', {1,1,4}, {24.54022f, 26.96551f, 31.52072f, 27.49343f});
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {1.}, {0,1});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test3) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp('c', {3}, {30.01562f, 31.14257f, 20.59581f});
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {}, {0,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test4) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp('c', {1,3,1}, {30.01562f, 31.14257f, 20.59581f});
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {1.}, {0,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test5) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp(28.08367f);
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test6) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp(28.08367f);
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test7) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp('c', {1,1,1}, {28.08367f});
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {1.f}, {0,1,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDev_test8) {
NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.});
NDArray<float> exp('c', {4}, {26.88246f, 29.53924f, 34.52921f, 30.11755f});
nd4j::ops::reduce_stdev<float> op;
auto result = op.execute({&x}, {0.f,1.f}, {0,1});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVarianceBP_test1) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {1,1}, {0.5f});
NDArray<float> gradO2(0.5f);
NDArray<float> exp12('c', {3,4}, {-0.5f, -0.4090909f, -0.3181818f, -0.22727273f, -0.13636364f, -0.045454547f, 0.045454547f, 0.13636364f, 0.22727273f, 0.3181818f, 0.4090909f, 0.5f});
NDArray<float> exp34('c', {3,4}, {-0.45833334f, -0.375f, -0.29166666f, -0.20833333f, -0.125f, -0.041666668f, 0.041666668f, 0.125f, 0.20833333f, 0.29166666f, 0.375f, 0.45833334f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_variance_bp<float> op;
auto result = op.execute({&x, &gradO2}, {0,1}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,1}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {0,0}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,0}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVarianceBP_test2) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {1,4}, {1.f,2.f,3.f,4.f});
NDArray<float> gradO2('c', {4}, {1.f,2.f,3.f,4.f});
NDArray<float> exp12('c', {3,4}, {-2.666667f, -5.333333f, -8.000000f, -10.666667f, 0.000000f, 0.000000f, 0.000000f, 0.000000f, 2.666667f, 5.333333f, 8.000000f, 10.666667f});
NDArray<float> exp34('c', {3,4}, {-4.000000f, -8.000000f, -12.000000f, -16.000000f, 0.000000f, 0.000000f, 0.000000f, 0.000000f, 4.000000f, 8.000000f, 12.000000f, 16.000000f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_variance_bp<float> op;
auto result = op.execute({&x, &gradO2}, {0,0}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,0}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {0,1}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,1}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceVarianceBP_test3) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {3,1}, {1.f,2.f,3.f});
NDArray<float> gradO2('c', {3}, {1.f,2.f,3.f});
NDArray<float> exp12('c', {3,4}, {-0.750000f, -0.250000f, 0.250000f, 0.750000f, -1.500000f, -0.500000f, 0.500000f, 1.500000f, -2.250000f, -0.750000f, 0.750000f, 2.250000f});
NDArray<float> exp34('c', {3,4}, {-1.000000f, -0.333333f, 0.333333f, 1.000000f, -2.000000f, -0.666667f, 0.666667f, 2.000000f, -3.000000f, -1.000000f, 1.000000f, 3.000000f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_variance_bp<float> op;
auto result = op.execute({&x, &gradO2}, {0,0}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,0}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {0,1}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,1}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDevBP_test1) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {1,1}, {0.5f});
NDArray<float> gradO2(0.5f);
NDArray<float> exp12('c', {3,4}, {-0.069337524f, -0.056730703f, -0.04412388f, -0.031517055f, -0.018910235f, -0.0063034114f, 0.0063034114f, 0.018910235f, 0.031517055f, 0.04412388f, 0.056730703f, 0.069337524f});
NDArray<float> exp34('c', {3,4}, {-0.06638563f, -0.05431551f, -0.0422454f, -0.030175284f, -0.01810517f, -0.006035057f, 0.006035057f, 0.01810517f, 0.030175284f, 0.0422454f, 0.05431551f, 0.06638563f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_stdev_bp<float> op;
auto result = op.execute({&x, &gradO2}, {0,1}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
// output->printIndexedBuffer();
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,1}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {0,0}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,0}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDevBP_test2) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {1,4}, {1.f,2.f,3.f,4.f});
NDArray<float> gradO2('c', {4}, {1.f,2.f,3.f,4.f});
NDArray<float> exp12('c', {3,4}, {-0.4082483f, -0.8164966f, -1.2247449f, -1.6329932f, 0.0, 0.0, 0.0, 0.0, 0.4082483f, 0.8164966f, 1.2247449f, 1.6329932f});
NDArray<float> exp34('c', {3,4}, {-0.5f, -1.0f, -1.5f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 1.0f, 1.5f, 2.0f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_stdev_bp<float> op;
auto result = op.execute({&x, &gradO2}, {0,0}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,0}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {0,1}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,1}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceStDevBP_test3) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {3,1}, {1.f,2.f,3.f});
NDArray<float> gradO2('c', {3}, {1.f,2.f,3.f});
NDArray<float> exp12('c', {3,4}, {-0.3354102f, -0.1118034f, 0.1118034f, 0.3354102f, -0.6708204f, -0.2236068f, 0.2236068f, 0.6708204f, -1.0062306f, -0.3354102f, 0.3354102f, 1.0062306f});
NDArray<float> exp34('c', {3,4}, {-0.38729835f, -0.12909944f, 0.12909944f, 0.38729835f, -0.7745967f, -0.2581989f, 0.2581989f, 0.7745967f, -1.161895f, -0.38729835f, 0.38729835f, 1.161895f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_stdev_bp<float> op;
auto result = op.execute({&x, &gradO2}, {0,0}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,0}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp12.isSameShape(output));
ASSERT_TRUE(exp12.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {0,1}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
result = op.execute({&x, &gradO1}, {1,1}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp34.isSameShape(output));
ASSERT_TRUE(exp34.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_1) {
NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.});
NDArray<float> exp(120.f);
//************************************//
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&input}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
//z->printIndexedBuffer("Result is ");
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_2) {
NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.});
NDArray<float> exp({15.f, 40.f, 65.f});
//************************************//
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&input}, {}, {1});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
// z->printIndexedBuffer("Result is ");
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_1) {
NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.});
NDArray<float> exp(1307674368000.f);
//************************************//
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&input}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
//z->printIndexedBuffer("Result is ");
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_2) {
NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.});
NDArray<float> exp({120.f, 30240.f, 360360.f});
//************************************//
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&input}, {}, {1});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
// z->printIndexedBuffer("Result is ");
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_01) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {4}, {66.f, 72.f, 78.f, 84.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_02) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,1,4}, {66.f, 72.f, 78.f, 84.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&x}, {1.}, {0, 1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_3) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {3}, {68.f, 100.f, 132.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&x}, {}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_4) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,3,1}, {68.f, 100.f, 132.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&x}, {1.}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_5) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp(300.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_6) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp(300.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_7) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,1,1}, {300.f});
NDArrayFactory<float>::linspace(1, x);
// x.printIndexedBuffer("Input with shape (2, 3, 4) is");
nd4j::ops::reduce_sum<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_01) {
NDArray<float> x('c', {2,3,2});
NDArray<float> exp('c', {2}, {10395.f, 46080.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_02) {
NDArray<float> x('c', {2,3,2});
NDArray<float> exp('c', {1,1,2}, {10395.f, 46080.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&x}, {1.}, {0, 1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_3) {
NDArray<float> x('c', {2,3,2});
NDArray<float> exp('c', {3}, {112.f, 1080.f, 3960.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&x}, {}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_4) {
NDArray<float> x('c', {2,3,2});
NDArray<float> exp('c', {1,3,1}, {112.f, 1080.f, 3960.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&x}, {1.}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_5) {
NDArray<float> x('c', {2,3,2});
NDArray<float> exp(479001600.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_6) {
NDArray<float> x('c', {2,3,2});
NDArray<float> exp(479001600.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_7) {
NDArray<float> x('c', {2,3,2});
NDArray<float> exp('c', {1, 1, 1}, {479001600.f});
NDArrayFactory<float>::linspace(1, x);
// x.printIndexedBuffer("Input with shape (2, 3, 4) is");
nd4j::ops::reduce_prod<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Min_1) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {4}, {1.f, 2.f, 3.f, 4.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_min<float> op;
auto result = op.execute({&x}, {}, {0, 1});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Min_2) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,1,4}, {1.f, 2.f, 3.f, 4.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_min<float> op;
auto result = op.execute({&x}, {1.}, {0, 1});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Min_3) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {3}, {1.f, 5.f, 9.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_min<float> op;
auto result = op.execute({&x}, {}, {0, 2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Min_4) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,3,1}, {1.f, 5.f, 9.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_min<float> op;
auto result = op.execute({&x}, {1.}, {0, 2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Min_5) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(1.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_min<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Min_6) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(1.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_min<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Min_7) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 1, 1}, {1.f});
NDArrayFactory<float>::linspace(1, x);
x.printIndexedBuffer("Input with shape (2, 3, 4) is");
nd4j::ops::reduce_min<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Max_1) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {4}, {21.f, 22.f, 23.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_max<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
output->printShapeInfo("Output shape");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Max_2) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,1,4}, {21.f, 22.f, 23.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_max<float> op;
auto result = op.execute({&x}, {1.}, {0, 1});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Max_3) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {3}, {16.f, 20.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_max<float> op;
auto result = op.execute({&x}, {}, {0, 2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Max_4) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,3,1}, {16.f, 20.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_max<float> op;
auto result = op.execute({&x}, {1.}, {0, 2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Max_5) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(24.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_max<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Max_6) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(24.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_max<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Max_7) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 1, 1}, {24.f});
NDArrayFactory<float>::linspace(1, x);
// x.printIndexedBuffer("Input with shape (2, 3, 4) is");
nd4j::ops::reduce_max<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_1) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {4}, {1.f, 2.f, 3.f, 4.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_dot_bp<float> op;
auto result = op.execute({&x, &exp}, {}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(x.isSameShape(output));
// ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
/*
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_2) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,1,4}, {1.f, 2.f, 3.f, 4.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_dot<float> op;
auto result = op.execute({&x}, {1.}, {0, 1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_3) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {3}, {112.f, 1080.f, 3960.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_dot<float> op;
auto result = op.execute({&x}, {}, {0, 2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_4) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,3,1}, {112.f, 1080.f, 3960.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_dot<float> op;
auto result = op.execute({&x}, {1.}, {0, 2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_5) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(479001600.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_dot<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_6) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(479001600.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_dot<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_7) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 1, 1}, {479001600.f});
NDArrayFactory<float>::linspace(1, x);
// x.printIndexedBuffer("Input with shape (2, 3, 4) is");
nd4j::ops::reduce_dot<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
*/
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_1) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {4}, {66.f, 72.f, 78.f, 84.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm1<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_2) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,1,4}, {66.f, 72.f, 78.f, 84.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm1<float> op;
auto result = op.execute({&x}, {1.}, {0, 1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_3) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {3}, {68.f, 100.f, 132.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm1<float> op;
auto result = op.execute({&x}, {}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_4) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,3,1}, {68.f, 100.f, 132.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm1<float> op;
auto result = op.execute({&x}, {1.}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_5) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(300.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm1<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_6) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(300.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm1<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_7) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 1, 1}, {300.f});
NDArrayFactory<float>::linspace(1, x);
// x.printIndexedBuffer("Input with shape (2, 3, 4) is");
nd4j::ops::reduce_norm1<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_1) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {4}, {31.7175f, 33.823071f, 35.97221f, 38.15757f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm2<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_2) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,1,4}, {31.7175f, 33.823071f, 35.97221f, 38.15757f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm2<float> op;
auto result = op.execute({&x}, {1.}, {0, 1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_3) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {3}, {29.597298f, 39.344631f, 49.759422f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm2<float> op;
auto result = op.execute({&x}, {}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_4) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,3,1}, {29.597298f, 39.344631f, 49.759422f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm2<float> op;
auto result = op.execute({&x}, {1.}, {0, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_5) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(70.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm2<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_6) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(70.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm2<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_7) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 1, 1}, {70.f});
NDArrayFactory<float>::linspace(1, x);
// x.printIndexedBuffer("Input with shape (2, 3, 4) is");
nd4j::ops::reduce_norm2<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_1) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {4}, {21.f, 22.f, 23.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm_max<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_2) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,1,4}, {21.f, 22.f, 23.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm_max<float> op;
auto result = op.execute({&x}, {1.f}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_3) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {3}, {16.f, 20.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm_max<float> op;
auto result = op.execute({&x}, {}, {0,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_4) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 3, 1}, {16.f, 20.f, 24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm_max<float> op;
auto result = op.execute({&x}, {1.f}, {0,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_5) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(24.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm_max<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_6) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(24.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm_max<float> op;
auto result = op.execute({&x}, {}, {0, 1, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_7) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 1, 1}, {24.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_norm_max<float> op;
auto result = op.execute({&x}, {1.f}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_1) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {4}, {1006.f, 1144.f, 1294.f, 1456.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sqnorm<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_2) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1,1,4}, {1006.f, 1144.f, 1294.f, 1456.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sqnorm<float> op;
auto result = op.execute({&x}, {1.f}, {0,1});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_3) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {3}, {876.f, 1548.f, 2476.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sqnorm<float> op;
auto result = op.execute({&x}, {}, {0,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_4) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 3, 1}, {876.f, 1548.f, 2476.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sqnorm<float> op;
auto result = op.execute({&x}, {1.f}, {0,2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_5) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(4900.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sqnorm<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_6) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp(4900.f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sqnorm<float> op;
auto result = op.execute({&x}, {}, {0, 1, 2});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_7) {
NDArray<float> x('c', {2, 3, 4});
NDArray<float> exp('c', {1, 1, 1}, {4900.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_sqnorm<float> op;
auto result = op.execute({&x}, {1.f}, {});
auto output = result->at(0);
// output->printIndexedBuffer("Result is");
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_1) {
NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.});
NDArray<float> eps(0.5f);
NDArray<float> exp('c', {3, 4}, {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,0.5f});
//************************************//
nd4j::ops::reduce_sum_bp<float> op;
auto result = op.execute({&input, &eps}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
// z->printIndexedBuffer("Result is ");
// z->printShapeInfo();
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_2) {
NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.});
NDArray<float> eps('c', {1, 1}, {0.5f});
NDArray<float> exp('c', {3, 4}, {0.5f, 0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,0.5f});
//************************************//
nd4j::ops::reduce_sum_bp<float> op;
auto result = op.execute({&input, &eps}, {1.f}, {});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
// z->printIndexedBuffer("Result is ");
// z->printShapeInfo();
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_3) {
NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.});
NDArray<float> eps('c', {4}, {1.f, 2.f, 3.f, 4.f});
NDArray<float> exp('c', {3, 4}, {1.f, 2.f, 3.f, 4.f,
1.f, 2.f, 3.f, 4.f,
1.f, 2.f, 3.f, 4.f});
//************************************//
nd4j::ops::reduce_sum_bp<float> op;
auto result = op.execute({&input, &eps}, {}, {0});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
// z->printIndexedBuffer("Result is ");
// z->printShapeInfo();
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_4) {
NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.});
NDArray<float> eps('c', {1, 4}, {1.f, 2.f, 3.f, 4.f});
NDArray<float> exp('c', {3, 4}, {1.f, 2.f, 3.f, 4.f,
1.f, 2.f, 3.f, 4.f,
1.f, 2.f, 3.f, 4.f});
//************************************//
nd4j::ops::reduce_sum_bp<float> op;
auto result = op.execute({&input, &eps}, {1.f}, {0});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
// z->printIndexedBuffer("Result is ");
// z->printShapeInfo();
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_BP_1) {
NDArray<float> input('c', {3, 5}, {1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f, 15.f});
NDArray<float> eps(1307674368000.f);
//************************************//
// NDArray<float> exp('c', {3, 4}, {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,0.5f});
//************************************//
NDArray<float> exp('c', {3, 5}, {1710012166826558903812096.f, 855006083413279451906048.f, 570004067618451974258688.f,
427503041706639725953024.f, 342002454982589992140800.f, 285002033809225987129344.f,
244287457550765131825152.f, 213751520853319862976512.f, 190001355872817324752896.f,
171001227491294996070400.f, 155455648254341989531648.f, 142501016904612993564672.f,
131539399526781282156544.f, 122143728775382565912576.f, 114000815325130245799936.f});
nd4j::ops::reduce_prod_bp<float> op;
auto result = op.execute({&input, &eps}, {}, {});
ASSERT_EQ(Status::OK(), result->status());
auto z = result->at(0);
// z->printIndexedBuffer("Result is ");
// z->printShapeInfo();
ASSERT_TRUE(exp.equalsTo(z));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMean_test1) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {4}, {11.f, 12.f, 13.f, 14.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean<float> op;
auto result = op.execute({&x}, {}, {0,1});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMean_test2) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,1,4}, {11.f, 12.f, 13.f, 14.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean<float> op;
auto result = op.execute({&x}, {1.}, {0,1});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMean_test3) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {3}, {8.5f, 12.5f, 16.5f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean<float> op;
auto result = op.execute({&x}, {}, {0,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMean_test4) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,3,1}, {8.5f, 12.5f, 16.5f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean<float> op;
auto result = op.execute({&x}, {1.f}, {0,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMean_test5) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp(12.5f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean<float> op;
auto result = op.execute({&x}, {}, {});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMean_test6) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp(12.5f);
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean<float> op;
auto result = op.execute({&x}, {}, {0,1,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMean_test7) {
NDArray<float> x('c', {2,3,4});
NDArray<float> exp('c', {1,1,1}, {12.5f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean<float> op;
auto result = op.execute({&x}, {1.}, {0,1,2});
auto output = result->at(0);
ASSERT_EQ(ND4J_STATUS_OK, result->status());
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMeanBP_test1) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1(0.5f);
NDArray<float> gradO2('c', {1,1}, {0.5f});
NDArray<float> exp('c', {3,4}, {1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean_bp<float> op;
auto result = op.execute({&x, &gradO1}, {0}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {1}, {});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMeanBP_test3) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {4}, {1.f, 2.f, 3.f, 4.f});
NDArray<float> gradO2('c', {1,4}, {1.f, 2.f, 3.f, 4.f});
NDArray<float> exp('c', {3,4}, {1.f/3.f, 2.f/3.f, 1.f, 4.f/3.f, 1.f/3.f, 2.f/3.f, 1.f, 4.f/3.f, 1.f/3.f, 2.f/3.f, 1.f, 4.f/3.f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean_bp<float> op;
auto result = op.execute({&x, &gradO1}, {0}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {1}, {0});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(DeclarableOpsTests8, reduceMeanBP_test5) {
NDArray<float> x('c', {3,4});
NDArray<float> gradO1('c', {3}, {1.f, 2.f, 3.f});
NDArray<float> gradO2('c', {3,1}, {1.f, 2.f, 3.f});
NDArray<float> exp('c', {3,4}, {0.25f, 0.25f, 0.25f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 0.75f, 0.75f, 0.75f, 0.75f});
NDArrayFactory<float>::linspace(1, x);
nd4j::ops::reduce_mean_bp<float> op;
auto result = op.execute({&x, &gradO1}, {0}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
auto output = result->at(0);
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
result = op.execute({&x, &gradO2}, {1}, {1});
ASSERT_EQ(ND4J_STATUS_OK, result->status());
output = result->at(0);
ASSERT_TRUE(exp.isSameShape(output));
ASSERT_TRUE(exp.equalsTo(output));
delete result;
}
| 32.83508 | 218 | 0.537316 | DongJiHui |
754db7453767ee9b479c44bcdf3863c1d8d05b5a | 2,674 | cpp | C++ | engine/src/Component/MeshComponents/Skeleton.cpp | kyle-piddington/MoonEngine | 243cce7988ee089d0fc51d817e2736501e019702 | [
"MIT",
"BSD-3-Clause"
] | 5 | 2017-01-20T00:23:23.000Z | 2018-07-17T07:48:04.000Z | engine/src/Component/MeshComponents/Skeleton.cpp | kyle-piddington/MoonEngine | 243cce7988ee089d0fc51d817e2736501e019702 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | engine/src/Component/MeshComponents/Skeleton.cpp | kyle-piddington/MoonEngine | 243cce7988ee089d0fc51d817e2736501e019702 | [
"MIT",
"BSD-3-Clause"
] | 2 | 2017-01-24T05:09:37.000Z | 2021-02-18T14:42:00.000Z | #include "Skeleton.h"
#include "Util/Logger.h"
#include <glm/gtc/type_ptr.hpp>
using namespace MoonEngine;
Bone::Bone(std::string name, int boneIdx, glm::mat4 offsetTransform):
name(name),
offsetTransform(offsetTransform),
localAnimTransform(1.0),
animTransform(1.0),
idx(boneIdx)
{
}
void Bone::setAnimatedTransform(glm::mat4 transform)
{
this->localAnimTransform = transform;
}
Skeleton::Skeleton():
Component()
{
}
Skeleton::Skeleton(AssimpModelInfo & info):
Component()
{
importBonesFromAssimp(info);
}
Skeleton::~Skeleton()
{
}
int Skeleton::getNumBones()
{
return bones.size();
}
void Skeleton::importBonesFromAssimp(AssimpBoneInfo & node, AssimpModelInfo & info, BoneTreeNode & thisNode)
{
int boneIdx = addBone(node);
thisNode.boneIdx = boneIdx;
for(int i = 0; i < node.childBones.size(); i++)
{
thisNode.children.push_back(BoneTreeNode());
AssimpBoneInfo childInfo = info.getBoneInfo(node.childBones[i]);
importBonesFromAssimp(childInfo, info, thisNode.children.back());
}
}
void Skeleton::importBonesFromAssimp(AssimpModelInfo & importInfo)
{
rootInverseTransform = importInfo.getRootInverseTransform();
AssimpBoneInfo rootInfo = importInfo.getBoneInfo(0);
boneRoot.children.push_back(BoneTreeNode());
importBonesFromAssimp(rootInfo,importInfo, boneRoot.children.back());
}
Bone * const Skeleton::getBone(std::string boneName)
{
auto boneId = boneMap.find(boneName);
if(boneId == boneMap.end())
{
LOG(ERROR, "No Bone named " + boneName + "In skeleton!");
return nullptr;
}
else
{
return &bones[boneId->second];
}
}
/**
* Returns index of added bone
*/
int Skeleton::addBone(AssimpBoneInfo & info)
{
LOG(INFO, "Adding bone " + info.boneName);
Bone bone(info.boneName,bones.size(),info.offsetMatrix);
bones.push_back(bone);
boneMap[info.boneName] = bone.getIndex();
return bone.getIndex();
}
void Skeleton::finalizeAnimation(BoneTreeNode & node, glm::mat4 parentMtx)
{
glm::mat4 aMtx = parentMtx * bones[node.boneIdx].localAnimTransform;
bones[node.boneIdx].animTransform = aMtx;
for (std::vector<BoneTreeNode>::iterator i = node.children.begin(); i != node.children.end(); ++i)
{
finalizeAnimation(*i, aMtx);
}
}
void Skeleton::finalizeAnimation()
{
for (std::vector<BoneTreeNode>::iterator i = boneRoot.children.begin(); i != boneRoot.children.end(); ++i)
{
finalizeAnimation(*i,rootInverseTransform);
}
}
std::shared_ptr<Component> Skeleton::clone() const
{
return std::make_shared<Skeleton>(*this);
}
| 23.051724 | 110 | 0.677636 | kyle-piddington |
75509c46638cb4b7864fb3e59fdd4b16bb0b3c22 | 2,894 | cpp | C++ | qlo/objects/obj_correlation_hw.cpp | eehlers/QuantLibAddin | bcbd9d1c0e7a4f4ce608470c6576d6e772305980 | [
"BSD-3-Clause"
] | 5 | 2016-07-13T14:05:01.000Z | 2022-01-24T15:15:17.000Z | qlo/objects/obj_correlation_hw.cpp | eehlers/QuantLibAddin | bcbd9d1c0e7a4f4ce608470c6576d6e772305980 | [
"BSD-3-Clause"
] | null | null | null | qlo/objects/obj_correlation_hw.cpp | eehlers/QuantLibAddin | bcbd9d1c0e7a4f4ce608470c6576d6e772305980 | [
"BSD-3-Clause"
] | 12 | 2016-01-28T07:18:28.000Z | 2021-11-15T03:48:52.000Z |
// BEGIN buffer b_lib_grp_cpp
#include <qlo/objects/obj_correlation.hpp>
#include <ql/legacy/libormarketmodels/lmlinexpcorrmodel.hpp>
#include <ql/models/marketmodels/correlations/cotswapfromfwdcorrelation.hpp>
#include <ql/models/marketmodels/correlations/timehomogeneousforwardcorrelation.hpp>
#include <ql/models/marketmodels/correlations/expcorrelations.hpp>
#include <ql/models/marketmodels/historicalforwardratesanalysis.hpp>
#include <ql/models/marketmodels/historicalratesanalysis.hpp>
#include <qlo/enumerations/factories/historicalforwardratesanalysisfactory.hpp>
QuantLibAddin::HistoricalForwardRatesAnalysis::HistoricalForwardRatesAnalysis(
const boost::shared_ptr<reposit::ValueObject>& properties,
// BEGIN typemap rp_tm_default
boost::shared_ptr< QuantLib::SequenceStatistics > const &SequenceStats,
QuantLib::Date const &StartDate,
QuantLib::Date const &EndDate,
QuantLib::Period const &Step,
boost::shared_ptr< QuantLib::IborIndex > const &IborIndex,
QuantLib::Period const &InitialGap,
QuantLib::Period const &Horizon,
std::vector< boost::shared_ptr< QuantLib::IborIndex > > const &IborIndexes,
std::vector< boost::shared_ptr< QuantLib::SwapIndex > > const &SwapIndexes,
QuantLib::DayCounter const &DayCounter,
std::string const &TraitsID,
std::string const &InterpolatorID,
QuantLib::Real BootstrapAccuracy,
// END typemap rp_tm_default
bool permanent)
: reposit::LibraryObject<QuantLib::HistoricalForwardRatesAnalysis>(properties, permanent) {
libraryObject_ = reposit::Create<boost::shared_ptr<
QuantLib::HistoricalForwardRatesAnalysis> >()(
TraitsID,
InterpolatorID,
SequenceStats,
StartDate,
EndDate,
Step,
IborIndex,
InitialGap,
Horizon,
IborIndexes,
SwapIndexes,
DayCounter,
BootstrapAccuracy);
}
QuantLibAddin::TimeHomogeneousForwardCorrelation::TimeHomogeneousForwardCorrelation(
const boost::shared_ptr<reposit::ValueObject>& properties,
// BEGIN typemap rp_tm_default
QuantLib::Matrix const &FwdCorrMatrix,
std::vector< QuantLib::Time > const &RateTimes,
// END typemap rp_tm_default
bool permanent)
: PiecewiseConstantCorrelation(properties, permanent) {
QL_REQUIRE(!RateTimes.empty(), "rate times vector is empty!");
libraryObject_ = boost::shared_ptr<QuantLib::PiecewiseConstantCorrelation>(new QuantLib::TimeHomogeneousForwardCorrelation(
// BEGIN typemap rp_tm_default
FwdCorrMatrix,
RateTimes
// END typemap rp_tm_default
));
}
// END buffer b_lib_grp_cpp
| 40.760563 | 127 | 0.681064 | eehlers |
7550c1f3aa84e96d53e506d0a5367d6d41ef9d00 | 3,475 | cpp | C++ | Visual Mercutio/zBaseLib/PSS_CommandLine.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 1 | 2022-01-31T06:24:24.000Z | 2022-01-31T06:24:24.000Z | Visual Mercutio/zBaseLib/PSS_CommandLine.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-04-11T15:50:42.000Z | 2021-06-05T08:23:04.000Z | Visual Mercutio/zBaseLib/PSS_CommandLine.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-01-08T00:55:18.000Z | 2022-01-31T06:24:18.000Z | /****************************************************************************
* ==> PSS_CommandLine -----------------------------------------------------*
****************************************************************************
* Description : Provides an encapsulated command line *
* Developer : Processsoft *
****************************************************************************/
#include <StdAfx.h>
#include "PSS_CommandLine.h"
// processsoft
#include "PSS_FileLauncher.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_CommandLine, CObject, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_CommandLine
//---------------------------------------------------------------------------
PSS_CommandLine::PSS_CommandLine(const CString& commandLine,
const CString& startupDir,
const CString& arguments,
DWORD priority) :
m_pProcessInfo(NULL),
m_CommandLine(commandLine),
m_StartupDir(startupDir),
m_Arguments(arguments),
m_Priority(priority),
m_HasBeenLaunched(FALSE)
{}
//---------------------------------------------------------------------------
PSS_CommandLine::PSS_CommandLine(const PSS_CommandLine& other) :
m_pProcessInfo(NULL),
m_Priority(0),
m_HasBeenLaunched(FALSE)
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_CommandLine::~PSS_CommandLine()
{
if (m_pProcessInfo)
delete m_pProcessInfo;
}
//---------------------------------------------------------------------------
const PSS_CommandLine& PSS_CommandLine::operator = (const PSS_CommandLine& other)
{
m_CommandLine = other.m_CommandLine;
m_StartupDir = other.m_StartupDir;
m_Arguments = other.m_Arguments;
m_Priority = other.m_Priority;
return *this;
}
//---------------------------------------------------------------------------
void PSS_CommandLine::Initialize(const CString& commandLine,
const CString& startupDir,
const CString& arguments,
DWORD priority)
{
m_CommandLine = commandLine;
m_StartupDir = startupDir;
m_Arguments = arguments;
m_Priority = priority;
}
//---------------------------------------------------------------------------
BOOL PSS_CommandLine::Launch()
{
PSS_FileLauncher fileLauncher(m_CommandLine, PSS_FileLauncher::IE_FM_Open, m_Arguments, m_StartupDir);
return fileLauncher.Launch();
}
//---------------------------------------------------------------------------
void PSS_CommandLine::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// write the elements
ar << m_CommandLine;
ar << m_StartupDir;
ar << m_Arguments;
ar << m_Priority;
}
else
{
// read the elements
ar >> m_CommandLine;
ar >> m_StartupDir;
ar >> m_Arguments;
ar >> m_Priority;
}
}
//---------------------------------------------------------------------------
| 35.10101 | 106 | 0.410072 | Jeanmilost |
7555fbe32477355e35b71e315e4754e44783a59b | 4,357 | cpp | C++ | libnaucrates/src/parser/CParseHandlerQueryOutput.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libnaucrates/src/parser/CParseHandlerQueryOutput.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libnaucrates/src/parser/CParseHandlerQueryOutput.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 EMC Corp.
//
// @filename:
// CParseHandlerQueryOutput.cpp
//
// @doc:
// Implementation of the SAX parse handler class parsing the list of
// output column references in a DXL query.
//---------------------------------------------------------------------------
#include "naucrates/dxl/parser/CParseHandlerQueryOutput.h"
#include "naucrates/dxl/parser/CParseHandlerScalarIdent.h"
#include "naucrates/dxl/parser/CParseHandlerFactory.h"
#include "naucrates/dxl/operators/CDXLOperatorFactory.h"
using namespace gpdxl;
XERCES_CPP_NAMESPACE_USE
//---------------------------------------------------------------------------
// @function:
// CParseHandlerQueryOutput::CParseHandlerQueryOutput
//
// @doc:
// Constructor
//
//---------------------------------------------------------------------------
CParseHandlerQueryOutput::CParseHandlerQueryOutput
(
IMemoryPool *pmp,
CParseHandlerManager *pphm,
CParseHandlerBase *pphRoot
)
:
CParseHandlerBase(pmp, pphm, pphRoot),
m_pdrgpdxln(NULL)
{
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerQueryOutput::~CParseHandlerQueryOutput
//
// @doc:
// Destructor
//
//---------------------------------------------------------------------------
CParseHandlerQueryOutput::~CParseHandlerQueryOutput()
{
m_pdrgpdxln->Release();
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerQueryOutput::PdrgpdxlnOutputCols
//
// @doc:
// Return the list of query output columns
//
//---------------------------------------------------------------------------
DrgPdxln *
CParseHandlerQueryOutput::PdrgpdxlnOutputCols()
{
GPOS_ASSERT(NULL != m_pdrgpdxln);
return m_pdrgpdxln;
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerQueryOutput::StartElement
//
// @doc:
// Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerQueryOutput::StartElement
(
const XMLCh* const xmlszUri,
const XMLCh* const xmlszLocalname,
const XMLCh* const xmlszQname,
const Attributes& attrs
)
{
if(0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), xmlszLocalname))
{
// start the query output section in the DXL document
GPOS_ASSERT(NULL == m_pdrgpdxln);
m_pdrgpdxln = GPOS_NEW(m_pmp) DrgPdxln(m_pmp);
}
else if(0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenScalarIdent), xmlszLocalname))
{
// we must have seen a proj list already and initialized the proj list node
GPOS_ASSERT(NULL != m_pdrgpdxln);
// start new scalar ident element
CParseHandlerBase *pphChild = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenScalarIdent), m_pphm, this);
m_pphm->ActivateParseHandler(pphChild);
// store parse handler
this->Append(pphChild);
pphChild->startElement(xmlszUri, xmlszLocalname, xmlszQname, attrs);
}
else
{
CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz());
}
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerQueryOutput::EndElement
//
// @doc:
// Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerQueryOutput::EndElement
(
const XMLCh* const, // xmlszUri,
const XMLCh* const xmlszLocalname,
const XMLCh* const // xmlszQname
)
{
if(0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), xmlszLocalname))
{
CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz());
}
const ULONG ulSize = this->UlLength();
for (ULONG ul = 0; ul < ulSize; ul++)
{
CParseHandlerScalarIdent *pphChild = dynamic_cast<CParseHandlerScalarIdent *>((*this)[ul]);
GPOS_ASSERT(NULL != pphChild);
CDXLNode *pdxlnIdent = pphChild->Pdxln();
pdxlnIdent->AddRef();
m_pdrgpdxln->Append(pdxlnIdent);
}
// deactivate handler
m_pphm->DeactivateHandler();
}
// EOF
| 27.402516 | 126 | 0.585495 | khannaekta |
755ad07141cddf984ead1963498ce2c26f79700d | 506 | hpp | C++ | src/hashes/PCompressG.hpp | funkysash/catena-variants | 5baf9c34b96e495a52f8ded6612187c7f0033efb | [
"MIT"
] | 4 | 2015-04-18T14:33:27.000Z | 2016-02-20T11:11:25.000Z | src/hashes/PCompressG.hpp | funkysash/catena-variants | 5baf9c34b96e495a52f8ded6612187c7f0033efb | [
"MIT"
] | null | null | null | src/hashes/PCompressG.hpp | funkysash/catena-variants | 5baf9c34b96e495a52f8ded6612187c7f0033efb | [
"MIT"
] | 3 | 2015-04-18T07:10:43.000Z | 2018-03-26T13:55:16.000Z | #pragma once
#include "../hashfast.hpp"
namespace Catena_Variants{
class PCompressG : public HashFast<PCompressG>
{
public:
PCompressG();
~PCompressG() = default;
PCompressG(PCompressG const&) = default;
PCompressG& operator=(PCompressG const&) = default;
virtual void Hash(int vindex, const uint8_t* i1, const uint8_t* i2,
uint8_t* hash);
/* Does nothing
*/
virtual void ResetState();
virtual uint16_t getHlenFast()const;
private:
uint16_t const H_LEN_FAST = 64;
};
} | 16.866667 | 70 | 0.699605 | funkysash |
755cd3720a4409d5bb29bba57511e2c3d301de1e | 36,420 | cpp | C++ | src/llbox.cpp | pullmoll/lualept | bfe6da74088e23fc895faa30dfb1cbde9d42a53d | [
"BSD-3-Clause"
] | 2 | 2018-05-17T12:05:43.000Z | 2018-11-22T14:59:23.000Z | src/llbox.cpp | pullmoll/lualept | bfe6da74088e23fc895faa30dfb1cbde9d42a53d | [
"BSD-3-Clause"
] | null | null | null | src/llbox.cpp | pullmoll/lualept | bfe6da74088e23fc895faa30dfb1cbde9d42a53d | [
"BSD-3-Clause"
] | null | null | null | /************************************************************************
* Copyright (c) Jürgen Buchmüller <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include "modules.h"
/**
* \file llbox.cpp
* \class Box
*
* A box: a quad of l_int32 (x, y, w, h).
*/
/** Set TNAME to the class name used in this source file */
#define TNAME LL_BOX
/** Define a function's name (_fun) with prefix Box */
#define LL_FUNC(x) FUNC(TNAME "." x)
/**
* \brief Destroy a Box* (%box).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box).
*
* Leptonica's Notes:
* (1) Decrements the ref count and, if 0, destroys the box.
* (2) Always nulls the input ptr.
* </pre>
* \param L Lua state.
* \return 0 for nothing on the Lua stack.
*/
static int
Destroy(lua_State *L)
{
LL_FUNC("Destroy");
Box *box = ll_take_udata<Box>(_fun, L, 1, TNAME);
DBG(LOG_DESTROY, "%s: '%s' %s = %p, %s = %d\n", _fun,
TNAME,
"box", reinterpret_cast<void *>(box),
"refcount", boxGetRefcount(box));
boxDestroy(&box);
return 0;
}
/**
* \brief Printable string for a Box* (%box).
* \param L Lua state.
* \return 1 string on the Lua stack.
*/
static int
toString(lua_State *L)
{
LL_FUNC("toString");
char *str = ll_calloc<char>(_fun, L, LL_STRBUFF);
Box *box = ll_check_Box(_fun, L, 1);
luaL_Buffer B;
l_int32 x, y, w, h;
luaL_buffinit(L, &B);
if (!box) {
luaL_addstring(&B, "nil");
} else {
snprintf(str, LL_STRBUFF,
TNAME "*: %p",
reinterpret_cast<void *>(box));
luaL_addstring(&B, str);
if (boxGetGeometry(box, &x, &y, &w, &h)) {
snprintf(str, LL_STRBUFF, "\n invalid");
} else {
snprintf(str, LL_STRBUFF, "\n %s = %d, %s = %d, %s = %d, %s = %d, %s = %d",
"x", x, "y", y, "w", w, "h", h, "area", w * h);
}
luaL_addstring(&B, str);
}
luaL_pushresult(&B);
ll_free(str);
return 1;
}
/**
* \brief Test equality of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
Equal(lua_State *L)
{
LL_FUNC("Equal");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_int32 same = FALSE;
if (boxEqual(box1, box2, &same))
return ll_push_nil(_fun, L);
return ll_push_boolean(_fun, L, same);
}
/**
* \brief Adjust sides of a Box* (%boxs).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxd).
* Arg #2 (i.e. self) is expected to be a Box* (boxs).
* Arg #3 is expected to be a l_int32 (delleft).
* Arg #4 is expected to be a l_int32 (delright).
* Arg #5 is expected to be a l_int32 (deltop).
* Arg #6 is expected to be a l_int32 (delbot).
*
* Leptonica's Notes:
* (1) Set boxd == NULL to get new box; boxd == boxs for in-place;
* or otherwise to resize existing boxd.
* (2) For usage, suggest one of these:
* boxd = boxAdjustSides(NULL, boxs, ...); // new
* boxAdjustSides(boxs, boxs, ...); // in-place
* boxAdjustSides(boxd, boxs, ...); // other
* (3) New box dimensions are cropped at left and top to x >= 0 and y >= 0.
* (4) For example, to expand in-place by 20 pixels on each side, use
* boxAdjustSides(box, box, -20, 20, -20, 20);
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
AdjustSides(lua_State *L)
{
LL_FUNC("AdjustSides");
Box *boxd = ll_opt_Box(_fun, L, 1);
Box *boxs = ll_check_Box(_fun, L, 2);
l_int32 delleft = ll_opt_l_int32(_fun, L, 3, 0);
l_int32 delright = ll_opt_l_int32(_fun, L, 4, 0);
l_int32 deltop = ll_opt_l_int32(_fun, L, 5, 0);
l_int32 delbot = ll_opt_l_int32(_fun, L, 6, 0);
Box *box = boxAdjustSides(boxd, boxs, delleft, delright, deltop, delbot);
ll_push_Box(_fun, L, box);
return 1;
}
/**
* \brief Get the bounding region of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
*
* Leptonica's Notes:
* (1) This is the geometric union of the two rectangles.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
BoundingRegion(lua_State *L)
{
LL_FUNC("BoundingRegion");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
Box *box = boxBoundingRegion(box1, box2);
ll_push_Box(_fun, L, box);
return 1;
}
/**
* \brief Change the Box* reference count.
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* Arg #2 (i.e. self) is expected to be a l_int32 (delta).
* </pre>
* \param L Lua state.
* \return 1 boolean on the stack.
*/
static int
ChangeRefcount(lua_State *L)
{
LL_FUNC("ChangeRefcount");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 delta = ll_check_l_int32(_fun, L, 2);
return ll_push_boolean(_fun, L, 0 == boxChangeRefcount(box, delta));
}
/**
* \brief Clip a Box* (%boxs) rectangle to width and height (%wi, %hi).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* Arg #2 is expected to be a l_int32 (wi).
* Arg #3 is expected to be a l_int32 (hi).
*
* Leptonica's Notes:
* (1) This can be used to clip a rectangle to an image.
* The clipping rectangle is assumed to have a UL corner at (0, 0),
* and a LR corner at (wi - 1, hi - 1).
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
ClipToRectangle(lua_State *L)
{
LL_FUNC("ClipToRectangle");
Box *boxs = ll_check_Box(_fun, L, 1);
l_int32 wi = ll_check_l_int32(_fun, L, 2);
l_int32 hi = ll_check_l_int32(_fun, L, 3);
Box *box = boxClipToRectangle(boxs, wi, hi);
return ll_push_Box(_fun, L, box);
}
/**
* \brief Clip a Box* (%boxs) rectangle to width and height (w,h).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
*
* Leptonica's Notes:
* (1) The return value should be checked. If it is 1, the
* returned parameter values are bogus.
* (2) This simplifies the selection of pixel locations within
* a given rectangle:
* for (i = ystart; i < yend; i++ {
* ...
* for (j = xstart; j < xend; j++ {
* ....
* </pre>
* \param L Lua state.
* \return 6 integers on the Lua stack (%xstart, %ystart, %xend, %yend, %bw, %bh).
*/
static int
ClipToRectangleParams(lua_State *L)
{
LL_FUNC("ClipToRectangleParams");
Box *boxs = ll_check_Box(_fun, L, 1);
l_int32 w = ll_check_l_int32(_fun, L, 2);
l_int32 h = ll_check_l_int32(_fun, L, 3);
l_int32 xstart = 0;
l_int32 ystart = 0;
l_int32 xend = 0;
l_int32 yend = 0;
l_int32 bw = 0;
l_int32 bh = 0;
if (boxClipToRectangleParams(boxs, w, h, &xstart, &ystart, &xend, ¥d, &bw, &bh))
return ll_push_nil(_fun, L);
ll_push_l_int32(_fun, L, xstart);
ll_push_l_int32(_fun, L, ystart);
ll_push_l_int32(_fun, L, xend);
ll_push_l_int32(_fun, L, yend);
ll_push_l_int32(_fun, L, bw);
ll_push_l_int32(_fun, L, bh);
return 6;
}
/**
* \brief Clone a Box* (%boxs).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
Clone(lua_State *L)
{
LL_FUNC("Clone");
Box *boxs = ll_check_Box(_fun, L, 1);
Box *box = boxClone(boxs);
return ll_push_Box(_fun, L, box);
}
/**
* \brief Compare the size of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
* Arg #3 is expected to be a string describing the type of comparison (type).
*
* Leptonica's Notes:
* (1) We're re-using the SORT enum for these comparisons.
* </pre>
* \param L Lua state.
* \return 1 string on the Lua stack.
*/
static int
CompareSize(lua_State *L)
{
LL_FUNC("CompareSize");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_int32 type = ll_check_sort_by(_fun, L, 3, L_SORT_BY_WIDTH);
l_int32 rel = 0;
if (boxCompareSize(box1, box2, type, &rel))
return ll_push_nil(_fun, L);
ll_push_string(_fun, L, ll_string_relation(rel));
return 1;
}
/**
* \brief Check if a Box* (%box1) contains another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
Contains(lua_State *L)
{
LL_FUNC("Contains");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_int32 contains = 0;
if (boxContains(box1, box2, &contains))
return ll_push_nil(_fun, L);
return ll_push_boolean(_fun, L, contains);
}
/**
* \brief Check if a Box* (%box) contains a point (%x, %y).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box).
* Arg #2 is expected to be a l_float32 (x).
* Arg #3 is expected to be a l_float32 (y).
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
ContainsPt(lua_State *L)
{
LL_FUNC("ContainsPt");
Box *box = ll_check_Box(_fun, L, 1);
l_float32 x = ll_check_l_float32(_fun, L, 2);
l_float32 y = ll_check_l_float32(_fun, L, 3);
l_int32 contains = FALSE;
if (boxContainsPt(box, x, y, &contains))
return ll_push_nil(_fun, L);
return ll_push_boolean(_fun, L, contains);
}
/**
* \brief Convert corners (%ncorners) of a Box* (%box) to a Pta* (%pta).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box).
* Arg #2 is expected to be a l_int32 (ncorners).
*
* Leptonica's Notes:
* (1) If ncorners == 2, we select the UL and LR corners.
* Otherwise we save all 4 corners in this order: UL, UR, LL, LR.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
ConvertToPta(lua_State *L)
{
LL_FUNC("ConvertToPta");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 ncorners = ll_check_l_int32(_fun, L, 2);
Pta *pta = boxConvertToPta(box, ncorners);
return ll_push_Pta(_fun, L, pta);
}
/**
* \brief Copy a Box* (%boxs).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
Copy(lua_State *L)
{
LL_FUNC("Copy");
Box *boxs = ll_check_Box(_fun, L, 1);
Box *box = boxCopy(boxs);
return ll_push_Box(_fun, L, box);
}
/**
* \brief Create a new Box*.
* <pre>
* Arg #1 is expected to be a l_int32 (x).
* Arg #2 is expected to be a l_int32 (y).
* Arg #3 is expected to be a l_int32 (w).
* Arg #4 is expected to be a l_int32 (h).
*
* Leptonica's Notes:
* (1) This clips the box to the +quad. If no part of the
* box is in the +quad, this returns NULL.
* (2) We allow you to make a box with w = 0 and/or h = 0.
* This does not represent a valid region, but it is useful
* as a placeholder in a boxa for which the index of the
* box in the boxa is important. This is an atypical
* situation; usually you want to put only valid boxes with
* nonzero width and height in a boxa. If you have a boxa
* with invalid boxes, the accessor boxaGetValidBox()
* will return NULL on each invalid box.
* (3) If you want to create only valid boxes, use boxCreateValid(),
* which returns NULL if either w or h is 0.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
Create(lua_State *L)
{
LL_FUNC("Create");
l_int32 x = ll_opt_l_int32(_fun, L, 1, 0);
l_int32 y = ll_opt_l_int32(_fun, L, 2, 0);
l_int32 w = ll_opt_l_int32(_fun, L, 3, 1);
l_int32 h = ll_opt_l_int32(_fun, L, 4, 1);
Box *box = boxCreate(x, y, w, h);
return ll_push_Box(_fun, L, box);
}
/**
* \brief Create a new Box* (%box) if the parameters are valid.
* <pre>
* Arg #1 is expected to be a l_int32 (x).
* Arg #2 is expected to be a l_int32 (y).
* Arg #3 is expected to be a l_int32 (w).
* Arg #4 is expected to be a l_int32 (h).
*
* Leptonica's Notes:
* (1) This returns NULL if either w = 0 or h = 0.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
CreateValid(lua_State *L)
{
LL_FUNC("CreateValid");
l_int32 x, y, w, h;
Box *box;
x = ll_opt_l_int32(_fun, L, 1, 0);
y = ll_opt_l_int32(_fun, L, 2, 0);
w = ll_opt_l_int32(_fun, L, 3, 1);
h = ll_opt_l_int32(_fun, L, 4, 1);
box = boxCreateValid(x, y, w, h);
return ll_push_Box(_fun, L, box);
}
/**
* \brief Get the center of a Box* (%box).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box).
* </pre>
* \param L Lua state.
* \return 2 numbers on the Lua stack (%cx, %cy).
*/
static int
GetCenter(lua_State *L)
{
LL_FUNC("GetCenter");
Box *box = ll_check_Box(_fun, L, 1);
l_float32 cx = 0.0f;
l_float32 cy = 0.0f;
if (boxGetCenter(box, &cx, &cy))
return ll_push_nil(_fun, L);
ll_push_l_float32(_fun, L, cx);
ll_push_l_float32(_fun, L, cy);
return 2;
}
/**
* \brief Get the Box* geometry.
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* </pre>
* \param L Lua state.
* \return 4 for four integers (or nil on error) on the stack.
*/
static int
GetGeometry(lua_State *L)
{
LL_FUNC("GetGeometry");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 x, y, w, h;
if (boxGetGeometry(box, &x, &y, &w, &h))
return ll_push_nil(_fun, L);
ll_push_l_int32(_fun, L, x);
ll_push_l_int32(_fun, L, y);
ll_push_l_int32(_fun, L, w);
ll_push_l_int32(_fun, L, h);
return 4;
}
/**
* \brief Get the Box* reference count.
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* </pre>
* \param L Lua state.
* \return 1 integers (or nil on error) on the stack.
*/
static int
GetRefcount(lua_State *L)
{
LL_FUNC("GetRefcount");
Box *box = ll_check_Box(_fun, L, 1);
ll_push_l_int32(_fun, L, boxGetRefcount(box));
return 1;
}
/**
* \brief Get the BOX side locations (left, right, top, bottom).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
*
* Leptonica's Notes:
* (1) All returned values are within the box.
* </pre>
* \param L Lua state.
* \return 4 for four integers (or nil on error) on the stack.
*/
static int
GetSideLocations(lua_State *L)
{
LL_FUNC("GetSideLocations");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 l, r, t, b;
if (boxGetSideLocations(box, &l, &r, &t, &b))
return ll_push_nil(_fun, L);
ll_push_l_int32(_fun, L, l);
ll_push_l_int32(_fun, L, r);
ll_push_l_int32(_fun, L, t);
ll_push_l_int32(_fun, L, b);
return 4;
}
/**
* \brief Intersect a Box* (%box) by a line (%x, %y).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box).
* Arg #2 is expected to be a l_int32 (x).
* Arg #3 is expected to be a l_int32 (y).
* Arg #4 is expected to be a l_float32 (slope).
*
* Leptonica's Notes:
* (1) If the intersection is at only one point (a corner), the
* coordinates are returned in (x1, y1).
* (2) Represent a vertical line by one with a large but finite slope.
* </pre>
* \param L Lua state.
* \return 5 integers on the Lua stack (%x1, %y1, %x2, %y2, %n).
*/
static int
IntersectByLine(lua_State *L)
{
LL_FUNC("IntersectByLine");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 x = ll_check_l_int32(_fun, L, 2);
l_int32 y = ll_check_l_int32(_fun, L, 3);
l_float32 slope = ll_check_l_float32(_fun, L, 4);
l_int32 x1 = 0;
l_int32 y1 = 0;
l_int32 x2 = 0;
l_int32 y2 = 0;
l_int32 n = 0;
if (boxIntersectByLine(box, x, y, slope, &x1, &y1, &x2, &y2, &n))
return ll_push_nil(_fun, L);
ll_push_l_int32(_fun, L, x1);
ll_push_l_int32(_fun, L, y1);
ll_push_l_int32(_fun, L, x2);
ll_push_l_int32(_fun, L, y2);
ll_push_l_int32(_fun, L, n);
return 5;
}
/**
* \brief Check if a Box* (%box1) intersects another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
Intersects(lua_State *L)
{
LL_FUNC("Intersects");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_int32 intersects = 0;
if (boxIntersects(box1, box2, &intersects))
return ll_push_nil(_fun, L);
return ll_push_boolean(_fun, L, intersects);
}
/**
* \brief Check if a Box* is valid.
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
IsValid(lua_State *L)
{
LL_FUNC("IsValid");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 valid = 0;
if (boxIsValid(box, &valid))
return ll_push_nil(_fun, L);
return ll_push_boolean(_fun, L, valid);
}
/**
* \brief Get the overlap area of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
* </pre>
* \param L Lua state.
* \return 1 integer on the Lua stack.
*/
static int
OverlapArea(lua_State *L)
{
LL_FUNC("OverlapArea");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_int32 area = 0.0f;
if (boxOverlapArea(box1, box2, &area))
return ll_push_nil(_fun, L);
ll_push_l_int32(_fun, L, area);
return 1;
}
/**
* \brief Get the overlap fraction of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
*
* Leptonica's Notes:
* (1) The result depends on the order of the input boxes,
* because the overlap is taken as a fraction of box2.
* </pre>
* \param L Lua state.
* \return 1 number on the Lua stack.
*/
static int
OverlapFraction(lua_State *L)
{
LL_FUNC("OverlapFraction");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_float32 fract = 0.0f;
if (boxOverlapFraction(box1, box2, &fract))
return ll_push_nil(_fun, L);
return ll_push_l_float32(_fun, L, fract);
}
/**
* \brief Get the overlap region of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
*
* Leptonica's Notes:
* (1) This is the geometric intersection of the two rectangles.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
OverlapRegion(lua_State *L)
{
LL_FUNC("OverlapRegion");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
Box *box = boxOverlapRegion(box1, box2);
ll_push_Box(_fun, L, box);
return 1;
}
/**
* \brief Print info about a Box* (%box) to a Lua stream (%stream).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box).
* Arg #2 is expected to be a luaL_Stream io handle (stream).
*
* Leptonica's Notes:
* (1) This outputs debug info. Use serialization functions to
* write to file if you want to read the data back.
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
PrintStreamInfo(lua_State *L)
{
LL_FUNC("PrintStreamInfo");
Box *box = ll_check_Box(_fun, L, 1);
luaL_Stream *stream = ll_check_stream(_fun, L, 2);
return ll_push_boolean(_fun, L, 0 == boxPrintStreamInfo(stream->f, box));
}
/**
* \brief Relocate one side of a Box* (%boxs).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
*
* Leptonica's Notes:
* (1) Set boxd == NULL to get new box; boxd == boxs for in-place;
* or otherwise to resize existing boxd.
* (2) For usage, suggest one of these:
* boxd = boxRelocateOneSide(NULL, boxs, ...); // new
* boxRelocateOneSide(boxs, boxs, ...); // in-place
* boxRelocateOneSide(boxd, boxs, ...); // other
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
RelocateOneSide(lua_State *L)
{
LL_FUNC("RelocateOneSide");
Box *boxs = ll_check_Box(_fun, L, 1);
l_int32 loc = ll_check_l_int32(_fun, L, 2);
l_int32 sideflag = ll_check_from_side(_fun, L, 3, L_FROM_LEFT);
Box *boxd = boxRelocateOneSide(nullptr, boxs, loc, sideflag);
ll_push_Box(_fun, L, boxd);
return 1;
}
/**
* \brief Rotate a Box* (%boxs) orthogonally.
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* Arg #2 is expected to be a l_int32 (w).
* Arg #3 is expected to be a l_int32 (h).
* Arg #4 is expected to be a rotation angle (rotation).
*
* Leptonica's Notes:
* (1) Rotate the image with the embedded box by the specified amount.
* (2) After rotation, the rotated box is always measured with
* respect to the UL corner of the image.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
RotateOrth(lua_State *L)
{
LL_FUNC("RotateOrth");
Box *boxs = ll_check_Box(_fun, L, 1);
l_int32 w = ll_check_l_int32(_fun, L, 2);
l_int32 h = ll_check_l_int32(_fun, L, 3);
l_int32 rotation = ll_check_rotation(_fun, L, 4, 0);
Box *box = boxRotateOrth(boxs, w, h, rotation);
return ll_push_Box(_fun, L, box);
}
/**
* \brief Get the separation distances of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
*
* Leptonica's Notes:
* (1) This measures horizontal and vertical separation of the
* two boxes. If the boxes are touching but have no pixels
* in common, the separation is 0. If the boxes overlap by
* a distance d, the returned separation is -d.
* </pre>
* \param L Lua state.
* \return 2 integers on the Lua stack.
*/
static int
SeparationDistance(lua_State *L)
{
LL_FUNC("SeparationDistance");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_int32 h_sep = 0;
l_int32 v_sep = 0;
if (boxSeparationDistance(box1, box2, &h_sep, &v_sep))
return ll_push_nil(_fun, L);
ll_push_l_int32(_fun, L, h_sep);
ll_push_l_int32(_fun, L, v_sep);
return 2;
}
/**
* \brief Set the Box* (%box) geometry.
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* Arg #2 is expected to be a lua_Integer (x).
* Arg #3 is expected to be a lua_Integer (y).
* Arg #4 is expected to be a lua_Integer (w).
* Arg #5 is expected to be a lua_Integer (h).
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
SetGeometry(lua_State *L)
{
LL_FUNC("SetGeometry");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 x = ll_opt_l_int32(_fun, L, 2, 0);
l_int32 y = ll_opt_l_int32(_fun, L, 3, 0);
l_int32 w = ll_opt_l_int32(_fun, L, 4, 1);
l_int32 h = ll_opt_l_int32(_fun, L, 5, 1);
return ll_push_boolean(_fun, L, 0 == boxSetGeometry(box, x, y, w, h));
}
/**
* \brief Set the Box* (%box) side locations (%l, %r, %t, %b).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box).
* Arg #2 is expected to be a lua_Integer (l).
* Arg #3 is expected to be a lua_Integer (r).
* Arg #4 is expected to be a lua_Integer (t).
* Arg #5 is expected to be a lua_Integer (b).
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
SetSideLocations(lua_State *L)
{
LL_FUNC("SetSideLocations");
Box *box = ll_check_Box(_fun, L, 1);
l_int32 l = ll_opt_l_int32(_fun, L, 2, 0);
l_int32 r = ll_opt_l_int32(_fun, L, 3, 0);
l_int32 t = ll_opt_l_int32(_fun, L, 4, 0);
l_int32 b = ll_opt_l_int32(_fun, L, 5, 0);
return ll_push_boolean(_fun, L, 0 == boxSetSideLocations(box, l, r, t, b));
}
/**
* \brief Test similarity of a Box* (%box1) and another Box* (%box2).
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (box1).
* Arg #2 is expected to be another Box* (box2).
* Arg #3 is expected to be a l_int32 (leftdiff).
* Arg #4 is expected to be a l_int32 (rightdiff).
* Arg #5 is expected to be a l_int32 (topdiff).
* Arg #6 is expected to be a l_int32 (botdiff).
*
* Leptonica's Notes:
* (1) The values of leftdiff (etc) are the maximum allowed deviations
* between the locations of the left (etc) sides. If any side
* pairs differ by more than this amount, the boxes are not similar.
* </pre>
* \param L Lua state.
* \return 1 boolean on the Lua stack.
*/
static int
Similar(lua_State *L)
{
LL_FUNC("Similar");
Box *box1 = ll_check_Box(_fun, L, 1);
Box *box2 = ll_check_Box(_fun, L, 2);
l_int32 leftdiff = ll_check_l_int32(_fun, L, 3);
l_int32 rightdiff = ll_opt_l_int32(_fun, L, 4, leftdiff);
l_int32 topdiff = ll_opt_l_int32(_fun, L, 5, rightdiff);
l_int32 botdiff = ll_opt_l_int32(_fun, L, 6, topdiff);
l_int32 similar = FALSE;
if (boxSimilar(box1, box2, leftdiff, rightdiff, topdiff, botdiff, &similar))
return ll_push_nil(_fun, L);
return ll_push_boolean(_fun, L, similar);
}
/**
* \brief Transform a Box* (%boxs) by shifting and scaling.
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* Arg #2 is expected to be a l_int32 (shiftx).
* Arg #3 is expected to be a l_int32 (shifty).
* Arg #4 is an optional l_float32 (scalex).
* Arg #5 is an optional l_float32 (scaley).
*
* Leptonica's Notes:
* (1) This is a very simple function that first shifts, then scales.
* (2) If the box is invalid, a new invalid box is returned.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
Transform(lua_State *L)
{
LL_FUNC("Transform");
Box *boxs = ll_check_Box(_fun, L, 1);
l_int32 shiftx = ll_check_l_int32(_fun, L, 2);
l_int32 shifty = ll_check_l_int32(_fun, L, 3);
l_float32 scalex = ll_opt_l_float32(_fun, L, 4, 1.0f);
l_float32 scaley = ll_opt_l_float32(_fun, L, 5, 1.0f);
Box *box = boxTransform(boxs, shiftx, shifty, scalex, scaley);
ll_push_Box(_fun, L, box);
return 1;
}
/**
* \brief Ordered transform a Box* (%boxs) by shifting, scaling, and rotation..
* <pre>
* Arg #1 (i.e. self) is expected to be a Box* (boxs).
* Arg #2 is an optional l_int32 (shiftx).
* Arg #3 is an optional l_int32 (shifty).
* Arg #4 is an optional l_float32 (scalex).
* Arg #5 is an optional l_float32 (scaley).
* Arg #6 is an optional l_int32 (xcen).
* Arg #7 is an optional l_int32 (ycen).
* Arg #8 is an optional l_float32 (angle).
* Arg #9 is an optional string describing the transform order (order).
*
* Leptonica's Notes:
* (1) This allows a sequence of linear transforms, composed of
* shift, scaling and rotation, where the order of the
* transforms is specified.
* (2) The rotation is taken about a point specified by (xcen, ycen).
* Let the components of the vector from the center of rotation
* to the box center be (xdif, ydif):
* xdif = (bx + 0.5 * bw) - xcen
* ydif = (by + 0.5 * bh) - ycen
* Then the box center after rotation has new components:
* bxcen = xcen + xdif * cosa + ydif * sina
* bycen = ycen + ydif * cosa - xdif * sina
* where cosa and sina are the cos and sin of the angle,
* and the enclosing box for the rotated box has size:
* rw = |bw * cosa| + |bh * sina|
* rh = |bh * cosa| + |bw * sina|
* where bw and bh are the unrotated width and height.
* Then the box UL corner (rx, ry) is
* rx = bxcen - 0.5 * rw
* ry = bycen - 0.5 * rh
* (3) The center of rotation specified by args %xcen and %ycen
* is the point BEFORE any translation or scaling. If the
* rotation is not the first operation, this function finds
* the actual center at the time of rotation. It does this
* by making the following assumptions:
* (1) Any scaling is with respect to the UL corner, so
* that the center location scales accordingly.
* (2) A translation does not affect the center of
* the image; it just moves the boxes.
* We always use assumption (1). However, assumption (2)
* will be incorrect if the apparent translation is due
* to a clipping operation that, in effect, moves the
* origin of the image. In that case, you should NOT use
* these simple functions. Instead, use the functions
* in affinecompose.c, where the rotation center can be
* computed from the actual clipping due to translation
* of the image origin.
* </pre>
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
static int
TransformOrdered(lua_State *L)
{
LL_FUNC("TransformOrdered");
Box *boxs = ll_check_Box(_fun, L, 1);
l_float32 xc, yc;
l_int32 ok = boxGetCenter(boxs, &xc, &yc);
l_int32 shiftx = ll_opt_l_int32(_fun, L, 2, 0);
l_int32 shifty = ll_opt_l_int32(_fun, L, 3, 0);
l_float32 scalex = ll_opt_l_float32(_fun, L, 4, 1.0f);
l_float32 scaley = ll_opt_l_float32(_fun, L, 5, 1.0f);
l_int32 xcen = ll_opt_l_int32(_fun, L, 6, ok ? static_cast<l_int32>(xc) : 0);
l_int32 ycen = ll_opt_l_int32(_fun, L, 7, ok ? static_cast<l_int32>(yc) : 0);
l_float32 angle = ll_opt_l_float32(_fun, L, 8, 0.0f);
l_int32 order = ll_check_trans_order(_fun, L, 9, L_TR_SC_RO);
Box *box = boxTransformOrdered(boxs, shiftx, shifty, scalex, scaley, xcen, ycen, angle, order);
return ll_push_Box(_fun, L, box);
}
/**
* \brief Check Lua stack at index %arg for user data of class Box*.
* \param _fun calling function's name
* \param L Lua state.
* \param arg index where to find the user data (usually 1)
* \return pointer to the Box* contained in the user data.
*/
Box *
ll_check_Box(const char *_fun, lua_State *L, int arg)
{
return *ll_check_udata<Box>(_fun, L, arg, TNAME);
}
/**
* \brief Optionally expect a Box* at index %arg on the Lua stack.
* \param _fun calling function's name
* \param L Lua state.
* \param arg index where to find the user data (usually 1)
* \return pointer to the Box* contained in the user data.
*/
Box *
ll_opt_Box(const char *_fun, lua_State *L, int arg)
{
if (!ll_isudata(_fun, L, arg, TNAME))
return nullptr;
return ll_check_Box(_fun, L, arg);
}
/**
* \brief Push Box* user data to the Lua stack and set its meta table.
* \param _fun calling function's name
* \param L Lua state.
* \param box pointer to the BOX
* \return 1 Box* on the Lua stack.
*/
int
ll_push_Box(const char *_fun, lua_State *L, Box *box)
{
if (!box)
return ll_push_nil(_fun, L);
return ll_push_udata(_fun, L, TNAME, box);
}
/**
* \brief Create and push a new Box*.
* \param L Lua state.
* \return 1 Box* on the Lua stack.
*/
int
ll_new_Box(lua_State *L)
{
FUNC("ll_new_Box");
Box *box = nullptr;
l_int32 x = 0, y = 0, w = 0, h = 0;
if (ll_isudata(_fun, L, 1, LL_BOX)) {
Box *boxs = ll_opt_Box(_fun, L, 1);
DBG(LOG_NEW_PARAM, "%s: create for %s* = %p\n", _fun,
TNAME, reinterpret_cast<void *>(boxs));
box = boxCopy(boxs);
}
if (!box && ll_isinteger(_fun, L, 1)) {
x = ll_opt_l_int32(_fun, L, 1, 0);
y = ll_opt_l_int32(_fun, L, 2, 0);
w = ll_opt_l_int32(_fun, L, 3, 1);
h = ll_opt_l_int32(_fun, L, 4, 1);
DBG(LOG_NEW_PARAM, "%s: create for %s = %d, %s = %d, %s = %d, %s = %d\n", _fun,
"x", x, "y", y, "w", w, "h", h);
box = boxCreate(x, y, w, h);
}
if (!box) {
x = y = w = h = 0;
DBG(LOG_NEW_PARAM, "%s: create for %s = %d, %s = %d, %s = %d, %s = %d\n", _fun,
"x", x, "y", y, "w", w, "h", h);
box = boxCreate(x, y, w, h);
}
DBG(LOG_NEW_CLASS, "%s: created %s* %p\n", _fun,
TNAME, reinterpret_cast<void *>(box));
return ll_push_Box(_fun, L, box);
}
/**
* \brief Register the Box* methods and functions in the Box meta table.
* \param L Lua state.
* \return 1 table on the Lua stack.
*/
int
ll_open_Box(lua_State *L)
{
static const luaL_Reg methods[] = {
{"__gc", Destroy},
{"__new", ll_new_Box},
{"__tostring", toString},
{"__eq", Equal},
{"__band", OverlapRegion}, /* box = box1 & box2 */
{"__bor", BoundingRegion}, /* box = box1 | box2 */
{"AdjustSides", AdjustSides},
{"BoundingRegion", BoundingRegion},
{"ChangeRefcount", ChangeRefcount},
{"ClipToRectangle", ClipToRectangle},
{"ClipToRectangleParams", ClipToRectangleParams},
{"Clone", Clone},
{"CompareSize", CompareSize},
{"Contains", Contains},
{"ContainsPt", ContainsPt},
{"ConvertToPta", ConvertToPta},
{"Copy", Copy},
{"Create", Create},
{"CreateValid", CreateValid},
{"Destroy", Destroy},
{"Equal", Equal},
{"GetCenter", GetCenter},
{"GetGeometry", GetGeometry},
{"GetRefcount", GetRefcount},
{"GetSideLocations", GetSideLocations},
{"IntersectByLine", IntersectByLine},
{"Intersects", Intersects},
{"IsValid", IsValid},
{"OverlapArea", OverlapArea},
{"OverlapFraction", OverlapFraction},
{"OverlapRegion", OverlapRegion},
{"PrintStreamInfo", PrintStreamInfo},
{"RelocateOneSide", RelocateOneSide},
{"RotateOrth", RotateOrth},
{"SeparationDistance", SeparationDistance},
{"SetGeometry", SetGeometry},
{"SetSideLocations", SetSideLocations},
{"Similar", Similar},
{"Transform", Transform},
{"TransformOrdered", TransformOrdered},
LUA_SENTINEL
};
LO_FUNC(TNAME);
ll_set_global_cfunct(_fun, L, TNAME, ll_new_Box);
ll_register_class(_fun, L, TNAME, methods);
return 1;
}
| 31.947368 | 99 | 0.602663 | pullmoll |
7561fb5f651de22dd8052cf17263ddc627770736 | 1,404 | hpp | C++ | code/editors/xrWeatherEditor/property_editor_color.hpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/editors/xrWeatherEditor/property_editor_color.hpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/editors/xrWeatherEditor/property_editor_color.hpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 5 | 2020-10-18T11:55:26.000Z | 2022-03-28T07:21:35.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : property_editor_color.hpp
// Created : 12.12.2007
// Modified : 12.12.2007
// Author : Dmitriy Iassenev
// Description : property editor color class
////////////////////////////////////////////////////////////////////////////
#ifndef PROPERTY_EDITOR_COLOR_HPP_INCLUDED
#define PROPERTY_EDITOR_COLOR_HPP_INCLUDED
public ref class property_editor_color : public System::Drawing::Design::UITypeEditor {
private:
typedef System::Drawing::Design::UITypeEditor inherited;
typedef System::ComponentModel::ITypeDescriptorContext ITypeDescriptorContext;
typedef System::Drawing::Design::PaintValueEventArgs PaintValueEventArgs;
public:
virtual bool GetPaintValueSupported (ITypeDescriptorContext^ context) override;
virtual void PaintValue (PaintValueEventArgs^ arguments) override;
public:
typedef System::Drawing::Design::UITypeEditorEditStyle UITypeEditorEditStyle;
typedef System::IServiceProvider IServiceProvider;
typedef System::Object Object;
virtual UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext^ context) override;
virtual Object^ EditValue (
ITypeDescriptorContext^ context,
IServiceProvider^ provider,
Object^ value
) override;
}; // ref class property_editor_color
#endif // ifndef PROPERTY_EDITOR_COLOR_HPP_INCLUDED | 40.114286 | 87 | 0.698006 | Rikoshet-234 |
75651d4ca257edd91258e6281cbc0b49b6f8543c | 718 | cpp | C++ | leetcode.com/Weekly Contest 217/3/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2020-08-20T11:02:49.000Z | 2020-08-20T11:02:49.000Z | leetcode.com/Weekly Contest 217/3/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | null | null | null | leetcode.com/Weekly Contest 217/3/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2022-01-01T23:23:13.000Z | 2022-01-01T23:23:13.000Z | #include <bits/stdc++.h>
using namespace std;
static int x = []() {
ios::sync_with_stdio(false);
cin.tie(0);
return 0;
}();
typedef long long ll;
int d[200100];
class Solution {
public:
int minMoves(vector<int>& nums, int limit) {
memset(d, 0, sizeof(d));
int n = nums.size();
for (int i = 0; i < n / 2; ++i) {
int l = 1 + min(nums[i], nums[n - i - 1]);
int r = limit + max(nums[i], nums[n - i - 1]);
int m = nums[i] + nums[n - i - 1];
d[l] += -1;
d[r + 1] += 1;
d[m] += -1;
d[m + 1] += 1;
}
int res = n;
int cur = n;
for (int i = 2; i < limit * 2 + 2; ++i) {
cur += d[i];
res = min(res, cur);
}
return res;
}
};
| 19.405405 | 52 | 0.456825 | sky-bro |
7566112585d82dcc28f739100d28e45b5eb655f6 | 659 | cpp | C++ | C++/scope/initializer/factor/Factor.cpp | fantaosha/SCOPE | 30519b52822d04fb7b5bf6f45e73227ad4260738 | [
"MIT"
] | 26 | 2021-10-10T18:34:38.000Z | 2022-03-03T03:00:40.000Z | C++/scope/initializer/factor/Factor.cpp | fantaosha/SCOPE | 30519b52822d04fb7b5bf6f45e73227ad4260738 | [
"MIT"
] | 3 | 2021-12-24T07:28:11.000Z | 2022-02-02T21:26:55.000Z | C++/scope/initializer/factor/Factor.cpp | fantaosha/SCOPE | 30519b52822d04fb7b5bf6f45e73227ad4260738 | [
"MIT"
] | 7 | 2021-11-06T15:23:08.000Z | 2022-02-28T03:40:03.000Z | #include <scope/initializer/factor/Factor.h>
namespace scope {
namespace Initializer {
Factor::Evaluation::Evaluation() : status(Status::INVALID) {}
int Factor::Evaluation::reset() {
status = Status::INVALID;
return 0;
}
int Factor::Evaluation::clear() {
reset();
error.resize(0);
return 0;
}
Factor::Linearization::Linearization() : status(Status::INVALID) {}
int Factor::Linearization::reset() {
status = Status::INVALID;
return 0;
}
int Factor::Linearization::clear() {
reset();
return 0;
}
Factor::Factor(const std::string &name, int index)
: mIndex(index), mName(name) {}
} // namespace Initializer
} // namespace scope
| 16.897436 | 67 | 0.679818 | fantaosha |
7566b292f5f7309c950ee83a1a94b9ae354b8e38 | 709 | cpp | C++ | C++/CheckPalindrome.cpp | keshavgbpecdelhi/HacktoberFest-2021 | 0ac2ed4c575750bb5ceb79e0d1fc519d7e6054f8 | [
"MIT"
] | 7 | 2021-10-01T05:10:17.000Z | 2021-10-30T07:19:27.000Z | C++/CheckPalindrome.cpp | keshavgbpecdelhi/HacktoberFest-2021 | 0ac2ed4c575750bb5ceb79e0d1fc519d7e6054f8 | [
"MIT"
] | 32 | 2021-10-01T06:08:04.000Z | 2021-11-03T11:12:22.000Z | C++/CheckPalindrome.cpp | keshavgbpecdelhi/HacktoberFest-2021 | 0ac2ed4c575750bb5ceb79e0d1fc519d7e6054f8 | [
"MIT"
] | 20 | 2021-10-01T06:06:44.000Z | 2021-10-31T05:31:49.000Z | #include <iostream>
#include <cstring>
using namespace std;
#include <cstring>
bool helper(char input[], int start, int end)
{
if (start >= end)
{
return true;
}
if (input[start] != input[end])
{
return false;
}
bool smallcheck = helper(input, start + 1, end - 1);
return smallcheck;
}
bool checkPalindrome(char input[])
{
int len = strlen(input);
int start = 0, end = len - 1;
return helper(input, start + 1, end - 1);
}
int main()
{
char input[50];
cin >> input;
if (checkPalindrome(input))
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
} | 17.292683 | 57 | 0.507757 | keshavgbpecdelhi |
7568d34b86c115cac9c3fc9bc91f05f92c81063a | 9,568 | cxx | C++ | ltnc/compiler/LtncStmtCompiler.cxx | JeneLitsch/LitanCompiler | be11dfd6f1a31a41a3bda2d41b1bfaa5066c9f18 | [
"MIT"
] | null | null | null | ltnc/compiler/LtncStmtCompiler.cxx | JeneLitsch/LitanCompiler | be11dfd6f1a31a41a3bda2d41b1bfaa5066c9f18 | [
"MIT"
] | null | null | null | ltnc/compiler/LtncStmtCompiler.cxx | JeneLitsch/LitanCompiler | be11dfd6f1a31a41a3bda2d41b1bfaa5066c9f18 | [
"MIT"
] | null | null | null | #include "LtncStmtCompiler.hxx"
#include <iostream>
std::string ltnc::StmtCompiler::compileProgram(CompilerPack & compPkg, std::shared_ptr<Program> program){
compPkg.getScopes().addFunctionScope(FxSignature(Type::VOI, "", {}));
for(const auto & function : program->functions) {
compPkg.registerFunction(function);
}
std::string code;
code += "-> MAIN \n";
code += this->compileEval(compPkg, std::make_shared<StmtExpr>(std::make_shared<ExprCall>("main")));
code += "exit \n";
for(const auto & function : program->functions) {
code += this->compileFunction(compPkg, function);
}
return code;
}
std::string ltnc::StmtCompiler::compileStmt(CompilerPack & compPkg, std::shared_ptr<Stmt> stmt){
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtAssign>(stmt)) {
return this->compileAssign(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtBlock>(stmt)) {
return this->compileBlock(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtIf>(stmt)) {
return this->compileIf(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtFor>(stmt)) {
return this->compileFor(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtRepeat>(stmt)) {
return this->compileRepeat(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtWhile>(stmt)) {
return this->compileWhile(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtPrint>(stmt)) {
return this->compilePrint(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtExpr>(stmt)) {
return this->compileEval(compPkg, stmt_);
}
if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtReturn>(stmt)) {
return this->compileReturn(compPkg, stmt_);
}
return "";
}
std::string ltnc::StmtCompiler::compilePrint(CompilerPack & compPkg, std::shared_ptr<StmtPrint> stmt) {
auto expr = exprCompiler.compileExpr(compPkg, stmt->expr);
switch (expr.type.type) {
case Type::INT: return expr.code + "print\n";
case Type::FLT: return expr.code + "print 1\n";
default: throw std::runtime_error("[should never occur] Error while compiling print");
}
}
std::string ltnc::StmtCompiler::compileAssign(CompilerPack & compPkg, std::shared_ptr<StmtAssign> stmt){
auto expr = exprCompiler.compileExpr(compPkg, stmt->expr);
Var var = compPkg.getScopes().get().getVar(stmt->name);
if(expr.type != var.type) throw std::runtime_error("Types do not match: " + expr.code);
return this->comment("assign to int var " + stmt->name) + expr.code
+ "store " + std::to_string(var.addr) + "\n";
}
std::string ltnc::StmtCompiler::compileRepeat(CompilerPack & compPkg, std::shared_ptr<StmtRepeat> stmt) {
// From and to expression
ExprInfo expr = this->exprCompiler.compileExpr(compPkg, stmt->expr);
if(expr.type != Type::INT){
throw std::runtime_error("Upper bound of for loop needs to be a integer expression.");
}
compPkg.getScopes().addBlockScope();
// iteration variable
// create code inside loop
std::string codeStmt = this->compileBlock(compPkg, stmt->stmt);
compPkg.getScopes().remove();
if(expr.constant) {
std::int64_t amount = std::get<std::int64_t>(expr.constant->value);
if(amount <= 0) {
std::cout << ">> [Warning] repeat loop: needs to be bigger than 0" << std::endl;
}
std::string code;
bool shouldBeOptimized =
(this->getOptimizationLevel() == 1 && amount < 128) ||
(this->getOptimizationLevel() == 2 && amount < 256) ||
(this->getOptimizationLevel() >= 3 && amount < 1024);
// unrolling
if(shouldBeOptimized) {
for(int idx = 0; idx <= amount; idx++) {
code += codeStmt;
}
return code;
}
}
// create code
return
"newi 0\n" +
expr.code +
"loop::range \n" +
"loop::idx \n" +
codeStmt +
"loop::cont \n";
}
std::string ltnc::StmtCompiler::compileFor(CompilerPack & compPkg, std::shared_ptr<StmtFor> stmt) {
// From and to expression
ExprInfo from = this->exprCompiler.compileExpr(compPkg, stmt->exprFrom);
ExprInfo to = this->exprCompiler.compileExpr(compPkg, stmt->exprTo);
if(from.type != Type::INT){
throw std::runtime_error("Lower bound of for loop needs to be a integer expression.");
}
if(to.type != Type::INT){
throw std::runtime_error("Upper bound of for loop needs to be a integer expression.");
}
compPkg.getScopes().addBlockScope();
// iteration variable
Var counter = compPkg.getScopes().get().registerVar(stmt->name, Type::INT);
// create code inside loop
std::string codeStmt = this->compileBlock(compPkg, stmt->stmt);
compPkg.getScopes().remove();
if(from.constant && to.constant) {
std::int64_t lowerBound = std::get<std::int64_t>(from.constant->value);
std::int64_t upperBound = std::get<std::int64_t>(to.constant->value);
if(lowerBound > upperBound) {
std::cout << ">> [Warning] for loop: Lower constant boundary needs to smaller than the upper Limit" << std::endl;
}
std::int64_t delta = std::abs(lowerBound - upperBound);
std::string code;
bool shouldBeOptimized =
(this->getOptimizationLevel() == 1 && delta < 128) ||
(this->getOptimizationLevel() == 2 && delta < 256) ||
(this->getOptimizationLevel() >= 3 && delta < 1024);
// unrolling
if(shouldBeOptimized) {
for(int idx = lowerBound; idx <= upperBound; idx++) {
code += "newi " + std::to_string(idx) + "\n";
code += "store " + std::to_string(counter.addr) + "\n";
code += codeStmt;
}
return code;
}
}
// create code
return
from.code +
to.code +
"loop::range \n" +
"loop::idx \n" +
"store " + std::to_string(counter.addr) + "\n" +
codeStmt +
"loop::cont \n";
}
std::string ltnc::StmtCompiler::compileWhile(CompilerPack & compPkg, std::shared_ptr<StmtWhile> stmt) {
auto codeExpr = this->exprCompiler.compileExpr(compPkg, stmt->expr);
auto codeStmt = this->compileStmt(compPkg, stmt->stmt);
auto endMark = compPkg.makeJumpMark("LOOP_END");
auto loopMark = compPkg.makeJumpMark("LOOP");
return
"-> " + loopMark + "\n" +
codeExpr.code +
"ifnot\n" +
"goto " + endMark + "\n" +
codeStmt +
"goto " + loopMark + "\n" +
"-> " + endMark + "\n";
}
std::string ltnc::StmtCompiler::compileBlock(CompilerPack & compPkg, std::shared_ptr<StmtBlock> block) {
compPkg.getScopes().addBlockScope();
std::string code;
for(const auto & decl : block->declarations) {
Var var = compPkg.getScopes().get().registerVar(decl->name, decl->type);
}
for(const auto & stmt : block->statements) {
code+= this->compileStmt(compPkg, stmt);
}
compPkg.getScopes().remove();
return code;
}
std::string ltnc::StmtCompiler::compileIf(CompilerPack & compPkg, std::shared_ptr<StmtIf> stmt) {
// make jump marks
std::string jmIf = compPkg.makeJumpMark("IF");
std::string jmElse = compPkg.makeJumpMark("ELSE");
std::string jmEnd = compPkg.makeJumpMark("END_IF");
std::string condition = this->exprCompiler.compileExpr(compPkg, stmt->condition).code;
std::string codeIf = this->compileStmt(compPkg, stmt->stmtIf);
if(stmt->stmtElse) {
std::string codeElse = this->compileStmt(compPkg, stmt->stmtElse);
return
condition +
"ifnx" + "\n" +
"goto " + jmIf + "\n" +
"goto " + jmElse + "\n" +
"-> " + jmIf + "\n" +
codeIf +
"goto " + jmEnd + "\n" +
"-> " + jmElse + "\n" +
codeElse +
"goto " + jmEnd + "\n" +
"-> " + jmEnd + "\n";
}
else {
return
condition +
"ifnx" + "\n" +
"goto " + jmIf + "\n" +
"goto " + jmEnd + "\n" +
"-> " + jmIf + "\n" +
codeIf +
"-> " + jmEnd + "\n";
}
}
std::string ltnc::StmtCompiler::compileFunction(CompilerPack & compPkg, std::shared_ptr<DeclFunction> decl) {
FxInfo fxInfo = *compPkg.matchFunction(decl->signature);
compPkg.getScopes().addFunctionScope(fxInfo.signature);
// register parameter
for(const Param & param : decl->signature.params) {
compPkg.getScopes().get().registerVar(param.name, param.type);
}
// create code;
std::string code;
code += this->comment(decl->signature.name + " " + std::to_string(decl->signature.params.size()) + " -> " + std::to_string(static_cast<int>(decl->signature.returnType.type)));
code += "-> " + fxInfo.jumpMark + "\n";
// load params into memory (backwards because LIFO)
for(auto param = decl->signature.params.rbegin(); param != decl->signature.params.rend(); ++param) {
// store parameter;
code += this->comment("store parameter " + param->name);
code += "store " + std::to_string(compPkg.getScopes().get().getVar((*param).name).addr) + "\n";
}
code += this->compileStmt(compPkg, decl->body);
compPkg.getScopes().remove();
return code;
}
std::string ltnc::StmtCompiler::compileEval(CompilerPack & compPkg, std::shared_ptr<StmtExpr> stmt) {
ExprInfo exprInfo = this->exprCompiler.compileExpr(compPkg, stmt->expr);
std::string code;
code += exprInfo.code + "\n";
if(exprInfo.type == Type::INT || exprInfo.type == Type::FLT) {
code += "scrap \n";
}
return code;
}
std::string ltnc::StmtCompiler::compileReturn(CompilerPack & compPkg, std::shared_ptr<StmtReturn> stmt) {
std::string code = "";
FxSignature signature = compPkg.getScopes().get().getFxSignature();
if(stmt->expr) {
ExprInfo exprInfo = this->exprCompiler.compileExpr(compPkg, stmt->expr);
if(exprInfo.type != signature.returnType) {
throw std::runtime_error("Type of return statement do not match return type of function");
}
code += exprInfo.code;
}
else {
if(Type::VOI != signature.returnType) {
throw std::runtime_error("Type of return statement do not match return type of function");
}
}
code += "return \n";
return code;
}
| 31.166124 | 176 | 0.670778 | JeneLitsch |
756a61b072edec80aaafb8086774d89542624af5 | 4,260 | cc | C++ | packager/media/crypto/sample_aes_ec3_cryptor_unittest.cc | Videofy/shaka-packager | 33792ca2daae5d3fdcd7a8f72ddb3d2455db2ece | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-13T03:50:58.000Z | 2021-01-13T03:50:58.000Z | packager/media/crypto/sample_aes_ec3_cryptor_unittest.cc | Videofy/shaka-packager | 33792ca2daae5d3fdcd7a8f72ddb3d2455db2ece | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | packager/media/crypto/sample_aes_ec3_cryptor_unittest.cc | Videofy/shaka-packager | 33792ca2daae5d3fdcd7a8f72ddb3d2455db2ece | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include "packager/media/crypto/sample_aes_ec3_cryptor.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
namespace shaka {
namespace media {
class MockAesCryptor : public AesCryptor {
public:
MockAesCryptor() : AesCryptor(kDontUseConstantIv) {}
MOCK_METHOD2(InitializeWithIv,
bool(const std::vector<uint8_t>& key,
const std::vector<uint8_t>& iv));
MOCK_METHOD4(CryptInternal,
bool(const uint8_t* text,
size_t text_size,
uint8_t* crypt_text,
size_t* crypt_text_size));
MOCK_METHOD0(SetIvInternal, void());
};
class SampleAesEc3CryptorTest : public ::testing::Test {
public:
SampleAesEc3CryptorTest()
: mock_cryptor_(new MockAesCryptor),
ec3_cryptor_(std::unique_ptr<MockAesCryptor>(mock_cryptor_)) {}
void SetUp() {
std::vector<uint8_t> key(16, 'k');
std::vector<uint8_t> iv(8, 'i');
EXPECT_CALL(*mock_cryptor_, InitializeWithIv(key, iv))
.WillOnce(Return(true));
EXPECT_TRUE(ec3_cryptor_.InitializeWithIv(key, iv));
EXPECT_EQ(iv, ec3_cryptor_.iv());
}
protected:
MockAesCryptor* mock_cryptor_; // Owned by |ec3_cryptor_|.
SampleAesEc3Cryptor ec3_cryptor_;
};
TEST_F(SampleAesEc3CryptorTest, Crypt) {
const std::vector<uint8_t> text = {
// First syncframe with 20 bytes.
0x0B, 0x77, 0x00, 0x09, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20,
// Second syncframe with 26 bytes.
0x0B, 0x77, 0x00, 0x0C, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22,
0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x32, 0x33, 0x34,
0x35, 0x36,
// Third syncframe with 16 bytes.
0x0B, 0x77, 0x00, 0x07, 0x15, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x32,
0x33, 0x34, 0x35, 0x36};
EXPECT_CALL(*mock_cryptor_, CryptInternal(_, _, _, _))
.WillRepeatedly(Invoke([](const uint8_t* text, size_t text_size,
uint8_t* crypt_text, size_t* crypt_text_size) {
*crypt_text_size = text_size;
for (size_t i = 0; i < text_size; ++i) {
*crypt_text++ = *text++ + 0x40;
}
return true;
}));
const std::vector<uint8_t> expected_crypt_text = {
// First syncframe with 20 bytes.
0x0B, 0x77, 0x00, 0x09, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16, 0x57, 0x58, 0x59, 0x60,
// Second syncframe with 26 bytes.
0x0B, 0x77, 0x00, 0x0C, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22,
0x23, 0x24, 0x25, 0x26, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74,
0x75, 0x76,
// Third syncframe with 16 bytes.
0x0B, 0x77, 0x00, 0x07, 0x15, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x32,
0x33, 0x34, 0x35, 0x36};
std::vector<uint8_t> crypt_text;
ASSERT_TRUE(ec3_cryptor_.Crypt(text, &crypt_text));
EXPECT_EQ(expected_crypt_text, crypt_text);
}
TEST_F(SampleAesEc3CryptorTest, InvalidEc3Syncword) {
const std::vector<uint8_t> text = {0x0C, 0x77, 0x00, 0x09, 0x05, 0x06, 0x07,
0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14,
0x15, 0x16, 0x17, 0x18, 0x19, 0x20};
EXPECT_CALL(*mock_cryptor_, CryptInternal(_, _, _, _))
.WillRepeatedly(Return(true));
std::vector<uint8_t> crypt_text;
ASSERT_FALSE(ec3_cryptor_.Crypt(text, &crypt_text));
}
TEST_F(SampleAesEc3CryptorTest, InvalidEc3SyncframeSize) {
const std::vector<uint8_t> text = {0x0B, 0x77, 0x00, 0x0A, 0x05, 0x06, 0x07,
0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14,
0x15, 0x16, 0x17, 0x18, 0x19, 0x20};
EXPECT_CALL(*mock_cryptor_, CryptInternal(_, _, _, _))
.WillRepeatedly(Return(true));
std::vector<uint8_t> crypt_text;
ASSERT_FALSE(ec3_cryptor_.Crypt(text, &crypt_text));
}
} // namespace media
} // namespace shaka
| 35.5 | 79 | 0.634507 | Videofy |
756cc73054eed2306d800f1605884d9d15d4f5c5 | 21,664 | cpp | C++ | tinyxml/ticpp.cpp | blazeroni/foxc | c143edb63b90a6c500193ea5eac95f9c89e3c4ff | [
"MIT"
] | null | null | null | tinyxml/ticpp.cpp | blazeroni/foxc | c143edb63b90a6c500193ea5eac95f9c89e3c4ff | [
"MIT"
] | null | null | null | tinyxml/ticpp.cpp | blazeroni/foxc | c143edb63b90a6c500193ea5eac95f9c89e3c4ff | [
"MIT"
] | null | null | null | /*
http://code.google.com/p/ticpp/
Copyright (c) 2006 Ryan Pusztai, Ryan Mulder
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// customization to force use of ticpp
#ifndef TIXML_USE_TICPP
#define TIXML_USE_TICPP
#endif
// end customization
#ifdef TIXML_USE_TICPP
#include "ticpp.h"
#include "ticpprc.h"
#include "tinyxml.h"
#include <sstream>
using namespace ticpp;
Attribute::Attribute()
{
SetTiXmlPointer( new TiXmlAttribute() );
m_impRC->InitRef();
}
Attribute::Attribute( TiXmlAttribute* attribute )
{
SetTiXmlPointer( attribute );
m_impRC->IncRef();
}
Attribute::Attribute( const std::string& name, const std::string& value )
{
SetTiXmlPointer( new TiXmlAttribute( name, value ) );
m_impRC->InitRef();
}
void Attribute::operator=( const Attribute& copy )
{
// Dropping the reference to the old object
this->m_impRC->DecRef();
// Pointing to the new Object
SetTiXmlPointer( copy.m_tiXmlPointer );
// The internal tixml pointer changed in the above line
this->m_impRC->IncRef();
}
Attribute::Attribute( const Attribute& copy ) : Base()
{
// Dropping the reference to the old object
this->m_impRC->DecRef();
// Pointing to the new Object
SetTiXmlPointer( copy.m_tiXmlPointer );
// The internal tixml pointer changed in the above line
this->m_impRC->IncRef();
}
Attribute::~Attribute()
{
m_impRC->DecRef();
}
std::string Attribute::Value()
{
ValidatePointer();
return m_tiXmlPointer->ValueStr();
}
std::string Attribute::Name()
{
ValidatePointer();
return m_tiXmlPointer->Name();
}
Attribute* Attribute::Next( bool throwIfNoAttribute )
{
ValidatePointer();
TiXmlAttribute* attribute = m_tiXmlPointer->Next();
if ( NULL == attribute )
{
if ( throwIfNoAttribute )
{
THROW( "No more attributes found" )
}
else
{
return NULL;
}
}
Attribute* temp = new Attribute( attribute );
m_spawnedWrappers.push_back( temp );
return temp;
}
Attribute* Attribute::Previous( bool throwIfNoAttribute )
{
ValidatePointer();
TiXmlAttribute* attribute = m_tiXmlPointer->Previous();
if ( NULL == attribute )
{
if ( throwIfNoAttribute )
{
THROW( "No more attributes found" )
}
else
{
return NULL;
}
}
Attribute* temp = new Attribute( attribute );
m_spawnedWrappers.push_back( temp );
return temp;
}
void Attribute::IterateNext( const std::string&, Attribute** next )
{
*next = Next( false );
}
void Attribute::IteratePrevious( const std::string&, Attribute** previous )
{
*previous = Previous( false );
}
void Attribute::Print( FILE* file, int depth )
{
ValidatePointer();
m_tiXmlPointer->Print( file, depth );
}
void Attribute::SetTiXmlPointer( TiXmlAttribute* newPointer )
{
m_tiXmlPointer = newPointer;
SetImpRC( newPointer );
}
//*****************************************************************************
Node* Node::NodeFactory( TiXmlNode* tiXmlNode, bool throwIfNull, bool rememberSpawnedWrapper )
{
if ( NULL == tiXmlNode )
{
if ( throwIfNull )
{
THROW( "tiXmlNode is NULL" )
}
else
{
return NULL;
}
}
Node* temp;
switch ( tiXmlNode->Type() )
{
case TiXmlNode::DOCUMENT:
temp = new Document( tiXmlNode->ToDocument() );
break;
case TiXmlNode::ELEMENT:
temp = new Element( tiXmlNode->ToElement() );
break;
case TiXmlNode::COMMENT:
temp = new Comment( tiXmlNode->ToComment() );
break;
case TiXmlNode::TEXT:
temp = new Text( tiXmlNode->ToText() );
break;
case TiXmlNode::DECLARATION:
temp = new Declaration( tiXmlNode->ToDeclaration() );
break;
default:
THROW( "Type is unsupported" )
}
if ( rememberSpawnedWrapper )
{
m_spawnedWrappers.push_back( temp );
}
return temp;
}
std::string Node::Value()
{
return GetTiXmlPointer()->ValueStr();
}
void Node::Clear()
{
GetTiXmlPointer()->Clear();
}
Node* Node::Parent( bool throwIfNoParent )
{
TiXmlNode* parent = GetTiXmlPointer()->Parent();
if ( ( NULL == parent ) && throwIfNoParent )
{
THROW( "No parent exists" );
}
return NodeFactory( parent, false );
}
Node* Node::FirstChild( bool throwIfNoChildren )
{
return FirstChild( "", throwIfNoChildren );
}
Node* Node::FirstChild( const std::string& value, bool throwIfNoChildren )
{
return FirstChild( value.c_str(), throwIfNoChildren );
}
Node* Node::FirstChild( const char* value, bool throwIfNoChildren )
{
TiXmlNode* childNode;
if ( 0 == strlen( value ) )
{
childNode = GetTiXmlPointer()->FirstChild();
}
else
{
childNode = GetTiXmlPointer()->FirstChild( value );
}
if ( ( NULL == childNode ) && throwIfNoChildren )
{
THROW( "Child with the value of \"" << value << "\" not found" );
}
return NodeFactory( childNode, false );
}
Node* Node::LastChild( bool throwIfNoChildren )
{
return LastChild( "", throwIfNoChildren );
}
Node* Node::LastChild( const std::string& value, bool throwIfNoChildren )
{
return LastChild( value.c_str(), throwIfNoChildren );
}
Node* Node::LastChild( const char* value, bool throwIfNoChildren )
{
TiXmlNode* childNode;
if ( 0 == strlen( value ) )
{
childNode = GetTiXmlPointer()->LastChild();
}
else
{
childNode = GetTiXmlPointer()->LastChild( value );
}
if ( ( NULL == childNode ) && throwIfNoChildren )
{
THROW( "Child with the value of \"" << value << "\" not found" );
}
return NodeFactory( childNode, false );
}
Node* Node::IterateChildren ( Node* previous )
{
TiXmlNode* pointer;
if ( NULL == previous )
{
pointer = GetTiXmlPointer()->IterateChildren( NULL );
}
else
{
pointer = GetTiXmlPointer()->IterateChildren( previous->GetTiXmlPointer() );
}
return NodeFactory( pointer, false );
}
Node* Node::IterateChildren( const std::string& value, Node* previous )
{
TiXmlNode* pointer;
if ( NULL == previous )
{
pointer = GetTiXmlPointer()->IterateChildren( value, NULL );
}
else
{
pointer = GetTiXmlPointer()->IterateChildren( value, previous->GetTiXmlPointer() );
}
return NodeFactory( pointer, false );
}
Node* Node::InsertEndChild( Node& addThis )
{
if ( addThis.Type() == TiXmlNode::DOCUMENT )
{
THROW( "Node is a Document and can't be inserted" );
}
// Increment reference count when adding to the tree
addThis.m_impRC->IncRef();
TiXmlNode* pointer = GetTiXmlPointer()->InsertEndChild( *addThis.GetTiXmlPointer() );
if ( NULL == pointer )
{
THROW( "Node can't be inserted" );
}
return NodeFactory( pointer );
}
Node* Node::LinkEndChild( Node* childNode )
{
if ( childNode->Type() == TiXmlNode::DOCUMENT )
{
THROW( "Node is a Document and can't be linked" );
}
// Increment reference count when adding to the tree
childNode->m_impRC->IncRef();
if ( NULL == GetTiXmlPointer()->LinkEndChild( childNode->GetTiXmlPointer() ) )
{
THROW( "Node can't be linked" );
}
return childNode;
}
Node* Node::InsertBeforeChild( Node* beforeThis, Node& addThis )
{
if ( addThis.Type() == TiXmlNode::DOCUMENT )
{
THROW( "Node is a Document and can't be inserted" );
}
// Increment reference count when adding to the tree
addThis.m_impRC->IncRef();
TiXmlNode* pointer = GetTiXmlPointer()->InsertBeforeChild( beforeThis->GetTiXmlPointer(), *addThis.GetTiXmlPointer() );
if ( NULL == pointer )
{
THROW( "Node can't be inserted" );
}
return NodeFactory( pointer );
}
Node* Node::InsertAfterChild( Node* afterThis, Node& addThis )
{
if ( addThis.Type() == TiXmlNode::DOCUMENT )
{
THROW( "Node is a Document and can't be inserted" );
}
// Increment reference count when adding to the tree
addThis.m_impRC->IncRef();
TiXmlNode* pointer = GetTiXmlPointer()->InsertAfterChild( afterThis->GetTiXmlPointer(), *addThis.GetTiXmlPointer() );
if ( NULL == pointer )
{
THROW( "Node can't be inserted" );
}
return NodeFactory( pointer );
}
Node* Node::ReplaceChild( Node* replaceThis, Node& withThis )
{
if ( withThis.Type() == TiXmlNode::DOCUMENT )
{
THROW( "Node is a Document and can't be inserted" );
}
// Increment reference count when adding to the tree
withThis.m_impRC->IncRef();
TiXmlNode* pointer = GetTiXmlPointer()->ReplaceChild( replaceThis->GetTiXmlPointer(), *withThis.GetTiXmlPointer() );
if ( NULL == pointer )
{
THROW( "Node can't be inserted" );
}
return NodeFactory( pointer );
}
void Node::RemoveChild( Node* removeThis )
{
if ( !GetTiXmlPointer()->RemoveChild( removeThis->GetTiXmlPointer() ) )
{
THROW( "Node to remove (" << removeThis->Value() << ") is not a child of this Node (" << Value() << ")" )
}
}
Node* Node::PreviousSibling( bool throwIfNoSiblings )
{
return PreviousSibling( "", throwIfNoSiblings );
}
Node* Node::PreviousSibling( const std::string& value, bool throwIfNoSiblings )
{
return PreviousSibling( value.c_str(), throwIfNoSiblings );
}
Node* Node::PreviousSibling( const char* value, bool throwIfNoSiblings )
{
TiXmlNode* sibling;
if ( 0 == strlen( value ) )
{
sibling = GetTiXmlPointer()->PreviousSibling();
}
else
{
sibling = GetTiXmlPointer()->PreviousSibling( value );
}
if ( ( NULL == sibling ) && throwIfNoSiblings )
{
THROW( "No Siblings found with value, '" << value << "', Prior to this Node (" << Value() << ")" )
}
return NodeFactory( sibling, false );
}
Node* Node::NextSibling( bool throwIfNoSiblings )
{
return NextSibling( "", throwIfNoSiblings );
}
Node* Node::NextSibling( const std::string& value, bool throwIfNoSiblings )
{
return NextSibling( value.c_str(), throwIfNoSiblings );
}
Node* Node::NextSibling( const char* value, bool throwIfNoSiblings )
{
TiXmlNode* sibling;
if ( 0 == strlen( value ) )
{
sibling = GetTiXmlPointer()->NextSibling();
}
else
{
sibling = GetTiXmlPointer()->NextSibling( value );
}
if ( ( NULL == sibling ) && throwIfNoSiblings )
{
THROW( "No Siblings found with value, '" << value << "', After this Node (" << Value() << ")" )
}
return NodeFactory( sibling, false );
}
Element* Node::NextSiblingElement( bool throwIfNoSiblings )
{
return NextSiblingElement( "", throwIfNoSiblings );
}
Element* Node::NextSiblingElement( const std::string& value, bool throwIfNoSiblings )
{
return NextSiblingElement( value.c_str(), throwIfNoSiblings );
}
Element* Node::NextSiblingElement( const char* value, bool throwIfNoSiblings )
{
TiXmlElement* sibling;
if ( 0 == strlen( value ) )
{
sibling = GetTiXmlPointer()->NextSiblingElement();
}
else
{
sibling = GetTiXmlPointer()->NextSiblingElement( value );
}
if ( NULL == sibling )
{
if ( throwIfNoSiblings )
{
THROW( "No Element Siblings found with value, '" << value << "', After this Node (" << Value() << ")" )
}
else
{
return NULL;
}
}
Element* temp = new Element( sibling );
m_spawnedWrappers.push_back( temp );
return temp;
}
Element* Node::FirstChildElement( bool throwIfNoChildren )
{
return FirstChildElement( "", throwIfNoChildren );
}
Element* Node::FirstChildElement( const std::string& value, bool throwIfNoChildren )
{
return FirstChildElement( value.c_str(), throwIfNoChildren );
}
Element* Node::FirstChildElement( const char* value, bool throwIfNoChildren )
{
TiXmlElement* element;
if ( 0 == strlen( value ) )
{
element = GetTiXmlPointer()->FirstChildElement();
}
else
{
element = GetTiXmlPointer()->FirstChildElement( value );
}
if ( NULL == element )
{
if( throwIfNoChildren )
{
THROW( "Element (" << Value() << ") does NOT contain a child with the value of '" << value << "'" )
}
else
{
return NULL;
}
}
Element* temp = new Element( element );
m_spawnedWrappers.push_back( temp );
return temp;
}
int Node::Type()
{
return GetTiXmlPointer()->Type();
}
Document* Node::GetDocument( bool throwIfNoDocument )
{
TiXmlDocument* doc = GetTiXmlPointer()->GetDocument();
if ( NULL == doc )
{
if( throwIfNoDocument )
{
THROW( "This node (" << Value() << ") is not linked under a document" )
}
else
{
return NULL;
}
}
Document* temp = new Document( doc );
m_spawnedWrappers.push_back( temp );
return temp;
}
bool Node::NoChildren()
{
return GetTiXmlPointer()->NoChildren();
}
Document* Node::ToDocument()
{
TiXmlDocument* doc = GetTiXmlPointer()->ToDocument();
if ( NULL == doc )
{
THROW( "This node (" << Value() << ") is not a Document" )
}
Document* temp = new Document( doc );
m_spawnedWrappers.push_back( temp );
return temp;
}
Element* Node::ToElement()
{
TiXmlElement* doc = GetTiXmlPointer()->ToElement();
if ( NULL == doc )
{
THROW( "This node (" << Value() << ") is not a Element" )
}
Element* temp = new Element( doc );
m_spawnedWrappers.push_back( temp );
return temp;
}
Comment* Node::ToComment()
{
TiXmlComment* doc = GetTiXmlPointer()->ToComment();
if ( NULL == doc )
{
THROW( "This node (" << Value() << ") is not a Comment" )
}
Comment* temp = new Comment( doc );
m_spawnedWrappers.push_back( temp );
return temp;
}
Text* Node::ToText()
{
TiXmlText* doc = GetTiXmlPointer()->ToText();
if ( NULL == doc )
{
THROW( "This node (" << Value() << ") is not a Text" )
}
Text* temp = new Text( doc );
m_spawnedWrappers.push_back( temp );
return temp;
}
Declaration* Node::ToDeclaration()
{
TiXmlDeclaration* doc = GetTiXmlPointer()->ToDeclaration();
if ( NULL == doc )
{
THROW( "This node (" << Value() << ") is not a Declaration" )
}
Declaration* temp = new Declaration( doc );
m_spawnedWrappers.push_back( temp );
return temp;
}
std::auto_ptr< Node > Node::Clone()
{
TiXmlNode* node = GetTiXmlPointer()->Clone();
if ( NULL == node )
{
THROW( "Node could not be cloned" );
}
std::auto_ptr< Node > temp( NodeFactory( node, false, false ) );
// Take ownership of the memory from TiXml
temp->m_impRC->InitRef();
return temp;
}
//*****************************************************************************
Comment::Comment()
: NodeImp< TiXmlComment >( new TiXmlComment() )
{
m_impRC->InitRef();
}
Comment::Comment( TiXmlComment* comment )
: NodeImp< TiXmlComment >( comment )
{
}
Comment::Comment( const std::string& comment )
: NodeImp< TiXmlComment >( new TiXmlComment() )
{
m_impRC->InitRef();
m_tiXmlPointer->SetValue( comment );
}
//*****************************************************************************
Text::Text()
: NodeImp< TiXmlText >( new TiXmlText("") )
{
m_impRC->InitRef();
}
Text::Text( const std::string& value )
: NodeImp< TiXmlText >( new TiXmlText( value ) )
{
m_impRC->InitRef();
}
Text::Text( TiXmlText* text )
: NodeImp< TiXmlText >( text )
{
}
//*****************************************************************************
Document::Document()
: NodeImp< TiXmlDocument >( new TiXmlDocument() )
{
m_impRC->InitRef();
}
Document::Document( TiXmlDocument* document )
: NodeImp< TiXmlDocument >( document )
{
}
Document::Document( const char* documentName )
: NodeImp< TiXmlDocument >( new TiXmlDocument( documentName ) )
{
m_impRC->InitRef();
}
Document::Document( const std::string& documentName )
: NodeImp< TiXmlDocument >( new TiXmlDocument( documentName ) )
{
m_impRC->InitRef();
}
std::string Document::GetAsString()
{
return m_tiXmlPointer->GetAsString();
}
void Document::LoadFile( TiXmlEncoding encoding )
{
if ( !m_tiXmlPointer->LoadFile( encoding ) )
{
THROW( "Couldn't load " << m_tiXmlPointer->Value() );
}
}
void Document::SaveFile( void ) const
{
if ( !m_tiXmlPointer->SaveFile() )
{
THROW( "Couldn't save " << m_tiXmlPointer->Value() );
}
}
void Document::LoadFile( const std::string& filename, TiXmlEncoding encoding )
{
if ( !m_tiXmlPointer->LoadFile( filename.c_str(), encoding ) )
{
THROW( "Couldn't load " << filename );
}
}
void Document::SaveFile( const std::string& filename ) const
{
if ( !m_tiXmlPointer->SaveFile( filename.c_str() ) )
{
THROW( "Couldn't save " << filename );
}
}
//*****************************************************************************
Element::Element()
: NodeImp< TiXmlElement >( new TiXmlElement( "DefaultValueCausedByCreatingAnElementWithNoParameters" ) )
{
m_impRC->InitRef();
}
Element::Element( const std::string& value )
: NodeImp< TiXmlElement >( new TiXmlElement( value ) )
{
m_impRC->InitRef();
}
Element::Element( TiXmlElement* element )
: NodeImp< TiXmlElement >( element )
{
}
Attribute* Element::FirstAttribute( bool throwIfNoAttributes )
{
ValidatePointer();
TiXmlAttribute* attribute = m_tiXmlPointer->FirstAttribute();
if ( ( NULL == attribute ) && throwIfNoAttributes )
{
THROW( "This Element (" << Value() << ") has no attributes" )
}
if ( NULL == attribute )
{
if( throwIfNoAttributes )
{
THROW( "Element (" << Value() << ") has no attributes" )
}
else
{
return NULL;
}
}
Attribute* temp = new Attribute( attribute );
m_spawnedWrappers.push_back( temp );
return temp;
}
Attribute* Element::LastAttribute( bool throwIfNoAttributes )
{
ValidatePointer();
TiXmlAttribute* attribute = m_tiXmlPointer->LastAttribute();
if ( ( NULL == attribute ) && throwIfNoAttributes )
{
THROW( "This Element (" << Value() << ") has no attributes" )
}
if ( NULL == attribute )
{
if( throwIfNoAttributes )
{
THROW( "Element (" << Value() << ") has no attributes" )
}
else
{
return NULL;
}
}
Attribute* temp = new Attribute( attribute );
m_spawnedWrappers.push_back( temp );
return temp;
}
bool Element::GetAttributeImp( const std::string& name, std::string* value )
{
ValidatePointer();
// Get value from TinyXML, if the attribute exists
const char* retVal = m_tiXmlPointer->Attribute( name.c_str() );
// TinyXML returns NULL if the attribute doesn't exist
if ( NULL == retVal )
{
return false;
}
else
{
*value = retVal;
return true;
}
}
bool Element::GetTextImp( std::string* value )
{
ValidatePointer();
// Get value from TinyXML, if the attribute exists
const char* retVal = m_tiXmlPointer->GetText();
// TinyXML returns NULL if the attribute doesn't exist
if ( NULL == retVal )
{
return false;
}
else
{
*value = retVal;
return true;
}
}
//*****************************************************************************
Declaration::Declaration()
: NodeImp< TiXmlDeclaration >( new TiXmlDeclaration() )
{
m_impRC->InitRef();
}
Declaration::Declaration( TiXmlDeclaration* declaration )
: NodeImp< TiXmlDeclaration >( declaration )
{
}
Declaration::Declaration( const std::string& version, const std::string& encoding, const std::string& standalone )
: NodeImp< TiXmlDeclaration >( new TiXmlDeclaration( version, encoding, standalone ) )
{
m_impRC->InitRef();
}
std::string Declaration::Version( void )
{
return m_tiXmlPointer->Version();
}
std::string Declaration::Encoding( void )
{
return m_tiXmlPointer->Encoding();
}
std::string Declaration::Standalone( void )
{
return m_tiXmlPointer->Standalone();
}
//*****************************************************************************
Exception::Exception(const std::string &details)
: m_details( details )
{
}
//*****************************************************************************
TiCppRC::TiCppRC()
{
// Spawn reference counter for this object
m_tiRC = new TiCppRCImp( this );
}
TiCppRC::~TiCppRC()
{
// Set pointer held by reference counter to NULL
this->m_tiRC->Nullify();
// Decrement reference - so reference counter will delete itself if necessary
this->m_tiRC->DecRef();
}
//*****************************************************************************
TiCppRCImp::TiCppRCImp( TiCppRC* tiCppRC )
: m_count( 1 ), m_tiCppRC ( tiCppRC )
{
}
void TiCppRCImp::IncRef()
{
m_count++;
}
void TiCppRCImp::DecRef()
{
m_count--;
if ( 0 == m_count )
{
delete m_tiCppRC;
delete this;
}
}
void TiCppRCImp::InitRef()
{
m_count = 1;
}
void TiCppRCImp::Nullify()
{
m_tiCppRC = NULL;
}
TiCppRC* TiCppRCImp::Get()
{
return m_tiCppRC;
}
bool TiCppRCImp::IsNull()
{
return NULL == m_tiCppRC;
}
#endif // TIXML_USE_TICPP
| 21.816717 | 121 | 0.627723 | blazeroni |
756cd09cc0f9cd3a7c6976d9afe11ce8c618ec29 | 2,448 | cpp | C++ | src/CMacierzKw.cpp | MarutTomasz/ZadanieSzablonDlaRownan | 17e311c18d6cc999896d1d0612ee21c79cae3ec5 | [
"MIT"
] | null | null | null | src/CMacierzKw.cpp | MarutTomasz/ZadanieSzablonDlaRownan | 17e311c18d6cc999896d1d0612ee21c79cae3ec5 | [
"MIT"
] | null | null | null | src/CMacierzKw.cpp | MarutTomasz/ZadanieSzablonDlaRownan | 17e311c18d6cc999896d1d0612ee21c79cae3ec5 | [
"MIT"
] | null | null | null | #include "SMacierzKw.cpp"
// NA STALE RZECZYWISTE
template class MacierzKw<Wektor,double,5>;
template std::istream & operator >> (std::istream &strm, MacierzKw<Wektor,double,5> &M);
template std::ostream & operator << (std::ostream &strm, const MacierzKw<Wektor,double,5> &M);
template MacierzKw<Wektor,double,5> operator * (double liczba, const MacierzKw<Wektor,double,5> &M);
// TYMCZASOWO
template class MacierzKw<Wektor,double,4>;
template class MacierzKw<Wektor,double,3>;
template class MacierzKw<Wektor,double,2>;
template class MacierzKw<Wektor,double,1>;
template MacierzKw<Wektor,double,4> pomniejsz_macierz(const MacierzKw<Wektor,double,5> &M, unsigned int index1, unsigned int index2);
template MacierzKw<Wektor,double,3> pomniejsz_macierz(const MacierzKw<Wektor,double,4> &M, unsigned int index1, unsigned int index2);
template MacierzKw<Wektor,double,2> pomniejsz_macierz(const MacierzKw<Wektor,double,3> &M, unsigned int index1, unsigned int index2);
template MacierzKw<Wektor,double,1> pomniejsz_macierz(const MacierzKw<Wektor,double,2> &M, unsigned int index1, unsigned int index2);
// NA STALE ZESPOLONE
template class MacierzKw<Wektor,LZespolona,5>;
template std::istream & operator >> (std::istream &strm, MacierzKw<Wektor,LZespolona,5> &M);
template std::ostream & operator << (std::ostream &strm, const MacierzKw<Wektor,LZespolona,5> &M);
template MacierzKw<Wektor,LZespolona,5> operator * (LZespolona liczba, const MacierzKw<Wektor,LZespolona,5> &M);
// TYMCZASOWO
template class MacierzKw<Wektor,LZespolona,4>;
template class MacierzKw<Wektor,LZespolona,3>;
template class MacierzKw<Wektor,LZespolona,2>;
template class MacierzKw<Wektor,LZespolona,1>;
template MacierzKw<Wektor,LZespolona,1> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,2> &M, unsigned int index1, unsigned int index2);
template MacierzKw<Wektor,LZespolona,2> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,3> &M, unsigned int index1, unsigned int index2);
template MacierzKw<Wektor,LZespolona,3> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,4> &M, unsigned int index1, unsigned int index2);
template MacierzKw<Wektor,LZespolona,4> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,5> &M, unsigned int index1, unsigned int index2);
template std::istream & operator >> (std::istream &strm, MacierzKw<Wektor,LZespolona,2> &M);
template std::ostream & operator << (std::ostream &strm, const MacierzKw<Wektor,LZespolona,2> &M);
| 56.930233 | 141 | 0.786356 | MarutTomasz |
756e2ee22783eb8f303db5cce4e715651441929c | 2,251 | hpp | C++ | Sockets/include/Sockets/TcpClientSocket.hpp | sanjeev-kumar-m/BrokerDataServer | 2db8a1bd4bd04a9dadcb4c1762f11a8e1e52d46e | [
"MIT"
] | null | null | null | Sockets/include/Sockets/TcpClientSocket.hpp | sanjeev-kumar-m/BrokerDataServer | 2db8a1bd4bd04a9dadcb4c1762f11a8e1e52d46e | [
"MIT"
] | null | null | null | Sockets/include/Sockets/TcpClientSocket.hpp | sanjeev-kumar-m/BrokerDataServer | 2db8a1bd4bd04a9dadcb4c1762f11a8e1e52d46e | [
"MIT"
] | null | null | null | #pragma once
/**
* @file TcpClientSocket.hpp
*
* This file declare Sockets::TcpClientSocket class
*/
#define SNJ_MAKE_NONCOPYABLE(c)\
private: \
c(const c&) noexcept = delete;\
c& operator=(const c&) noexcept = delete
#define SNJ_MAKE_NONMOVABLE(c)\
private: \
c(c&&) noexcept = delete; \
c& operator=(c&&) noexcept = delete
#include <memory>
#include <sys/socket.h>
namespace Sockets {
class TcpClientSocket {
public:
//Life cycle functions
~TcpClientSocket() = default;
SNJ_MAKE_NONCOPYABLE(TcpClientSocket);
SNJ_MAKE_NONMOVABLE(TcpClientSocket);
public:
//This is the constructor
TcpClientSocket();
/**
* This function is used to bind the port number
* to the socket
*/
bool Open();
/**
* This function is used to connect the client
* socket to the server socket
*
* @param[in] t_address
* address of the server to connect
*
* @param[in] t_port
* port number of the process on the
* server to connect
*
* @return
* boolean value indicating whether connectin
* to the server was sucessfull or not
*/
bool Connect(uint32_t t_address, uint16_t t_port);
/**
* This function returns the socket descriptor
*
* @return
* socket descriptor integer value
*/
inline int SocketDescriptor() {
return _m_socket_descriptor;
}
/**
* This function is used to set the socket
* to be non-blocking
*/
void setNonBlocking();
/**
* This function reads the data from the socket
* and copy that to buffer.
*
* @param[in] t_buffer
* pointer to the buffer where the read
* data to be copied
*
* @param[in] t_read_size
* amount of bytes to be read from the socket
*
* @return retval
* actual number of bytes read from the buffer
*/
size_t ReadN(char *t_buffer, size_t t_read_size);
/**
* This function closes opened socket
*/
void Close();
private:
/**
* This holds socket descriptor, when the socket
* is opened
*/
int _m_socket_descriptor;
};
}
| 22.068627 | 54 | 0.594847 | sanjeev-kumar-m |
75719231b1fba36f05c18ad5341bd59d35278aa9 | 1,720 | cpp | C++ | apal_cxx/src/cahn_hilliard.cpp | davidkleiven/APAL | f3d549498d312b98f55aad5db7c4ad061785ecbf | [
"MIT"
] | null | null | null | apal_cxx/src/cahn_hilliard.cpp | davidkleiven/APAL | f3d549498d312b98f55aad5db7c4ad061785ecbf | [
"MIT"
] | 15 | 2019-05-23T07:18:19.000Z | 2019-12-17T08:01:10.000Z | apal_cxx/src/cahn_hilliard.cpp | davidkleiven/APAL | f3d549498d312b98f55aad5db7c4ad061785ecbf | [
"MIT"
] | null | null | null | #include "cahn_hilliard.hpp"
#include <cmath>
using namespace std;
CahnHilliard::CahnHilliard(const vector<double> &coefficients): coeff(coefficients){};
double CahnHilliard::evaluate(double x) const{
double res = 0.0;
unsigned int N = coeff.size();
for (unsigned int i=0;i<coeff.size();i++){
res += pow(x, N-i-1)*coeff[i];
}
if (has_bounds){
res += penalty*regularization(x);
}
return res;
}
double CahnHilliard::deriv(double x) const{
double res = 0.0;
unsigned int N = coeff.size();
for (unsigned int i=0;i<N-1;i++){
res += (N-i-1)*pow(x, N-i-2)*coeff[i];
}
if (has_bounds){
res += penalty*regularization_deriv(x);
}
return res;
}
void CahnHilliard::set_bounds(double lower, double upper){
has_bounds = true;
lower_bound = lower;
upper_bound = upper;
}
bool CahnHilliard::is_outside_range(double x) const{
return x >= upper_bound || x < lower_bound;
}
double CahnHilliard::regularization(double x) const{
if (!is_outside_range(x)){
return 0.0;
}
double range = upper_bound - lower_bound;
double scale = rng_scale*range;
if (x >= upper_bound){
return exp((x-upper_bound)/scale);
}
else if (x < lower_bound){
return exp((lower_bound-x)/scale);
}
return 0.0;
}
double CahnHilliard::regularization_deriv(double x) const{
if (!is_outside_range(x)){
return 0.0;
}
double range = upper_bound - lower_bound;
double scale = rng_scale*range;
if (x > upper_bound){
return exp((x-upper_bound)/scale)/scale;
}
else if(x < lower_bound){
return -exp((lower_bound-x)/scale)/scale;
}
return 0.0;
} | 22.933333 | 86 | 0.619186 | davidkleiven |
757694c82c162d4ec357dbe70e8f57109ac12453 | 19,209 | cpp | C++ | mainwindow.cpp | adricatena/EA3-ControlHorno- | fcb0c8a6edddc09f2b03c83e97331ceddac9987e | [
"MIT"
] | null | null | null | mainwindow.cpp | adricatena/EA3-ControlHorno- | fcb0c8a6edddc09f2b03c83e97331ceddac9987e | [
"MIT"
] | null | null | null | mainwindow.cpp | adricatena/EA3-ControlHorno- | fcb0c8a6edddc09f2b03c83e97331ceddac9987e | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qcustomplot.h"
//------------Variables generales----------
QByteArray pedido_com, datos_com;
QString SetPoint;
int n = 0, h = 0, l = 0, j = 0, r = 0, k = 0, w = 0, q = 0, f = 0;
float i = 0;
bool ok, Boton = false, SP_Send = false, SP_Seted = false, BUG_Seted = false, flag_conn = false, flag_test = false;
//----------------------------------------
//-----------Variables PID---------------
int control;
float Ts = 1, Kr, Ti, Td;
float a, b, c;
float TEMPERATURA_LIMITE;
float rT=0, yT=0, eT=0, iT=0, dT=0, uT=0, iT0 = 0, eT0 = 0, yant = 25, xant = 0, xdat = 0;
float max = 122, min = 1;
//---------------------------------------
//---------Variables PID 2---------------
float pT = 0, e_k = 0, e_k_1 = 0, e_k_2 = 0, uT_1 = 0;
//---------------------------------------
//--------Variables para graficar--------
QVector<double> xg(201), yg(201), zg(201), wg(201); // initialize with entries 0..1000
//---------------------------------------
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort(this);
Serial_Conf(); //función que se encarga de configurar la comunicación serie
connect(serial,SIGNAL(readyRead()),this,SLOT(Serial_Pedir())); //enlazamos la función de lectura de dato por serie a una señal de lectura
//ui->Set_Point->setVisible(false);
ui->SetPoint->setEnabled(false);
ui->Spin_Kr->setEnabled(false);
ui->Spin_Ti->setEnabled(false);
ui->Spin_Td->setEnabled(false);
ui->Temp_Prog->setValue(30);
ui->Bot_Debug->setIcon(QIcon(":/pics/bug1.png"));
ui->Bot_Debug->setEnabled(false);
ui->groupBox_6->setVisible(false);
ui->groupBox_7->setVisible(false);
ui->checkBox->setChecked(false);
ui->Bot_Envio->setEnabled(false);
ui->Edit_Envio->setEnabled(false);
ui->pushButton_3->setEnabled(false);
ui->pushButton_4->setEnabled(false);
ui->Conectar_Com->setIcon(QIcon(":/pics/red-usb-disconnected-256.png"));
flag_conn = false;
MainWindow::SetupGraph();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::Serial_Conf()
{
serial->setPortName("COM3"); //puerto com por el que nos comunicaremos con la placa adquisidora
serial->setBaudRate(QSerialPort::Baud1200); //configuramos los baudios para conexión serie
serial->setDataBits(QSerialPort::Data8); //cantidad de bits por dato
serial->setParity(QSerialPort::NoParity); //paridad
serial->setStopBits(QSerialPort::OneStop); //bit de stop
serial->setFlowControl(QSerialPort::NoFlowControl); //control de flujo
}
void MainWindow::Serial_Conect()
{
if((serial->open(QIODevice::ReadWrite))) //indicador de conexión serie establecida
{
//ui->Set_Point->setEnabled(true);
//ui->SetPoint->setEnabled(true);
//ui->Spin_Kr->setEnabled(true);
//ui->Spin_Ti->setEnabled(true);
//ui->Spin_Td->setEnabled(true);
ui->Temp_Prog->setValue(30);
ui->Bot_Debug->setEnabled(true);
ui->groupBox_6->setEnabled(true);
ui->groupBox_7->setEnabled(true);
ui->pushButton_3->setEnabled(false);
ui->pushButton_4->setEnabled(true);
ui->pushButton_4->setText("Iniciar");
ui->Conectar_Com->setIcon(QIcon(":/pics/usbcon.png"));
flag_conn = true;
Iniciar_Horno();
}
else
Serial_Error();
}
void MainWindow::Iniciar_Horno(void){
char m = 0xFD;
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
k = 1;
SP_Seted = false;
}
void MainWindow::Serial_Desconect()
{
//ui->Set_Point->setEnabled(false);
ui->SetPoint->setEnabled(false);
ui->Spin_Kr->setEnabled(false);
ui->Spin_Ti->setEnabled(false);
ui->Spin_Td->setEnabled(false);
ui->Bot_Debug->setEnabled(false);
ui->groupBox_6->setEnabled(false);
ui->groupBox_7->setEnabled(false);
ui->Conectar_Com->setIcon(QIcon(":/pics/red-usb-disconnected-256.png"));
flag_conn = false;
k = 0;
serial->close();
}
void MainWindow::Serial_Error(){ //mensaje en caso de error de conexión
QMessageBox error;
error.setText("Verifique la conexión de la placa.");
error.setIcon(QMessageBox::Warning);
error.exec();
}
void MainWindow::Serial_Pedir() //función encargada de pedir datos a la placa
{
if(SP_Seted){
k++;
ui->label_25->setText(QString::number(k));
serial->waitForReadyRead(10);
if(serial->bytesAvailable() > 0) //en caso de bytes disponibles para lectura, lee
datos_com = serial->readAll();
QString Temp;
Temp.clear();
Temp.append(datos_com.toHex());
int x = 0;
x = Temp.toInt(&ok,16); // Valor decimal de la temperatura leida
if((x > 100)&&(x != 0x7E))
x = xant;
xant = x;
ui->Dato_PIC->setText(datos_com); // Label agregado para testear dato recibido a 1200 Baud
ui->label_10->setText(datos_com.toHex());
ui->label_12->setText(QString::number(Temp.toInt(&ok,16)));
if(x == 0x7E){ // Me pide PID o Setpoint
f++;
ui->Pedido_SP->setText(QString::number(f));
Enviar_SP();
}
else{
int y = 0;
ui->Temp_Hex->setText(QString::number(x));
if (x < 30)
y = 30;
else if (x > 80)
y = 80;
else
y = x;
ui->Temp_Prog->setValue(y);
yT = (float)x;
CalcularPID();
//-----------------------------------------
// QThread::msleep(300);
datos_com.clear();
//------Respuesta al pedido por USART------
if((SP_Seted) && (x != 127)&&(!SP_Send)) // ((!flag_test) && (SP_Seted))
Enviar();
Graficar();
}
if(i < 200)
i ++;
else
{ i = 0;
ui->plot->graph(0)->removeDataBefore(250);
ui->plot->graph(1)->removeDataBefore(250);
}
}
}
void MainWindow::Enviar()
{
if(!BUG_Seted){
char m;
if(k == 1){ // Revisar condición
m = TEMPERATURA_LIMITE;
k = 1;
}
// else if(SP_Send == true){
// //m = TEMPERATURA_LIMITE;
// m=0xFD;
// SP_Send = false;
//}
else{
m = control;
}
pedido_com.clear();
pedido_com.append(m); //acá va m en vez de xant // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
}
}
void MainWindow::Enviar_SP(){
char m = TEMPERATURA_LIMITE;
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
}
void MainWindow::CalcularPID()
{
a = Kr; b = (Kr * Ts) / Ti; c = (Kr * Td) / Ts;
rT = TEMPERATURA_LIMITE;
e_k = rT - yT;
pT = a * (e_k - e_k_1);
iT = b * e_k;
dT = c * (e_k_2 * e_k_1 + e_k_2);
uT = uT_1 + pT + iT + dT;
if (uT > max)
uT = max;
else{
if(uT < min)
uT = min;
}
control = (int)uT; // Dato calculado para enviar
ui->Label_yT->setText(QString::number(yT));
ui->Label_Kr->setText(QString::number(a));
ui->Label_Ti->setText(QString::number(b));
ui->Label_Td->setText(QString::number(c));
ui->Label_ek->setText(QString::number(e_k));
ui->Label_ek1->setText(QString::number(e_k_1));
ui->Label_ek2->setText(QString::number(e_k_2));
ui->Label_uT->setText(QString::number(uT));
ui->Label_uT1->setText(QString::number(uT_1));
ui->Label_rt->setText(QString::number(rT));
iT0 = iT;
eT0 = eT;
uT_1 = uT; e_k_2 = e_k_1; e_k_1 = e_k;
ui->DATO->setText(QString::number(control));
}
void MainWindow::Graficar()
{
//------------Gráfica Funcional-------------
// if((yT - yant) > 10) //probando horno de los vagos
// yT = yant;
ui->plot->graph(0)->addData(i, yT); //setData(xg, yg);
ui->plot->graph(1)->addData(i, TEMPERATURA_LIMITE); //setData(xg, zg);
ui->plot->graph(1)->setPen(QPen(Qt::red));
ui->plot->replot();
}
void MainWindow::SetupGraph()
{
ui->plot->addGraph();
ui->plot->graph(0)->setName("Estado del Sistema");
ui->plot->graph(0)->setPen(QPen(Qt::blue));
ui->plot->addGraph();
ui->plot->graph(1)->setName("Set Point");
ui->plot->graph(1)->setPen(QPen(Qt::red));
//ui->plot->addGraph();
//ui->plot->graph(2)->setName("Señal de Control");
//ui->plot->graph(2)->setPen(QPen(Qt::black));
ui->plot->axisRect()->setupFullAxesBox();
ui->plot->legend->setVisible(true);
ui->plot->xAxis->setLabel("Samples");
ui->plot->yAxis->setLabel("T ºC");
ui->plot->xAxis->setRange(0, 249);
ui->plot->yAxis->setRange(-10, 150);
}
void MainWindow::on_Conectar_Com_clicked()
{
if(!flag_conn){
Serial_Conect();
Boton = true;
//ui->Set_Point->setEnabled(false);
}
else{
Serial_Desconect();
//ui->Set_Point->setEnabled(true);
}
}
void MainWindow::on_Desconectar_Com_clicked()
{
Serial_Desconect();
}
void MainWindow::on_Set_Point_clicked()
{
flag_test = true;
TEMPERATURA_LIMITE = (int)ui->SetPoint->value(); // Ajuste del valor de ºC a mV
i = 0;
ui->plot->graph(0)->removeDataBefore(250);
ui->plot->graph(1)->removeDataBefore(250);
iT0 = 0;
eT0 = 0;
Kr = ui->Spin_Kr->value();
Ti = ui->Spin_Ti->value();
Td = ui->Spin_Td->value();
uT_1 = 0; e_k_2 = 0; e_k_1 = 0; e_k = 0; uT = 0;
if(!SP_Seted){
Enviar_SP();
SP_Seted = true;
}
}
void MainWindow::Reinicio(){
if(SP_Send == false){
char m = 0xFD;
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
SP_Send = true;
}
else{
char m = TEMPERATURA_LIMITE;
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
SP_Send = false;
}
}
void MainWindow::on_Bot_Envio_clicked()
{
flag_test = false;
char m = ui->Edit_Envio->text().toInt(&ok,16);//QString::number(ui->Edit_Envio->text().toInt(&ok));
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
ui->Dato_PC->clear();
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(pedido_com.toHex());
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
}
void MainWindow::on_checkBox_clicked()
{
if(ui->checkBox->isChecked()){
ui->Bot_Envio->setEnabled(true);
ui->Edit_Envio->setEnabled(true);
BUG_Seted = true;
}
else{
ui->Bot_Envio->setEnabled(false);
ui->Edit_Envio->setEnabled(false);
BUG_Seted = false;
Enviar();
}
}
void MainWindow::on_Bot_Debug_clicked()
{
if(ui->groupBox_6->isVisible()){
ui->groupBox_6->setVisible(false);
ui->groupBox_6->setEnabled(true);
ui->groupBox_7->setVisible(false);
ui->groupBox_7->setEnabled(true);
ui->layoutWidget->setSizeIncrement(747,688);
ui->Bot_Debug->setIcon(QIcon(":/pics/bug1.png"));
}
else{
ui->groupBox_6->setVisible(true);
ui->groupBox_7->setVisible(true);
ui->Bot_Debug->setIcon(QIcon(":/pics/bug2.png"));
}
}
void MainWindow::on_pushButton_clicked()
{
char m;
flag_test = true;
m = 252;
ui->check_calib->setText("Ajuste PC");
// ui->pushButton_2->setText("Siguiente");
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
}
void MainWindow::on_pushButton_2_clicked()
{
char m;
flag_test = true;
m = 254;
ui->check_calib->setText("Ajuste Horno");
// ui->pushButton_2->setText("Siguiente");
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
}
void MainWindow::on_pushButton_3_clicked()
{
if((serial->open(QIODevice::ReadWrite))) //indicador de conexión serie establecida
{
//ui->Set_Point->setEnabled(false);
ui->SetPoint->setEnabled(false);
ui->Spin_Kr->setEnabled(false);
ui->Spin_Ti->setEnabled(false);
ui->Spin_Td->setEnabled(false);
ui->pushButton_4->setEnabled(true);
ui->pushButton_4->setText("Detener");
ui->pushButton_3->setEnabled(false);
//ui->Bot_Debug->setEnabled(false);
//ui->groupBox_6->setEnabled(false);
//ui->groupBox_7->setEnabled(false);
//ui->Conectar_Com->setIcon(QIcon(":/pics/orange-usb-connected-256.png"));
flag_conn = true;
char m = 0xFD;
pedido_com.clear();
pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete
QString Out;
Out.clear();
Out.append(pedido_com.toHex());
ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC
ui->label_6->setText(Out);
ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16)));
serial->write(pedido_com); //escribimos en el buffer
serial->waitForBytesWritten(30);
flag_test = true;
TEMPERATURA_LIMITE = (int)ui->SetPoint->value(); // Ajuste del valor de ºC a mV
i = 0;
ui->plot->graph(0)->removeDataBefore(250);
ui->plot->graph(1)->removeDataBefore(250);
iT0 = 0;
eT0 = 0;
Kr = ui->Spin_Kr->value();
Ti = ui->Spin_Ti->value();
Td = ui->Spin_Td->value();
uT_1 = 0; e_k_2 = 0; e_k_1 = 0; e_k = 0; uT = 0;
if(!SP_Seted){
Enviar_SP();
SP_Seted = true;
}
//ui->Set_Point->setEnabled(false);
}
}
void MainWindow::on_pushButton_4_clicked()
{
if((flag_conn)&&(Boton == true)){
//ui->Set_Point->setEnabled(true);
ui->SetPoint->setEnabled(true);
ui->Spin_Kr->setEnabled(true);
ui->Spin_Ti->setEnabled(true);
ui->Spin_Td->setEnabled(true);
ui->Temp_Prog->setValue(30);
ui->Bot_Debug->setEnabled(true);
ui->groupBox_6->setEnabled(true);
ui->pushButton_3->setEnabled(true);
ui->pushButton_4->setEnabled(false);
//ui->groupBox_7->setEnabled(true);
//ui->Conectar_Com->setIcon(QIcon(":/pics/red-usb-disconnected-256.png"));
flag_conn = false;
k = 0;
SP_Seted = false;
//ui->Set_Point->setEnabled(true);
serial->close();
}}
| 36.728489 | 165 | 0.544641 | adricatena |
757c539a328d5eea7fef40c39262bb64741accd5 | 1,257 | cpp | C++ | C++/1679.MaxNumberOfK-SumPairs.cpp | SSKale1/LeetCode-Solutions | dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b | [
"MIT"
] | null | null | null | C++/1679.MaxNumberOfK-SumPairs.cpp | SSKale1/LeetCode-Solutions | dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b | [
"MIT"
] | null | null | null | C++/1679.MaxNumberOfK-SumPairs.cpp | SSKale1/LeetCode-Solutions | dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b | [
"MIT"
] | null | null | null | /*class Solution {
public:
int maxOperations(vector<int>& nums, int k) {
int ops = 0;
sort(begin(nums), end(nums));
int start = 0;
int end = nums.size()-1;
while(start<end)
{
int temp = nums[start]+nums[end];
if(temp==k)
{
ops++;
start++;
end--;
}
else if(temp<k)
start++;
else
end--;
}
return ops;
}
};
/*
TC: O(nlongn)
SC: O(1)
*/
class Solution {
public:
int maxOperations(vector<int>& nums, int k) {
int ops = 0;
int temp;
unordered_map<int, int> m;
for(int i=0; i<nums.size(); i++)
{
//fixing 1 value as nums[i] and looking for k-nums[i] in the map
temp = k-nums[i];
//if the value exists, incrementing the operations count and decrementing the value from map
if(m[temp]>0)
{
ops++;
m[temp]--;
}
//if not, adding nums[i] value to the map
else
m[nums[i]]++;
}
return ops;
}
};
/*
TC: O(n)
SC: O(n)
*/
| 20.274194 | 104 | 0.405728 | SSKale1 |
757d59b96b2afcc57f24535990100505d52adc8e | 6,238 | cpp | C++ | Test/Automation/ResourceTest/Helper_dll/Helper_dll.cpp | SecurityInnovation/Holodeck | 54b97675a73b668f8eec8d9c8a8c7733e1a53db3 | [
"MIT"
] | 35 | 2015-05-16T06:36:47.000Z | 2021-08-31T15:32:09.000Z | Test/Automation/ResourceTest/Helper_dll/Helper_dll.cpp | crypticterminal/Holodeck | 54b97675a73b668f8eec8d9c8a8c7733e1a53db3 | [
"MIT"
] | 3 | 2015-06-18T06:16:51.000Z | 2017-11-16T23:23:59.000Z | Test/Automation/ResourceTest/Helper_dll/Helper_dll.cpp | crypticterminal/Holodeck | 54b97675a73b668f8eec8d9c8a8c7733e1a53db3 | [
"MIT"
] | 10 | 2015-04-07T14:45:48.000Z | 2021-11-14T15:14:45.000Z | // Helper_dll.cpp : Defines the entry point for the DLL application.
//
#include "Helper_dll.h"
#include <commctrl.h>
#include <string>
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
HELPER_DLL_API int GetListViewItemNumber (HWND listViewHWnd)
{
return ListView_GetItemCount (listViewHWnd);
} // GetListViewItemNumber
HELPER_DLL_API char** EnumListViewItemTexts (DWORD processID,
HWND listViewHWnd)
{
const int textSize = 100;
int i = 0;
int count = ListView_GetItemCount (listViewHWnd);
HANDLE hProcess = OpenProcess (STANDARD_RIGHTS_REQUIRED | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID);
char *pTextProcess = (char *) VirtualAllocEx (hProcess, NULL, textSize, MEM_COMMIT, PAGE_READWRITE);
LV_ITEM *pListViewItemProcess = (LV_ITEM *) VirtualAllocEx (hProcess, NULL, sizeof (LV_ITEM), MEM_COMMIT, PAGE_READWRITE);
char** itemTexts = new char*[count];
for (i=0; i<count; i++) {
BOOL result = FALSE;
char pszText[textSize];
// std::string message;
ZeroMemory (pszText, textSize * sizeof (char));
unsigned long bytesRead = 0;
unsigned long bytesWritten = 0;
LV_ITEM listViewItem;
ZeroMemory (&listViewItem, sizeof (listViewItem));
listViewItem.mask = LVIF_TEXT;
listViewItem.iItem = i;
listViewItem.iSubItem = 0;
listViewItem.cchTextMax = textSize;
listViewItem.pszText = pTextProcess;
result = WriteProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesWritten);
if (!result) {
char *msg = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL);
MessageBox (NULL, msg, "WriteProcessMemory Error", MB_OK);
LocalFree (msg);
msg = NULL;
break;
}
result = ListView_GetItem (listViewHWnd, pListViewItemProcess);
if (!result) {
MessageBox (NULL, "ListView_GetItem failed", "ListView_GetItem Error", MB_OK);
break;
}
result = ReadProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesRead);
if (!result) {
char *msg = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL);
MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK);
LocalFree (msg);
msg = NULL;
break;
}
result = ReadProcessMemory (hProcess, listViewItem.pszText, pszText, textSize, &bytesRead);
if (!result) {
char *msg = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL);
MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK);
LocalFree (msg);
msg = NULL;
break;
}
/*
message = i;
message += "/";
message += count;
message += ": ";
message += pszText;
MessageBox (NULL, message, "itemtext", MB_OK);
*/
// MessageBox (NULL, pszText, "itemtext", MB_OK);
itemTexts[i] = new char[bytesRead+1];
strncpy (itemTexts[i], pszText, bytesRead);
itemTexts[i][bytesRead] = '\0';
} // for (0 <= i < count)
return itemTexts;
} // EnumListViewItemTexts
HELPER_DLL_API char* GetListViewItemText (DWORD processID,
HWND listViewHWnd,
int itemNum)
{
const int textSize = 100;
HANDLE hProcess = OpenProcess (STANDARD_RIGHTS_REQUIRED | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID);
char *pTextProcess = (char *) VirtualAllocEx (hProcess, NULL, textSize, MEM_COMMIT, PAGE_READWRITE);
LV_ITEM *pListViewItemProcess = (LV_ITEM *) VirtualAllocEx (hProcess, NULL, sizeof (LV_ITEM), MEM_COMMIT, PAGE_READWRITE);
BOOL result = FALSE;
char pszText[textSize];
ZeroMemory (pszText, textSize * sizeof (char));
unsigned long bytesRead = 0;
unsigned long bytesWritten = 0;
LV_ITEM listViewItem;
ZeroMemory (&listViewItem, sizeof (listViewItem));
listViewItem.mask = LVIF_TEXT;
listViewItem.iItem = itemNum;
listViewItem.iSubItem = 0;
listViewItem.cchTextMax = textSize;
listViewItem.pszText = pTextProcess;
result = WriteProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesWritten);
if (!result) {
char *msg = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL);
MessageBox (NULL, msg, "WriteProcessMemory Error", MB_OK);
LocalFree (msg);
msg = NULL;
return NULL;
}
result = ListView_GetItem (listViewHWnd, pListViewItemProcess);
if (!result) {
MessageBox (NULL, "ListView_GetItem failed", "ListView_GetItem Error", MB_OK);
return NULL;
}
result = ReadProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesRead);
if (!result) {
char *msg = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL);
MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK);
LocalFree (msg);
msg = NULL;
return NULL;
}
result = ReadProcessMemory (hProcess, listViewItem.pszText, pszText, textSize, &bytesRead);
if (!result) {
char *msg = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL);
MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK);
LocalFree (msg);
msg = NULL;
return NULL;
}
char *itemText = new char[bytesRead+1];
ZeroMemory (itemText, (bytesRead + 1) * sizeof (char));
strncpy (itemText, pszText, bytesRead);
return itemText;
} // GetListViewItemText
| 33.718919 | 201 | 0.730683 | SecurityInnovation |
757d70ec3f31ffdac6aeb7da598032de7bdd2dd0 | 3,344 | cpp | C++ | src/concepts.cpp | WillCoates/QuickCalc | 49a4946c5c9b3781d1d5820815bda8395a8ed0dd | [
"MIT"
] | null | null | null | src/concepts.cpp | WillCoates/QuickCalc | 49a4946c5c9b3781d1d5820815bda8395a8ed0dd | [
"MIT"
] | null | null | null | src/concepts.cpp | WillCoates/QuickCalc | 49a4946c5c9b3781d1d5820815bda8395a8ed0dd | [
"MIT"
] | null | null | null | #include "concepts.hpp"
#include <unordered_map>
#include <cmath>
using namespace quickcalc;
namespace {
constexpr double QC_FALSE = 0.0;
constexpr double QC_TRUE = 1.0;
constexpr double QC_EPSILON = 1e-15;
// C++17 doesn't define a pi constant, so we'll use our own
constexpr double QC_PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164063;
double qcIf(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
if (params.size() < 2) {
return NAN;
}
double param0 = exec.evaluate(params[0].get());
// false
if (abs(param0) < QC_EPSILON) {
if (params.size() >= 3) {
return exec.evaluate(params[2].get());
} else {
return param0;
}
} else {
return exec.evaluate(params[1].get());
}
}
double qcEq(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
if (params.size() < 2) {
return NAN;
}
return abs(exec.evaluate(params[0].get()) - exec.evaluate(params[1].get())) < QC_EPSILON;
}
double qcNe(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
if (params.size() < 2) {
return NAN;
}
return abs(exec.evaluate(params[0].get()) - exec.evaluate(params[1].get())) >= QC_EPSILON;
}
double qcGt(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
if (params.size() < 2) {
return NAN;
}
return exec.evaluate(params[0].get()) > exec.evaluate(params[1].get());
}
double qcLt(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
if (params.size() < 2) {
return NAN;
}
return exec.evaluate(params[0].get()) < exec.evaluate(params[1].get());
}
double qcGe(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
if (params.size() < 2) {
return NAN;
}
return exec.evaluate(params[0].get()) >= exec.evaluate(params[1].get());
}
double qcLe(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
if (params.size() < 2) {
return NAN;
}
return exec.evaluate(params[0].get()) <= exec.evaluate(params[1].get());
}
double qcTrue(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
return QC_TRUE;
}
double qcFalse(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
return QC_FALSE;
}
double qcEpsilon(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
return QC_EPSILON;
}
double qcPi(Executor &exec, const std::vector<ExprNode::ptr> ¶ms) {
return QC_PI;
}
std::unordered_map<std::string, ExecutorState::Func> functions = {
{ "if", &qcIf },
{ "eq", &qcEq },
{ "ne", &qcNe },
{ "gt", &qcGt },
{ "lt", &qcLt },
{ "ge", &qcGe },
{ "le", &qcLe },
{ "TRUE", &qcTrue },
{ "true", &qcTrue },
{ "FALSE", &qcFalse },
{ "false", &qcFalse },
{ "EPSILON", &qcEpsilon },
{ "PI", &qcPi },
};
}
void quickcalc::loadConcepts(ExecutorState &state) {
for (auto &func : functions) {
state.setFunction(func.first, func.second);
}
}
| 29.857143 | 105 | 0.546651 | WillCoates |
758a31c0af23360e53d7a26e9beb6315892c4cb9 | 548 | cpp | C++ | Interview Preparation Kit - CPP/01. Warm-up Challenges/002. Counting Valleys.cpp | atul070/interview | 505444570bba6e9d5672272eea5f3784834d2d9e | [
"Apache-2.0"
] | 1 | 2020-10-18T22:06:12.000Z | 2020-10-18T22:06:12.000Z | Interview Preparation Kit - CPP/01. Warm-up Challenges/002. Counting Valleys.cpp | atul070/interview | 505444570bba6e9d5672272eea5f3784834d2d9e | [
"Apache-2.0"
] | null | null | null | Interview Preparation Kit - CPP/01. Warm-up Challenges/002. Counting Valleys.cpp | atul070/interview | 505444570bba6e9d5672272eea5f3784834d2d9e | [
"Apache-2.0"
] | null | null | null | // Problem: https://www.hackerrank.com/challenges/counting-valleys/problem
// Score: 15
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string str;
cin >> str;
int ans = 0;
int current_level = 0;
for (char c: str){
if (c == 'D') {
if (current_level == 0){
ans++;
}
current_level--;
}
else if (c == 'U') current_level++;
}
cout << ans;
return 0;
}
| 15.657143 | 75 | 0.452555 | atul070 |
758dabfa6a951d27c84c1942f757adac38e03b30 | 6,531 | cpp | C++ | iOS/CustomAudioUnit.cpp | DaCao/Sonic | 0bc327b97560c83cb6cc22b2b2a1e399554194d8 | [
"MIT"
] | null | null | null | iOS/CustomAudioUnit.cpp | DaCao/Sonic | 0bc327b97560c83cb6cc22b2b2a1e399554194d8 | [
"MIT"
] | null | null | null | iOS/CustomAudioUnit.cpp | DaCao/Sonic | 0bc327b97560c83cb6cc22b2b2a1e399554194d8 | [
"MIT"
] | null | null | null | //
// CustomAudioUnit.cpp
// Demo
//
// Created by Philadelphia Game Lab on 6/11/14.
// Copyright (c) 2014 Philadelphia Game Lab. All rights reserved.
//
#include "CustomAudioUnit.h"
#define BUF_SIZE 512
#define BIT_DEPTH 16
#define SAMPLE_RATE 44100
static OSStatus recordingCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) {
//Please dont remove the following commented code
//The following code will be used if we use recording callback
//TODO: Use inRefCon to access our interface object to do stuff
//Then use inNumberFrames to figure out how much data is available and make that much space available in buffers in AudioBufferList
//AudioBufferList list;
//list.mNumberBuffers = 1;
//list.mBuffers[0].mData = sampleBuffer;
//list.mBuffers[0].mDataByteSize = 2* inNumberFrames;
//list.mBuffers[0].mNumberChannels = 1;
//AudioUnitRender([audioInterface audioUnitInstance], ioActionFlags, inTimeStamp, 1, inNumberFrames, &list);
return noErr;
}
static OSStatus playbackCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) {
//Please dont remove the following commented code
//The following code will be used for immediate debugging
//Notes: ioData contains buffers (may be more than one)
//Fill them up as much as you can. Remember to set the size value in each buffer to match how much data is in each buffer.
//ioData->mBuffers[i].mNumberChannels is no. of channels per buffer
//*ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
//for (UInt32 i=0; i<ioData->mNumberBuffers; ++i) {
// memset(ioData->mBuffers[i].mData, 10000, ioData->mBuffers[i].mDataByteSize);
// std::cout<<"\naksjdhka " << ioData->mBuffers[i].mDataByteSize <<" i=" << i <<" "<<inBusNumber;
//
//}
//clock_t t1, t2;
//t1 = clock();
mixer3D->performMix((short *)ioData->mBuffers[0].mData, (short *) ioData->mBuffers[1].mData);
//t2 = clock();
//cout<<"The time consumption is "<<((double)(t2-t1))/CLOCKS_PER_SEC<<endl;
return noErr;
}
void CustomAudioUnit::init () {
mixer3D = new Mixer3D(BUF_SIZE, SAMPLE_RATE, BIT_DEPTH, myWorld);
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_RemoteIO;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
AudioComponent component = AudioComponentFindNext(NULL, &desc);
AudioComponentInstanceNew(component, &audioUnitInstance);
UInt32 enableIO;
AudioUnitElement inputBus = 1;
AudioUnitElement outputBus = 0;
//Disabling IO for recording
enableIO = 0;
AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, inputBus, &enableIO, sizeof(enableIO));
//Enabling IO for playback
enableIO = 1;
AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, outputBus, &enableIO, sizeof(enableIO));
UInt32 bytesPerSample = sizeof(short) ; //sizeof(AudioUnitSampleType);
AudioStreamBasicDescription stereoStreamFormat = {0};
stereoStreamFormat.mBitsPerChannel = 8 * bytesPerSample;
stereoStreamFormat.mBytesPerFrame = bytesPerSample;
stereoStreamFormat.mBytesPerPacket = bytesPerSample;
stereoStreamFormat.mChannelsPerFrame = 2; // 2 incdicates stereo
stereoStreamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger |
kAudioFormatFlagsNativeEndian |
kAudioFormatFlagIsPacked |
kAudioFormatFlagIsNonInterleaved;
stereoStreamFormat.mFormatID = kAudioFormatLinearPCM;
stereoStreamFormat.mFramesPerPacket = 1;
stereoStreamFormat.mReserved = 0;
stereoStreamFormat.mSampleRate = 44100.0;
AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, inputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription));
AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, outputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription));
//Setting input callback
AURenderCallbackStruct callbackStruct;
callbackStruct.inputProc = &recordingCallback; //////Should there be an ampersand
callbackStruct.inputProcRefCon = audioUnitInstance;
AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Output, inputBus, &callbackStruct, sizeof(callbackStruct)); /////Not sure of scope and bus/element
//Setting output callback
callbackStruct.inputProc = &playbackCallback;
callbackStruct.inputProcRefCon = audioUnitInstance;
AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, outputBus, &callbackStruct, sizeof(callbackStruct));
AudioUnitInitialize(audioUnitInstance);
}
CustomAudioUnit::CustomAudioUnit() {
myWorld = new World;
init();
std::cout<<"\nConstructor";
}
CustomAudioUnit::~CustomAudioUnit() {
AudioUnitUninitialize(audioUnitInstance);
AudioComponentInstanceDispose(audioUnitInstance);
std::cout<<"\nDestructor";
}
void CustomAudioUnit::play() {
//init();
myWorld->createWriteThread();
AudioOutputUnitStart(audioUnitInstance);
std::cout<<"\nPlay";
}
void CustomAudioUnit::stop() {
AudioOutputUnitStop(audioUnitInstance);
//AudioUnitUninitialize(audioUnitInstance);
//AudioComponentInstanceDispose(audioUnitInstance);
std::cout<<"\nStop";
}
AudioObj* CustomAudioUnit::addAudioObjectInWorld(string wavFile, VariableForLocation x, VariableForLocation y, VariableForLocation z)
{
if(myWorld != nullptr)
{
Location loc = Location(x, y, z);
Velocity vel = Velocity();
return myWorld->addAudioObj(loc,vel,wavFile);
}
else
{
throw("World has to be created before adding audio objects");
return nullptr;
}
}
void CustomAudioUnit::setPlayerPosition(VariableForLocation x, VariableForLocation y, VariableForLocation z)
{
myWorld->setPlayerPosition(x, y, z);
}
void CustomAudioUnit::setPlayerBearing(float bearing)
{
myWorld->setPlayerBearing(bearing);
}
| 37.32 | 203 | 0.740009 | DaCao |
759013fd7f21515fac3ea4e693f277b4004598b3 | 9,994 | cpp | C++ | common/quote.cpp | chwash/wwiv | 0d67acdede788f8a4fd2b442e92caeb411552359 | [
"Apache-2.0"
] | null | null | null | common/quote.cpp | chwash/wwiv | 0d67acdede788f8a4fd2b442e92caeb411552359 | [
"Apache-2.0"
] | null | null | null | common/quote.cpp | chwash/wwiv | 0d67acdede788f8a4fd2b442e92caeb411552359 | [
"Apache-2.0"
] | null | null | null | /**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)1998-2022, WWIV Software Services */
/* */
/* 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 "common/quote.h"
#include "common/common_events.h"
#include "common/input.h"
#include "common/output.h"
#include "core/datetime.h"
#include "core/eventbus.h"
#include "core/strings.h"
#include "core/textfile.h"
#include "fmt/printf.h"
#include "local_io/keycodes.h"
#include "sdk/filenames.h"
#include "sdk/msgapi/parsed_message.h"
#include <memory>
#include <string>
#include <vector>
using namespace wwiv::core;
using namespace wwiv::sdk;
using namespace wwiv::local::io;
using namespace wwiv::strings;
namespace wwiv::common {
static std::unique_ptr<std::vector<std::string>> quotes_ind;
static std::string FirstLettersOfVectorAsString(const std::vector<std::string>& parts) {
std::string result;
for (const auto& part : parts) {
result.push_back(part.front());
}
return result;
}
void set_quotes_ind(std::unique_ptr<std::vector<std::string>>&& u) { quotes_ind = std::move(u); }
std::string GetQuoteInitials(const std::string& orig_name) {
if (orig_name.empty()) {
return {};
}
auto name = orig_name;
if (starts_with(name, "``")) {
name = name.substr(2);
}
if (const auto paren_start = name.find('(');
paren_start != std::string::npos && !isdigit(name.at(paren_start + 1))) {
const auto inner = name.substr(paren_start + 1);
return GetQuoteInitials(inner);
}
const auto last = name.find_first_of("#<>()[]`");
const auto parts =
last != std::string::npos ? SplitString(name.substr(0, last), " ") : SplitString(name, " ");
return FirstLettersOfVectorAsString(parts);
}
void clear_quotes(wwiv::common::SessionContext& ctx) {
File::Remove(FilePath(ctx.dirs().temp_directory(), QUOTES_TXT), true);
quotes_ind.reset();
}
static std::string to_quote_date_format(time_t t, bool use_24h_format) {
const auto dt = DateTime::from_time_t(t);
std::ostringstream ss;
ss << dt.to_string("%A,%B %d, %Y") << " at ";
if (use_24h_format) {
ss << dt.to_string("%H:%M");
} else {
ss << dt.to_string("%I:%M %p");
}
return ss.str();
}
static std::string to_quote_date_line(quote_date_format_t type, bool use_24h_format, time_t tt,
const std::string& tb) {
const auto datetime = to_quote_date_format(tt, use_24h_format);
std::string date_line;
switch (type) {
case quote_date_format_t::generic:
date_line =
fmt::sprintf("%c3On %c1%s, %c2%s%c3 wrote:%c0", 0x03, 0x03, datetime, 0x03, tb, 0x03, 0x03);
break;
case quote_date_format_t::email:
date_line = fmt::sprintf("%c3In your e-mail of %c2%s%c3, you wrote:%c0", 0x03, 0x03, datetime,
0x03, 0x03);
break;
case quote_date_format_t::post:
date_line = fmt::sprintf("%c3In a message posted %c2%s%c3, you wrote:%c0", 0x03, 0x03, datetime,
0x03, 0x03);
break;
case quote_date_format_t::forward:
date_line = fmt::sprintf("%c3Message forwarded from %c2%s%c3, sent on %s.%c0", 0x03, 0x03, tb,
0x03, datetime, 0x03);
break;
case quote_date_format_t::no_quote:
default:
return {};
}
date_line.append("\r\n");
return date_line;
}
std::vector<std::string> create_quoted_text_from_message(std::string& raw_text,
const std::string& to_name,
quote_date_format_t type,
bool use_24h_format, time_t tt) {
const msgapi::WWIVParsedMessageText pmt(raw_text);
msgapi::parsed_message_lines_style_t style{};
style.line_length = 72;
style.ctrl_lines = msgapi::control_lines_t::no_control_lines;
style.add_wrapping_marker = false;
// experimental
style.reattribute_quotes = true;
auto lines = pmt.to_lines(style);
auto it = std::begin(lines);
const auto end = std::end(lines);
if (lines.size() < 2) {
return {};
}
const auto to_node = *it++;
++it;
const auto quote_initials = GetQuoteInitials(to_name);
std::vector<std::string> out;
if (type != quote_date_format_t::no_quote) {
out.emplace_back(
to_quote_date_line(type, use_24h_format, tt, properize(strip_to_node(to_node))));
}
for (; it != end; ++it) {
auto line = *it;
StringReplace(&line,
"\x03"
"0",
"\x03"
"5");
out.emplace_back(fmt::sprintf("%c%c%s%c%c> %c%c%s%c0", 0x03, '1', quote_initials, 0x03, '7',
0x03, '5', line, 0x03));
}
return out;
}
void auto_quote(std::string& raw_text, const std::string& to_name, quote_date_format_t type,
time_t tt, wwiv::common::Context& ctx) {
const auto fn = FilePath(ctx.session_context().dirs().temp_directory(), INPUT_MSG);
File::Remove(fn);
TextFile f(fn, "w");
if (!f) {
return;
}
const auto use_24h_format = ctx.u().twentyfour_clock();
auto lines = create_quoted_text_from_message(raw_text, to_name, type, use_24h_format, tt);
for (const auto& l : lines) {
f.WriteLine(l);
}
if (ctx.u().messages_posted() < 10) {
bout.printfile(QUOTE_NOEXT);
}
}
void grab_quotes(std::string& raw_text, const std::string& to_name, wwiv::common::Context& ctx) {
if (raw_text.back() == CZ) {
// Since CZ isn't special on Win32/Linux. Don't write it out
// to the quotes file.
raw_text.pop_back();
}
clear_quotes(ctx.session_context());
File f(FilePath(ctx.session_context().dirs().temp_directory(), QUOTES_TXT));
if (f.Open(File::modeDefault | File::modeCreateFile | File::modeTruncate, File::shareDenyNone)) {
f.Write(raw_text);
}
const auto use_24h_format = ctx.u().twentyfour_clock();
quotes_ind = std::make_unique<std::vector<std::string>>(create_quoted_text_from_message(
raw_text, to_name, quote_date_format_t::no_quote, use_24h_format, 0));
}
std::vector<std::string> query_quote_lines(wwiv::common::SessionContext& ctx) {
std::vector<std::string> lines;
if (!quotes_ind || quotes_ind->empty()) {
return {};
}
int start_line;
int end_line;
auto num_lines = 0;
do {
start_line = 0;
end_line = 0;
auto iter = std::begin(*quotes_ind);
auto end = std::end(*quotes_ind);
num_lines = 1;
auto abort = false;
for (; iter != end; ++iter) {
// Skip control line (^D)
auto& line = *iter;
if (!line.empty() && line.front() == 0x04) {
continue;
}
StringTrimCRLF(&line);
bout.bpla(fmt::format("{:>3} {}", num_lines++, line), &abort);
if (abort) {
break;
}
// Add line s to the list of lines.
lines.emplace_back(line);
}
--num_lines;
bout.nl();
// If the user has hungup, this will throw an exception.
bus().invoke<CheckForHangupEvent>();
if (lines.empty() || ctx.hangup()) {
return {};
}
bout.format("|#2Quote from line 1-{}? (?=relist, Q=quit) ", num_lines);
auto k = bin.input_number_hotkey(1, {'Q', '?'}, 1, num_lines);
if (k.key == 'Q') {
return {};
}
if (k.key == '?') {
bout.nl();
continue;
}
start_line = k.num;
if (start_line == num_lines) {
end_line = start_line;
} else {
bout.format("|#2through line {} - {} ? (Q=quit) ", start_line, num_lines);
k = bin.input_number_hotkey(start_line, {'Q', '?'}, start_line, num_lines);
if (k.key == 'Q') {
return {};
}
if (k.key == '?') {
bout.nl();
continue;
}
end_line = k.num;
}
if (start_line == end_line) {
bout << "|#5Quote line " << start_line << "? ";
} else {
bout << "|#5Quote lines " << start_line << "-" << end_line << "? ";
}
if (!bin.noyes()) {
return {};
}
break;
} while (!ctx.hangup());
return std::vector<std::string>(std::begin(lines) + start_line - 1, std::begin(lines) + end_line);
}
std::string strip_to_node(const std::string& txt) {
std::ostringstream os;
if (txt.find('@') != std::string::npos) {
bool ok = true;
for (auto i = txt.begin(); i != txt.end(); i++) {
if (ok) {
os << *i;
}
if ((i + 1) != txt.end() && (i + 2) != txt.end() && *(i + 2) == '#') {
ok = false;
}
}
return os.str();
} else if (txt.find("AT") != std::string::npos) {
bool ok = true;
for (std::string::const_iterator i = txt.begin() + 2; i != txt.end(); ++i) {
if (ok) {
os << *i;
}
if (*(i + 1) == '`') {
ok = false;
}
}
return os.str();
}
return txt;
}
} // namespace wwiv::common | 32.553746 | 100 | 0.555033 | chwash |
759518dc8b02f8bb90fc9519b95b32ce60120ca1 | 3,433 | cpp | C++ | pod/DekrispatorDroneBox/drifter.cpp | MrBlueXav/DaisyExamples | 41f5e3a646c24b2bab8bcbc9bbe5b36efd7f6400 | [
"MIT"
] | 1 | 2021-11-05T19:04:32.000Z | 2021-11-05T19:04:32.000Z | pod/DekrispatorDroneBox/drifter.cpp | MrBlueXav/DaisyExamples | 41f5e3a646c24b2bab8bcbc9bbe5b36efd7f6400 | [
"MIT"
] | null | null | null | pod/DekrispatorDroneBox/drifter.cpp | MrBlueXav/DaisyExamples | 41f5e3a646c24b2bab8bcbc9bbe5b36efd7f6400 | [
"MIT"
] | 1 | 2020-08-16T07:36:34.000Z | 2020-08-16T07:36:34.000Z | /**
******************************************************************************
* File Name : drifter.c
* Author : Xavier Halgand
* Date :
* Description : random segment waveform generator
******************************************************************************
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "drifter.h"
/*-------------------------------------------------------------------------------------------*/
Drifter_t d1 _CCM_;
Drifter_t d2 _CCM_;
Drifter_t d3 _CCM_;
/*-------------------------------------------------------------------------------------------*/
void Drifter_amp_set(uint8_t val) {
d1.gain = d2.gain = d3.gain = (val / MIDI_MAX) * (val / MIDI_MAX);
}
/*-------------------------------------------------------------------------------------------*/
void Drifter_minFreq_set(uint8_t val) {
d1.fmin = d2.fmin = d3.fmin = .1f + 50 * val / MIDI_MAX;
}
/*-------------------------------------------------------------------------------------------*/
void Drifter_maxFreq_set(uint8_t val) {
float x;
x = (1 + 19 * val / MIDI_MAX) * d1.fmin;
if (x > 10000)
d1.fmax = d2.fmax = d3.fmax = 10000;
else {
d1.fmax = d2.fmax = d3.fmax = x;
}
}
/*-------------------------------------------------------------------------------------------*/
void drifter_newSegment(Drifter_t *d) //
{
d->n = 0;
d->initial = d->final;
d->minLength = 0.5f * SAMPLERATE / d->fmax;
d->maxLength = 0.5f * SAMPLERATE / d->fmin;
d->length = frand_a_b(d->minLength, d->maxLength);
d->final = frand_a_b(-1, 1);
d->slope = (d->final - d->initial) / d->length;
}
/*-------------------------------------------------------------------------------------------*/
float drifter_nextSample(Drifter_t *d) //
{
d->out = d->gain * (d->slope * d->n + d->initial);
(d->n)++;
if (d->n >= d->length) {
drifter_newSegment(d);
}
return d->out;
}
/*-------------------------------------------------------------------------------------------*/
float d1_drifter_nextSample(void) //
{
return drifter_nextSample(&d1);
}
/*-------------------------------------------------------------------------------------------*/
float d2_drifter_nextSample(void) //
{
return drifter_nextSample(&d2);
}
/*---------------------------------------------------------------------------------------------*/
void drifter_prepare(Drifter_t *d) {
d->final = 0;
d->fmax = 4;
d->fmin = 2;
d->gain = .01f;
drifter_newSegment(d);
}
/*---------------------------------------------------------------------------------------------*/
void drifter_init(void) {
drifter_prepare(&d1);
drifter_prepare(&d2);
drifter_prepare(&d3);
}
/*------------------------------------------END--------------------------------------------*/
| 33.009615 | 97 | 0.429945 | MrBlueXav |
7598a31d36c90da882a8847f2526c9b2c7c26177 | 6,073 | cc | C++ | bindings/ruby/ext/memory.cc | mgallien/typelib | e27ef63564f623c9362d13c6f443c9944c351841 | [
"CECILL-B"
] | 1 | 2021-06-03T22:56:53.000Z | 2021-06-03T22:56:53.000Z | bindings/ruby/ext/memory.cc | mgallien/typelib | e27ef63564f623c9362d13c6f443c9944c351841 | [
"CECILL-B"
] | null | null | null | bindings/ruby/ext/memory.cc | mgallien/typelib | e27ef63564f623c9362d13c6f443c9944c351841 | [
"CECILL-B"
] | null | null | null | #include "typelib.hh"
#include <typelib/value_ops.hh>
#include <ruby.h>
#include <ruby/st.h>
using namespace Typelib;
using namespace std;
using namespace typelib_ruby;
#undef VERBOSE
static VALUE cMemoryZone;
static st_table* MemoryTable;
/* For those who are wondering, st_data_t is always the size of an void*
* (see the first lines of st.h
*/
static int memory_table_compare(void* a, void* b)
{
return (a != b);
}
static int memory_table_hash(void* a)
{
/* Use the low-order bits as hash value, as they are the most likely to
* change */
return (long)a;
}
static struct st_hash_type memory_table_type = {
(int (*)(...))memory_table_compare,
(int (*)(...))memory_table_hash
};
struct RbMemoryLayout
{
int refcount;
MemoryLayout layout;
boost::shared_ptr<Registry> registry;
RbMemoryLayout()
: refcount(0) {}
RbMemoryLayout(MemoryLayout const& layout, boost::shared_ptr<Registry> registry)
: layout(layout), registry(registry) {}
};
// MemoryTypes actually holds the memory layout of each memory zone. We cannot
// simply use the Type object as, at exit, the Ruby GC do not order finalization
// and therefore the registry can be deleted before the Type instances.
typedef std::map< void const*, void const* > MemoryTypes;
typedef std::map< void const*, RbMemoryLayout > TypeLayouts;
MemoryTypes memory_types;
TypeLayouts memory_layouts;
static void
memory_unref(void *ptr)
{
st_delete(MemoryTable, (st_data_t*)&ptr, 0);
MemoryTypes::iterator type_it = memory_types.find(ptr);
if (type_it != memory_types.end())
{
TypeLayouts::iterator layout_it = memory_layouts.find(type_it->second);
RbMemoryLayout& layout = layout_it->second;
if (0 == --layout.refcount)
memory_layouts.erase(layout_it);
memory_types.erase(type_it);
}
}
static void
memory_delete(void *ptr)
{
MemoryTypes::iterator it = memory_types.find(ptr);
if (it != memory_types.end())
{
TypeLayouts::iterator layout_it = memory_layouts.find(it->second);
if (layout_it != memory_layouts.end())
{
RbMemoryLayout& layout = layout_it->second;
Typelib::ValueOps::destroy(
static_cast<uint8_t*>(ptr),
layout.layout.begin(), layout.layout.end());
}
}
free(ptr);
memory_unref(ptr);
}
static VALUE
memory_aref(void *ptr)
{
VALUE val;
if (!st_lookup(MemoryTable, (st_data_t)ptr, &val)) {
return Qnil;
}
if (val == Qundef)
rb_bug("found undef in memory table");
return val;
}
static void
memory_aset(void *ptr, VALUE obj)
{
if (! NIL_P(memory_aref(ptr)))
rb_raise(rb_eArgError, "there is already a wrapper for %x", ptr);
st_insert(MemoryTable, (st_data_t)ptr, obj);
}
VALUE
typelib_ruby::memory_allocate(size_t size)
{
void* ptr = malloc(size);
VALUE zone = Data_Wrap_Struct(cMemoryZone, 0, &memory_delete, ptr);
# ifdef VERBOSE
fprintf(stderr, "%x: new allocated zone of size %i\n", ptr, size);
# endif
memory_aset(ptr, zone);
return zone;
}
void
typelib_ruby::memory_init(VALUE ptr, VALUE type)
{
try {
void* cptr = memory_cptr(ptr);
MemoryTypes::iterator it = memory_types.find(cptr);
if (it != memory_types.end())
rb_raise(rb_eArgError, "memory zone already initialized");
// For deinitialization later, get or register the type's layout
Type const& t(rb2cxx::object<Type>(type));
TypeLayouts::iterator layout_it = memory_layouts.find(&t);
if (layout_it == memory_layouts.end())
{
cxx2rb::RbRegistry& registry = rb2cxx::object<cxx2rb::RbRegistry>(type_get_registry(type));
layout_it = memory_layouts.insert(
make_pair( &t, RbMemoryLayout(layout_of(t, true), registry.registry) )
).first;
}
RbMemoryLayout& layout = layout_it->second;
++layout.refcount;
memory_types.insert( make_pair(cptr, &t) );
Typelib::ValueOps::init(static_cast<uint8_t*>(cptr), layout.layout.begin(), layout.layout.end());
} catch(std::runtime_error const& e) {
rb_raise(rb_eArgError, "internal error: %s", e.what());
}
}
VALUE
typelib_ruby::memory_wrap(void* ptr)
{
VALUE zone = memory_aref(ptr);
if (NIL_P(zone))
{
# ifdef VERBOSE
fprintf(stderr, "%x: wrapping new memory zone\n", ptr);
# endif
zone = Data_Wrap_Struct(cMemoryZone, 0, &memory_unref, ptr);
memory_aset(ptr, zone);
}
else
{
# ifdef VERBOSE
fprintf(stderr, "%x: already known memory zone\n", ptr);
# endif
}
return zone;
}
void*
typelib_ruby::memory_cptr(VALUE ptr)
{
void* cptr;
Data_Get_Struct(ptr, void, cptr);
return cptr;
}
static VALUE
memory_zone_address(VALUE self)
{
void* ptr = memory_cptr(self);
return LONG2NUM((long)ptr);
}
static VALUE
memory_zone_to_ptr(VALUE self)
{
VALUE result = memory_allocate(sizeof(void*));
void* newptr = memory_cptr(result);
void* ptr = memory_cptr(self);
*reinterpret_cast<void**>(newptr) = ptr;
rb_iv_set(result, "@pointed_to_memory", self);
return result;
}
static VALUE
string_to_memory_ptr(VALUE self)
{
rb_str_modify(self);
VALUE ptr = memory_wrap(StringValuePtr(self));
rb_iv_set(ptr, "@buffer_string", self);
return ptr;
}
void memory_table_mark(void* ptr)
{
}
void typelib_ruby::Typelib_init_memory()
{
VALUE mTypelib = rb_define_module("Typelib");
MemoryTable = st_init_table(&memory_table_type);
VALUE table = Data_Wrap_Struct(rb_cObject, &memory_table_mark, 0, MemoryTable);
rb_iv_set(mTypelib, "@__memory_table__", table);
cMemoryZone = rb_define_class_under(mTypelib, "MemoryZone", rb_cObject);
rb_define_method(cMemoryZone, "zone_address", RUBY_METHOD_FUNC(memory_zone_address), 0);
rb_define_method(cMemoryZone, "to_ptr", RUBY_METHOD_FUNC(memory_zone_to_ptr), 0);
rb_define_method(rb_cString, "to_memory_ptr", RUBY_METHOD_FUNC(string_to_memory_ptr), 0);
}
| 26.290043 | 105 | 0.671497 | mgallien |
759bbd0bdc623a447a4cbbd4b64d262ee35ec4ac | 3,317 | cpp | C++ | remote_core/remote_core/src/Controllers/HardwareController.cpp | DaveAMoore/remote_core | a46280a7cee5d52ca08d11ea2de518a7d5e12ca5 | [
"MIT"
] | null | null | null | remote_core/remote_core/src/Controllers/HardwareController.cpp | DaveAMoore/remote_core | a46280a7cee5d52ca08d11ea2de518a7d5e12ca5 | [
"MIT"
] | null | null | null | remote_core/remote_core/src/Controllers/HardwareController.cpp | DaveAMoore/remote_core | a46280a7cee5d52ca08d11ea2de518a7d5e12ca5 | [
"MIT"
] | null | null | null | //
// HardwareController.cpp
// remote_core
//
// Created by David Moore on 11/5/18.
// Copyright © 2018 David Moore. All rights reserved.
//
#include <algorithm>
#include <thread>
#include <sys/stat.h>
#include "HardwareController.hpp"
#include "CommandLine.hpp"
#define REMOTE_CONFIGURATION_FILE_DIRECTORY "."
using namespace RemoteCore;
HardwareController::HardwareController() {
}
bool HardwareController::doesRemoteExist(Remote &remote) {
auto relativePath = (REMOTE_CONFIGURATION_FILE_DIRECTORY + remote.getRemoteID() + ".lircd.conf").c_str();
struct stat buffer;
return (stat (relativePath, &buffer) == 0);
}
void HardwareController::sendCommandForRemoteWithCompletionHandler(Command command, Remote remote,
CompletionHandler completionHandler) {
/* ***************** Send the command. ***************** */
auto commandString = "irsend SEND_ONCE " + remote.getRemoteID() + " " + command.getCommandID();
CommandLine::sharedCommandLine()->executeCommandWithResultHandler(commandString.c_str(), [=](std::string result, bool isComplete) {
if (isComplete) {
completionHandler(Error::None);
}
});
// // Create a lirc thread that handles the sending.
// auto lircThread = std::thread([completionHandler]() {
// // initialize lirc socket and store file descriptor
// int fd = lirc_init("remote_core", 0);
// if (fd == -1) {
// // Handle init fail
// }
//
// // Check for remote existence
// /*
// if (!checkRemoteConfig(remote.getRemoteID)) {
// // Handle remote not found
// }
// */
//
// // Send command
// if (lirc_send_one(lirc_get_local_socket(NULL, 1), remote.getRemoteID().c_str(), command.getCommandID().c_str()) == -1) {
// // Handle fail send
// }
//
// // Deinitialize lirc socket
// lirc_deinit();
//
// completionHandler(Error::None);
// });
// Detach the thread.
// lircThread.detach();
}
std::shared_ptr<TrainingSession> HardwareController::newTrainingSessionForRemote(Remote remote) {
// Create a new training session.
auto trainingSession = std::make_shared<TrainingSession>(remote);
// Keep the session identifier stored.
sessionIDs.push_back(trainingSession->getSessionID());
return trainingSession;
}
void HardwareController::startTrainingSession(std::shared_ptr<TrainingSession> trainingSession) {
// It is an error to start a new training session when there is currently an active session.
if (currentTrainingSession != nullptr) {
throw std::logic_error("Expected 'currentTrainingSession' to be nullptr.");
}
// Retain the training session.
currentTrainingSession = trainingSession;
// Start the training session.
currentTrainingSession->start();
}
void HardwareController::suspendTrainingSession(std::shared_ptr<TrainingSession> trainingSession) {
if (currentTrainingSession != trainingSession) {
return;
}
// Suspend the training session.
currentTrainingSession->suspend();
// Nullify our reference to the training session.
currentTrainingSession = nullptr;
}
| 31.590476 | 135 | 0.644558 | DaveAMoore |
759c382ca4554b7ae1d4feae680b6589035ad5de | 58,082 | cpp | C++ | source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_Point_RV2FP.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_Point_RV2FP.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_Point_RV2FP.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | #include "source_code\Hyd_Headers_Precompiled.h"
//#include "Hyd_Coupling_Point_RV2FP.h"
//constructor
Hyd_Coupling_Point_RV2FP::Hyd_Coupling_Point_RV2FP(void){
this->river_profile_index_up=-1;
this->river_profile_up=NULL;
this->river_profile_index_down=-1;
this->river_profile_down=NULL;
this->floodplain_elem_index=-1;
this->floodplain_elem=NULL;
this->floodplain_index=-1;
this->fpl_section_id=-1;
this->first_found_elem_index=-1;
this->mid_height=0.0;
this->mid_basepoint=0.0;
this->mid_basepoint_profile=0.0;
this->mid_fac_up=0.0;
this->mid_fac_down=0.0;
this->mid_waterlevel=0.0;
this->overflow_flag=true;
this->overflow_flag_fixed=false;
this->horizontal_backwater_flag=false;
this->horizontal_backwater_flag_upstream=false;
this->current_q_break=0.0;
this->old_q_break = 0.0;
this->coupling_v_break=0.0;
this->break_flag=false;
this->index_break=-1;
this->stop_break_flag=false;
this->break_height=0.0;
this->break_width=0.0;
this->total_flow_width=0.0;
this->overflow_width=0.0;
this->delta_h_rv2fp_break=0.0;
this->max_h_2break.maximum=0.0;
this->max_h_2break.time_point=0.0;
this->max_h.maximum=0.0;
this->max_h.time_point=0.0;
this->max_deltah2break=0.0;
this->grad_q_current=0.0;
this->grad_q_before=0.0;
this->oscilation_smoother=1.0;
this->number_osci_counter=2.0;
this->no_osci_counter=0.0;
this->grad_q_break_current=0.0;
this->grad_q_break_before=0.0;
this->oscilation_smoother_break=1.0;
this->number_osci_counter_break=2.0;
this->no_osci_counter_break=0.0;
this->predicted_h_two=0.0;
this->corrected_h_two=0.0;
this->gradient_list_h_two.clear();
for(int i=0; i< constant::no_stored_grad; i++){
this->gradient_list_h_two.append(0.0);
}
this->gradient_h_two=0.0;
this->calc_h_two=0.0;
this->old_calc_h_two=0.0;
this->store_grad_q_before=0.0;
this->store_oscilation_smoother=1.0;
this->store_number_osci_counter=2.0;
this->store_no_osci_counter=0.0;
this->store_grad_q_break_before=0.0;
this->store_oscilation_smoother_break=1.0;
this->store_number_osci_counter_break=2.0;
this->store_no_osci_counter_break=0.0;
this->store_old_q_break=0.0;
//count the memory
Sys_Memory_Count::self()->add_mem(sizeof(Hyd_Coupling_Point_RV2FP), _sys_system_modules::HYD_SYS);
}
//Copy constructor
Hyd_Coupling_Point_RV2FP::Hyd_Coupling_Point_RV2FP(const Hyd_Coupling_Point_RV2FP& object){
_Hyd_Coupling_Point::operator =(object);
this->river_profile_index_up=object.river_profile_index_up;
this->river_profile_up=object.river_profile_up;
this->river_profile_index_down=object.river_profile_index_down;
this->river_profile_down=object.river_profile_down;
this->floodplain_index=object.floodplain_index;
this->floodplain_elem_index=object.floodplain_elem_index;
this->first_found_elem_index=object.first_found_elem_index;
this->floodplain_elem=object.floodplain_elem;
this->fpl_section_id=object.fpl_section_id;
this->mid_basepoint=object.mid_basepoint;
this->mid_basepoint_profile=object.mid_basepoint_profile;
this->mid_height=object.mid_height;
this->mid_fac_up=object.mid_fac_up;
this->mid_fac_down=object.mid_fac_down;
this->mid_waterlevel=object.mid_waterlevel;
this->overflow_flag=object.overflow_flag;
this->overflow_flag_fixed=object.overflow_flag_fixed;
this->horizontal_backwater_flag=object.horizontal_backwater_flag;
this->horizontal_backwater_flag_upstream=object.horizontal_backwater_flag_upstream;
this->current_q_break = object.current_q_break;
this->old_q_break = object.old_q_break;
this->coupling_v_break = object.coupling_v_break;
this->break_flag=object.break_flag;
this->index_break=object.index_break;
this->stop_break_flag=object.stop_break_flag;
this->break_height=object.break_height;
this->break_width=object.break_width;
this->total_flow_width=object.total_flow_width;
this->overflow_width=object.overflow_width;
this->delta_h_rv2fp_break=object.delta_h_rv2fp_break;
this->max_h_2break=object.max_h_2break;
this->max_h=object.max_h;
this->max_deltah2break=object.max_deltah2break;
this->grad_q_current=object.grad_q_current;
this->grad_q_before=object.grad_q_before;
this->oscilation_smoother=object.oscilation_smoother;
this->number_osci_counter=object.number_osci_counter;
this->no_osci_counter=object.no_osci_counter;
this->grad_q_break_current=object.grad_q_break_current;
this->grad_q_break_before=object.grad_q_break_before;
this->oscilation_smoother_break=object.oscilation_smoother_break;
this->no_osci_counter_break=object.no_osci_counter_break;
this->number_osci_counter_break=object.number_osci_counter_break;
this->corrected_h_two=object.corrected_h_two;
this->predicted_h_two=object.predicted_h_two;
this->gradient_h_two=object.gradient_h_two;
this->calc_h_two=object.calc_h_two;
this->old_calc_h_two=object.old_calc_h_two;
this->gradient_list_h_two.clear();
for(int i=0; i< constant::no_stored_grad; i++){
this->gradient_list_h_two.append(0.0);
}
this->store_grad_q_before=object.store_grad_q_before;
this->store_oscilation_smoother=object.store_oscilation_smoother;
this->store_number_osci_counter=object.store_number_osci_counter;
this->store_no_osci_counter=object.store_no_osci_counter;
this->store_grad_q_break_before=object.store_grad_q_break_before;
this->store_oscilation_smoother_break=object.store_oscilation_smoother_break;
this->store_no_osci_counter_break=object.store_no_osci_counter_break;
this->store_number_osci_counter_break=object.store_number_osci_counter_break;
this->store_old_q_break=object.store_old_q_break;
//count the memory
Sys_Memory_Count::self()->add_mem(sizeof(Hyd_Coupling_Point_RV2FP), _sys_system_modules::HYD_SYS);
}
//destructor
Hyd_Coupling_Point_RV2FP::~Hyd_Coupling_Point_RV2FP(void){
//count the memory
Sys_Memory_Count::self()->minus_mem(sizeof(Hyd_Coupling_Point_RV2FP), _sys_system_modules::HYD_SYS);
}
//_________
//public
//Set the pointer/index members (without the geometrical members) from the given point
void Hyd_Coupling_Point_RV2FP::set_couplingpoint_members(Hyd_Coupling_Point_RV2FP *object){
//from this class
this->river_profile_index_up=object->river_profile_index_up;
this->river_profile_up=object->river_profile_up;
this->river_profile_index_down=object->river_profile_index_down;
this->river_profile_down=object->river_profile_down;
this->floodplain_index=object->floodplain_index;
this->floodplain_elem_index=object->floodplain_elem_index;
this->set_pointer_floodplain_element(object->floodplain_elem);
this->first_found_elem_index=object->first_found_elem_index;
this->fpl_section_id=object->fpl_section_id;
}
//Output the header for the setted member (static))
void Hyd_Coupling_Point_RV2FP::output_header_setted_member(ostringstream *cout){
*cout <<W(10) << "Id_rv_up," << W(10) << "Id_rv_down," << W(7) << "Id_fp," << W(11) << "Id_fp_elem,";
*cout <<W(15) << "Coupling,"<< W(15) << "Overflow," << W(15) <<"Dist_upstr" << label::m<<"," <<W(15)<< "Dist_downstr" << label::m << ",";
*cout << W(15)<< "abs_Height" <<label::m << ",";
*cout << W(10)<< "Break," << W(16) << "Stop_break,";
*cout << W(15)<< "Dist_inflow" <<label::m << ",";
*cout << W(15)<< "x" << label::m << "," << W(17) << "y" <<label::m << ",";
*cout << W(17)<<"Id_fpl_sec" << "," << W(7) << "mid_fac_down" << "," << W(7) << "mid_fac_up";
*cout<< endl;
Sys_Common_Output::output_hyd->output_txt(cout,true);
}
//Output the setted members
void Hyd_Coupling_Point_RV2FP::output_setted_members(ostringstream *cout){
*cout <<W(8) << this->river_profile_index_up << "," << W(10) << this->river_profile_index_down << ",";
*cout <<W(10) << this->floodplain_index << W(10)<<"," << this->floodplain_elem_index << ",";
*cout <<W(15) << functions::convert_boolean2string(this->coupling_flag) << ",";
*cout <<W(15) << functions::convert_boolean2string(this->overflow_flag) << ",";
*cout <<W(15) <<P(2)<< FORMAT_FIXED_REAL << this->distance_down << ",";
*cout <<W(21) <<P(2)<< FORMAT_FIXED_REAL << this->distance_up << ",";
*cout <<W(17) <<P(2)<< FORMAT_FIXED_REAL << this->mid_height << ",";
*cout <<W(17) << functions::convert_boolean2string(this->break_flag) << ",";
*cout <<W(15) << functions::convert_boolean2string(this->stop_break_flag) << ",";
*cout <<W(17) << this->distance_along_polysegment << ",";
*cout <<W(21) <<P(2)<< FORMAT_FIXED_REAL << this->x_coordinate << ",";
*cout <<W(21) <<P(2)<< FORMAT_FIXED_REAL << this->y_coordinate << ",";
*cout <<W(21) <<P(0)<< FORMAT_FIXED_REAL << this->fpl_section_id << ",";
*cout << W(21) << P(10) << FORMAT_FIXED_REAL << this->mid_fac_down << ",";
*cout << W(21) << P(10) << FORMAT_FIXED_REAL << this->mid_fac_up;
*cout<< endl;
Sys_Common_Output::output_hyd->output_txt(cout, true);
}
//Set the indices for the upwards river profile (corresponding to the index of the polysegment of the river bank line) and the element index of the Hyd_Floodplain_Element, which is used for calculation
void Hyd_Coupling_Point_RV2FP::set_indices(const int up_river_profile, const int floodplain_model_elem){
this->river_profile_index_up=up_river_profile;
this->river_profile_index_down=this->river_profile_index_up+1;
this->floodplain_elem_index=floodplain_model_elem;
}
//Set the pointers to the river profiles with help of the indices
void Hyd_Coupling_Point_RV2FP::set_pointer_river_profiles(Hyd_Model_River *river_model){
if(this->river_profile_index_up<0 || this->river_profile_index_up>river_model->Param_RV.get_number_profiles()){
this->river_profile_up=NULL;
this->river_profile_down=NULL;
}
//inflow profile upwards
else if(this->river_profile_index_up==0){
this->river_profile_up=&(river_model->inflow_river_profile);
this->river_profile_down=&(river_model->river_profiles[this->river_profile_index_down-1]);
}
//outflow profile downwards
else if(this->river_profile_index_up==river_model->Param_RV.get_number_profiles()-2){
this->river_profile_up=&(river_model->river_profiles[this->river_profile_index_up-1]);
this->river_profile_down=&(river_model->outflow_river_profile);
}
//just inbetween profiles
else{
this->river_profile_up=&(river_model->river_profiles[this->river_profile_index_up-1]);
this->river_profile_down=&(river_model->river_profiles[this->river_profile_index_down-1]);
}
}
//Set the indexof the first found Hyd_Floodplain_Element; it is not necessarily used for calculation (e.g. river elements)
void Hyd_Coupling_Point_RV2FP::set_first_found_elem_index(const int index){
this->first_found_elem_index=index;
}
//Set the pointers to the floodplain elements
void Hyd_Coupling_Point_RV2FP::set_pointer_floodplain_element(Hyd_Element_Floodplain *floodplain){
this->floodplain_elem=floodplain;
if(this->floodplain_elem!=NULL && this->floodplain_elem_index>=0){
this->floodplain_elem->element_type->set_coupling_data();
}
}
//Set the index of the floodplain element
void Hyd_Coupling_Point_RV2FP::set_index_floodplain_element(const int index){
this->floodplain_elem_index=index;
}
//Get the index of the floodplain element
int Hyd_Coupling_Point_RV2FP::get_index_floodplain_element(void){
return this->floodplain_elem_index;
}
//Set the index of the coupled floodplain
void Hyd_Coupling_Point_RV2FP::set_floodplain_index(const int index){
this->floodplain_index=index;
}
//Get the index of the coupled floodplain
int Hyd_Coupling_Point_RV2FP::get_floodplain_index(void){
return this->floodplain_index;
}
//Get the index of the coupled fpl-section
int Hyd_Coupling_Point_RV2FP::get_fpl_section_index(void){
return this->fpl_section_id;
}
//Get the mid of waterlevel of the two profiles in the river
double Hyd_Coupling_Point_RV2FP::get_mid_waterlevel(void){
return this->mid_waterlevel;
}
//Calculate the current mid-waterlevel via the factors in the river
void Hyd_Coupling_Point_RV2FP::calculate_mid_waterlevel(void){
if(this->coupling_flag==true){
this->horizontal_backwater_flag=false;
this->horizontal_backwater_flag_upstream=false;
//set the mid_waterlevel via the factors
if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon && this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon){
this->mid_waterlevel=this->mid_fac_down*this->river_profile_down->get_actual_global_waterlevel()+this->mid_fac_up*this->river_profile_up->get_actual_global_waterlevel();
}
else if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon&& this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon){
this->mid_waterlevel=this->river_profile_up->get_actual_global_waterlevel();
this->horizontal_backwater_flag_upstream=true;
}
else if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon&& this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon){
this->mid_waterlevel=this->river_profile_down->get_actual_global_waterlevel();
this->horizontal_backwater_flag=true;
}
else if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon && this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon){
this->mid_waterlevel=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_global_z_min()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_global_z_min();
}
}
}
//Calculate the current delta h between river and floodplain in case of an break
void Hyd_Coupling_Point_RV2FP::calculate_delta_h_break(void){
if(this->coupling_flag==true && this->break_flag==true){
double delta_fp=this->floodplain_elem->element_type->get_s_value()-this->break_height;
double delta_rv=this->mid_waterlevel-this->break_height;
if(delta_fp <= 0.0 && delta_rv<=0.0){
this->delta_h_rv2fp_break=0.0;
}
else if(delta_fp > 0.0 && delta_rv<=0.0){
this->delta_h_rv2fp_break=-1.0*delta_fp;
}
else if(delta_fp <= 0.0 && delta_rv>0.0){
this->delta_h_rv2fp_break=delta_rv;
}
else if(delta_fp > 0.0 && delta_rv>0.0){
this->delta_h_rv2fp_break=delta_rv-delta_fp;
}
//set boundary
if(abs(this->delta_h_rv2fp_break)<=constant::flow_epsilon){
this->delta_h_rv2fp_break=0.0;
}
}
else{
this->delta_h_rv2fp_break=0.0;
}
}
//Get a pointer to the current delta h between river and floodplain in case of an break
double *Hyd_Coupling_Point_RV2FP::get_delta_h_break(void){
return &this->delta_h_rv2fp_break;
}
//Get the mid height for the overflow-coupling (global)
double Hyd_Coupling_Point_RV2FP::get_mid_height(void){
return this->mid_height;
}
//Get the mid basepoint height for a break coupling (global)
double Hyd_Coupling_Point_RV2FP::get_mid_basepoint_height(void){
return this->mid_basepoint;
}
//Get the mid basepoint height (just profile) for a break coupling (global)
double Hyd_Coupling_Point_RV2FP::get_mid_basepoint_height_profile(void){
return this->mid_basepoint_profile;
}
//Get the pointer to the downstream river profile
_Hyd_River_Profile* Hyd_Coupling_Point_RV2FP::get_downstream_rvprofile(void){
return this->river_profile_down;
}
//Get the pointer to the upstream river profile
_Hyd_River_Profile* Hyd_Coupling_Point_RV2FP::get_upstream_rvprofile(void){
return this->river_profile_up;
}
//Get the index of the downstream river profile
int Hyd_Coupling_Point_RV2FP::get_index_downstream_rvprofile(void){
if(this->river_profile_down==NULL){
return -1;
}
else{
return this->river_profile_down->get_profile_number();
}
}
//Get the index to the upstream river profile
int Hyd_Coupling_Point_RV2FP::get_index_upstream_rvprofile(void){
if(this->river_profile_up==NULL){
return -1;
}
else{
return this->river_profile_up->get_profile_number();
}
}
//Get the pointer to the floodplain element
Hyd_Element_Floodplain* Hyd_Coupling_Point_RV2FP::get_floodplain_element(void){
return this->floodplain_elem;
}
//Get the upwards factor for the mid-value calculation of the mid_height and the mid_waterlevel depending on the distances
double Hyd_Coupling_Point_RV2FP::get_upwards_mid_factor(void){
return this->mid_fac_up;
}
//Get the downwards factor for the mid-value calculation of the mid_height and the mid_waterlevel depending on the distances
double Hyd_Coupling_Point_RV2FP::get_downwards_mid_factor(void){
return this->mid_fac_down;
}
//Get the distance from the coupling point to the element mid point
double Hyd_Coupling_Point_RV2FP::get_distancecoupling2elem_mid(void){
double distance=-1.0;
if(this->coupling_flag==false || this->floodplain_elem==NULL){
return distance;
}
else{
distance=this->distance(this->floodplain_elem->get_mid_point());
}
return distance;
}
//Transfer the coupling characteristics of the coupled elements
void Hyd_Coupling_Point_RV2FP::transfer_coupling_characteristics(const bool left_river_flag){
if(this->river_profile_index_up<0 || this->floodplain_elem_index<0 || this->river_profile_index_down<0){
this->coupling_flag=false;
return;
}
if(this->floodplain_elem->get_elem_type()==_hyd_elem_type::STANDARD_ELEM || this->floodplain_elem->get_elem_type()==_hyd_elem_type::DIKELINE_ELEM){
this->coupling_flag=true;
//left river bank
if(left_river_flag==true){
this->transfer_coupling_characteristics_leftbank();
}
//right river bank
else{
this->transfer_coupling_characteristics_rightbank();
}
//Daniel ok? If this is used no direct in coupling is possible
//if(abs(this->distance_down)<=constant::meter_epsilon){
//this->coupling_flag=false;
//}
}
else{
this->coupling_flag=false;
return;
}
}
//Reset the current coupling discharge of the points and the coupled element
void Hyd_Coupling_Point_RV2FP::reset_coupling_discharge(const bool left_river_flag){
_Hyd_Coupling_Point::reset_coupling_discharge();
if(this->coupling_flag==true){
if(this->overflow_flag==true){
this->floodplain_elem->element_type->reset_coupling_discharge_rv_overflow();
if(left_river_flag==true){
this->river_profile_up->reset_coupling_discharge_left_bank();
this->river_profile_down->reset_coupling_discharge_left_bank();
}
else{
this->river_profile_up->reset_coupling_discharge_right_bank();
this->river_profile_down->reset_coupling_discharge_right_bank();
}
}
if(this->break_flag==true){
this->floodplain_elem->element_type->reset_coupling_discharge_rv_dikebreak();
if(left_river_flag==true){
this->river_profile_up->reset_dikebreak_coupling_discharge_left_bank();
this->river_profile_down->reset_dikebreak_coupling_discharge_left_bank();
}
else{
this->river_profile_up->reset_dikebreak_coupling_discharge_right_bank();
this->river_profile_down->reset_dikebreak_coupling_discharge_right_bank();
}
}
}
}
//Syncronisation of the coupled models with the couplingspoint
void Hyd_Coupling_Point_RV2FP::syncronisation_coupled_models(const double timepoint, const double delta_t, const bool left_river_flag, const bool time_check, const int internal_counter){
_Hyd_Coupling_Point::syncronisation_coupled_models();
this->delta_t=delta_t;
this->time_check=time_check;
if(this->coupling_flag==false){
return;
}
else{
//calculate the current midwaterlevel in the river
this->calculate_mid_waterlevel();
double h_one_buff=0.0;
double h_two_buff=0.0;
this->predict_values(internal_counter);
h_one_buff=0.5*(this->predicted_h_one+this->calc_h_one);
h_two_buff=0.5*(this->predicted_h_two+this->calc_h_two);
if(this->time_check==true){
this->store_grad_q_before=this->grad_q_before;
this->store_oscilation_smoother=this->oscilation_smoother;
this->store_number_osci_counter=this->number_osci_counter;
this->store_no_osci_counter=this->no_osci_counter;
this->store_grad_q_break_before=this->grad_q_break_before;
this->store_oscilation_smoother_break=this->oscilation_smoother_break;
this->store_number_osci_counter_break=this->number_osci_counter_break;
this->store_no_osci_counter_break=this->no_osci_counter_break;
this->store_old_q_break=this->old_q_break;
this->store_old_q=this->old_q;
}
else{
this->grad_q_before=this->store_grad_q_before;
this->oscilation_smoother=this->store_oscilation_smoother;
this->number_osci_counter=this->store_number_osci_counter;
this->no_osci_counter=this->store_no_osci_counter;
this->grad_q_break_before=this->store_grad_q_break_before;
this->oscilation_smoother_break=this->store_oscilation_smoother_break;
this->number_osci_counter_break=this->store_number_osci_counter_break;
this->no_osci_counter_break=this->store_no_osci_counter_break;
this->old_q_break=this->store_old_q_break;
this->old_q=this->store_old_q;
//left river bank
if(left_river_flag==true){
if(this->overflow_flag==true){
this->syncronisation_coupled_models_overflow(timepoint, this->river_profile_up->get_overflow_poleni_left(), h_one_buff, h_two_buff);
if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){
//discharge to river profile segment: division to the profiles weighted with the factors
this->river_profile_up->add_coupling_discharge_left_bank(this->current_q*this->mid_fac_up);
this->river_profile_down->add_coupling_discharge_left_bank(this->current_q*this->mid_fac_down);
}
else if(this->horizontal_backwater_flag==true){
//discharge to river profile segment: just to/out of the downstream profile
this->river_profile_down->add_coupling_discharge_left_bank(this->current_q);
}
else if(this->horizontal_backwater_flag_upstream==true){
//discharge to river profile segment: just to/out of the upstream profile
this->river_profile_up->add_coupling_discharge_left_bank(this->current_q);
}
}
if(this->break_flag==true && this->index_break>=0){
this->syncronisation_coupled_models_break(timepoint, h_one_buff, h_two_buff);
//discharge to river profile segment: division to the profiles weighted with the factors
if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){
this->river_profile_up->add_dikebreak_coupling_discharge_left_bank(this->current_q_break*this->mid_fac_up);
this->river_profile_down->add_dikebreak_coupling_discharge_left_bank(this->current_q_break*this->mid_fac_down);
}
else if(this->horizontal_backwater_flag==true){
//discharge to river profile segment: just to/out of the downstream profile
this->river_profile_down->add_dikebreak_coupling_discharge_left_bank(this->current_q_break);
}
else if(this->horizontal_backwater_flag_upstream==true){
//discharge to river profile segment: just to/out of the upstream profile
this->river_profile_up->add_dikebreak_coupling_discharge_left_bank(this->current_q_break);
}
}
if(this->time_check==false){
//calculate maximum waterlevel for a break
this->calculate_max_h2break(true, timepoint);
}
}
//right river bank
else{
if(this->overflow_flag==true){
this->syncronisation_coupled_models_overflow(timepoint, this->river_profile_up->get_overflow_poleni_right(), h_one_buff, h_two_buff);
//discharge to river profile segment: division to the profiles weighted with the factors
if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){
this->river_profile_up->add_coupling_discharge_right_bank(this->current_q*this->mid_fac_up);
this->river_profile_down->add_coupling_discharge_right_bank(this->current_q*this->mid_fac_down);
}
else if(this->horizontal_backwater_flag==true){
//discharge to river profile segment: just to/out of the downstream profile
this->river_profile_down->add_coupling_discharge_right_bank(this->current_q);
}
else if(this->horizontal_backwater_flag_upstream==true){
//discharge to river profile segment: just to/out of the upstream profile
this->river_profile_up->add_coupling_discharge_right_bank(this->current_q);
}
}
if(this->break_flag==true && this->index_break>=0){
this->syncronisation_coupled_models_break(timepoint, h_one_buff, h_two_buff);
//discharge to river profile segment: division to the profiles weighted with the factors
if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){
this->river_profile_up->add_dikebreak_coupling_discharge_right_bank(this->current_q_break*this->mid_fac_up);
this->river_profile_down->add_dikebreak_coupling_discharge_right_bank(this->current_q_break*this->mid_fac_down);
}
else if(this->horizontal_backwater_flag==true){
//discharge to river profile segment: just to/out of the downstream profile
this->river_profile_down->add_dikebreak_coupling_discharge_right_bank(this->current_q_break);
}
else if(this->horizontal_backwater_flag_upstream==true){
//discharge to river profile segment: just to/out of the upstream profile
this->river_profile_up->add_dikebreak_coupling_discharge_right_bank(this->current_q_break);
}
}
}
}
if(this->time_check==false){
//calculate maximum waterlevel for a break
this->calculate_max_h2break(false, timepoint);
}
}
}
//Set the flag if a coupling due to a overflow is applicable
void Hyd_Coupling_Point_RV2FP::set_overflow_flag(const bool flag){
this->overflow_flag=flag;
}
//Set the fixed overflow flag to true; it is not more dependent of the profiles
void Hyd_Coupling_Point_RV2FP::set_fixed_overflow_flag(void){
this->overflow_flag_fixed=true;
}
//Get the flag if a coupling due to a break is applicable
bool Hyd_Coupling_Point_RV2FP::get_break_flag(void){
return this->break_flag;
}
//Get a flag if the break width is as same as the total overflow width => break is total
bool Hyd_Coupling_Point_RV2FP::get_break_is_total(void){
if(this->break_width==this->total_flow_width){
return true;
}
else{
return false;
}
}
//Set the flag if a coupling due to a break is applicable
void Hyd_Coupling_Point_RV2FP::set_break_flag(const bool flag){
this->break_flag=flag;
}
//Set the break width; the break height is related to the base points
bool Hyd_Coupling_Point_RV2FP::add_break_width(const double delta_break_width){
bool is_full_flag=true;
if(this->break_flag==true){
if(abs(this->break_width-this->total_flow_width)<constant::meter_epsilon){
is_full_flag=true;
}
else{
is_full_flag=false;
this->break_width=this->break_width+delta_break_width;
if(this->break_width>=this->total_flow_width){
this->break_width=this->total_flow_width;
this->overflow_width=this->total_flow_width-this->break_width;
}
else{
this->overflow_width=this->total_flow_width-this->break_width;
}
}
}
else{
is_full_flag=true;
}
return is_full_flag;
}
//Set the starting break width
void Hyd_Coupling_Point_RV2FP::set_begin_break_width(const double begin_break_width){
if(this->break_flag==true){
this->break_height=this->mid_height;
this->break_width=begin_break_width;
this->overflow_width=this->total_flow_width-this->break_width;
}
}
//Set a reduction of the overflow height in the starting breach (slow reduction of the height due to numerical reasons)
bool Hyd_Coupling_Point_RV2FP::set_overflow_height_reduction(const double height_reduction){
if(this->break_flag==true){
bool break_init_finished=false;
this->break_height=this->break_height-height_reduction;
if(this->break_height<=this->mid_basepoint){
this->break_height=this->mid_basepoint;
break_init_finished=true;
return break_init_finished;
}
else{
break_init_finished=false;
return break_init_finished;
}
}
else{
return false;
}
}
//Set the mid basepoint height as the break height
void Hyd_Coupling_Point_RV2FP::set_mid_basepoint2breakheight(void){
if(this->break_flag==true){
this->break_height=this->mid_basepoint;
}
}
//Set the flag, that a breach is stopped here to true
void Hyd_Coupling_Point_RV2FP::set_stop_break_flag(void){
this->stop_break_flag=true;
}
//Get the flag, that a breach is stopped here
bool Hyd_Coupling_Point_RV2FP::get_stop_break_flag(void){
return this->stop_break_flag;
}
//Set the index of the break class
void Hyd_Coupling_Point_RV2FP::set_index_break_class(const int index){
this->index_break=index;
}
//Get the index of the break class
int Hyd_Coupling_Point_RV2FP::get_index_break_class(void){
return this->index_break;
}
//Get the current discharge through a break
double Hyd_Coupling_Point_RV2FP::get_q_break(void){
return this->current_q_break;
}
//Get the current velocity through a break
double Hyd_Coupling_Point_RV2FP::get_v_break(void){
return this->coupling_v_break;
}
//Get the maximum waterlevel at this coupling point by the maximum delta waterlevel relevant for a break
_hyd_max_values Hyd_Coupling_Point_RV2FP::get_max_h_2break(void){
return this->max_h_2break;
}
//Get the delta waterlevel between river and floodplain at this coupling point
double Hyd_Coupling_Point_RV2FP::get_max_deltah_2break(void){
return this->max_deltah2break;
}
//Get maximum waterlevel at this coupling point related to the mid base points of the profiles
_hyd_max_values Hyd_Coupling_Point_RV2FP::get_max_h(void){
return this->max_h;
}
//Reset the break width
void Hyd_Coupling_Point_RV2FP::reset_break_width(void){
this->break_width=0.0;
this->overflow_width=this->total_flow_width-this->break_width;
this->index_break=-1;
}
//Reset the hydrological balance values and the maximum calculated values
void Hyd_Coupling_Point_RV2FP::reset_hydro_balance_max_values(void){
_Hyd_Coupling_Point::reset_hydro_balance_max_values();
this->max_coupling_v_break.maximum=0.0;
this->max_coupling_v_break.time_point=0.0;
this->max_h_2break.maximum=0.0;
this->max_h_2break.time_point=0.0;
this->max_deltah2break=0.0;
this->max_h.maximum=0.0;
this->max_h.time_point=0.0;
this->reset_break_width();
this->coupling_volume_break.volume_in=0.0;
this->coupling_volume_break.volume_out=0.0;
this->coupling_volume_break.volume_total=0.0;
}
//Reset the smoothing calculation members
void Hyd_Coupling_Point_RV2FP::reset_smoothing(void){
_Hyd_Coupling_Point::reset_smoothing();
this->grad_q_current=0.0;
this->grad_q_before=0.0;
this->oscilation_smoother=1.0;
this->number_osci_counter=2.0;
this->no_osci_counter=0.0;
this->grad_q_break_current=0.0;
this->grad_q_break_before=0.0;
this->oscilation_smoother_break=1.0;
this->number_osci_counter_break=2.0;
this->no_osci_counter_break=0.0;
this->predicted_h_two=0.0;
this->corrected_h_two=0.0;
this->gradient_list_h_two.clear();
for(int i=0; i< constant::no_stored_grad; i++){
this->gradient_list_h_two.append(0.0);
}
this->gradient_h_two=0.0;
this->calc_h_two=0.0;
this->old_calc_h_two=0.0;
this->store_grad_q_before=0.0;
this->store_oscilation_smoother=1.0;
this->store_number_osci_counter=2.0;
this->store_no_osci_counter=0.0;
this->store_grad_q_break_before=0.0;
this->store_oscilation_smoother_break=1.0;
this->store_number_osci_counter_break=2.0;
this->store_no_osci_counter_break=0.0;
this->store_old_q_break=0.0;
}
//Get the maximum waterlevel gradient
double Hyd_Coupling_Point_RV2FP::get_maximum_h_grad(void){
double buffer=0.0;
double buffer_max=0.0;
buffer=abs(this->grad_q_break_current/this->min_area);
if(buffer_max<buffer){
buffer_max=buffer;
}
buffer=abs(this->grad_q_current/this->min_area);
if(buffer_max<buffer){
buffer_max=buffer;
}
return buffer_max;
}
//Copy operator
Hyd_Coupling_Point_RV2FP& Hyd_Coupling_Point_RV2FP::operator=(const Hyd_Coupling_Point_RV2FP& object){
_Hyd_Coupling_Point::operator =(object);
this->river_profile_index_up=object.river_profile_index_up;
this->river_profile_up=object.river_profile_up;
this->river_profile_index_down=object.river_profile_index_down;
this->river_profile_down=object.river_profile_down;
this->floodplain_index=object.floodplain_index;
this->fpl_section_id=object.fpl_section_id;
this->floodplain_elem_index=object.floodplain_elem_index;
this->first_found_elem_index=object.first_found_elem_index;
this->floodplain_elem=object.floodplain_elem;
this->mid_height=object.mid_height;
this->mid_basepoint=object.mid_basepoint;
this->mid_basepoint_profile=object.mid_basepoint_profile;
this->mid_fac_up=object.mid_fac_up;
this->mid_fac_down=object.mid_fac_down;
this->mid_waterlevel=object.mid_waterlevel;
this->overflow_flag=object.overflow_flag;
this->overflow_flag_fixed=object.overflow_flag_fixed;
this->break_flag=object.break_flag;
this->index_break=object.index_break;
this->stop_break_flag=object.stop_break_flag;
this->break_height=object.break_height;
this->break_width=object.break_width;
this->total_flow_width=object.total_flow_width;
this->overflow_width=object.overflow_width;
this->delta_h_rv2fp_break=object.delta_h_rv2fp_break;
this->max_h_2break=object.max_h_2break;
this->max_deltah2break=object.max_deltah2break;
this->max_h=object.max_h;
this->horizontal_backwater_flag=object.horizontal_backwater_flag;
this->horizontal_backwater_flag_upstream=object.horizontal_backwater_flag_upstream;
this->current_q_break = object.current_q_break;
this->coupling_v_break = object.coupling_v_break;
this->grad_q_current=object.grad_q_current;
this->old_q_break = object.old_q_break;
this->grad_q_before=object.grad_q_before;
this->oscilation_smoother=object.oscilation_smoother;
this->number_osci_counter=object.number_osci_counter;
this->no_osci_counter=object.no_osci_counter;
this->grad_q_break_current=object.grad_q_break_current;
this->grad_q_break_before=object.grad_q_break_before;
this->oscilation_smoother_break=object.oscilation_smoother_break;
this->no_osci_counter_break=object.no_osci_counter_break;
this->number_osci_counter_break=object.number_osci_counter_break;
this->corrected_h_two=object.corrected_h_two;
this->predicted_h_two=object.predicted_h_two;
this->gradient_h_two=object.gradient_h_two;
this->calc_h_two=object.calc_h_two;
this->old_calc_h_two=object.old_calc_h_two;
this->store_grad_q_before=object.store_grad_q_before;
this->store_oscilation_smoother=object.store_oscilation_smoother;
this->store_number_osci_counter=object.store_number_osci_counter;
this->store_no_osci_counter=object.store_no_osci_counter;
this->store_grad_q_break_before=object.store_grad_q_break_before;
this->store_oscilation_smoother_break=object.store_oscilation_smoother_break;
this->store_no_osci_counter_break=object.store_no_osci_counter_break;
this->store_number_osci_counter_break=object.store_number_osci_counter_break;
this->store_old_q_break=object.store_old_q_break;
return *this;
}
//______________
//private
//Transfer the coupling characteristics of the coupled elements for a left river bank (in flow direction)
void Hyd_Coupling_Point_RV2FP::transfer_coupling_characteristics_leftbank(void){
//check if a overflow coupling is given by the profiles
if(this->overflow_flag_fixed==false){
if(this->river_profile_up->get_overflow_flag_left()==false ){
this->overflow_flag=false;
}
else{
this->overflow_flag=true;
}
}
//check if a break is applied
if(this->river_profile_down->get_break_flag_left()==true && this->river_profile_up->get_break_flag_left()==true){
this->break_flag=true;
}
else{
this->break_flag=false;
}
//set the fpl index, if available
this->fpl_section_id=this->river_profile_up->get_fpl_section_id_left();
//this->coupling_flag=true;
//set the factors for the mid-value calculation depending on the distances
double total_prof_distance=0.0;
double distance_prof_up=0.0;
double distance_prof_down=0.0;
//calculate the distances to the profiles for a point between the coupling points => hmid
total_prof_distance=abs(this->river_profile_down->typ_of_profile->get_first_point()->get_global_x_y_coordinates().distance(&(this->river_profile_up->typ_of_profile->get_first_point()->get_global_x_y_coordinates())));
distance_prof_up=abs(this->distance(&(this->river_profile_up->typ_of_profile->get_first_point()->get_global_x_y_coordinates())));
distance_prof_up=distance_prof_up-this->distance_down*0.5;
distance_prof_down=abs(this->distance(&(this->river_profile_down->typ_of_profile->get_first_point()->get_global_x_y_coordinates())));
//check for stop flags by special types and coupling points, which are caused by a riverprofile
if(abs(distance_prof_down)<=constant::meter_epsilon && (this->river_profile_down->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE || this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE
|| this->river_profile_down->get_connection_type()==_hyd_connection_types::INFLOW_CONN || this->river_profile_down->get_connection_type()==_hyd_connection_types::OUTFLOW_CONN)){
this->set_stop_break_flag();
}
distance_prof_down=distance_prof_down+this->distance_down*0.5;
//set the factors via the distances
this->mid_fac_down=(1.0-distance_prof_down/total_prof_distance);
this->mid_fac_up=(1.0-distance_prof_up/total_prof_distance);
//check for a weir profile
if(this->river_profile_up->get_profile_type()==_hyd_profile_types::WEIR_TYPE){
//full weight to the downstream profile
this->mid_fac_down=1.0;
this->mid_fac_up=0.0;
}
if(this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE){
//full weight to the upstream profile
this->mid_fac_down=0.0;
this->mid_fac_up=1.0;
}
//set the mid_height via the factors
//this->mid_height=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_first_point()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_first_point()->get_global_z_coordinate();
this->mid_height=this->mid_fac_down*this->river_profile_down->get_height_left_bank_abs()+this->mid_fac_up*this->river_profile_up->get_height_left_bank_abs();
//if the height of the element is above the river bank line set the element height
this->mid_height=max(this->mid_height, this->floodplain_elem->get_z_value());
//set the width
this->total_flow_width=this->distance_down;
this->overflow_width=this->total_flow_width;
//set minimal area
this->min_area=this->floodplain_elem->element_type->get_relevant_area();
//special settings for a breaking
if(this->break_flag==true){
this->mid_basepoint_profile=this->mid_fac_down*this->river_profile_down->get_left_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_left_basepoint()->get_global_z_coordinate();
this->mid_basepoint=this->mid_fac_down*this->river_profile_down->get_left_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_left_basepoint()->get_global_z_coordinate();
this->mid_basepoint=max(this->mid_basepoint, this->floodplain_elem->get_z_value());
//check if the mid_base point is equal to the mid of the global z_min values; than increase the height by 0.05 m
double mid_zmin=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_global_z_min()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_global_z_min();
if(this->mid_basepoint<=mid_zmin+0.05){
//increase the mid_basepoint, otherwise the riversgements gets numerical problems with to much outflow before getting dry
this->mid_basepoint=this->mid_basepoint+0.05;
}
//there is no break, if floodplain is heigher than floodprotection line
if(this->mid_basepoint>=this->mid_height){
this->break_flag=false;
}
}
}
//Transfer the coupling characteristics of the coupled elements for a right river bank (in flow direction)
void Hyd_Coupling_Point_RV2FP::transfer_coupling_characteristics_rightbank(void){
//check if a overflow coupling is given by the profiles
if(this->overflow_flag_fixed==false){
if(this->river_profile_up->get_overflow_flag_right()==false){
this->overflow_flag=false;
}
else{
this->overflow_flag=true;
}
}
//check if a break is applied
if(this->river_profile_down->get_break_flag_right()==true && this->river_profile_up->get_break_flag_right()==true){
this->break_flag=true;
}
else{
this->break_flag=false;
}
//set the fpl index, if available
this->fpl_section_id=this->river_profile_up->get_fpl_section_id_right();
//this->coupling_flag=true;
//set the factors for the mid-value calculation depending on the distances
double total_prof_distance=0.0;
double distance_prof_up=0.0;
double distance_prof_down=0.0;
//calculate the distances to the profiles
total_prof_distance=abs(this->river_profile_down->typ_of_profile->get_last_point()->get_global_x_y_coordinates().distance(&(this->river_profile_up->typ_of_profile->get_last_point()->get_global_x_y_coordinates())));
distance_prof_up=abs(this->distance(&(this->river_profile_up->typ_of_profile->get_last_point()->get_global_x_y_coordinates())));
distance_prof_up=distance_prof_up-0.5*this->distance_down;
distance_prof_down=abs(this->distance(&(this->river_profile_down->typ_of_profile->get_last_point()->get_global_x_y_coordinates())));
//check for stop flags by special types and coupling points, which are caused by a riverprofile
if(abs(distance_prof_down)<=constant::meter_epsilon && (this->river_profile_down->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE || this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE
|| this->river_profile_down->get_connection_type()==_hyd_connection_types::INFLOW_CONN || this->river_profile_down->get_connection_type()==_hyd_connection_types::OUTFLOW_CONN)){
this->set_stop_break_flag();
}
distance_prof_down=distance_prof_down+0.5*this->distance_down;
//set the factors via the distances
this->mid_fac_down=(1.0-distance_prof_down/total_prof_distance);
this->mid_fac_up=(1.0-distance_prof_up/total_prof_distance);
//set the mid_height via the factors
//this->mid_height=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_last_point()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_last_point()->get_global_z_coordinate();
this->mid_height=this->mid_fac_down*this->river_profile_down->get_height_right_bank_abs()+this->mid_fac_up*this->river_profile_up->get_height_right_bank_abs();
//if the height of the element is above the river bank line set the element height
this->mid_height=max(this->mid_height, this->floodplain_elem->get_z_value());
//check for a weir profile
if(this->river_profile_up->get_profile_type()==_hyd_profile_types::WEIR_TYPE || this->river_profile_up->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE){
//full weight to the downstream profile
this->mid_fac_down=1.0;
this->mid_fac_up=0.0;
}
if(this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE || this->river_profile_down->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE){
//full weight to the upstream profile
this->mid_fac_down=0.0;
this->mid_fac_up=1.0;
}
//set the width
this->total_flow_width=this->distance_down;
this->overflow_width=this->total_flow_width;
//set minimal area
this->min_area=this->floodplain_elem->element_type->get_relevant_area();
//special settings for a breaking
if(this->break_flag==true){
this->mid_basepoint_profile=this->mid_fac_down*this->river_profile_down->get_right_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_right_basepoint()->get_global_z_coordinate();
this->mid_basepoint=this->mid_fac_down*this->river_profile_down->get_right_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_right_basepoint()->get_global_z_coordinate();
this->mid_basepoint=max(this->mid_basepoint, this->floodplain_elem->get_z_value());
//check if the mid_base point is equal to the mid of the global z_min values; than increase the height by 0.05 m
double mid_zmin=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_global_z_min()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_global_z_min();
if(this->mid_basepoint<=mid_zmin+0.05){
//increase the mid_basepoint, otherwise the riversgements gets numerical problems with to much outflow before getting dry
this->mid_basepoint=this->mid_basepoint+0.05;
}
//there is no break, if floodplain is heigher than floodprotection line
if(this->mid_basepoint>=this->mid_height){
this->break_flag=false;
}
}
}
//Syncronisation of the coupled models with the couplingspoint for overflow
void Hyd_Coupling_Point_RV2FP::syncronisation_coupled_models_overflow(const double timepoint, const double poleni, const double h_one, const double h_two){
double delta_h_river=0.0;
double delta_h_elem=0.0;
double q_buff=0.0;
delta_h_river=h_two-this->mid_height;
//if(delta_h_river>0.0){
// cout <<"Test"<<endl;
//}
delta_h_elem=(this->floodplain_elem->get_z_value()+h_one)-this->mid_height;
//no width
if(abs(this->overflow_width)<constant::flow_epsilon){
this->coupling_v=0.0;
q_buff=0.0;
}
//same waterlevels=> no flow
else if(abs(delta_h_river-delta_h_elem)<constant::dry_hyd_epsilon){
this->coupling_v=0.0;
q_buff=0.0;
}
//both waterlevel are under the weirsill=> no flow
else if(delta_h_river<=0.0 && delta_h_elem<=0.0){
this->coupling_v=0.0;
q_buff=0.0;
}
//flow out of the river model into the floodplain without submerged reduction
else if(delta_h_river> 0.0 && delta_h_elem <= 0.0){
q_buff=-1.0*constant::Cfacweir*poleni*pow(delta_h_river,(3.0/2.0))*this->overflow_width;
//factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000])
q_buff=constant::side_weir_reduction*q_buff;
//calculate the velocity
this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_river);
}
//flow out of the floodplain element into the river model without submerged reduction
else if(delta_h_river<= 0.0 && delta_h_elem > 0.0){
q_buff=constant::Cfacweir*poleni*pow(delta_h_elem,(3.0/2.0))*this->overflow_width;
//calculate the velocity
this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_elem);
}
//flow without submerged reduction
else if(delta_h_river > 0.0 && delta_h_elem > 0.0){
//flow out of the river model into the floodplain with sideweir reduction
if(delta_h_river>delta_h_elem){
q_buff=constant::Cfacweir*poleni*pow(delta_h_river,(3.0/2.0))*this->overflow_width;
//reduction of the discharge (submerged weirflow)
double reduction_term=(1.0-delta_h_elem/delta_h_river);
//replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values
if(reduction_term<=0.000463529){
q_buff=-1.0*q_buff*0.057965266895*atan(8984.365582471040*reduction_term);
}
else{
q_buff=-1.0*q_buff*pow(reduction_term,(1.0/3.0));
}
//factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000])
q_buff=constant::side_weir_reduction*q_buff;
//calculate the velocity
this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_river);
}
//flow out of the floodplain element into the river model without sideweir reduction
else{
q_buff=constant::Cfacweir*poleni*pow(delta_h_elem,(3.0/2.0))*this->overflow_width;
//reduction of the discharge (submerged weirflow)
double reduction_term=(1.0-delta_h_river/delta_h_elem);
//replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values
if(reduction_term<=0.000463529){
q_buff=q_buff*0.057965266895*atan(8984.365582471040*reduction_term);
}
else{
q_buff=q_buff*pow(reduction_term,(1.0/3.0));
}
//calculate the velocity
this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_elem);
}
}
//set a boundary to the discharge
if(abs(q_buff)<=this->discharge_boundary){
q_buff=0.0;
this->coupling_v=0.0;
}
//smooth it for numerical reasons
q_buff=this->smooth_coupling_discharge(q_buff, &this->old_q);
this->current_q=q_buff;
this->calculate_maximum_values(timepoint, this->current_q, &this->max_coupling_v);
this->calculate_hydrological_balance(this->current_q, &this->coupling_volume);
//discharge to element
this->floodplain_elem->element_type->add_coupling_discharge_rv_overflow((-1.0)*this->current_q);
}
//Syncronisation of the coupled models with the couplingspoint for the discharge throught the break
void Hyd_Coupling_Point_RV2FP::syncronisation_coupled_models_break(const double timepoint, const double h_one, const double h_two){
double delta_h_river=0.0;
double delta_h_elem=0.0;
double q_buff=0.0;
this->current_q_break=0.0;
this->coupling_v_break=0.0;
delta_h_river=h_two-this->break_height;
delta_h_elem=(this->floodplain_elem->get_z_value()+h_one)-this->break_height;
//no width
if(abs(this->break_width)<constant::flow_epsilon){
this->coupling_v_break=0.0;
q_buff=0.0;
}
//same waterlevels=> no flow
else if(abs(delta_h_river-delta_h_elem)<constant::flow_epsilon){
this->coupling_v_break=0.0;
q_buff=0.0;
}
//both waterlevel are under the weirsill=> no flow
else if(delta_h_river<=0.0 && delta_h_elem<=0.0){
this->coupling_v_break=0.0;
q_buff=0.0;
}
//flow out of the river model into the floodplain without submerged reduction, with sideweir reduction
else if(delta_h_river> 0.0 && delta_h_elem <= 0.0){
q_buff=-1.0*constant::Cfacweir*constant::poleni_const*pow(delta_h_river,(3.0/2.0))*this->break_width;
//factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000])
q_buff=constant::side_weir_reduction*q_buff;
//calculate the velocity
this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_river);
}
//flow out of the floodplain element into the river model without submerged reduction, withtout sideweir reduction
else if(delta_h_river<= 0.0 && delta_h_elem > 0.0){
q_buff=constant::Cfacweir*constant::poleni_const*pow(delta_h_elem,(3.0/2.0))*this->break_width;
//calculate the velocity
this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_elem);
}
//weir flow with submerged reduction
else if(delta_h_river > 0.0 && delta_h_elem > 0.0){
//flow out of the river model into the floodplain with sideweir reduction
if(delta_h_river>delta_h_elem){
q_buff=constant::Cfacweir*constant::poleni_const*pow(delta_h_river,(3.0/2.0))*this->break_width;
//reduction of the discharge (submerged weirflow)
double reduction_term=(1.0-delta_h_elem/delta_h_river);
//replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values
if(reduction_term<=0.000463529){
q_buff=-1.0*q_buff*0.057965266895*atan(8984.365582471040*reduction_term);
}
else{
q_buff=-1.0*q_buff*pow(reduction_term,(1.0/3.0));
}
//factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000])
q_buff=constant::side_weir_reduction*q_buff;
//calculate the velocity
this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_river);
}
//flow out of the floodplain element into the river model without sideweir reduction
else{
q_buff=constant::Cfacweir*constant::poleni_const*pow(delta_h_elem,(3.0/2.0))*this->break_width;
//reduction of the discharge (submerged weirflow)
double reduction_term=(1.0-delta_h_river/delta_h_elem);
//replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values
if(reduction_term<=0.000463529){
q_buff=q_buff*0.057965266895*atan(8984.365582471040*reduction_term);
}
else{
q_buff=q_buff*pow(reduction_term,(1.0/3.0));
}
//calculate the velocity
this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_elem);
}
}
//set a boundary to the discharge
if(abs(q_buff)<=this->discharge_boundary){
q_buff=0.0;
this->coupling_v_break=0.0;
}
//smooth it for numerical reasons
q_buff=this->smooth_coupling_dikebreak_discharge(q_buff, &this->old_q_break);
this->current_q_break=q_buff;
this->calculate_maximum_values(timepoint, this->current_q_break, &this->max_coupling_v_break);
this->calculate_hydrological_balance(this->current_q_break, &this->coupling_volume_break);
//discharge to element
this->floodplain_elem->element_type->add_coupling_discharge_rv_dikebreak((-1.0)*this->current_q_break);
}
//Smooth the coupling discharge with the coupling discharge calculated one internal timestep before
double Hyd_Coupling_Point_RV2FP::smooth_coupling_discharge(const double q_current, double *old_q){
double smooth_q=0.0;
if(this->delta_t>0.0){
this->grad_q_current=(q_current-*old_q)/(this->delta_t);
if((this->grad_q_before>=0.0 && this->grad_q_current<0.0)|| (this->grad_q_before<=0.0 && this->grad_q_current>0.0)){
this->oscilation_smoother=this->oscilation_smoother+this->number_osci_counter;
//this->oscilation_smoother=this->oscilation_smoother+1.0;
this->no_osci_counter=0.0;
this->number_osci_counter=2.0;
if(this->oscilation_smoother>=100.0){
this->oscilation_smoother=100.0;
}
}
else{
this->oscilation_smoother=this->oscilation_smoother-pow(this->no_osci_counter,0.75);
//this->oscilation_smoother=this->oscilation_smoother-pow(this->no_osci_counter,1.5);
this->no_osci_counter++;
this->number_osci_counter=2.0;
if(this->oscilation_smoother<1.0){
this->oscilation_smoother=1.0;
}
}
this->grad_q_before=this->grad_q_current;
}
smooth_q=q_current*(1.0/this->oscilation_smoother)+(*old_q)*(1.0-(1.0/this->oscilation_smoother));
if(this->delta_t>0.0){
this->grad_q_current=(smooth_q-*old_q)/(this->delta_t);
this->grad_q_before=this->grad_q_current;
}
*old_q=smooth_q;
return smooth_q;
}
//Smooth the coupling discharge with the coupling dikebreak discharge calculated one internal timestep before
double Hyd_Coupling_Point_RV2FP::smooth_coupling_dikebreak_discharge(const double q_current, double *old_q){
double smooth_q=0.0;
if(this->delta_t>0.0){
this->grad_q_break_current=(q_current-*old_q)/(this->delta_t);
if((this->grad_q_break_before>=0.0 && this->grad_q_break_current<0.0)|| (this->grad_q_break_before<=0.0 && this->grad_q_break_current>0.0)){
this->oscilation_smoother_break=this->oscilation_smoother_break+this->number_osci_counter_break;
this->number_osci_counter_break=2.0;
this->no_osci_counter_break=0.0;
if(this->oscilation_smoother_break>=100.0){
this->oscilation_smoother_break=100.0;
}
}
else{
this->oscilation_smoother_break=this->oscilation_smoother_break-pow(this->no_osci_counter_break,0.75);
this->no_osci_counter_break++;
this->number_osci_counter_break=2.0;
if(this->oscilation_smoother_break<1.0){
this->oscilation_smoother_break=1.0;
}
}
this->grad_q_break_before=this->grad_q_break_current;
}
smooth_q=q_current*(1.0/this->oscilation_smoother_break)+(*old_q)*(1.0-(1.0/this->oscilation_smoother_break));
if(this->delta_t>0.0){
this->grad_q_break_current=(smooth_q-*old_q)/(this->delta_t);
this->grad_q_break_before=this->grad_q_break_current;
}
*old_q=smooth_q;
return smooth_q;
}
//Calculate the maximum waterlevel at the maximim waterlevel difference between river and floodplain
void Hyd_Coupling_Point_RV2FP::calculate_max_h2break(const bool left_flag, const double timepoint){
double buffer=0.0;
if(this->river_profile_up==NULL || this->floodplain_elem ==NULL || this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon){
return;
}
if(this->break_width>0.0){
return;
}
if(this->break_flag==false){
return;
}
buffer=this->mid_waterlevel-this->mid_basepoint;
if(buffer>0.0){
this->river_profile_up->set_delta_waterlevel_rv2fp2break(this->mid_waterlevel, buffer, left_flag);
if(this->mid_waterlevel-this->mid_basepoint>this->max_deltah2break){
this->max_deltah2break=this->mid_waterlevel-this->mid_basepoint;
this->max_h_2break.maximum=this->mid_waterlevel-this->mid_basepoint_profile;
this->max_h_2break.time_point=timepoint;
}
if(this->mid_waterlevel-this->mid_basepoint_profile>this->max_h.maximum){
this->max_h.maximum=this->mid_waterlevel-this->mid_basepoint_profile;
this->max_h.time_point=timepoint;
}
}
}
//Predict the values
void Hyd_Coupling_Point_RV2FP::predict_values(const int int_counter){
if(this->delta_t>0.0){
//one
this->calc_h_one=this->floodplain_elem->element_type->get_h_value();
this->gradient_h_one=(this->calc_h_one-this->old_calc_h_one)/this->delta_t;
if(this->time_check==false){
this->old_calc_h_one=this->calc_h_one;
this->replace_first_grad_list(&this->gradient_list_h_one, this->gradient_h_one);
}
else{
this->swap_grad_list(&this->gradient_list_h_one, this->gradient_h_one);
}
//this->predicted_h_one=this->calc_h_one+(1.0/12.0)*(23.0*this->gradient_list_h_one.at(0)-16.0*this->gradient_list_h_one.at(1)+5.0*this->gradient_list_h_one.at(2))*this->delta_t;
//this->predicted_h_one=this->calc_h_one+(0.5)*(3.0*this->gradient_list_h_one.at(0)-1.0*this->gradient_list_h_one.at(1))*this->delta_t;
this->predicted_h_one=this->calc_h_one+(this->gradient_list_h_one.at(0))*this->delta_t;
//two
this->calc_h_two=this->mid_waterlevel;
this->gradient_h_two=(this->calc_h_two-this->old_calc_h_two)/this->delta_t;
if(this->time_check==false){
this->old_calc_h_two=this->calc_h_two;
this->replace_first_grad_list(&this->gradient_list_h_two, this->gradient_h_two);
}
else{
this->swap_grad_list(&this->gradient_list_h_two, this->gradient_h_two);
}
if(int_counter>3){
//this->predicted_h_two=this->calc_h_two+(1.0/12.0)*(23.0*this->gradient_list_h_two.at(0)-16.0*this->gradient_list_h_two.at(1)+5.0*this->gradient_list_h_two.at(2))*this->delta_t;
//this->predicted_h_two=this->calc_h_two+(0.5)*(3.0*this->gradient_list_h_two.at(0)-1.0*this->gradient_list_h_two.at(1))*this->delta_t;
this->predicted_h_two=this->calc_h_two+(this->gradient_list_h_two.at(0))*this->delta_t;
this->predicted_h_one=this->calc_h_one+(this->gradient_list_h_one.at(0))*this->delta_t;
}
else{
this->predicted_h_two=this->calc_h_two;
this->predicted_h_one=this->calc_h_one;
}
}
} | 42.180102 | 229 | 0.779088 | dabachma |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.