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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12d6710714f7de44b43a998ec1f72793984562dc
| 367
|
hpp
|
C++
|
library/ATF/tagCONTROLINFO.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/tagCONTROLINFO.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/tagCONTROLINFO.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <HACCEL__.hpp>
START_ATF_NAMESPACE
struct tagCONTROLINFO
{
unsigned int cb;
HACCEL__ *hAccel;
unsigned __int16 cAccel;
unsigned int dwFlags;
};
END_ATF_NAMESPACE
| 21.588235
| 108
| 0.694823
|
lemkova
|
12da3d353b84c8f6e8db0831ff11a4ef89ac2d7c
| 751
|
hpp
|
C++
|
NINJA/TreeBuilder.hpp
|
jebrosen/NINJA
|
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
|
[
"MIT"
] | null | null | null |
NINJA/TreeBuilder.hpp
|
jebrosen/NINJA
|
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
|
[
"MIT"
] | null | null | null |
NINJA/TreeBuilder.hpp
|
jebrosen/NINJA
|
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
|
[
"MIT"
] | null | null | null |
/*
* TreeBuilder.hpp
*
* Created on: Jan 24, 2016
* Author: michel
*/
#ifndef TREEBUILDER_HPP
#define TREEBUILDER_HPP
#include <string>
#include <vector>
#include "TreeNode.hpp"
class TreeBuilder{
public:
TreeBuilder (std::string** names, int** distances, int namesSize);
~TreeBuilder();
TreeNode* build ();
static bool distInMem;
static bool rebuildStepsConstant;
static float rebuildStepRatio;
static int rebuildSteps;
static const int clustCnt = 30;
static int candidateIters;
static int verbose;
int K;
protected:
std::string** names;
int** D;
long int *R;
TreeNode **nodes;
int *redirect;
int *nextActiveNode;
int *prevActiveNode;
int firstActiveNode;
void finishMerging();
};
#endif
| 16.326087
| 68
| 0.695073
|
jebrosen
|
12e2bbd0fd4211ed71f3ca599a3633bc077a2eee
| 2,292
|
hpp
|
C++
|
code/source/util/profiling.hpp
|
crafn/clover
|
586acdbcdb34c3550858af125e9bb4a6300343fe
|
[
"MIT"
] | 12
|
2015-01-12T00:19:20.000Z
|
2021-08-05T10:47:20.000Z
|
code/source/util/profiling.hpp
|
crafn/clover
|
586acdbcdb34c3550858af125e9bb4a6300343fe
|
[
"MIT"
] | null | null | null |
code/source/util/profiling.hpp
|
crafn/clover
|
586acdbcdb34c3550858af125e9bb4a6300343fe
|
[
"MIT"
] | null | null | null |
#ifndef CLOVER_UTIL_PROFILING_HPP
#define CLOVER_UTIL_PROFILING_HPP
#include "build.hpp"
#include "util/preproc_join.hpp"
#include <thread>
// No profiling on windows due to odd crashes with mingw 4.8.2
#define PROFILING_ENABLED (ATOMIC_PTR_READWRITE == true)
namespace clover {
namespace util {
namespace detail {
struct BlockInfo {
const char* funcName;
uint32 line;
/// Don't assume that labels with same string will point to
/// the same memory - depends on compiler optimizations
const char* label;
uint64 exclusiveMemAllocs;
uint64 inclusiveMemAllocs;
};
struct BlockProfiler {
static BlockInfo createBlockInfo( const char* func,
uint32 line,
const char* label);
BlockProfiler(BlockInfo& info);
~BlockProfiler();
};
struct StackJoiner {
StackJoiner();
~StackJoiner();
};
struct StackDetacher {
StackDetacher();
~StackDetacher();
};
void setSuperThread(std::thread::id super_id);
} // detail
/// Call in main() -- we don't want to see any impl defined pre-main stuff
void tryEnableProfiling();
#if PROFILING_ENABLED
/// Should be called on system memory allocation
void profileSystemMemAlloc();
#else
inline void profileSystemMemAlloc() {};
#endif
} // util
} // clover
#if PROFILING_ENABLED
/// Same as PROFILE but with a label
#define PROFILE_(label)\
static util::detail::BlockInfo JOIN(profiler_block_info_, __LINE__)= \
util::detail::BlockProfiler::createBlockInfo( \
__PRETTY_FUNCTION__, \
__LINE__, \
label); \
util::detail::BlockProfiler JOIN(profiler_, __LINE__)(JOIN(profiler_block_info_, __LINE__))
/// Marks current block to be profiled
#define PROFILE()\
PROFILE_(nullptr)
/// Notifies profiler of a super thread
#define PROFILER_SUPER_THREAD(thread_id)\
util::detail::setSuperThread(thread_id)
/// Joins callstacks of this and super thread in current scope
#define PROFILER_STACK_JOIN()\
util::detail::StackJoiner JOIN(stack_joiner_, __LINE__)
/// Detaches callstacks of this and super thread in current scope
#define PROFILER_STACK_DETACH()\
util::detail::StackDetacher JOIN(stack_detacher_, __LINE__)
#else
#define PROFILE_(label)
#define PROFILE()
#define PROFILER_SUPER_THREAD(thread_id)
#define PROFILER_STACK_JOIN()
#define PROFILER_STACK_DETACH()
#endif
#endif // CLOVER_UTIL_PROFILING_HPP
| 23.387755
| 92
| 0.756108
|
crafn
|
12e58bca092d23af2cab801bee2e0b6248e5d27d
| 7,949
|
cpp
|
C++
|
loginframe.cpp
|
mobile-pos/amp
|
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
|
[
"MIT"
] | 6
|
2020-09-12T08:16:46.000Z
|
2020-11-19T04:05:35.000Z
|
loginframe.cpp
|
mobile-pos/amp
|
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
|
[
"MIT"
] | null | null | null |
loginframe.cpp
|
mobile-pos/amp
|
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
|
[
"MIT"
] | 2
|
2020-12-11T02:27:56.000Z
|
2021-11-18T02:15:01.000Z
|
#include "loginframe.h"
#include <QLabel>
#include <QLineEdit>
#include <QDebug>
#include <QCryptographicHash>
#include <QMessageBox>
#include "vkeyboardex.h"
#include "datathread.h"
#include "mainwindow.h"
extern MainWindow* gWnd;
///////////////////////////////////////////////////////////
/// \brief LoginFrame::LoginFrame
/// \param parent
///
LoginFrame::LoginFrame(QWidget *parent) :
QFrame(parent)
{
this->setObjectName("loginWnd");
this->setStyleSheet("LoginFrame#loginWnd{ border-image: url(:/res/img/grass.jpg);}");
_layout = new GridLayoutEx(15, this);
_layout->setObjectName("loginArea");
_layout->setStyleSheet("#loginArea{ background: gray;}");
_layout->setCellBord(0);
//半透明设置
// _layout->setWindowFlags(Qt::FramelessWindowHint);
// _layout->setAttribute(Qt::WA_TranslucentBackground);
_layout->setWindowOpacity(0.5);
_vkb = new VKeyboardEx(this);
_vkb->setObjectName("virtualKB");
_vkb->setCellBord(0);
_vkb->setStyleSheet("#virtualKB{ background: rgb(116, 122, 131);}");
init();
}
LoginFrame::~LoginFrame()
{
}
void LoginFrame::init() {
/**
+------------------------+
| title |
| name: |
| pwd : |
|------------------------|
| OK cancel |
|------------------------|
| virtual keyboard |
+------------------------+
*/
qDebug() << "LoginFrame::init";
//1行15个单元
{
//title
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
{
QLabel* _l = new POSLabelEx(QObject::tr("请登录"), _layout);
// _l->setStyleSheet("background-color: rgb(80, 114, 165)");
_l->setAlignment(Qt::AlignCenter);
_l->setObjectName("LoginTitle");
_layout->addWidget(_l, 10, 2);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 2, 2);
}
} {
//输入用户名
{
QLabel* _l = new POSLabelEx(QObject::tr("账号:"), _layout);
_l->setAlignment(Qt::AlignRight |Qt::AlignCenter);
_layout->addWidget(_l, 4, 2);
} {
LineEditEx* _e = new LineEditEx(_layout);
this->connect(_e, SIGNAL(focussed(QWidget*, bool)), this, SLOT(focussed(QWidget*, bool)));
_e->setPlaceholderText(QObject::tr("请输入账号"));
_e->setObjectName("LoginAccout");
_e->setText("demoroot");
_layout->addWidget(_e, 10, 2, 1000);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 1, 2);
}
}{
//输入密码
{
QLabel* _l = new POSLabelEx(QObject::tr("密码:"), _layout);
_l->setAlignment(Qt::AlignRight |Qt::AlignCenter);
_layout->addWidget(_l, 4, 2);
} {
LineEditEx* _e = new LineEditEx(_layout);
this->connect(_e, SIGNAL(focussed(QWidget*, bool)), this, SLOT(focussed(QWidget*, bool)));
_e->setEchoMode(QLineEdit::Password);
_e->setPlaceholderText(QObject::tr("请输入密码"));
_e->setObjectName("LoginPasswd");
_e->setText("1356@aiwaiter");
_layout->addWidget(_e, 10, 2, 1001);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 1, 2);
}
} {
//空行
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 15, 1);
}
} {
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
{
VKeyItemButton* _btn = new VKeyItemButton("OK", this, _layout);
_btn->setText(QObject::tr("点击登录"));
_btn->setStyleSheet("background-color: rgb(80, 114, 165)");
_btn->setFocus();
_layout->addWidget(_btn, 3, 2);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
{
VKeyItemButton* _btn = new VKeyItemButton("Cancel", this, _layout);
_btn->setText(QObject::tr("重置"));
_btn->setStyleSheet("background-color: rgb(80, 114, 165)");
_layout->addWidget(_btn, 3, 2);
}
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 3, 2);
}
} {
//空一行
{
QLabel* _l = new QLabel("", _layout);
_layout->addWidget(_l, 15, 1);
}
} {
_vkb->init(0);
_vkb->hide();
}
qDebug() << "LoginFrame::init end";
}
void LoginFrame::login(bool isAdmin) {
QLabel* lab = dynamic_cast<QLabel*>( _layout->getItembyObjectName("LoginTitle") );
if(true == isAdmin) {
lab->setText(tr("请管理员登陆"));
} else {
lab->setText(tr("请登陆"));
}
this->showMaximized();
}
void LoginFrame::resizeEvent(QResizeEvent* e) {
QFrame::resizeEvent(e);
QRect rect = this->geometry();
int w = 400;
int h = 200;
QRect center( rect.width()/2 - w/2, rect.height() * 0.3 - h/2, w, h);
_layout->setRowHeight(h/10);
_layout->setGeometry(center);
QRect lrect = _layout->geometry();
_vkb->setGeometry(lrect.left() - 100, lrect.bottom() + 5, lrect.width() + 200, rect.height() -lrect.bottom() - 30);
}
void LoginFrame::onKeyDown(const QString& value) {
qDebug() << "onKeyDown: " << value;
if( "Cancel" == value) {
LineEditEx* _edit = dynamic_cast<LineEditEx*>(_layout->getItembyID(1000));
_edit->setText("");
_edit = dynamic_cast<LineEditEx*>(_layout->getItembyID(1001));
_edit->setText("");
} else if("OK" == value) {
//调用登录接口
LineEditEx* _en = dynamic_cast<LineEditEx*>(dynamic_cast<LineEditEx*>(_layout->getItembyID(1000)));
LineEditEx* _ep = dynamic_cast<LineEditEx*>(dynamic_cast<LineEditEx*>(_layout->getItembyID(1001)));
QString name = _en->text();
QString pwd = _ep->text();
if(name == "") {
_en->setPlaceholderText(QObject::tr("账号不能为空"));
return;
}
if(pwd == "") {
_en->setPlaceholderText(QObject::tr("密码不能为空"));
return;
}
QString key = name + pwd;
QString md5 = QString(QCryptographicHash::hash( key.toUtf8(),QCryptographicHash::Md5).toHex());
QVariantMap ret = DataThread::inst().login(name, md5);
// //@Task Todo for test
// ret["account"] = "r002";
// ret["id"] = 2;
if(ret.empty() || 0 != ret["code"].toInt()) {
QMessageBox::warning(this, "登录失败", QString("用户名或密码不对,请重试 或是网络异常: %1").arg(ret["msg"].toString()));
gWnd->recordPOSEvent("login", "login failed, 用户名或密码不对,请重试 或是网络异常");
return;
}
if( ret["id"].toInt() != DataThread::inst().getRestaurantInfo()["rid"].toInt()) {
QMessageBox::warning(this, "登录失败", "非本店账号不能登录");
gWnd->recordPOSEvent("login", "login failed, 非本店账号不能登录");
return;
}
DataThread::inst().setLogin(ret["account"].toString(), ret);
_ep->setText("");
this->hide();
gWnd->Home();
gWnd->updateLoginInfo();
//
if(0 != DataThread::inst().updateTables2Cloud()) {
QMessageBox::warning(this, "出错", "更新桌台信息到云端失败,可能影响到扫码点餐");
}
gWnd->recordPOSEvent("login", "login OK");
}
}
void LoginFrame::onVKeyDown(const QString& value) {
qDebug() << "onVKeyDown: " << value;
if("OK" == value) {
}
}
void LoginFrame::focussed(QWidget* _this, bool hasFocus) {
if(true == hasFocus) {
LineEditEx* _edit = dynamic_cast<LineEditEx*>(_this);
// _edit->setStyleSheet("background-color: red(255, 255, 255)");
_vkb->setTarget( _edit );
_vkb->show();
} else {
_vkb->hide();
}
}
| 29.550186
| 119
| 0.525349
|
mobile-pos
|
12ec4045586b0a03ddb1f52dc847cd06f99b7244
| 7,183
|
cpp
|
C++
|
libgpopt/src/operators/CLogicalDynamicGet.cpp
|
khannaekta/gporca
|
94e509d0a2456851a2cabf02e933c3523946b87b
|
[
"ECL-2.0",
"Apache-2.0"
] | 1
|
2019-03-05T10:08:56.000Z
|
2019-03-05T10:08:56.000Z
|
libgpopt/src/operators/CLogicalDynamicGet.cpp
|
khannaekta/gporca
|
94e509d0a2456851a2cabf02e933c3523946b87b
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
libgpopt/src/operators/CLogicalDynamicGet.cpp
|
khannaekta/gporca
|
94e509d0a2456851a2cabf02e933c3523946b87b
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CLogicalDynamicGet.cpp
//
// @doc:
// Implementation of dynamic table access
//---------------------------------------------------------------------------
#include "gpos/base.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/base/CConstraintInterval.h"
#include "gpopt/base/CColRefSet.h"
#include "gpopt/base/CPartIndexMap.h"
#include "gpopt/base/CColRefSetIter.h"
#include "gpopt/base/CColRefTable.h"
#include "gpopt/base/COptCtxt.h"
#include "gpopt/operators/CExpressionHandle.h"
#include "gpopt/operators/CLogicalDynamicGet.h"
#include "gpopt/metadata/CTableDescriptor.h"
#include "gpopt/metadata/CName.h"
using namespace gpopt;
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::CLogicalDynamicGet
//
// @doc:
// ctor - for pattern
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::CLogicalDynamicGet
(
IMemoryPool *pmp
)
:
CLogicalDynamicGetBase(pmp)
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::CLogicalDynamicGet
//
// @doc:
// ctor
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::CLogicalDynamicGet
(
IMemoryPool *pmp,
const CName *pnameAlias,
CTableDescriptor *ptabdesc,
ULONG ulPartIndex,
DrgPcr *pdrgpcrOutput,
DrgDrgPcr *pdrgpdrgpcrPart,
ULONG ulSecondaryPartIndexId,
BOOL fPartial,
CPartConstraint *ppartcnstr,
CPartConstraint *ppartcnstrRel
)
:
CLogicalDynamicGetBase(pmp, pnameAlias, ptabdesc, ulPartIndex, pdrgpcrOutput, pdrgpdrgpcrPart, ulSecondaryPartIndexId, fPartial, ppartcnstr, ppartcnstrRel)
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::CLogicalDynamicGet
//
// @doc:
// ctor
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::CLogicalDynamicGet
(
IMemoryPool *pmp,
const CName *pnameAlias,
CTableDescriptor *ptabdesc,
ULONG ulPartIndex
)
:
CLogicalDynamicGetBase(pmp, pnameAlias, ptabdesc, ulPartIndex)
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::~CLogicalDynamicGet
//
// @doc:
// dtor
//
//---------------------------------------------------------------------------
CLogicalDynamicGet::~CLogicalDynamicGet()
{
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::UlHash
//
// @doc:
// Operator specific hash function
//
//---------------------------------------------------------------------------
ULONG
CLogicalDynamicGet::UlHash() const
{
ULONG ulHash = gpos::UlCombineHashes(COperator::UlHash(), m_ptabdesc->Pmdid()->UlHash());
ulHash = gpos::UlCombineHashes(ulHash, CUtils::UlHashColArray(m_pdrgpcrOutput));
return ulHash;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::FMatch
//
// @doc:
// Match function on operator level
//
//---------------------------------------------------------------------------
BOOL
CLogicalDynamicGet::FMatch
(
COperator *pop
)
const
{
return CUtils::FMatchDynamicScan(this, pop);
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::PopCopyWithRemappedColumns
//
// @doc:
// Return a copy of the operator with remapped columns
//
//---------------------------------------------------------------------------
COperator *
CLogicalDynamicGet::PopCopyWithRemappedColumns
(
IMemoryPool *pmp,
HMUlCr *phmulcr,
BOOL fMustExist
)
{
DrgPcr *pdrgpcrOutput = NULL;
if (fMustExist)
{
pdrgpcrOutput = CUtils::PdrgpcrRemapAndCreate(pmp, m_pdrgpcrOutput, phmulcr);
}
else
{
pdrgpcrOutput = CUtils::PdrgpcrRemap(pmp, m_pdrgpcrOutput, phmulcr, fMustExist);
}
DrgDrgPcr *pdrgpdrgpcrPart = PdrgpdrgpcrCreatePartCols(pmp, pdrgpcrOutput, m_ptabdesc->PdrgpulPart());
CName *pnameAlias = GPOS_NEW(pmp) CName(pmp, *m_pnameAlias);
m_ptabdesc->AddRef();
CPartConstraint *ppartcnstr = m_ppartcnstr->PpartcnstrCopyWithRemappedColumns(pmp, phmulcr, fMustExist);
CPartConstraint *ppartcnstrRel = m_ppartcnstrRel->PpartcnstrCopyWithRemappedColumns(pmp, phmulcr, fMustExist);
return GPOS_NEW(pmp) CLogicalDynamicGet(pmp, pnameAlias, m_ptabdesc, m_ulScanId, pdrgpcrOutput, pdrgpdrgpcrPart, m_ulSecondaryScanId, m_fPartial, ppartcnstr, ppartcnstrRel);
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::FInputOrderSensitive
//
// @doc:
// Not called for leaf operators
//
//---------------------------------------------------------------------------
BOOL
CLogicalDynamicGet::FInputOrderSensitive() const
{
GPOS_ASSERT(!"Unexpected function call of FInputOrderSensitive");
return false;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::PxfsCandidates
//
// @doc:
// Get candidate xforms
//
//---------------------------------------------------------------------------
CXformSet *
CLogicalDynamicGet::PxfsCandidates
(
IMemoryPool *pmp
)
const
{
CXformSet *pxfs = GPOS_NEW(pmp) CXformSet(pmp);
(void) pxfs->FExchangeSet(CXform::ExfDynamicGet2DynamicTableScan);
return pxfs;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::OsPrint
//
// @doc:
// debug print
//
//---------------------------------------------------------------------------
IOstream &
CLogicalDynamicGet::OsPrint
(
IOstream &os
)
const
{
if (m_fPattern)
{
return COperator::OsPrint(os);
}
else
{
os << SzId() << " ";
// alias of table as referenced in the query
m_pnameAlias->OsPrint(os);
// actual name of table in catalog and columns
os << " (";
m_ptabdesc->Name().OsPrint(os);
os <<"), ";
m_ppartcnstr->OsPrint(os);
os << "), Columns: [";
CUtils::OsPrintDrgPcr(os, m_pdrgpcrOutput);
os << "] Scan Id: " << m_ulScanId << "." << m_ulSecondaryScanId;
if (!m_ppartcnstr->FUnbounded())
{
os << ", ";
m_ppartcnstr->OsPrint(os);
}
}
return os;
}
//---------------------------------------------------------------------------
// @function:
// CLogicalDynamicGet::PstatsDerive
//
// @doc:
// Load up statistics from metadata
//
//---------------------------------------------------------------------------
IStatistics *
CLogicalDynamicGet::PstatsDerive
(
IMemoryPool *pmp,
CExpressionHandle &exprhdl,
DrgPstat * // not used
)
const
{
CReqdPropRelational *prprel = CReqdPropRelational::Prprel(exprhdl.Prp());
IStatistics *pstats = PstatsDeriveFilter(pmp, exprhdl, prprel->PexprPartPred());
CColRefSet *pcrs = GPOS_NEW(pmp) CColRefSet(pmp, m_pdrgpcrOutput);
CUpperBoundNDVs *pubndv = GPOS_NEW(pmp) CUpperBoundNDVs(pcrs, pstats->DRows());
CStatistics::PstatsConvert(pstats)->AddCardUpperBound(pubndv);
return pstats;
}
// EOF
| 24.940972
| 174
| 0.540303
|
khannaekta
|
12f20952bf329e98c0583356186b08930a02c495
| 4,514
|
hpp
|
C++
|
include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: SceneSetupData
#include "GlobalNamespace/SceneSetupData.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: BeatmapEditorSceneSetupData
// [TokenAttribute] Offset: FFFFFFFF
class BeatmapEditorSceneSetupData : public GlobalNamespace::SceneSetupData {
public:
// private System.String _levelDirPath
// Size: 0x8
// Offset: 0x10
::Il2CppString* levelDirPath;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String _levelAssetPath
// Size: 0x8
// Offset: 0x18
::Il2CppString* levelAssetPath;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: BeatmapEditorSceneSetupData
BeatmapEditorSceneSetupData(::Il2CppString* levelDirPath_ = {}, ::Il2CppString* levelAssetPath_ = {}) noexcept : levelDirPath{levelDirPath_}, levelAssetPath{levelAssetPath_} {}
// Get instance field reference: private System.String _levelDirPath
::Il2CppString*& dyn__levelDirPath();
// Get instance field reference: private System.String _levelAssetPath
::Il2CppString*& dyn__levelAssetPath();
// public System.String get_levelDirPath()
// Offset: 0x11EB008
::Il2CppString* get_levelDirPath();
// public System.String get_levelAssetPath()
// Offset: 0x11EB010
::Il2CppString* get_levelAssetPath();
// public System.Void .ctor(System.String levelDirPath, System.String levelAssetPath)
// Offset: 0x11EB018
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BeatmapEditorSceneSetupData* New_ctor(::Il2CppString* levelDirPath, ::Il2CppString* levelAssetPath) {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::BeatmapEditorSceneSetupData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BeatmapEditorSceneSetupData*, creationType>(levelDirPath, levelAssetPath)));
}
}; // BeatmapEditorSceneSetupData
#pragma pack(pop)
static check_size<sizeof(BeatmapEditorSceneSetupData), 24 + sizeof(::Il2CppString*)> __GlobalNamespace_BeatmapEditorSceneSetupDataSizeCheck;
static_assert(sizeof(BeatmapEditorSceneSetupData) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapEditorSceneSetupData*, "", "BeatmapEditorSceneSetupData");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::get_levelDirPath
// Il2CppName: get_levelDirPath
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::BeatmapEditorSceneSetupData::*)()>(&GlobalNamespace::BeatmapEditorSceneSetupData::get_levelDirPath)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapEditorSceneSetupData*), "get_levelDirPath", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::get_levelAssetPath
// Il2CppName: get_levelAssetPath
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::BeatmapEditorSceneSetupData::*)()>(&GlobalNamespace::BeatmapEditorSceneSetupData::get_levelAssetPath)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapEditorSceneSetupData*), "get_levelAssetPath", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 55.728395
| 208
| 0.746566
|
Fernthedev
|
12f3fcf8b2653271ac4021d0de49448b66472c07
| 17,881
|
cpp
|
C++
|
OpenXaml/XamlObjects/TextBlock.cpp
|
benroywillis/OpenXaml
|
a6313c096b5221344ee2dbcfe6e5a4db8345115c
|
[
"MIT"
] | 1
|
2019-09-23T03:11:04.000Z
|
2019-09-23T03:11:04.000Z
|
OpenXaml/XamlObjects/TextBlock.cpp
|
benroywillis/OpenXaml
|
a6313c096b5221344ee2dbcfe6e5a4db8345115c
|
[
"MIT"
] | null | null | null |
OpenXaml/XamlObjects/TextBlock.cpp
|
benroywillis/OpenXaml
|
a6313c096b5221344ee2dbcfe6e5a4db8345115c
|
[
"MIT"
] | 2
|
2019-11-03T01:12:22.000Z
|
2022-03-07T16:59:32.000Z
|
#include "OpenXaml/XamlObjects/TextBlock.h"
#include "OpenXaml/Environment/Environment.h"
#include "OpenXaml/Environment/Window.h"
#include "OpenXaml/GL/GLConfig.h"
#include "OpenXaml/Properties/Alignment.h"
#include "OpenXaml/Properties/TextWrapping.h"
#include <algorithm>
#include <codecvt>
#include <glad/glad.h>
#include <harfbuzz/hb.h>
#include <iostream>
#include <locale>
#include <cmath>
#include <sstream>
#include <string>
#include <utility>
using namespace std;
namespace OpenXaml::Objects
{
void TextBlock::Draw()
{
glBindVertexArray(TextBlock::VAO);
glUseProgram(GL::xamlShader);
int vertexColorLocation = glGetUniformLocation(GL::xamlShader, "thecolor");
int modeLoc = glGetUniformLocation(GL::xamlShader, "mode");
glUniform4f(vertexColorLocation, 0.0F, 0.0F, 0.0F, 1.0F);
glUniform1i(modeLoc, 2);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, edgeBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBindTexture(GL_TEXTURE_2D, font->getFontAtlasTexture());
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)(2 * sizeof(float)));
glDrawElements(GL_TRIANGLES, 6 * glyphCount, GL_UNSIGNED_SHORT, nullptr);
}
void TextBlock::Initialize()
{
glGenVertexArrays(1, &(TextBlock::VAO));
glBindVertexArray(TextBlock::VAO);
glGenBuffers(1, &edgeBuffer);
glGenBuffers(1, &vertexBuffer);
Update();
}
void TextBlock::Update()
{
XamlObject::Update();
font = Environment::GetFont(FontProperties{FontFamily, FontSize});
if (font == nullptr)
{
return;
}
vector<size_t> indexes;
for (size_t i = 0; i < Text.size(); i++)
{
char32_t a = Text.at(i);
if (a == U'\n')
{
indexes.push_back(i);
}
}
float wordWidth = 0; //width of current word
size_t currentIndex = 0;
int lineCount = 0; //number of lines
float width = 0; //width of current line
float maxWidth = 0; //max line width
size_t charsToRender = 0;
float fBounds = (localMax.x - localMin.x);
vector<u32string> splitStrings;
for (uint32_t i = 0; i < indexes.size() + 1; i++)
{
size_t index = i == indexes.size() ? Text.size() : indexes.at(i);
u32string subString = Text.substr(currentIndex, index - currentIndex);
if (i < indexes.size())
{
currentIndex = indexes.at(i) + 1;
}
//we should render this line
auto formattedText = font->FormatText(subString);
for (auto character : formattedText)
{
wordWidth += character.xAdvance;
if (font->IsSeperator(character.Character))
{
if (TextWrapping != TextWrapping::NoWrap && width + wordWidth > fBounds)
{
lineCount++;
maxWidth = std::max(maxWidth, width);
width = wordWidth;
wordWidth = 0;
}
else
{
width += wordWidth;
wordWidth = 0;
}
}
}
//we now know the number of lines in this 'line' as well as its width, so increment and set the width
lineCount++;
maxWidth = std::max(maxWidth, wordWidth);
charsToRender += formattedText.size();
}
maxWidth = std::max(maxWidth, width);
//we now know the true number of lines and the true width
//so we can start rendering
if (charsToRender == 0)
{
lineCount = 0;
//return;
}
auto *vBuffer = (float *)calloc(16 * charsToRender, sizeof(float));
auto *eBuffer = (unsigned short *)calloc(6 * charsToRender, sizeof(unsigned short));
wordWidth = 0;
width = 0;
int height = (font->Height >> 6);
float fWidth = maxWidth;
float fHeight = height * lineCount;
switch (VerticalAlignment)
{
case VerticalAlignment::Bottom:
{
minRendered.y = localMin.y;
maxRendered.y = min(localMax.y, localMin.y + fHeight);
break;
}
case VerticalAlignment::Top:
{
maxRendered.y = localMax.y;
minRendered.y = max(localMin.y, localMax.y - fHeight);
break;
}
case VerticalAlignment::Center:
{
float mean = 0.5F * (localMax.y + localMin.y);
maxRendered.y = min(localMax.y, mean + fHeight / 2);
minRendered.y = max(localMin.y, mean - fHeight / 2);
break;
}
case VerticalAlignment::Stretch:
{
maxRendered.y = localMax.y;
minRendered.y = localMin.y;
break;
}
}
switch (HorizontalAlignment)
{
case HorizontalAlignment::Left:
{
minRendered.x = localMin.x;
maxRendered.x = min(localMax.x, localMin.x + fWidth);
break;
}
case HorizontalAlignment::Right:
{
maxRendered.x = localMax.x;
minRendered.x = max(localMin.x, localMax.x - fWidth);
break;
}
case HorizontalAlignment::Center:
{
float mean = 0.5F * (localMax.x + localMin.x);
maxRendered.x = min(localMax.x, mean + fWidth / 2);
minRendered.x = max(localMin.x, mean - fWidth / 2);
break;
}
case HorizontalAlignment::Stretch:
{
maxRendered.x = localMax.x;
minRendered.x = localMin.x;
break;
}
}
int arrayIndex = 0;
float penX;
float penY = maxRendered.y - (height - (font->VerticalOffset >> 6));
currentIndex = 0;
for (uint32_t i = 0; i < indexes.size() + 1; i++)
{
int priorIndex = 0;
int ppIndex = 0;
size_t index = i == indexes.size() ? Text.size() : indexes.at(i);
u32string subString = Text.substr(currentIndex, index - currentIndex);
if (i < indexes.size())
{
currentIndex = indexes.at(i) + 1;
}
auto formattedText = font->FormatText(subString);
int k = 0;
for (auto character : formattedText)
{
wordWidth += character.xAdvance;
if (font->IsSeperator(character.Character))
{
if (TextWrapping != TextWrapping::NoWrap && width + wordWidth > fBounds)
{
switch (TextAlignment)
{
case TextAlignment::Center:
{
penX = (minRendered.x + maxRendered.x) * 0.5F - width * 0.5F;
break;
}
case TextAlignment::End:
{
penX = (maxRendered.x) - width;
break;
}
case TextAlignment::Start:
{
penX = minRendered.x;
break;
}
}
for (int j = priorIndex; j < ppIndex + 1; j++)
{
if (penX > localMax.x)
{
break;
}
RenderCharacter(formattedText.at(j), penX, penY, vBuffer, eBuffer, arrayIndex);
}
priorIndex = ++ppIndex;
penY -= height;
if (penY < localMin.y - height)
{
break;
}
width = wordWidth;
}
else
{
width += wordWidth;
}
wordWidth = 0;
ppIndex = k;
}
k++;
}
switch (TextAlignment)
{
case TextAlignment::Center:
{
penX = (minRendered.x + maxRendered.x) * 0.5F - wordWidth * 0.5F;
break;
}
case TextAlignment::End:
{
penX = (maxRendered.x) - width;
break;
}
case TextAlignment::Start:
{
penX = minRendered.x;
break;
}
}
for (uint32_t j = priorIndex; j < formattedText.size(); j++)
{
if (penX > localMax.x)
{
break;
}
RenderCharacter(formattedText.at(j), penX, penY, vBuffer, eBuffer, arrayIndex);
}
penY -= height;
width = 0;
}
boxWidth = (maxRendered.x - minRendered.x);
boxHeight = (maxRendered.y - minRendered.y);
glBindVertexArray(TextBlock::VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, edgeBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * (size_t)arrayIndex * sizeof(unsigned short), eBuffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 16 * (size_t)arrayIndex * sizeof(float), vBuffer, GL_STATIC_DRAW);
std::free(eBuffer);
std::free(vBuffer);
glyphCount = arrayIndex;
}
void TextBlock::RenderCharacter(UChar ch, float &penX, float &penY, float *vertexBuffer, unsigned short *edgeBuffer, int &index)
{
auto uchar = font->GlyphMap[ch.Character];
float x0;
float x1;
float y0;
float y1;
float tx0;
float tx1;
float ty0;
float ty1;
float dx0;
float dx1;
float dy0;
float dy1;
dx0 = penX + (ch.xOffset + uchar.xBearingH);
dx1 = dx0 + uchar.width;
dy1 = penY + (ch.yOffset + uchar.yBearingH);
dy0 = dy1 - uchar.height;
x0 = clamp(dx0, localMin.x, localMax.x);
x1 = clamp(dx1, localMin.x, localMax.x);
y0 = clamp(dy0, localMin.y, localMax.y);
y1 = clamp(dy1, localMin.y, localMax.y);
float dwidth = dx1 - dx0;
float dheight = dy1 - dy0;
auto textureLoc = font->GlyphMap[ch.Character];
//handle the font textures, note that they are upside down
if (x0 != dx0)
{
//we are missing part of the left
tx0 = textureLoc.txMax - (textureLoc.txMax - textureLoc.txMin) * (x1 - x0) / dwidth;
}
else
{
tx0 = textureLoc.txMin;
}
if (x1 != dx1)
{
//we are missing part of the right
tx1 = textureLoc.txMin + (textureLoc.txMax - textureLoc.txMin) * (x1 - x0) / dwidth;
}
else
{
tx1 = textureLoc.txMax;
}
if (y0 != dy0)
{
//we are missing part of the bottom
ty0 = textureLoc.tyMax - (textureLoc.tyMax - textureLoc.tyMin) * (y1 - y0) / dheight;
}
else
{
ty0 = textureLoc.tyMin;
}
if (y1 != dy1)
{
//we are missing part of the bottom
ty1 = textureLoc.tyMin + (textureLoc.tyMax - textureLoc.tyMin) * (y1 - y0) / dheight;
}
else
{
ty1 = textureLoc.tyMax;
}
vertexBuffer[16 * index + 0] = x0;
vertexBuffer[16 * index + 1] = y1;
vertexBuffer[16 * index + 2] = tx0;
vertexBuffer[16 * index + 3] = ty1;
vertexBuffer[16 * index + 4] = x1;
vertexBuffer[16 * index + 5] = y1;
vertexBuffer[16 * index + 6] = tx1;
vertexBuffer[16 * index + 7] = ty1;
vertexBuffer[16 * index + 8] = x0;
vertexBuffer[16 * index + 9] = y0;
vertexBuffer[16 * index + 10] = tx0;
vertexBuffer[16 * index + 11] = ty0;
vertexBuffer[16 * index + 12] = x1;
vertexBuffer[16 * index + 13] = y0;
vertexBuffer[16 * index + 14] = tx1;
vertexBuffer[16 * index + 15] = ty0;
edgeBuffer[6 * index + 0] = 0 + 4 * index;
edgeBuffer[6 * index + 1] = 1 + 4 * index;
edgeBuffer[6 * index + 2] = 2 + 4 * index;
edgeBuffer[6 * index + 3] = 1 + 4 * index;
edgeBuffer[6 * index + 4] = 2 + 4 * index;
edgeBuffer[6 * index + 5] = 3 + 4 * index;
index++;
penX += ch.xAdvance;
penY -= ch.yAdvance;
}
TextBlock::TextBlock()
{
boxHeight = 0;
boxWidth = 0;
edgeBuffer = 0;
vertexBuffer = 0;
font = nullptr;
}
TextBlock::~TextBlock()
{
//glBindVertexArray(TextBlock::VAO);
//glDeleteVertexArrays(1, &TextBlock::VAO);
XamlObject::~XamlObject();
}
void TextBlock::setText(u32string text)
{
this->Text = std::move(text);
}
u32string TextBlock::getText()
{
return this->Text;
}
void TextBlock::setText(const string &text)
{
std::wstring_convert<codecvt_utf8<char32_t>, char32_t> conv;
this->Text = conv.from_bytes(text);
}
void TextBlock::setTextWrapping(OpenXaml::TextWrapping textWrapping)
{
this->TextWrapping = textWrapping;
}
TextWrapping TextBlock::getTextWrapping()
{
return this->TextWrapping;
}
void TextBlock::setFontFamily(string family)
{
this->FontFamily = std::move(family);
}
string TextBlock::getFontFamily()
{
return this->FontFamily;
}
void TextBlock::setFontSize(float size)
{
this->FontSize = size;
}
float TextBlock::getFontSize() const
{
return this->FontSize;
}
void TextBlock::setFill(unsigned int fill)
{
this->Fill = fill;
}
unsigned int TextBlock::getFill() const
{
return this->Fill;
}
void TextBlock::setTextAlignment(OpenXaml::TextAlignment alignment)
{
this->TextAlignment = alignment;
}
TextAlignment TextBlock::getTextAlignment()
{
return this->TextAlignment;
}
int TextBlock::getWidth()
{
return std::ceil(max(this->Width, this->boxWidth));
}
int TextBlock::getHeight()
{
return std::ceil(max(this->Height, this->boxHeight));
}
vec2<float> TextBlock::getDesiredDimensions()
{
if (font == nullptr)
{
font = Environment::GetFont(FontProperties{FontFamily, FontSize});
}
vec2<float> result = {0, 0};
vector<size_t> indexes;
for (size_t i = 0; i < Text.size(); i++)
{
char32_t a = Text.at(i);
if (a == U'\n')
{
indexes.push_back(i);
}
}
float wordWidth = 0; //width of current word
size_t currentIndex = 0;
int lineCount = 0; //number of lines
float width = 0; //width of current line
float maxWidth = 0; //max line width
size_t charsToRender = 0;
vector<u32string> splitStrings;
for (uint32_t i = 0; i < indexes.size() + 1; i++)
{
size_t index = i == indexes.size() ? Text.size() : indexes.at(i);
u32string subString = Text.substr(currentIndex, index - currentIndex);
if (i < indexes.size())
{
currentIndex = indexes.at(i) + 1;
}
//we should render this line
auto formattedText = font->FormatText(subString);
for (auto character : formattedText)
{
wordWidth += character.xAdvance;
if (font->IsSeperator(character.Character))
{
width += wordWidth;
wordWidth = 0;
}
}
//we now know the number of lines in this 'line' as well as its width, so increment and set the width
lineCount++;
maxWidth = std::max(maxWidth, wordWidth);
charsToRender += formattedText.size();
}
maxWidth = std::max(maxWidth, width);
result.x = std::ceil(maxWidth);
result.y = lineCount * (font->Height >> 6);
return result;
}
} // namespace OpenXaml::Objects
| 34.189293
| 133
| 0.472904
|
benroywillis
|
12f46b29d5676b69947ac6fcd389eb7817116c7a
| 17,917
|
cpp
|
C++
|
export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp
|
seanbashaw/frozenlight
|
47c540d30d63e946ea2dc787b4bb602cc9347d21
|
[
"MIT"
] | null | null | null |
export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp
|
seanbashaw/frozenlight
|
47c540d30d63e946ea2dc787b4bb602cc9347d21
|
[
"MIT"
] | null | null | null |
export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp
|
seanbashaw/frozenlight
|
47c540d30d63e946ea2dc787b4bb602cc9347d21
|
[
"MIT"
] | null | null | null |
// Generated by Haxe 3.4.7
#include <hxcpp.h>
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime_utils_Log
#include <lime/utils/Log.h>
#endif
#ifndef INCLUDED_openfl__internal_stage3D_atf_ATFReader
#include <openfl/_internal/stage3D/atf/ATFReader.h>
#endif
#ifndef INCLUDED_openfl_errors_Error
#include <openfl/errors/Error.h>
#endif
#ifndef INCLUDED_openfl_errors_IllegalOperationError
#include <openfl/errors/IllegalOperationError.h>
#endif
#ifndef INCLUDED_openfl_utils_ByteArrayData
#include <openfl/utils/ByteArrayData.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataInput
#include <openfl/utils/IDataInput.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataOutput
#include <openfl/utils/IDataOutput.h>
#endif
#ifndef INCLUDED_openfl_utils__ByteArray_ByteArray_Impl_
#include <openfl/utils/_ByteArray/ByteArray_Impl_.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_9e15a0b592410441_30_new,"openfl._internal.stage3D.atf.ATFReader","new",0x0b38c27e,"openfl._internal.stage3D.atf.ATFReader.new","openfl/_internal/stage3D/atf/ATFReader.hx",30,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_82_readHeader,"openfl._internal.stage3D.atf.ATFReader","readHeader",0x33e29b25,"openfl._internal.stage3D.atf.ATFReader.readHeader","openfl/_internal/stage3D/atf/ATFReader.hx",82,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_126_readTextures,"openfl._internal.stage3D.atf.ATFReader","readTextures",0x07ab1ed0,"openfl._internal.stage3D.atf.ATFReader.readTextures","openfl/_internal/stage3D/atf/ATFReader.hx",126,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_163___readUInt24,"openfl._internal.stage3D.atf.ATFReader","__readUInt24",0xb1c572f4,"openfl._internal.stage3D.atf.ATFReader.__readUInt24","openfl/_internal/stage3D/atf/ATFReader.hx",163,0x63888776)
HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_174___readUInt32,"openfl._internal.stage3D.atf.ATFReader","__readUInt32",0xb1c573d1,"openfl._internal.stage3D.atf.ATFReader.__readUInt32","openfl/_internal/stage3D/atf/ATFReader.hx",174,0x63888776)
namespace openfl{
namespace _internal{
namespace stage3D{
namespace atf{
void ATFReader_obj::__construct( ::openfl::utils::ByteArrayData data,int byteArrayOffset){
HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_30_new)
HXLINE( 38) this->version = (int)0;
HXLINE( 44) data->position = byteArrayOffset;
HXLINE( 45) ::String signature = data->readUTFBytes((int)3);
HXLINE( 46) data->position = byteArrayOffset;
HXLINE( 48) if ((signature != HX_("ATF",f3,9b,31,00))) {
HXLINE( 50) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF signature not found",a0,f7,2f,3a)));
}
HXLINE( 54) int length = (int)0;
HXLINE( 57) if ((data->b->__get((byteArrayOffset + (int)6)) == (int)255)) {
HXLINE( 59) this->version = data->b->__get((byteArrayOffset + (int)7));
HXLINE( 60) data->position = (byteArrayOffset + (int)8);
HXLINE( 61) length = this->_hx___readUInt32(data);
}
else {
HXLINE( 65) this->version = (int)0;
HXLINE( 66) data->position = (byteArrayOffset + (int)3);
HXLINE( 67) length = this->_hx___readUInt24(data);
}
HXLINE( 71) int _hx_tmp = (byteArrayOffset + length);
HXDLIN( 71) if ((_hx_tmp > ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(data))) {
HXLINE( 73) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF length exceeds byte array length",d7,29,45,0f)));
}
HXLINE( 77) this->data = data;
}
Dynamic ATFReader_obj::__CreateEmpty() { return new ATFReader_obj; }
void *ATFReader_obj::_hx_vtable = 0;
Dynamic ATFReader_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< ATFReader_obj > _hx_result = new ATFReader_obj();
_hx_result->__construct(inArgs[0],inArgs[1]);
return _hx_result;
}
bool ATFReader_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x687242c6;
}
bool ATFReader_obj::readHeader(int _hx___width,int _hx___height,bool cubeMap){
HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_82_readHeader)
HXLINE( 84) int tdata = this->data->readUnsignedByte();
HXLINE( 85) int type = ((int)tdata >> (int)(int)7);
HXLINE( 87) bool _hx_tmp;
HXDLIN( 87) if (!(cubeMap)) {
HXLINE( 87) _hx_tmp = (type != (int)0);
}
else {
HXLINE( 87) _hx_tmp = false;
}
HXDLIN( 87) if (_hx_tmp) {
HXLINE( 89) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map not expected",a7,74,ca,c8)));
}
HXLINE( 93) bool _hx_tmp1;
HXDLIN( 93) if (cubeMap) {
HXLINE( 93) _hx_tmp1 = (type != (int)1);
}
else {
HXLINE( 93) _hx_tmp1 = false;
}
HXDLIN( 93) if (_hx_tmp1) {
HXLINE( 95) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map expected",fa,fe,ed,52)));
}
HXLINE( 99) this->cubeMap = cubeMap;
HXLINE( 101) this->atfFormat = ((int)tdata & (int)(int)127);
HXLINE( 104) bool _hx_tmp2;
HXDLIN( 104) if ((this->atfFormat != (int)3)) {
HXLINE( 104) _hx_tmp2 = (this->atfFormat != (int)5);
}
else {
HXLINE( 104) _hx_tmp2 = false;
}
HXDLIN( 104) if (_hx_tmp2) {
HXLINE( 106) ::lime::utils::Log_obj::warn(HX_("Only ATF block compressed textures without JPEG-XR+LZMA are supported",25,8c,50,6a),hx::SourceInfo(HX_("ATFReader.hx",e8,b6,75,e1),106,HX_("openfl._internal.stage3D.atf.ATFReader",8c,6b,52,5f),HX_("readHeader",83,ed,7b,f6)));
}
HXLINE( 110) this->width = ((int)(int)1 << (int)this->data->readUnsignedByte());
HXLINE( 111) this->height = ((int)(int)1 << (int)this->data->readUnsignedByte());
HXLINE( 113) bool _hx_tmp3;
HXDLIN( 113) if ((this->width == _hx___width)) {
HXLINE( 113) _hx_tmp3 = (this->height != _hx___height);
}
else {
HXLINE( 113) _hx_tmp3 = true;
}
HXDLIN( 113) if (_hx_tmp3) {
HXLINE( 115) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF width and height dont match",3f,49,15,70)));
}
HXLINE( 119) this->mipCount = this->data->readUnsignedByte();
HXLINE( 121) return (this->atfFormat == (int)5);
}
HX_DEFINE_DYNAMIC_FUNC3(ATFReader_obj,readHeader,return )
void ATFReader_obj::readTextures( ::Dynamic uploadCallback){
HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_126_readTextures)
HXLINE( 130) int gpuFormats;
HXDLIN( 130) if ((this->version < (int)3)) {
HXLINE( 130) gpuFormats = (int)3;
}
else {
HXLINE( 130) gpuFormats = (int)4;
}
HXLINE( 131) int sideCount;
HXDLIN( 131) if (this->cubeMap) {
HXLINE( 131) sideCount = (int)6;
}
else {
HXLINE( 131) sideCount = (int)1;
}
HXLINE( 133) {
HXLINE( 133) int _g1 = (int)0;
HXDLIN( 133) int _g = sideCount;
HXDLIN( 133) while((_g1 < _g)){
HXLINE( 133) _g1 = (_g1 + (int)1);
HXDLIN( 133) int side = (_g1 - (int)1);
HXLINE( 134) {
HXLINE( 134) int _g3 = (int)0;
HXDLIN( 134) int _g2 = this->mipCount;
HXDLIN( 134) while((_g3 < _g2)){
HXLINE( 134) _g3 = (_g3 + (int)1);
HXDLIN( 134) int level = (_g3 - (int)1);
HXLINE( 136) {
HXLINE( 136) int _g5 = (int)0;
HXDLIN( 136) int _g4 = gpuFormats;
HXDLIN( 136) while((_g5 < _g4)){
HXLINE( 136) _g5 = (_g5 + (int)1);
HXDLIN( 136) int gpuFormat = (_g5 - (int)1);
HXLINE( 138) int blockLength;
HXDLIN( 138) if ((this->version == (int)0)) {
HXLINE( 138) blockLength = this->_hx___readUInt24(this->data);
}
else {
HXLINE( 138) blockLength = this->_hx___readUInt32(this->data);
}
HXLINE( 140) int a = (this->data->position + blockLength);
HXDLIN( 140) int b = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(this->data);
HXDLIN( 140) bool aNeg = (a < (int)0);
HXDLIN( 140) bool bNeg = (b < (int)0);
HXDLIN( 140) bool _hx_tmp;
HXDLIN( 140) if ((aNeg != bNeg)) {
HXLINE( 140) _hx_tmp = aNeg;
}
else {
HXLINE( 140) _hx_tmp = (a > b);
}
HXDLIN( 140) if (_hx_tmp) {
HXLINE( 142) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("Block length exceeds ATF file length",15,23,c0,24)));
}
HXLINE( 146) bool aNeg1 = (blockLength < (int)0);
HXDLIN( 146) bool bNeg1 = ((int)0 < (int)0);
HXDLIN( 146) bool _hx_tmp1;
HXDLIN( 146) if ((aNeg1 != bNeg1)) {
HXLINE( 146) _hx_tmp1 = aNeg1;
}
else {
HXLINE( 146) _hx_tmp1 = (blockLength > (int)0);
}
HXDLIN( 146) if (_hx_tmp1) {
HXLINE( 148) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(blockLength);
HXLINE( 149) ::openfl::utils::ByteArrayData _hx_tmp2 = this->data;
HXDLIN( 149) _hx_tmp2->readBytes(::openfl::utils::_ByteArray::ByteArray_Impl__obj::fromArrayBuffer(bytes),(int)0,blockLength);
HXLINE( 151) int _hx_tmp3 = ((int)this->width >> (int)level);
HXDLIN( 151) uploadCallback(side,level,gpuFormat,_hx_tmp3,((int)this->height >> (int)level),blockLength,bytes);
}
}
}
}
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,readTextures,(void))
int ATFReader_obj::_hx___readUInt24( ::openfl::utils::ByteArrayData data){
HX_STACKFRAME(&_hx_pos_9e15a0b592410441_163___readUInt24)
HXLINE( 165) int value = ((int)data->readUnsignedByte() << (int)(int)16);
HXLINE( 167) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)8));
HXLINE( 168) value = ((int)value | (int)data->readUnsignedByte());
HXLINE( 169) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt24,return )
int ATFReader_obj::_hx___readUInt32( ::openfl::utils::ByteArrayData data){
HX_STACKFRAME(&_hx_pos_9e15a0b592410441_174___readUInt32)
HXLINE( 176) int value = ((int)data->readUnsignedByte() << (int)(int)24);
HXLINE( 178) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)16));
HXLINE( 179) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)8));
HXLINE( 180) value = ((int)value | (int)data->readUnsignedByte());
HXLINE( 181) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt32,return )
hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__new( ::openfl::utils::ByteArrayData data,int byteArrayOffset) {
hx::ObjectPtr< ATFReader_obj > __this = new ATFReader_obj();
__this->__construct(data,byteArrayOffset);
return __this;
}
hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__alloc(hx::Ctx *_hx_ctx, ::openfl::utils::ByteArrayData data,int byteArrayOffset) {
ATFReader_obj *__this = (ATFReader_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ATFReader_obj), true, "openfl._internal.stage3D.atf.ATFReader"));
*(void **)__this = ATFReader_obj::_hx_vtable;
__this->__construct(data,byteArrayOffset);
return __this;
}
ATFReader_obj::ATFReader_obj()
{
}
void ATFReader_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(ATFReader);
HX_MARK_MEMBER_NAME(atfFormat,"atfFormat");
HX_MARK_MEMBER_NAME(cubeMap,"cubeMap");
HX_MARK_MEMBER_NAME(data,"data");
HX_MARK_MEMBER_NAME(height,"height");
HX_MARK_MEMBER_NAME(mipCount,"mipCount");
HX_MARK_MEMBER_NAME(version,"version");
HX_MARK_MEMBER_NAME(width,"width");
HX_MARK_END_CLASS();
}
void ATFReader_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(atfFormat,"atfFormat");
HX_VISIT_MEMBER_NAME(cubeMap,"cubeMap");
HX_VISIT_MEMBER_NAME(data,"data");
HX_VISIT_MEMBER_NAME(height,"height");
HX_VISIT_MEMBER_NAME(mipCount,"mipCount");
HX_VISIT_MEMBER_NAME(version,"version");
HX_VISIT_MEMBER_NAME(width,"width");
}
hx::Val ATFReader_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"data") ) { return hx::Val( data ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { return hx::Val( width ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { return hx::Val( height ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"cubeMap") ) { return hx::Val( cubeMap ); }
if (HX_FIELD_EQ(inName,"version") ) { return hx::Val( version ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"mipCount") ) { return hx::Val( mipCount ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"atfFormat") ) { return hx::Val( atfFormat ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"readHeader") ) { return hx::Val( readHeader_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"readTextures") ) { return hx::Val( readTextures_dyn() ); }
if (HX_FIELD_EQ(inName,"__readUInt24") ) { return hx::Val( _hx___readUInt24_dyn() ); }
if (HX_FIELD_EQ(inName,"__readUInt32") ) { return hx::Val( _hx___readUInt32_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
hx::Val ATFReader_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"data") ) { data=inValue.Cast< ::openfl::utils::ByteArrayData >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { width=inValue.Cast< int >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"cubeMap") ) { cubeMap=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"version") ) { version=inValue.Cast< int >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"mipCount") ) { mipCount=inValue.Cast< int >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"atfFormat") ) { atfFormat=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void ATFReader_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c"));
outFields->push(HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c"));
outFields->push(HX_HCSTRING("data","\x2a","\x56","\x63","\x42"));
outFields->push(HX_HCSTRING("height","\xe7","\x07","\x4c","\x02"));
outFields->push(HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e"));
outFields->push(HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c"));
outFields->push(HX_HCSTRING("width","\x06","\xb6","\x62","\xca"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo ATFReader_obj_sMemberStorageInfo[] = {
{hx::fsInt,(int)offsetof(ATFReader_obj,atfFormat),HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c")},
{hx::fsBool,(int)offsetof(ATFReader_obj,cubeMap),HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c")},
{hx::fsObject /*::openfl::utils::ByteArrayData*/ ,(int)offsetof(ATFReader_obj,data),HX_HCSTRING("data","\x2a","\x56","\x63","\x42")},
{hx::fsInt,(int)offsetof(ATFReader_obj,height),HX_HCSTRING("height","\xe7","\x07","\x4c","\x02")},
{hx::fsInt,(int)offsetof(ATFReader_obj,mipCount),HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e")},
{hx::fsInt,(int)offsetof(ATFReader_obj,version),HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c")},
{hx::fsInt,(int)offsetof(ATFReader_obj,width),HX_HCSTRING("width","\x06","\xb6","\x62","\xca")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *ATFReader_obj_sStaticStorageInfo = 0;
#endif
static ::String ATFReader_obj_sMemberFields[] = {
HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c"),
HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c"),
HX_HCSTRING("data","\x2a","\x56","\x63","\x42"),
HX_HCSTRING("height","\xe7","\x07","\x4c","\x02"),
HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e"),
HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c"),
HX_HCSTRING("width","\x06","\xb6","\x62","\xca"),
HX_HCSTRING("readHeader","\x83","\xed","\x7b","\xf6"),
HX_HCSTRING("readTextures","\xae","\x44","\x04","\xa1"),
HX_HCSTRING("__readUInt24","\xd2","\x98","\x1e","\x4b"),
HX_HCSTRING("__readUInt32","\xaf","\x99","\x1e","\x4b"),
::String(null()) };
static void ATFReader_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(ATFReader_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void ATFReader_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(ATFReader_obj::__mClass,"__mClass");
};
#endif
hx::Class ATFReader_obj::__mClass;
void ATFReader_obj::__register()
{
hx::Object *dummy = new ATFReader_obj;
ATFReader_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl._internal.stage3D.atf.ATFReader","\x8c","\x6b","\x52","\x5f");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = ATFReader_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(ATFReader_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< ATFReader_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = ATFReader_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ATFReader_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ATFReader_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace _internal
} // end namespace stage3D
} // end namespace atf
| 41.86215
| 274
| 0.673718
|
seanbashaw
|
12f5591da05d6c59955f5a184bef2c6547d7eee4
| 1,465
|
cpp
|
C++
|
gym/100283/I.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | 1
|
2021-07-16T19:59:39.000Z
|
2021-07-16T19:59:39.000Z
|
gym/100283/I.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | null | null | null |
gym/100283/I.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#ifdef Adrian
#include "debug.h"
#else
#define debug(...)
#endif
typedef long long ll;
typedef long double ld;
typedef complex<ll> point;
#define F first
#define S second
const double EPS=1e-8,oo=1e9;
struct fraction
{
ll x,y;
fraction(ll _x, ll _y)
{
ll g = __gcd(_x,_y);
x = _x / g;
y = _y / g;
}
bool operator <(const fraction other)const
{
return x * other.y < y * other.x;
}
fraction operator -(fraction other)
{
return fraction(other.y * x - other.x * y, y * other.y);
}
fraction operator +(fraction other)
{
return fraction(other.y * x + other.x * y, y * other.y);
}
void print()
{
cout<<x<<"/"<<y<<'\n';
}
};
void generate(vector<fraction> &v, ll pos, fraction f)
{
if(f.x != 0)
v.push_back(f);
if(pos == 14) return;
for(ll i = 0; i<pos; i++)
{
fraction temp = f + fraction(i,pos);
if(temp < fraction(1,1))
generate(v, pos + 1, temp);
}
}
int main()
{
freopen("zanzibar.in", "r", stdin);
ios_base::sync_with_stdio(0), cin.tie(0);
vector<fraction> v;
generate(v, 2, fraction(0, 1));
v.push_back(fraction(1,1));
v.push_back(fraction(0,1));
sort(v.begin(), v.end());
int t;
cin>>t;
for(int c = 1; c<=t; c++)
{
ll x,y;
cin>>x>>y;
fraction f(x,y);
int pos = lower_bound(v.begin(), v.end(), f) - v.begin();
fraction ans = v[pos] - f;
if(pos != 0)
ans = min(ans, f - v[pos - 1]);
cout<<"Case "<<c<<": ";
ans.print();
}
return 0;
}
| 16.647727
| 59
| 0.585666
|
albexl
|
12fa797a258ef128ff053fdf0cdc7bb9d06a08bc
| 4,803
|
hpp
|
C++
|
test_interface.hpp
|
Anadani/oop4
|
133508256b02dd3cd45569b51cea2367cf880c7a
|
[
"MIT"
] | null | null | null |
test_interface.hpp
|
Anadani/oop4
|
133508256b02dd3cd45569b51cea2367cf880c7a
|
[
"MIT"
] | null | null | null |
test_interface.hpp
|
Anadani/oop4
|
133508256b02dd3cd45569b51cea2367cf880c7a
|
[
"MIT"
] | null | null | null |
#ifndef TEST_INTERFACE_HPP
#define TEST_INTERFACE_HPP
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
#include <sstream>
#include "tests.hpp"
#include "Money.hpp"
#include "HotdogStand.hpp"
void TEST_INSERTION(bool sign);
void TEST_EXTRACTION(bool dSign);
void runTests()
{
using std::cout;
using std::left;
using std::setw;
using std::endl;
namespace MAB = MyAwesomeBusiness;
char prev = cout.fill('.');
cout << "Money Class Tests\n";
cout << setw(40) << left << "Negative (+ -> -)" << (IS_EQUAL(-550, (-(MAB::Money(5.50)).getPennies()))) << endl;
cout << setw(40) << left << "Negative (- -> +)" << (IS_EQUAL(550, (-(MAB::Money(-5.50)).getPennies()))) << endl;
cout << setw(40) << left << "Equality (T)" << (EXPECT_TRUE((MAB::Money(6) == MAB::Money(6)))) << endl;
cout << setw(40) << left << "Equality (F)" << (EXPECT_FALSE((MAB::Money(6) == MAB::Money(2)))) << endl;
cout << setw(40) << left << "Prefix++" << (IS_EQUAL(MAB::Money(6), ++(MAB::Money(5)))) << endl;
cout << setw(40) << left << "Postfix++" << (IS_EQUAL(MAB::Money(5), (MAB::Money(5))++)) << endl;
cout << setw(40) << left << "Prefix--" << (IS_EQUAL(MAB::Money(6), --(MAB::Money(7)))) << endl;
cout << setw(40) << left << "Postfix--" << (IS_EQUAL(MAB::Money(6), (MAB::Money(6))--)) << endl;
cout << setw(40) << left << "Addition" << (IS_EQUAL(MAB::Money(7), (MAB::Money(2.5) + MAB::Money(4, 50)))) << endl;
cout << setw(40) << left << "Multiplication (Money x int)" << (IS_EQUAL(MAB::Money(11), (MAB::Money(2.75) * 4))) << endl;
cout << setw(40) << left << "Multiplication (int x Money)" << (IS_EQUAL(MAB::Money(11), (4 * MAB::Money(2.75)))) << endl;
cout << setw(40) << left << "Multiplication (Money x double)" << (IS_EQUAL(MAB::Money(2.75), (MAB::Money(11) * 0.25))) << endl;
cout << setw(40) << left << "Multiplication (double x Money)" << (IS_EQUAL(MAB::Money(2.75), (0.25 * MAB::Money(11)))) << endl;
cout << setw(40) << left << "Less Than (T)" << (EXPECT_TRUE((MAB::Money(1) < MAB::Money(6)))) << endl;
cout << setw(40) << left << "Less Than (F)" << (EXPECT_FALSE((MAB::Money(10) < MAB::Money(2)))) << endl;
cout << setw(40) << left << "Less Than (F, ==)" << (EXPECT_FALSE((MAB::Money(2) < MAB::Money(2)))) << endl;
cout << setw(40) << left << "Less Than or Equal (T)" << (EXPECT_TRUE((MAB::Money(6) <= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Less Than or Equal (T, ==)" << (EXPECT_TRUE((MAB::Money(6) <= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Less Than or Equal (F)" << (EXPECT_FALSE((MAB::Money(6) <= MAB::Money(2)))) << endl;
cout << setw(40) << left << "Greater Than (T)" << (EXPECT_TRUE((MAB::Money(6) > MAB::Money(4)))) << endl;
cout << setw(40) << left << "Greater Than (F)" << (EXPECT_FALSE((MAB::Money(2) > MAB::Money(6)))) << endl;
cout << setw(40) << left << "Greater Than (F, ==)" << (EXPECT_FALSE((MAB::Money(6) > MAB::Money(6)))) << endl;
cout << setw(40) << left << "Greater Than or Equal (T)" << (EXPECT_TRUE((MAB::Money(6) >= MAB::Money(5)))) << endl;
cout << setw(40) << left << "Greater Than or Equal (T, ==)" << (EXPECT_TRUE((MAB::Money(6) >= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Greater Than or Equal (F)" << (EXPECT_FALSE((MAB::Money(2) >= MAB::Money(6)))) << endl;
cout << setw(40) << left << "Inequality (T)" << (EXPECT_TRUE((MAB::Money(2) != MAB::Money(6)))) << endl;
cout << setw(40) << left << "Inequality (F)" << (EXPECT_FALSE((MAB::Money(6) != MAB::Money(6)))) << endl;
cout << setw(40) << left << "Insertion (<<, +)"; (TEST_INSERTION(true)); std::cout << endl;
cout << setw(40) << left << "Insertion (<<, -)"; (TEST_INSERTION(false)); std::cout << endl;
cout << setw(40) << left << "Extraction (>>, $)"; (TEST_EXTRACTION(true)); std::cout << endl;
cout << setw(40) << left << "Extraction (>>)"; (TEST_EXTRACTION(false)); std::cout << endl;
cout.fill(prev);
}
void TEST_INSERTION(bool sign)
{
namespace MAB = MyAwesomeBusiness;
std::stringstream ss;
std::string str;
if (sign) {
MAB::Money money(5, 75);
ss << money;
str = ss.str();
std::cout << (IS_EQUAL(std::string("$5.75"), str));
} else {
MAB::Money money(-5, -75);
ss << money;
str = ss.str();
std::cout << (IS_EQUAL(std::string("($5.75)"), str));
}
ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
void TEST_EXTRACTION(bool dSign)
{
namespace MAB = MyAwesomeBusiness;
std::stringstream ss;
std::string str;
if (dSign)
ss << "$5.75";
else
ss << "5.75";
MAB::Money money;
ss >> money;
std::cout << (IS_EQUAL(575, money.getPennies()));
}
#endif
| 48.515152
| 131
| 0.549865
|
Anadani
|
420173a5e0f49f6d9fc8da4b577e813c3708bfdc
| 2,152
|
hh
|
C++
|
yagi/include/typemanager.hh
|
IDAPluginProject/Yagi
|
a4528c83dff7f87c804140727b06e0359aca1d99
|
[
"Apache-2.0"
] | null | null | null |
yagi/include/typemanager.hh
|
IDAPluginProject/Yagi
|
a4528c83dff7f87c804140727b06e0359aca1d99
|
[
"Apache-2.0"
] | null | null | null |
yagi/include/typemanager.hh
|
IDAPluginProject/Yagi
|
a4528c83dff7f87c804140727b06e0359aca1d99
|
[
"Apache-2.0"
] | null | null | null |
#ifndef __YAGI_TYPEMANAGER__
#define __YAGI_TYPEMANAGER__
#include <libdecomp.hh>
#include <vector>
#include <string>
#include <optional>
#include <map>
#include <string>
#include "yagiarchitecture.hh"
namespace yagi
{
/*!
* \brief Factory become a manager because it's based on the factory backend link to IDA
*/
class TypeManager : public TypeFactory
{
protected:
/*!
* \brief pointer the global architecture
*/
YagiArchitecture* m_archi;
/*!
* \brief find type by inner id
* \param n name of the type
* \param id id of the type
* \return found type
*/
Datatype* findById(const string& n, uint8 id) override;
/*!
* \brief inject API is not available throw normal API
* We need to use XML tricks...
* \param fd function data to update
* \param inject_name name of th injection
*/
void setInjectAttribute(Funcdata& fd, std::string inject_name);
public:
/*!
* \brief ctor
*/
explicit TypeManager(YagiArchitecture* architecture);
virtual ~TypeManager() = default;
/*!
* \brief Disable copy of IdaTypeFactory prefer moving
*/
TypeManager(const TypeManager&) = delete;
TypeManager& operator=(const TypeManager&) = delete;
/*!
* \brief Moving is allowed because unique_ptr allow it
* and we use std map as container
*/
TypeManager(TypeManager&&) noexcept = default;
TypeManager& operator=(TypeManager&&) noexcept = default;
/*!
* \brief Parse a function information type interface
* Try to create a Ghidra type code
* \param typeInfo backend type information
*/
TypeCode* parseFunc(const FuncInfo& typeInfo);
/*!
* \brief parse a type information generic interface
* to transform into ghidra type
* \param backend type information interface
* \return ghidra type
*/
Datatype* parseTypeInfo(const TypeInfo& typeInfo);
/*!
* \brief Find a type from typeinformation interface
* \param typeInfo interface to find
* \return ghidra type
*/
Datatype* findByTypeInfo(const TypeInfo& typeInfo);
/*!
* \brief update function information data
*/
void update(Funcdata& func);
};
}
#endif
| 23.139785
| 89
| 0.687268
|
IDAPluginProject
|
420a42cce075876c01340818edbe4721e3914442
| 2,370
|
hpp
|
C++
|
include/mgpp/signals/dispatcher.hpp
|
mjgigli/libmgpp
|
87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0
|
[
"MIT"
] | 1
|
2018-12-22T17:35:45.000Z
|
2018-12-22T17:35:45.000Z
|
include/mgpp/signals/dispatcher.hpp
|
mjgigli/libmgpp
|
87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0
|
[
"MIT"
] | null | null | null |
include/mgpp/signals/dispatcher.hpp
|
mjgigli/libmgpp
|
87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2018 Matt Gigli
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE
* SOFTWARE.
*/
#ifndef MGPP_SIGNALS_DISPATCHER_HPP_
#define MGPP_SIGNALS_DISPATCHER_HPP_
#include <memory>
#include <unordered_map>
#include <boost/signals2.hpp>
#include <mgpp/signals/event.hpp>
namespace mgpp {
namespace signals {
// Define callback templates and pointer types
using EventCallbackTemplate = void(EventConstPtr);
using EventCallback = std::function<EventCallbackTemplate>;
template <typename T>
using EventMemberCallback = void (T::*)(EventConstPtr);
// Use boost signals2 signals/slots for the event dispatcher
typedef boost::signals2::signal<EventCallbackTemplate> EventSignal;
typedef boost::signals2::connection Connection;
// Subscribe functions
Connection Subscribe(const int id, const EventCallback cb);
template <typename T>
Connection Subscribe(const int id, const EventMemberCallback<T> mcb,
const T &obj) {
return Subscribe(id, boost::bind(mcb, const_cast<T *>(&obj), _1));
}
// Unsubscribe functions
void Unsubscribe(const int id, const Connection &conn);
// UnsubscribeAll function
void UnsubscribeAll(const int id = -1);
// Publish function
void Publish(EventConstPtr event);
int NumSlots(const int id);
} // namespace signals
} // namespace mgpp
#endif // MGPP_SIGNALS_DISPATCHER_HPP_
| 32.465753
| 79
| 0.760338
|
mjgigli
|
420eea7d8446fc86ddd296db29aee2919795b575
| 1,733
|
cpp
|
C++
|
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp
|
szabi-luxonis/openvino
|
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
|
[
"Apache-2.0"
] | 2
|
2020-11-18T14:14:06.000Z
|
2020-11-28T04:55:57.000Z
|
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp
|
szabi-luxonis/openvino
|
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
|
[
"Apache-2.0"
] | 30
|
2020-11-13T11:44:07.000Z
|
2022-02-21T13:03:16.000Z
|
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp
|
szabi-luxonis/openvino
|
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
|
[
"Apache-2.0"
] | 1
|
2020-12-18T15:47:45.000Z
|
2020-12-18T15:47:45.000Z
|
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision_transformations/fake_quantize_transformation.hpp"
#include <memory>
#include <tuple>
#include <vector>
#include <string>
#include <ie_core.hpp>
#include <transformations/init_node_info.hpp>
namespace LayerTestsDefinitions {
std::string FakeQuantizeTransformation::getTestCaseName(testing::TestParamInfo<FakeQuantizeTransformationParams> obj) {
InferenceEngine::Precision netPrecision;
InferenceEngine::SizeVector inputShapes;
std::string targetDevice;
ngraph::pass::low_precision::LayerTransformation::Params params;
ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantizeOnData;
std::tie(netPrecision, inputShapes, targetDevice, params, fakeQuantizeOnData) = obj.param;
std::ostringstream result;
result << getTestCaseNameByParams(netPrecision, inputShapes, targetDevice, params) << "_" << fakeQuantizeOnData;
return result.str();
}
void FakeQuantizeTransformation::SetUp() {
InferenceEngine::SizeVector inputShape;
InferenceEngine::Precision netPrecision;
ngraph::pass::low_precision::LayerTransformation::Params params;
ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantizeOnData;
std::tie(netPrecision, inputShape, targetDevice, params, fakeQuantizeOnData) = this->GetParam();
function = ngraph::builder::subgraph::FakeQuantizeFunction::getOriginal(
FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision),
inputShape,
fakeQuantizeOnData);
ngraph::pass::InitNodeInfo().run_on_function(function);
}
TEST_P(FakeQuantizeTransformation, CompareWithRefImpl) {
Run();
};
} // namespace LayerTestsDefinitions
| 34.66
| 119
| 0.772072
|
szabi-luxonis
|
42190727be040632b2fb81d13aac31992fd155d3
| 1,333
|
cpp
|
C++
|
f9tws/ExgTradingLineFixFactory.cpp
|
fonwin/Plan
|
3bfa9407ab04a26293ba8d23c2208bbececb430e
|
[
"Apache-2.0"
] | 21
|
2019-01-29T14:41:46.000Z
|
2022-03-11T00:22:56.000Z
|
f9tws/ExgTradingLineFixFactory.cpp
|
fonwin/Plan
|
3bfa9407ab04a26293ba8d23c2208bbececb430e
|
[
"Apache-2.0"
] | null | null | null |
f9tws/ExgTradingLineFixFactory.cpp
|
fonwin/Plan
|
3bfa9407ab04a26293ba8d23c2208bbececb430e
|
[
"Apache-2.0"
] | 9
|
2019-01-27T14:19:33.000Z
|
2022-03-11T06:18:24.000Z
|
// \file f9tws/ExgTradingLineFixFactory.cpp
// \author fonwinz@gmail.com
#include "f9tws/ExgTradingLineFixFactory.hpp"
#include "fon9/fix/FixBusinessReject.hpp"
namespace f9tws {
ExgTradingLineFixFactory::ExgTradingLineFixFactory(std::string fixLogPathFmt, Named&& name)
: base(std::move(fixLogPathFmt), std::move(name)) {
ExgTradingLineFix::InitFixConfig(this->FixConfig_);
f9fix::InitRecvRejectMessage(this->FixConfig_);
}
fon9::io::SessionSP ExgTradingLineFixFactory::CreateTradingLine(ExgTradingLineMgr& lineMgr,
const fon9::IoConfigItem& cfg,
std::string& errReason) {
ExgTradingLineFixArgs args;
args.Market_ = lineMgr.Market_;
errReason = ExgTradingLineFixArgsParser(args, ToStrView(cfg.SessionArgs_));
if (!errReason.empty())
return fon9::io::SessionSP{};
std::string fixLogPath;
errReason = this->MakeLogPath(fixLogPath);
if (!errReason.empty())
return fon9::io::SessionSP{};
fon9::fix::IoFixSenderSP fixSender;
errReason = MakeExgTradingLineFixSender(args, &fixLogPath, fixSender);
if (!errReason.empty())
return fon9::io::SessionSP{};
return this->CreateTradingLineFix(lineMgr, args, std::move(fixSender));
}
} // namespaces
| 35.078947
| 94
| 0.672918
|
fonwin
|
4224193f63fde7260b305d76f39e2554c9c08301
| 1,050
|
hpp
|
C++
|
TypeTraits/IsClassType.hpp
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | 2
|
2021-06-09T00:38:46.000Z
|
2021-09-04T21:55:33.000Z
|
TypeTraits/IsClassType.hpp
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | null | null | null |
TypeTraits/IsClassType.hpp
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | 1
|
2021-08-30T00:46:12.000Z
|
2021-08-30T00:46:12.000Z
|
//
// Created by James Landess on 2/4/20.
//
#ifndef LANDESSDEVCORE_ISCLASSTYPE_HPP
#define LANDESSDEVCORE_ISCLASSTYPE_HPP
#include "TypeTraits/IsIntegralType.hpp"
#include "TypeTraits/IsUnion.hpp"
namespace LD
{
namespace Detail
{
template<typename T>
struct IsClassType
{
static const bool value = !IsIntegrelType<T>::value;
};
//template <bool _Bp, class _Tp = void> using Enable_If_T = typename EnableIf<_Bp, _Tp>::type;
template<typename T> using IsClassType_V = typename IsClassType<T>::value;
}
}
namespace LD
{
namespace Detail
{
template <class T>
LD::Detail::IntegralConstant<bool, !LD::Detail::IsUnion<T>::value> test(int T::*);
template <class>
LD::FalseType test(...);
template <class T>
struct IsClass : decltype(LD::Detail::test<T>(nullptr))
{};
}
template<typename T>
constexpr bool IsClass = LD::Detail::IsClass<T>::value;
}
#endif //LANDESSDEVCORE_ISCLASSTYPE_HPP
| 18.421053
| 102
| 0.630476
|
jlandess
|
4225050630bbee8dac61f9eab48420340b96eec3
| 624
|
cpp
|
C++
|
thirdparty/ULib/tests/ulib/test_twilio.cpp
|
liftchampion/nativejson-benchmark
|
6d575ffa4359a5c4230f74b07d994602a8016fb5
|
[
"MIT"
] | null | null | null |
thirdparty/ULib/tests/ulib/test_twilio.cpp
|
liftchampion/nativejson-benchmark
|
6d575ffa4359a5c4230f74b07d994602a8016fb5
|
[
"MIT"
] | null | null | null |
thirdparty/ULib/tests/ulib/test_twilio.cpp
|
liftchampion/nativejson-benchmark
|
6d575ffa4359a5c4230f74b07d994602a8016fb5
|
[
"MIT"
] | null | null | null |
// test_twilio.cpp
#include <ulib/net/client/twilio.h>
int main(int argc, char *argv[])
{
U_ULIB_INIT(argv);
U_TRACE(5,"main(%d)",argc)
UTwilioClient tc(U_STRING_FROM_CONSTANT("SID"), U_STRING_FROM_CONSTANT("TOKEN"));
bool ok = tc.getCompletedCalls();
U_INTERNAL_ASSERT(ok)
ok = tc.makeCall(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("http://xxxx"));
U_INTERNAL_ASSERT(ok)
ok = tc.sendSMS(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("\"Hello, how are you?\""));
U_INTERNAL_ASSERT(ok)
}
| 24.96
| 141
| 0.709936
|
liftchampion
|
422833be4725423ad37c6953658757a96f12a245
| 21,894
|
cpp
|
C++
|
src/lib.cpp
|
anticrisis/act-http
|
18a48a35efc76c54e38a1eac762828bd7addf8c0
|
[
"BSD-3-Clause"
] | 2
|
2021-02-05T21:20:09.000Z
|
2022-01-19T13:43:39.000Z
|
src/lib.cpp
|
anticrisis/tcl-http
|
18a48a35efc76c54e38a1eac762828bd7addf8c0
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib.cpp
|
anticrisis/tcl-http
|
18a48a35efc76c54e38a1eac762828bd7addf8c0
|
[
"BSD-3-Clause"
] | null | null | null |
#include "dllexport.h"
#include "http_tcl/http_tcl.h"
#include "util.h"
#include "version.h"
#include <algorithm>
#include <iostream>
#include <memory>
#include <optional>
#include <tcl.h>
#include <thread>
#include <vector>
// need a macro for compile-time string concatenation
#define theNamespaceName "::act::http"
#define theUrlNamespaceName "::act::url"
static constexpr auto theParentNamespace = "::act";
static constexpr auto thePackageName = "act::http";
static constexpr auto thePackageVersion = PROJECT_VERSION;
// Configuration structure with refcounted Tcl objects. Managed using
// the 'http::configure' command.
//
// TCL callbacks have the following specifications:
//
// OPTIONS: -> {status content content_type} or see below
// HEAD: -> {status content_length content_type}
// GET: -> {status content content_type}
// POST: -> {status content content_type}
// PUT: -> {status}
// DELETE: -> {status content content_type}
//
// where
//
// target = string request path, e.g. "/foo"
// body = string request body
// status = integer HTTP status code
// content_length = integer to place in 'Content-Length' header
// content_type = string to place in 'Content-Type' header
//
// and
//
// Each callback, not just OPTIONS, may optionally return an additional value
// as the last element of the list. That value is a dictionary of key/value
// pairs to add to the response headers. For example:
//
// proc post {target body} {
// list 200 "hello" "text/plain" {Set-Cookie foo X-Other-Header bar}
// }
//
struct config_t
{
bool valid{ false };
TclObj options{};
TclObj head{};
TclObj get{};
TclObj post{};
TclObj put{};
TclObj delete_{};
TclObj req_target{};
TclObj req_body{};
TclObj req_headers{};
TclObj host{};
TclObj port{};
TclObj exit_target{};
TclObj max_connections{};
void
init();
};
void
config_t::init()
{
// call after Tcl_InitStubs
auto empty_string = [] {
return Tcl_NewStringObj("", 0);
};
options = empty_string();
head = empty_string();
get = empty_string();
post = empty_string();
put = empty_string();
delete_ = empty_string();
req_target = empty_string();
req_body = empty_string();
req_headers = empty_string();
host = empty_string();
port = empty_string();
exit_target = empty_string();
max_connections = empty_string();
valid = true;
}
struct tcl_handler final : public http_tcl::thread_safe_handler<tcl_handler>
{
Tcl_Interp* interp_;
config_t config_;
void
set_target(std::string_view target)
{
maybe_set_var(interp_, config_.req_target.value(), target);
}
void
set_body(std::string_view body)
{
maybe_set_var(interp_, config_.req_body.value(), body);
}
void
set_headers(headers_access&& get_headers)
{
// only ask server to copy headers out of its internal
// structure if we're actually going to use them.
auto var_name_sv = get_string(config_.req_headers.value());
if (! var_name_sv.empty())
{
auto dict = to_dict(interp_, get_headers());
Tcl_ObjSetVar2(interp_,
config_.req_headers.value(),
nullptr,
dict,
TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG);
}
}
std::optional<int>
get_int(Tcl_Obj* obj)
{
int val{ 0 };
if (Tcl_GetIntFromObj(interp_, obj, &val) == TCL_OK)
return val;
return std::nullopt;
}
std::optional<std::tuple<int, Tcl_Obj**>>
get_list(Tcl_Obj* list)
{
int length{ 0 };
Tcl_Obj** objv;
if (Tcl_ListObjGetElements(interp_, list, &length, &objv) != TCL_OK)
return std::nullopt;
return std::make_tuple(length, objv);
}
std::optional<http_tcl::headers>
get_dict(Tcl_Obj* dict)
{
return ::get_dict(interp_, dict);
}
std::optional<std::tuple<int, Tcl_Obj**>>
eval_to_list(Tcl_Obj* obj)
{
if (Tcl_EvalObjEx(interp_, obj, TCL_EVAL_GLOBAL) != TCL_OK)
return std::nullopt;
return get_list(Tcl_GetObjResult(interp_));
}
std::string
error_info()
{
if (auto cs = Tcl_GetVar(interp_, "errorInfo", TCL_GLOBAL_ONLY); cs)
return cs;
return "";
}
public:
void
init(Tcl_Interp* i)
{
interp_ = i;
config_.init();
}
auto&
config()
{
return config_;
}
options_r
do_options(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> options_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
// Not-so-secret back door to force exit, only if -exittarget is set. This
// is used for test suites.
if (auto exit = get_string(config_.exit_target.value()); ! exit.empty())
{
if (target == exit)
{
// exit after 50ms, hopefully enough time to cleanly complete the
// response
std::thread{
[] {
using namespace std::chrono_literals;
std::this_thread::sleep_for(100ms);
Tcl_Exit(0);
}
}.detach();
return { 204, std::nullopt, "", "" };
}
}
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.options.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto res_body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ res_body.data(), res_body.size() },
{ content_type.data(), content_type.size() } };
}
head_r
do_head(std::string_view target, headers_access&& get_headers)
{
static const auto error
= std::make_tuple(500, std::nullopt, 0, "text/plain");
constexpr auto req_args = 3;
set_target(target);
set_body("");
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.head.value());
if (! list)
return error;
auto [objc, objv] = *list;
if (objc < req_args)
return error;
auto sc = get_int(*objv++);
auto content_length = get_int(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc || ! content_length)
return error;
return { *sc,
headers,
static_cast<size_t>(*content_length),
{ content_type.data(), content_type.size() } };
}
get_r
do_get(std::string_view target, headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> get_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
set_target(target);
set_body("");
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.get.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ body.data(), body.size() },
{ content_type.data(), content_type.size() } };
}
post_r
do_post(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> post_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.post.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto res_body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ res_body.data(), res_body.size() },
{ content_type.data(), content_type.size() } };
}
put_r
do_put(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
static const auto error = std::make_tuple(500, http_tcl::headers{});
constexpr auto req_args = 1;
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.put.value());
if (! list)
return error;
auto [objc, objv] = *list;
if (objc < req_args)
return error;
auto sc = get_int(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return error;
return { *sc, headers };
}
delete_r
do_delete_(std::string_view target,
std::string_view body,
headers_access&& get_headers)
{
constexpr auto req_args = 3;
const auto make_error = [&](char const* msg = nullptr) -> delete_r {
return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" };
};
set_target(target);
set_body(body);
set_headers(std::move(get_headers));
auto list = eval_to_list(config_.delete_.value());
if (! list)
return make_error();
auto [objc, objv] = *list;
if (objc < req_args)
return make_error("wrong number of items returned from callback");
auto sc = get_int(*objv++);
auto res_body = get_string(*objv++);
auto content_type = get_string(*objv++);
std::optional<http_tcl::headers> headers;
if (objc > req_args)
headers = get_dict(*objv++);
if (! sc)
return make_error(
"could not understand status code returned from callback");
return { *sc,
headers,
{ res_body.data(), res_body.size() },
{ content_type.data(), content_type.size() } };
}
};
struct client_data
{
tcl_handler handler;
void
init(Tcl_Interp*);
};
void
client_data::init(Tcl_Interp* i)
{
handler.init(i);
}
// global
client_data theClientData;
//
int
configure(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
static const char* options[] = { "-head",
"-get",
"-post",
"-put",
"-delete",
"-reqtargetvariable",
"-reqbodyvariable",
"-reqheadersvariable",
"-host",
"-port",
"-options",
"-exittarget",
"-maxconnections",
nullptr };
auto cd_ptr = static_cast<client_data*>(cd);
auto& my_config = cd_ptr->handler.config();
if (objc == 2)
{
// return value of single option
int opt{ -1 };
if (Tcl_GetIndexFromObj(i, objv[1], options, "option", 0, &opt) != TCL_OK)
return TCL_ERROR;
std::vector<Tcl_Obj*> objv;
switch (opt)
{
case 0: objv.push_back(my_config.head.value()); break;
case 1: objv.push_back(my_config.get.value()); break;
case 2: objv.push_back(my_config.post.value()); break;
case 3: objv.push_back(my_config.put.value()); break;
case 4: objv.push_back(my_config.delete_.value()); break;
case 5: objv.push_back(my_config.req_target.value()); break;
case 6: objv.push_back(my_config.req_body.value()); break;
case 7: objv.push_back(my_config.req_headers.value()); break;
case 8: objv.push_back(my_config.host.value()); break;
case 9: objv.push_back(my_config.port.value()); break;
case 10: objv.push_back(my_config.options.value()); break;
case 11: objv.push_back(my_config.exit_target.value()); break;
case 12: objv.push_back(my_config.max_connections.value()); break;
default: return TCL_ERROR;
}
auto list = Tcl_NewListObj(objv.size(), objv.data());
Tcl_SetObjResult(i, list);
return TCL_OK;
}
// require odd number of arguments
if (objc % 2 == 0)
{
Tcl_WrongNumArgs(
i,
objc,
objv,
"?-host host? ?-port port? ?-head headCmd? ?-get getCmd? "
"?-post postCmd? ?-put "
"putCmd? ?-delete delCmd? ?-options optCmd? ?-reqtargetvariable varName? "
"?-reqbodyvariable varName? ?-reqheadersvariable varName? ?-exittarget "
"target? ?-maxconnections n?");
return TCL_ERROR;
}
if (objc == 1)
{
// return list of configuration
std::vector<Tcl_Obj*> objv;
objv.reserve(20);
objv.push_back(Tcl_NewStringObj("-host", -1));
objv.push_back(my_config.host.value());
objv.push_back(Tcl_NewStringObj("-port", -1));
objv.push_back(my_config.port.value());
objv.push_back(Tcl_NewStringObj("-head", -1));
objv.push_back(my_config.head.value());
objv.push_back(Tcl_NewStringObj("-get", -1));
objv.push_back(my_config.get.value());
objv.push_back(Tcl_NewStringObj("-post", -1));
objv.push_back(my_config.post.value());
objv.push_back(Tcl_NewStringObj("-put", -1));
objv.push_back(my_config.put.value());
objv.push_back(Tcl_NewStringObj("-delete", -1));
objv.push_back(my_config.delete_.value());
objv.push_back(Tcl_NewStringObj("-options", -1));
objv.push_back(my_config.options.value());
objv.push_back(Tcl_NewStringObj("-reqtargetvariable", -1));
objv.push_back(my_config.req_target.value());
objv.push_back(Tcl_NewStringObj("-reqbodyvariable", -1));
objv.push_back(my_config.req_body.value());
objv.push_back(Tcl_NewStringObj("-reqheadersvariable", -1));
objv.push_back(my_config.req_headers.value());
objv.push_back(Tcl_NewStringObj("-exittarget", -1));
objv.push_back(my_config.exit_target.value());
objv.push_back(Tcl_NewStringObj("-maxconnections", -1));
objv.push_back(my_config.max_connections.value());
auto list = Tcl_NewListObj(objv.size(), objv.data());
Tcl_SetObjResult(i, list);
return TCL_OK;
}
for (auto idx = 1; idx < objc - 1; idx += 2)
{
int opt{ -1 };
if (Tcl_GetIndexFromObj(i, objv[idx], options, "option", 0, &opt) != TCL_OK)
return TCL_ERROR;
auto obj = objv[idx + 1];
switch (opt)
{
case 0: my_config.head = obj; break;
case 1: my_config.get = obj; break;
case 2: my_config.post = obj; break;
case 3: my_config.put = obj; break;
case 4: my_config.delete_ = obj; break;
case 5: my_config.req_target = obj; break;
case 6: my_config.req_body = obj; break;
case 7: my_config.req_headers = obj; break;
case 8: my_config.host = obj; break;
case 9: my_config.port = obj; break;
case 10: my_config.options = obj; break;
case 11: my_config.exit_target = obj; break;
case 12: my_config.max_connections = obj; break;
default: return TCL_ERROR;
}
}
return TCL_OK;
}
int
http_client(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
static const char* options[]
= { "-host", "-port", "-target", "-method", "-body", "-headers", nullptr };
auto const error = [&i, &objc, &objv] {
Tcl_WrongNumArgs(
i,
objc,
objv,
"?-host host? ?-port port? ?-target target? ?-method http-method? "
"?-body body? ?-headers headerDict?");
return TCL_ERROR;
};
// require odd number of arguments
if (objc % 2 == 0)
return error();
std::string host;
std::string port{ "80" };
std::string target{ "/" };
std::string method{ "get" };
std::string body;
std::optional<http_tcl::headers> headers;
for (auto idx = 1; idx < objc - 1; idx += 2)
{
int opt{ -1 };
if (Tcl_GetIndexFromObj(i, objv[idx], options, "option", 0, &opt) != TCL_OK)
return TCL_ERROR;
auto obj = objv[idx + 1];
switch (opt)
{
case 0: host = get_string(obj); break;
case 1: port = get_string(obj); break;
case 2: target = get_string(obj); break;
case 3: method = get_string(obj); break;
case 4: body = get_string(obj); break;
case 5: headers = get_dict(i, obj); break;
default: return TCL_ERROR;
}
}
if (host.empty())
return error();
tolower(method);
auto [sc, heads, res_body]
= http_tcl::http_client(method, host, port, target, headers, body);
std::vector<Tcl_Obj*> resv{
Tcl_NewStringObj(std::to_string(sc).c_str(), -1),
to_dict(i, heads),
Tcl_NewStringObj(res_body.c_str(), -1),
};
auto list = Tcl_NewListObj(resv.size(), resv.data());
Tcl_SetObjResult(i, list);
return TCL_OK;
}
int
run(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
auto cd_ptr = static_cast<client_data*>(cd);
auto& my_config = cd_ptr->handler.config();
auto host = Tcl_GetString(my_config.host.value());
int port{ 0 };
int max_connections{ 0 };
if (Tcl_GetIntFromObj(i, my_config.port.value(), &port) != TCL_OK)
{
Tcl_SetObjResult(i, Tcl_NewStringObj("Invalid port number.", -1));
return TCL_ERROR;
}
// if bad value or not set, ignore the option and use server's default
if (Tcl_GetIntFromObj(i, my_config.max_connections.value(), &max_connections)
!= TCL_OK)
max_connections = 0;
if (max_connections)
http_tcl::run(host, port, &cd_ptr->handler, max_connections);
else
http_tcl::run(host, port, &cd_ptr->handler);
return TCL_OK;
}
int
percent_encode(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
if (objc != 2)
{
Tcl_WrongNumArgs(i, objc, objv, "string");
return TCL_ERROR;
}
auto in = get_string(objv[1]);
auto out = url::percent_encode(in);
Tcl_SetObjResult(i, Tcl_NewStringObj(out.c_str(), out.size()));
return TCL_OK;
}
int
percent_decode(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[])
{
if (objc != 2)
{
Tcl_WrongNumArgs(i, objc, objv, "string");
return TCL_ERROR;
}
auto in = get_string(objv[1]);
auto out = url::percent_decode(in);
if (out)
{
Tcl_SetObjResult(i, Tcl_NewStringObj(out->c_str(), out->size()));
return TCL_OK;
}
else
{
Tcl_AddErrorInfo(i, "could not decode string.");
return TCL_ERROR;
}
}
extern "C"
{
DllExport int
Act_http_Init(Tcl_Interp* i)
{
if (Tcl_InitStubs(i, TCL_VERSION, 0) == nullptr)
return TCL_ERROR;
theClientData.init(i);
#define def(name, func) \
Tcl_CreateObjCommand(i, \
theNamespaceName "::" name, \
(func), \
&theClientData, \
nullptr)
#define urldef(name, func) \
Tcl_CreateObjCommand(i, \
theUrlNamespaceName "::" name, \
(func), \
&theClientData, \
nullptr)
auto parent_ns
= Tcl_CreateNamespace(i, theParentNamespace, nullptr, nullptr);
auto ns = Tcl_CreateNamespace(i, theNamespaceName, nullptr, nullptr);
auto url_ns = Tcl_CreateNamespace(i, theUrlNamespaceName, nullptr, nullptr);
def("configure", configure);
def("run", run);
def("client", http_client);
urldef("encode", percent_encode);
urldef("decode", percent_decode);
if (Tcl_Export(i, ns, "*", 0) != TCL_OK)
return TCL_ERROR;
if (Tcl_Export(i, url_ns, "*", 0) != TCL_OK)
return TCL_ERROR;
if (Tcl_Export(i, parent_ns, "*", 0) != TCL_OK)
return TCL_ERROR;
Tcl_CreateEnsemble(i, theNamespaceName, ns, 0);
Tcl_CreateEnsemble(i, theUrlNamespaceName, url_ns, 0);
Tcl_PkgProvide(i, thePackageName, thePackageVersion);
return TCL_OK;
#undef def
#undef urldef
}
DllExport int
Act_http_Unload(Tcl_Interp* i, int flags)
{
auto ns = Tcl_FindNamespace(i, theNamespaceName, nullptr, 0);
auto url_ns = Tcl_CreateNamespace(i, theUrlNamespaceName, nullptr, nullptr);
Tcl_DeleteNamespace(ns);
Tcl_DeleteNamespace(url_ns);
// init client data again to free variables in the prior configuration
theClientData.init(i);
return TCL_OK;
}
}
| 27.784264
| 80
| 0.591669
|
anticrisis
|
42284a1b50025daf4b313acf93994d4c4491247c
| 4,314
|
hxx
|
C++
|
ImageSharpOpenJpegNative/src/openjpeg.stream.hxx
|
cinderblocks/ImageSharp.OpenJpeg
|
bf5c976a6dbfa0d2666be566c845a7410440cea2
|
[
"Apache-2.0"
] | null | null | null |
ImageSharpOpenJpegNative/src/openjpeg.stream.hxx
|
cinderblocks/ImageSharp.OpenJpeg
|
bf5c976a6dbfa0d2666be566c845a7410440cea2
|
[
"Apache-2.0"
] | null | null | null |
ImageSharpOpenJpegNative/src/openjpeg.stream.hxx
|
cinderblocks/ImageSharp.OpenJpeg
|
bf5c976a6dbfa0d2666be566c845a7410440cea2
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2022 Sjofn LLC. 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.
*/
#ifndef _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_
#define _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_
#include "ImageSharpOpenJpeg_Exports.hxx"
#include "shared.hxx"
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_destroy(opj_stream_t* p_stream)
{
::opj_stream_destroy(p_stream);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_default_create(const bool p_is_read_stream)
{
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_default_create(b);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create(const uint64_t p_buffer_size,
const bool p_is_read_stream)
{
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_create(p_buffer_size, b);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_read_function(opj_stream_t* p_stream,
const opj_stream_read_fn p_function)
{
::opj_stream_set_read_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_write_function(opj_stream_t* p_stream,
const opj_stream_write_fn p_function)
{
::opj_stream_set_write_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_skip_function(opj_stream_t* p_stream,
const opj_stream_skip_fn p_function)
{
::opj_stream_set_skip_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_seek_function(opj_stream_t* p_stream,
const opj_stream_seek_fn p_function)
{
::opj_stream_set_seek_function(p_stream, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_user_data(opj_stream_t* p_stream,
void* p_data,
const opj_stream_free_user_data_fn p_function)
{
::opj_stream_set_user_data(p_stream, p_data, p_function);
}
IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_user_data_length(opj_stream_t* p_stream,
const uint64_t data_length)
{
::opj_stream_set_user_data_length(p_stream, data_length);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create_default_file_stream(const char *fname,
const uint32_t fname_len,
const bool p_is_read_stream)
{
const auto str = std::string(fname, fname_len);
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_create_default_file_stream(str.c_str(), b);
}
IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create_file_stream(const char *fname,
const uint32_t fname_len,
const uint64_t p_buffer_size,
const bool p_is_read_stream)
{
const auto str = std::string(fname, fname_len);
const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE;
return ::opj_stream_create_file_stream(str.c_str(), p_buffer_size, b);
}
#endif // _CPP_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_
| 44.474227
| 119
| 0.64905
|
cinderblocks
|
422a2115bc21c765bd1cca906ed584b4d1ca0c01
| 3,783
|
cpp
|
C++
|
.RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp
|
i-saint/RemoteTalk
|
3ac2528ab66ed923cb9c56596944effdeaecee50
|
[
"MIT"
] | 36
|
2018-12-18T22:33:36.000Z
|
2021-10-31T07:03:15.000Z
|
.RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp
|
i-saint/RemoteTalk
|
3ac2528ab66ed923cb9c56596944effdeaecee50
|
[
"MIT"
] | 1
|
2020-04-04T16:13:43.000Z
|
2020-04-05T05:08:17.000Z
|
.RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp
|
i-saint/RemoteTalk
|
3ac2528ab66ed923cb9c56596944effdeaecee50
|
[
"MIT"
] | 3
|
2019-04-12T17:37:23.000Z
|
2020-09-30T15:50:31.000Z
|
#include "pch.h"
#include "rtcvCommon.h"
#include "rtcvHookHandler.h"
#include "rtcvTalkServer.h"
namespace rtcv {
TalkServer::TalkServer()
{
auto exe_path = rt::GetMainModulePath();
auto config_path = rt::GetCurrentModuleDirectory() + "\\" + rtcvConfigFile;
auto settings = rt::GetOrAddServerSettings(config_path, exe_path, rtcvDefaultPort);
m_settings.port = settings.port;
m_tmp_path = rt::GetCurrentModuleDirectory() + "\\tmp.wav";
}
void TalkServer::addMessage(MessagePtr mes)
{
super::addMessage(mes);
processMessages();
}
bool TalkServer::isReady()
{
return false;
}
TalkServer::Status TalkServer::onStats(StatsMessage& mes)
{
auto ifs = rtGetTalkInterface_();
auto& stats = mes.stats;
ifs->getParams(stats.params);
{
int n = ifs->getNumCasts();
for (int i = 0; i < n; ++i)
stats.casts.push_back(*ifs->getCastInfo(i));
}
stats.host = ifs->getClientName();
stats.plugin_version = ifs->getPluginVersion();
stats.protocol_version = ifs->getProtocolVersion();
return Status::Succeeded;
}
TalkServer::Status TalkServer::onTalk(TalkMessage& mes)
{
if (m_task_talk.valid()) {
if (m_task_talk.wait_for(std::chrono::milliseconds(0)) == std::future_status::timeout)
return Status::Failed;
}
m_params = mes.params;
auto ifs = rtGetTalkInterface_();
ifs->setParams(mes.params);
ifs->setText(mes.text.c_str());
if (m_mode == Mode::ExportFile) {
ifs->setTempFilePath(m_tmp_path.c_str());
if (!ifs->play())
return Status::Failed;
auto data = std::make_shared<rt::AudioData>();
if (!rt::ImportWave(*data, m_tmp_path.c_str()))
return Status::Failed;
std::remove(m_tmp_path.c_str());
m_data_queue.push_back(data);
m_data_queue.push_back(std::make_shared<rt::AudioData>());
}
else {
ifs->setTempFilePath("");
WaveOutHandler::getInstance().mute = m_params.mute;
if (!ifs->play())
Status::Failed;
m_task_talk = std::async(std::launch::async, [this, ifs]() {
ifs->wait();
WaveOutHandler::getInstance().mute = false;
{
auto terminator = std::make_shared<rt::AudioData>();
std::unique_lock<std::mutex> lock(m_data_mutex);
m_data_queue.push_back(terminator);
}
});
}
mes.task = std::async(std::launch::async, [this, &mes]() {
std::vector<rt::AudioDataPtr> tmp;
for (;;) {
{
std::unique_lock<std::mutex> lock(m_data_mutex);
tmp = m_data_queue;
m_data_queue.clear();
}
for (auto& ad : tmp) {
ad->serialize(*mes.respond_stream);
}
if (!tmp.empty() && tmp.back()->data.empty())
break;
else
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
return Status::Succeeded;
}
TalkServer::Status TalkServer::onStop(StopMessage& mes)
{
auto ifs = rtGetTalkInterface_();
return ifs->stop() ? Status::Succeeded : Status::Failed;
}
#ifdef rtDebug
TalkServer::Status TalkServer::onDebug(DebugMessage& mes)
{
return rtGetTalkInterface_()->onDebug() ? Status::Succeeded : Status::Failed;
}
#endif
void TalkServer::onUpdateBuffer(const rt::AudioData& data)
{
auto ifs = rtGetTalkInterface_();
if (!ifs->isPlaying())
return;
auto tmp = std::make_shared<rt::AudioData>(data);
if (m_params.force_mono)
tmp->convertToMono();
{
std::unique_lock<std::mutex> lock(m_data_mutex);
m_data_queue.push_back(tmp);
}
}
} // namespace rtcv
| 27.215827
| 94
| 0.597409
|
i-saint
|
422abceab02e1f78d551c813dcfafaeb7b3316f8
| 1,027
|
cpp
|
C++
|
DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp
|
sumanthbolle/DataStructures-Algorithms
|
d04edbcdd0794f5668e26bd003b46548150eccbc
|
[
"MIT"
] | 1
|
2021-02-11T15:07:17.000Z
|
2021-02-11T15:07:17.000Z
|
DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp
|
sumanthbolle/DataStructures-Algorithms
|
d04edbcdd0794f5668e26bd003b46548150eccbc
|
[
"MIT"
] | null | null | null |
DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp
|
sumanthbolle/DataStructures-Algorithms
|
d04edbcdd0794f5668e26bd003b46548150eccbc
|
[
"MIT"
] | null | null | null |
// O(nlogn)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> arr(n, 0);
for (int i = 0; i < n; ++i)
cin >> arr[i];
sort(arr.begin(), arr.end());
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
/* =============================== */
// O(n)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> arr(n, 0);
int num[3] = {0};
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
num[arr[i]]++;
}
for (int i = 0; i < n; ++i)
{
if (num[0])
{
arr[i] = 0;
num[0]--;
}
else if (num[1])
{
arr[i] = 1;
num[1]--;
}
else if (num[2])
{
arr[i] = 2;
num[2]--;
}
}
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
| 13.693333
| 37
| 0.351509
|
sumanthbolle
|
422f8f65625cf6e361471362aadeddbdb1afa670
| 2,040
|
cpp
|
C++
|
als/main.cpp
|
al-petrushin/kubsu-cpp-tasks
|
c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9
|
[
"MIT"
] | null | null | null |
als/main.cpp
|
al-petrushin/kubsu-cpp-tasks
|
c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9
|
[
"MIT"
] | null | null | null |
als/main.cpp
|
al-petrushin/kubsu-cpp-tasks
|
c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9
|
[
"MIT"
] | null | null | null |
//
// Created by Александр Петрушин on 26.04.2021.
//
#include <vector>
#include <functional>
#include <iostream>
#include <fstream>
#include "linear_regression.h"
#include "gradient.h"
#include "errors.h"
//#include "matplotlibcpp.h"
using namespace std;
std::function<double(double)> Eval(vector<double> input, vector<double> output, vector<double> start_params)
{
auto function = [](double v, vector<double> params) {
return params[0] * (v * v) + params[1] * v + params[2];
};
auto minized = [input, output, function](vector<double> params) {
vector<double> result(input.size());
for (int i = 0; i < input.size(); i++) {
result[i] = function(input[i], params);
}
return MSE(result, output);
};
auto best_params = GradientSolve((std::function<double(vector<double>)>)minized, start_params, 0.01, 1000);
return [best_params, function](double v) {
return function(v, best_params);
};
}
int main()
{
vector<double> input = {1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3};
vector<double> output = {5.21, 4.196, 3.759, 3.672, 4.592, 4.621, 5.758, 7.173, 9.269};
int size = input.size();
auto evalFunc = Eval(input, output, {1, 1, 1});
auto regression = LinearRegression(input, output);
vector<double> nonLinearRegressionOut(size), linearRegressionOut(size);
for (int i = 0; i < size; i++) {
nonLinearRegressionOut[i] = evalFunc(input[i]);
linearRegressionOut[i] = regression(input[i]);
}
cout << "MSE for non-linear regression = " << MSE(output, nonLinearRegressionOut) << endl;
cout << "MSE for linear regression = " << MSE(output, linearRegressionOut) << endl;
// matplotlibcpp::figure_size(1200, 780);
// matplotlibcpp::named_plot("target", input);
// matplotlibcpp::named_plot("linear", out2);
// matplotlibcpp::named_plot("linear", out1);
// matplotlibcpp::title("Sample figure");
// matplotlibcpp::legend();
// matplotlibcpp::save("./basic.png");
return 0;
}
| 29.565217
| 111
| 0.631373
|
al-petrushin
|
42343997e5cbaabd2bfbd8b043a5e62720235bc0
| 3,837
|
cpp
|
C++
|
sysy2riscv/ast_tigger.cpp
|
Yibo-He/sysyCompiler
|
fd95b17153b565d9ccb69c296cdcc8be64670b11
|
[
"MIT"
] | 7
|
2021-06-06T05:26:38.000Z
|
2021-12-25T08:19:43.000Z
|
sysy2riscv/ast_tigger.cpp
|
Yibo-He/sysyCompiler
|
fd95b17153b565d9ccb69c296cdcc8be64670b11
|
[
"MIT"
] | null | null | null |
sysy2riscv/ast_tigger.cpp
|
Yibo-He/sysyCompiler
|
fd95b17153b565d9ccb69c296cdcc8be64670b11
|
[
"MIT"
] | null | null | null |
#include "ast_tigger.hpp"
int string2num(const string s){
return atoi(s.c_str());
}
string num2string_3(int num){
string ans = to_string(num);
return ans;
}
int op2int(string op){
if(!strcmp(op.c_str(),"+")) return Plus;
if(!strcmp(op.c_str(),"-")) return Minus;
if(!strcmp(op.c_str(),"*")) return Multi;
if(!strcmp(op.c_str(),"/")) return Divi;
if(!strcmp(op.c_str(),"%")) return Mod;
if(!strcmp(op.c_str(),"!")) return Not;
if(!strcmp(op.c_str(),">")) return More;
if(!strcmp(op.c_str(),"<")) return Less;
if(!strcmp(op.c_str(),">=")) return MorEq;
if(!strcmp(op.c_str(),"<=")) return LorEq;
if(!strcmp(op.c_str(),"&&")) return And;
if(!strcmp(op.c_str(),"||")) return Or;
if(!strcmp(op.c_str(),"!=")) return Neq;
if(!strcmp(op.c_str(),"==")) return Eq;
return -1;
}
void ProgramAST::generator(){
for(auto i:varDecls) i->generator();
riscvCode.push_back(" ");
for(auto i:funDefs) i->generator();
for(auto &i: riscvCode)
cout << i << endl;
cout << endl;
}
void GlobalVarDeclAST::generator(){
if(isMalloc){
riscvCode.push_back(" .comm "+ varName +", "+ num +", 4");
}else{
riscvCode.push_back(" .global " + varName);
riscvCode.push_back(" .section .sdata");
riscvCode.push_back(" .align 2");
riscvCode.push_back(" .type " + varName + ", @object");
riscvCode.push_back(" .size " + varName + ", 4");
riscvCode.push_back(varName + ":");
riscvCode.push_back(" .word " + num);
}
}
void FunctionDefAST::generator(){
funHead->generator();
exps->generator();
funEnd->generator();
}
void FunctionHeaderAST::generator(){
riscvCode.push_back(" .text");
riscvCode.push_back(" .align 2");
riscvCode.push_back(" .global " + funName);
riscvCode.push_back(" .type " + funName + ", @function");
riscvCode.push_back(funName + ":");
int STK = (n2 / 4 + 1) * 16;
vector<BaseTiggerAST*>::iterator itBegin = dynamic_cast<ExpressionsAST*>(dynamic_cast<FunctionDefAST*>(funDef)->exps)->exp.begin();
vector<BaseTiggerAST*>::iterator itEnd = dynamic_cast<ExpressionsAST*>(dynamic_cast<FunctionDefAST*>(funDef)->exps)->exp.end();
for(itBegin;itBegin!=itEnd;++itBegin){
(*itBegin)->STK = STK;
}
if(STK<=2047 && STK>=-2048){
riscvCode.push_back(" addi sp, sp, -" + num2string_3(STK));
riscvCode.push_back(" sw ra, " + num2string_3(STK-4) + "(sp)");
}else {
riscvCode.push_back(" li s0, " + num2string_3(STK));
riscvCode.push_back(" sub sp, sp, s0");
riscvCode.push_back(" add s0, s0, sp");
riscvCode.push_back(" sw ra, -4(s0)");
}
}
void ExpressionsAST::generator(){
for(auto i: exp){
i->generator();
}
}
void FunctionEndAST::generator(){
riscvCode.push_back(" .size " + funName + ", .-" + funName);
}
void ExpressionAST::generator(){
list<string>::iterator it = riscvAction.begin();
if(!strcmp(it->c_str(), "ret")){
if(STK<=2047 && STK>=-2048){
string tmp;
tmp = " lw ra, "+num2string_3(STK-4)+"(sp)";
riscvCode.push_back(tmp);
tmp = " addi sp, sp, "+num2string_3(STK);
riscvCode.push_back(tmp);
tmp = " ret";
riscvCode.push_back(tmp);
}else {
riscvCode.push_back(" li s0, " + num2string_3(STK));
riscvCode.push_back(" add s0, s0, sp");
riscvCode.push_back(" lw ra, -4(s0)");
riscvCode.push_back(" li s0, " + num2string_3(STK));
riscvCode.push_back(" add sp, sp, s0");
riscvCode.push_back(" ret");
}
} else {
riscvCode.splice(riscvCode.end(), riscvAction);
}
}
| 35.201835
| 135
| 0.562419
|
Yibo-He
|
4236f3c151d40f8581667f417cbe6145c80ffa77
| 2,335
|
hpp
|
C++
|
addons/main/weapons/CfgWeapMG.hpp
|
johnb432/Weapons-Balance-FOW
|
9d72a7f5a86b59ed6c651b62a39cc08dd21f694e
|
[
"MIT"
] | null | null | null |
addons/main/weapons/CfgWeapMG.hpp
|
johnb432/Weapons-Balance-FOW
|
9d72a7f5a86b59ed6c651b62a39cc08dd21f694e
|
[
"MIT"
] | null | null | null |
addons/main/weapons/CfgWeapMG.hpp
|
johnb432/Weapons-Balance-FOW
|
9d72a7f5a86b59ed6c651b62a39cc08dd21f694e
|
[
"MIT"
] | null | null | null |
//https://old.weaponsystems.net/weaponsystem/AA06%20-%20Bren.html
class fow_w_bren: fow_rifle_base {
ACE_barrelLength = 635;
ACE_barrelTwist = 254;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "Bren Mk.II";
magazineReloadTime = 0;
magazineWell[] += {"CBA_303B_BREN"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 228.2;
};
};
class fow_w_fg42: fow_rifle_base {
ACE_barrelLength = 500;
ACE_barrelTwist = 240;
displayName = "FG 42";
magazineWell[] += {"CBA_792x57_FG42"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 93;
};
};
class fow_w_m1918a2: fow_rifle_base {
ACE_barrelLength = 610;
ACE_barrelTwist = 254;
displayName = "M1918A2 BAR";
magazineWell[] += {"CBA_3006_BAR"};
};
class fow_w_m1918a2_bak: fow_w_m1918a2 {
displayName = "M1918A2 BAR (Bakelite)";
};
class fow_w_m1919: fow_rifle_base {
ACE_barrelLength = 610;
ACE_barrelTwist = 254;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "M1919A4";
magazineWell[] += {"CBA_3006_Belt"};
class WeaponSlotsInfo: WeaponSlotsInfo {};
};
class fow_w_m1919a4: fow_w_m1919 {
displayName = "M1919A4";
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 310;
};
};
class fow_w_m1919a6: fow_w_m1919 {
displayName = "M1919A6";
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 330.7;
};
};
class fow_w_mg34: fow_rifle_base {
ACE_barrelLength = 627;
ACE_barrelTwist = 240;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "MG 34";
magazineReloadTime = 0;
magazineWell[] += {"CBA_792x57_LINKS"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 264.5;
};
};
class fow_w_mg42: fow_rifle_base {
ACE_barrelLength = 530;
ACE_barrelTwist = 240;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "MG 42";
magazineReloadTime = 0;
magazineWell[] += {"CBA_792x57_LINKS"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 254.5;
};
};
class fow_w_type99_lmg: fow_rifle_base {
ACE_barrelLength = 550;
ACE_barrelTwist = 254;
ACE_Overheating_allowSwapBarrel = 1;
displayName = "Type 99 LMG";
magazineReloadTime = 0;
magazineWell[] += {"CBA_77x58_Type99"};
class WeaponSlotsInfo: WeaponSlotsInfo {
mass = 299;
};
};
| 25.944444
| 65
| 0.667238
|
johnb432
|
423765ec487b397f7871841a4b4f5ae931495248
| 1,882
|
cpp
|
C++
|
src/ColdTowerShopItem.cpp
|
dgi09/Tower-Defence
|
2edd53d50c9f913d00de26e7e2bdc5e8b950cc02
|
[
"BSD-2-Clause"
] | 1
|
2021-07-28T15:24:00.000Z
|
2021-07-28T15:24:00.000Z
|
src/ColdTowerShopItem.cpp
|
dgi09/Tower-Defence
|
2edd53d50c9f913d00de26e7e2bdc5e8b950cc02
|
[
"BSD-2-Clause"
] | null | null | null |
src/ColdTowerShopItem.cpp
|
dgi09/Tower-Defence
|
2edd53d50c9f913d00de26e7e2bdc5e8b950cc02
|
[
"BSD-2-Clause"
] | null | null | null |
#include "ColdTowerShopItem.h"
#include "GamePlayMediator.h"
#include "ArenaHeap.h"
#include <functional>
#include "GUISystem.h"
#include "TowerCreationTool.h"
#include "ToolManager.h"
#include "SplashCreationTool.h"
ColdTowerShopItem::ColdTowerShopItem(void)
{
}
ColdTowerShopItem::~ColdTowerShopItem(void)
{
}
void ColdTowerShopItem::updateState(PlayerStat & stat)
{
if(stat.gold < itemCost)
{
button->loadImageFromFile("Data/ShopImages/coldTurretUnavailable.png");
state = UNACTIVE;
}
else
{
button->loadImageFromFile("Data/ShopImages/coldTurret.png");
state = ACTIVE;
}
button->setWidth(buttonW);
button->setHeight(buttonH);
}
void ColdTowerShopItem::init()
{
initGUI("Cold Tower","Data/ShopImages/coldTurret.png");
button->subsribeEvent(PRESS,new MemberSubsciber<ColdTowerShopItem>(&ColdTowerShopItem::onClick,this));
tower = ArenaHeap::getPtr()->ColdTowers.New();
tower->init();
}
void ColdTowerShopItem::onDestroy()
{
destroyGUI();
tower->destroy();
tower->removeFromHeap();
}
void ColdTowerShopItem::onClick(Widget * sender)
{
if(state == ACTIVE)
{
TowerCreationTool * tool = new TowerCreationTool();
tool->setTower(tower->copy());
tool->setTowerCost(itemCost);
ToolManager::getPtr()->setActiveTool(tool);
}
}
void ColdTowerShopItem::setDamage(double damage)
{
tower->setDamageValue(damage);
}
void ColdTowerShopItem::setAmmoSpeed(int speed)
{
tower->setAmmoSpeed(speed);
}
void ColdTowerShopItem::setRange(double range)
{
tower->setRangeValue(range);
}
void ColdTowerShopItem::setShootRate(int ms)
{
tower->setShootRate(ms);
}
void ColdTowerShopItem::setSlowDuration(int ms)
{
tower->setSlowingDuration(ms);
}
void ColdTowerShopItem::setSpeedDecrease(int speedDecrease)
{
tower->setSpeedDecrease(speedDecrease);
}
void ColdTowerShopItem::postPropertySet()
{
ic.init(itemCost,tower);
ic.attach(info);
}
| 17.109091
| 103
| 0.745484
|
dgi09
|
423e648f5f47046258fed6b8938ba99d024c7d8f
| 3,229
|
cpp
|
C++
|
src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | 1
|
2020-04-30T15:47:35.000Z
|
2020-04-30T15:47:35.000Z
|
src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "glextensions.h"
#define RESOLVE_GL_FUNC(f) ok &= bool((f = (_gl##f) context->getProcAddress(QLatin1String("gl" #f))));
bool GLExtensionFunctions::resolve(const QGLContext *context)
{
bool ok = true;
RESOLVE_GL_FUNC(GenFramebuffersEXT)
RESOLVE_GL_FUNC(GenRenderbuffersEXT)
RESOLVE_GL_FUNC(BindRenderbufferEXT)
RESOLVE_GL_FUNC(RenderbufferStorageEXT)
RESOLVE_GL_FUNC(DeleteFramebuffersEXT)
RESOLVE_GL_FUNC(DeleteRenderbuffersEXT)
RESOLVE_GL_FUNC(BindFramebufferEXT)
RESOLVE_GL_FUNC(FramebufferTexture2DEXT)
RESOLVE_GL_FUNC(FramebufferRenderbufferEXT)
RESOLVE_GL_FUNC(CheckFramebufferStatusEXT)
RESOLVE_GL_FUNC(ActiveTexture)
RESOLVE_GL_FUNC(TexImage3D)
RESOLVE_GL_FUNC(GenBuffers)
RESOLVE_GL_FUNC(BindBuffer)
RESOLVE_GL_FUNC(BufferData)
RESOLVE_GL_FUNC(DeleteBuffers)
RESOLVE_GL_FUNC(MapBuffer)
RESOLVE_GL_FUNC(UnmapBuffer)
return ok;
}
bool GLExtensionFunctions::fboSupported() {
return GenFramebuffersEXT
&& GenRenderbuffersEXT
&& BindRenderbufferEXT
&& RenderbufferStorageEXT
&& DeleteFramebuffersEXT
&& DeleteRenderbuffersEXT
&& BindFramebufferEXT
&& FramebufferTexture2DEXT
&& FramebufferRenderbufferEXT
&& CheckFramebufferStatusEXT;
}
bool GLExtensionFunctions::openGL15Supported() {
return ActiveTexture
&& TexImage3D
&& GenBuffers
&& BindBuffer
&& BufferData
&& DeleteBuffers
&& MapBuffer
&& UnmapBuffer;
}
#undef RESOLVE_GL_FUNC
| 35.483516
| 102
| 0.691855
|
power-electro
|
4244cf3519c3f83103e5e498a05f02df486a4631
| 91
|
cc
|
C++
|
muduo/net/boilerplate.cc
|
923310233/muduoTest
|
03c291df5605479ece4fc031ab3dd619c8c8f73a
|
[
"BSD-3-Clause"
] | null | null | null |
muduo/net/boilerplate.cc
|
923310233/muduoTest
|
03c291df5605479ece4fc031ab3dd619c8c8f73a
|
[
"BSD-3-Clause"
] | null | null | null |
muduo/net/boilerplate.cc
|
923310233/muduoTest
|
03c291df5605479ece4fc031ab3dd619c8c8f73a
|
[
"BSD-3-Clause"
] | null | null | null |
#include "muduo/net/BoilerPlate.h"
using namespace muduo;
using namespace muduo::net;
| 10.111111
| 34
| 0.747253
|
923310233
|
424639e79751125238e05d98a96dd490fced1f81
| 1,074
|
cpp
|
C++
|
workshop8/IntlPhone.cpp
|
PavanKamra96/BTP200
|
516f5ed60452da53d47206caef22423825a3145e
|
[
"MIT"
] | null | null | null |
workshop8/IntlPhone.cpp
|
PavanKamra96/BTP200
|
516f5ed60452da53d47206caef22423825a3145e
|
[
"MIT"
] | null | null | null |
workshop8/IntlPhone.cpp
|
PavanKamra96/BTP200
|
516f5ed60452da53d47206caef22423825a3145e
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "Phone.h"
IntlPhone::IntlPhone(){
country_Code = 0;
}
IntlPhone::IntlPhone(int regionCode, int areaCode, int localNumber): Phone(areaCode, localNumber) {
//ctor
if (regionCode >= 1 && regionCode <= 999) {
country_Code = regionCode;
} else
*this = IntlPhone();
}
void IntlPhone::display() const {
std::cout << country_Code << '-';
Phone::display();
}
bool IntlPhone::isValid() const {
return country_Code != 0;
}
std::istream & operator >> (std::istream & is, IntlPhone & p) {
int tempRegionCode;
int tempAreaCode;
int tempLocaleNumber;
std::cout << "Country : ";
is >> tempRegionCode;
if (tempRegionCode >= 1 && tempRegionCode <= 999) {
std::cout << "Area Code : ";
is >> tempAreaCode;
std::cout << "Local No. : ";
is >> tempLocaleNumber;
}
IntlPhone temp(tempRegionCode, tempAreaCode, tempLocaleNumber);
p = temp;
return is;
}
std::ostream & operator << (std::ostream & os,
const IntlPhone & p) {
p.display();
return os;
}
| 21.918367
| 100
| 0.608007
|
PavanKamra96
|
42465f2891251668ec041517ceea4841891deed4
| 800
|
cpp
|
C++
|
src/components/src/core/Component.cpp
|
walter-strazak/chimarrao
|
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
|
[
"MIT"
] | 6
|
2021-04-20T10:32:29.000Z
|
2021-06-05T11:48:56.000Z
|
src/components/src/core/Component.cpp
|
walter-strazak/chimarrao
|
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
|
[
"MIT"
] | 1
|
2021-05-18T21:00:12.000Z
|
2021-06-02T07:59:03.000Z
|
src/components/src/core/Component.cpp
|
walter-strazak/chimarrao
|
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
|
[
"MIT"
] | 3
|
2020-09-12T08:54:04.000Z
|
2021-04-17T11:16:36.000Z
|
#include "Component.h"
#include "ComponentOwner.h"
namespace components::core
{
Component::Component(ComponentOwner* ownerInit) : owner{ownerInit} {}
void Component::loadDependentComponents() {}
void Component::update(utils::DeltaTime, const input::Input&) {}
void Component::lateUpdate(utils::DeltaTime, const input::Input&) {}
void Component::enable()
{
enabled = true;
}
void Component::disable()
{
enabled = false;
}
bool Component::isEnabled() const
{
return enabled;
}
std::string Component::getOwnerName() const
{
return owner->getName();
}
unsigned int Component::getOwnerId() const
{
return owner->getId();
}
bool Component::shouldBeRemoved() const
{
return owner->shouldBeRemoved();
}
ComponentOwner& Component::getOwner() const
{
return *owner;
}
}
| 16
| 69
| 0.70625
|
walter-strazak
|
4247f6d342a62cdcce8c0dab9c859a873e016ffa
| 13,178
|
cpp
|
C++
|
Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp
|
Milxnor/Nacro
|
eebabf662bbce6d5af41820ea0342d3567a0aecc
|
[
"BSD-2-Clause"
] | 11
|
2021-08-08T23:25:10.000Z
|
2022-02-19T23:07:22.000Z
|
Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp
|
Milxnor/Nacro
|
eebabf662bbce6d5af41820ea0342d3567a0aecc
|
[
"BSD-2-Clause"
] | 1
|
2022-01-01T22:51:59.000Z
|
2022-01-08T16:14:15.000Z
|
Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp
|
Milxnor/Nacro
|
eebabf662bbce6d5af41820ea0342d3567a0aecc
|
[
"BSD-2-Clause"
] | 8
|
2021-08-09T13:51:54.000Z
|
2022-01-26T20:33:37.000Z
|
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortAccountItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Update_Bang_State(class UFortAccountItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State");
UBP_FortExpeditionListItem_C_Update_Bang_State_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Success_Chance(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance");
UBP_FortExpeditionListItem_C_Set_Success_Chance_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Expedition (ConstParm, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Vehicle_Icon(class UFortExpeditionItem* Expedition)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon");
UBP_FortExpeditionListItem_C_Set_Vehicle_Icon_Params params;
params.Expedition = Expedition;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* InputPin (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Expedition_Returns_Data(class UFortExpeditionItem* InputPin)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data");
UBP_FortExpeditionListItem_C_Set_Expedition_Returns_Data_Params params;
params.InputPin = InputPin;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_In_Progress_State(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State");
UBP_FortExpeditionListItem_C_Set_In_Progress_State_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Remaining_Expiration_Time(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time");
UBP_FortExpeditionListItem_C_Set_Remaining_Expiration_Time_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rarity(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity");
UBP_FortExpeditionListItem_C_Set_Rarity_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rating(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating");
UBP_FortExpeditionListItem_C_Set_Rating_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rewards(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards");
UBP_FortExpeditionListItem_C_Set_Rewards_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
// class UFortExpeditionItemDefinition* Item_Def (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Get_Expedition_Item_Definition(class UFortItem* Item, class UFortExpeditionItemDefinition** Item_Def)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition");
UBP_FortExpeditionListItem_C_Get_Expedition_Item_Definition_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Item_Def != nullptr)
*Item_Def = params.Item_Def;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Name(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name");
UBP_FortExpeditionListItem_C_Set_Name_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Expedition (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Setup_Base_Item_Data(class UFortExpeditionItem* Expedition)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data");
UBP_FortExpeditionListItem_C_Setup_Base_Item_Data_Params params;
params.Expedition = Expedition;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.SetData
// (Event, Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UObject** InData (Parm, ZeroConstructor, IsPlainOldData)
// class UCommonListView** OwningList (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::SetData(class UObject** InData, class UCommonListView** OwningList)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.SetData");
UBP_FortExpeditionListItem_C_SetData_Params params;
params.InData = InData;
params.OwningList = OwningList;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnSelected
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnSelected()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnSelected");
UBP_FortExpeditionListItem_C_OnSelected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnItemChanged()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged");
UBP_FortExpeditionListItem_C_OnItemChanged_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnDeselected
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnDeselected()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnDeselected");
UBP_FortExpeditionListItem_C_OnDeselected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature
// (BlueprintEvent)
// Parameters:
// class UWidget* ActiveWidget (Parm, ZeroConstructor, IsPlainOldData)
// int ActiveWidgetIndex (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature(class UWidget* ActiveWidget, int ActiveWidgetIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature");
UBP_FortExpeditionListItem_C_BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature_Params params;
params.ActiveWidget = ActiveWidget;
params.ActiveWidgetIndex = ActiveWidgetIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnHovered
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnHovered()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnHovered");
UBP_FortExpeditionListItem_C_OnHovered_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::ExecuteUbergraph_BP_FortExpeditionListItem(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem");
UBP_FortExpeditionListItem_C_ExecuteUbergraph_BP_FortExpeditionListItem_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 33.277778
| 213
| 0.773258
|
Milxnor
|
424b68c2de65ac475af42da66f7a935a66b8460f
| 299
|
cpp
|
C++
|
13_ploymorph/main.cpp
|
Aaron-labo/Cpp_StudyNotes
|
afff37736468b26dad87e9b5cda90f1e5f1efb06
|
[
"Unlicense"
] | 1
|
2021-06-17T11:37:42.000Z
|
2021-06-17T11:37:42.000Z
|
13_ploymorph/main.cpp
|
Aaron-labo/Cpp_StudyNotes
|
afff37736468b26dad87e9b5cda90f1e5f1efb06
|
[
"Unlicense"
] | null | null | null |
13_ploymorph/main.cpp
|
Aaron-labo/Cpp_StudyNotes
|
afff37736468b26dad87e9b5cda90f1e5f1efb06
|
[
"Unlicense"
] | null | null | null |
#include "Circle.h"
#include "Rect.h"
int main()
{
Circle c(1, 2, 3);
Rect r(10, 20, 30, 40);
Shape s(1, 2);
s.show();
int input;
while (1) {
cin >> input;
switch (input)
{
case 1:
s = &c;;
s->show();
break;
case 2:
s = &r;;
s->show();
break;
}
}
return 0;
}
| 10.678571
| 24
| 0.478261
|
Aaron-labo
|
424f0a9d20c8f5343f00778ce197924e1945e367
| 1,178
|
cpp
|
C++
|
Based_Engine/Based_Engine/TextureResource.cpp
|
Sanmopre/Based_Engine
|
2a408dc501f6357bde9872e2eef70f67295e0a3a
|
[
"MIT"
] | null | null | null |
Based_Engine/Based_Engine/TextureResource.cpp
|
Sanmopre/Based_Engine
|
2a408dc501f6357bde9872e2eef70f67295e0a3a
|
[
"MIT"
] | null | null | null |
Based_Engine/Based_Engine/TextureResource.cpp
|
Sanmopre/Based_Engine
|
2a408dc501f6357bde9872e2eef70f67295e0a3a
|
[
"MIT"
] | null | null | null |
#include "TextureResource.h"
#include "FileSystem.h"
TextureResource::TextureResource(uint uid, const char* assetsFile, const char* libraryFile)
: Resource(uid, FileType::IMAGE, assetsFile, libraryFile)
{
}
TextureResource::~TextureResource()
{
}
const Texture TextureResource::GetTexture() const
{
return texture;
}
bool TextureResource::LoadInMemory()
{
texture = TextureLoader::Load(assetsFile.c_str());
if (texture.id != NULL)
return true;
return false;
}
bool TextureResource::Unload()
{
texture = { NULL, NULL, NULL };
return true;
}
//void Input::ProccesImage(std::string file)
//{
// GameObject* object = App->objects->selected;
// if (!object)
// {
// object = App->objects->AddObject(nullptr, App->objects->selected, true, "Plane");
// object->AddMeshComponent("Library/Meshes/plane.monki", file.c_str());
// }
// else
// {
// bool found = false;
// for (uint c = 0; c < object->components.size(); c++)
// {
// if (object->components[c]->AddTexture(file.c_str()))
// {
// found = true;
// break;
// }
// }
// if (!found)
// object->AddMeshComponent("Library/Meshes/plane.monki", file.c_str());
// }
//}
| 20.666667
| 91
| 0.643463
|
Sanmopre
|
425b96f71cb7f3ec403821d7c11418ca6bf893b4
| 2,999
|
hpp
|
C++
|
include/libtorrent/aux_/websocket_tracker_connection.hpp
|
redchief/libtorrent
|
42917790b1606b5ea0cf5385fde44536c7040a27
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
include/libtorrent/aux_/websocket_tracker_connection.hpp
|
redchief/libtorrent
|
42917790b1606b5ea0cf5385fde44536c7040a27
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
include/libtorrent/aux_/websocket_tracker_connection.hpp
|
redchief/libtorrent
|
42917790b1606b5ea0cf5385fde44536c7040a27
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2019 Paul-Louis Ageneau
Copyright (c) 2020, Paul-Louis Ageneau
All rights reserved.
You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/
#ifndef TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED
#define TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED
#include "libtorrent/config.hpp"
#if TORRENT_USE_RTC
#include "libtorrent/aux_/rtc_signaling.hpp" // for rtc_offer and rtc_answer
#include "libtorrent/aux_/websocket_stream.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io_context.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/aux_/resolver_interface.hpp"
#include "libtorrent/aux_/tracker_manager.hpp" // for tracker_connection
#include "libtorrent/aux_/ssl.hpp"
#include <boost/beast/core/flat_buffer.hpp>
#include <map>
#include <memory>
#include <queue>
#include <tuple>
#include <variant>
#include <optional>
namespace libtorrent::aux {
struct tracker_answer
{
sha1_hash info_hash;
peer_id pid;
aux::rtc_answer answer;
};
struct TORRENT_EXTRA_EXPORT websocket_tracker_connection : tracker_connection
{
friend class tracker_manager;
websocket_tracker_connection(
io_context& ios
, tracker_manager& man
, tracker_request const& req
, std::weak_ptr<request_callback> cb);
~websocket_tracker_connection() override = default;
void start() override;
void close() override;
bool is_started() const;
bool is_open() const;
void queue_request(tracker_request req, std::weak_ptr<request_callback> cb);
void queue_answer(tracker_answer ans);
private:
std::shared_ptr<websocket_tracker_connection> shared_from_this()
{
return std::static_pointer_cast<websocket_tracker_connection>(
tracker_connection::shared_from_this());
}
void send_pending();
void do_send(tracker_request const& req);
void do_send(tracker_answer const& ans);
void do_read();
void on_timeout(error_code const& ec) override;
void on_connect(error_code const& ec);
void on_read(error_code ec, std::size_t bytes_read);
void on_write(error_code const& ec, std::size_t bytes_written);
void fail(operation_t op, error_code const& ec);
io_context& m_io_context;
ssl::context m_ssl_context;
std::shared_ptr<aux::websocket_stream> m_websocket;
boost::beast::flat_buffer m_read_buffer;
std::string m_write_data;
using tracker_message = std::variant<tracker_request, tracker_answer>;
std::queue<std::tuple<tracker_message, std::weak_ptr<request_callback>>> m_pending;
std::map<sha1_hash, std::weak_ptr<request_callback>> m_callbacks;
bool m_sending = false;
};
struct websocket_tracker_response {
sha1_hash info_hash;
std::optional<tracker_response> resp;
std::optional<aux::rtc_offer> offer;
std::optional<aux::rtc_answer> answer;
};
TORRENT_EXTRA_EXPORT std::variant<websocket_tracker_response, std::string>
parse_websocket_tracker_response(span<char const> message, error_code &ec);
}
#endif // TORRENT_USE_RTC
#endif // TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED
| 27.263636
| 84
| 0.791931
|
redchief
|
425f925acdc49fd521e74e7d0237aea88e107117
| 470
|
hpp
|
C++
|
Results.hpp
|
h-g-s/ddtree
|
4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4
|
[
"MIT"
] | 1
|
2019-11-30T14:48:40.000Z
|
2019-11-30T14:48:40.000Z
|
Results.hpp
|
h-g-s/ddtree
|
4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4
|
[
"MIT"
] | null | null | null |
Results.hpp
|
h-g-s/ddtree
|
4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4
|
[
"MIT"
] | null | null | null |
/*
* Results.hpp
*
* Created on: 27 de fev de 2019
* Author: haroldo
*/
#ifndef RESULTS_HPP_
#define RESULTS_HPP_
#include <string>
#include <vector>
#include "InstanceSet.hpp"
class Results
{
public:
Results( const InstanceSet &_iset, const char *resFile );
const std::vector< std::string > &algorithms() const;
virtual ~Results ();
private:
const InstanceSet &iset_;
std::vector< std::string > algs_;
};
#endif /* RESULTS_HPP_ */
| 15.666667
| 61
| 0.659574
|
h-g-s
|
42659843db1fe95995440df1b137db6d97ff4dfe
| 16,470
|
cpp
|
C++
|
Windows Pin/Windows Pin.cpp
|
barty32/windows-pin
|
d89fb0352c5934c403efcfb6518979717920876c
|
[
"MIT"
] | null | null | null |
Windows Pin/Windows Pin.cpp
|
barty32/windows-pin
|
d89fb0352c5934c403efcfb6518979717920876c
|
[
"MIT"
] | null | null | null |
Windows Pin/Windows Pin.cpp
|
barty32/windows-pin
|
d89fb0352c5934c403efcfb6518979717920876c
|
[
"MIT"
] | null | null | null |
// Windows Pin.cpp : Defines the entry point for the application.
//
#include "Windows Pin.h"
#include "PinDll.h"
bool g_bPinning = false;
HCURSOR g_hPinCursor = NULL;
std::list<HWND> g_pinnedWnds;
// Global Variables:
HINSTANCE hInst;
HWND hWndMain;
const UINT WM_TASKBARCREATED = RegisterWindowMessageW(L"TaskbarCreated");
HHOOK hHook = NULL;
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow){
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
hInst = hInstance;
g_hPinCursor = LoadCursorW(hInst, MAKEINTRESOURCEW(IDI_PIN_CURSOR));
// Register main window class (hidden)
WNDCLASSEXW wcex = {0};
wcex.cbSize = sizeof(WNDCLASSEXW);
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = L"WindowsPinWndClass";
if(!RegisterClassExW(&wcex)){
ErrorHandler(L"Class registration failed", GetLastError());
return false;
}
hWndMain = CreateWindowExW(WS_EX_LAYERED, L"WindowsPinWndClass", L"Windows Pin", WS_POPUP, 0, 0, 0, 0, 0, 0, hInstance, 0);
if(!hWndMain){
ErrorHandler(L"Window creation failed", GetLastError());
return false;
}
NOTIFYICONDATAW* nid = CreateTrayIcon(hWndMain);
if(!Shell_NotifyIconW(NIM_ADD, (PNOTIFYICONDATAW)GetPropW(hWndMain, L"trayIcon"))){
ErrorHandler(L"Tray icon creation failed", GetLastError());
return false;
}
// Prepare tray popup menu
HMENU hPopMenu = CreatePopupMenu();
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_ABOUT, L"About");
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_PIN, L"Pin a window");
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_UNPIN, L"Unpin all pinned windows");
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_SEPARATOR, 0, NULL);
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_EXIT, L"Exit");
SetPropW(hWndMain, L"hPopMenu", hPopMenu);
// Inject DLL to all 32-bit processes
hHook = SetWindowsHookExW(WH_GETMESSAGE, ExportHookProc, GetModuleHandleW(L"PinDll32"), 0);
if(!hHook){
ErrorHandler(L"32-bit hooking failed", GetLastError());
return false;
}
HANDLE currentProcess = nullptr;
if(Is64BitWindows()){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
currentProcess = OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId());
std::wstring cmd = L"Inject64.exe --handle " + std::to_wstring((int)currentProcess);
// Start the child process.
if(!CreateProcessW(nullptr,
(LPWSTR)cmd.data(),
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
TRUE, // Handle inheritance
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
){
ErrorHandler(L"64-bit hook execution failed", GetLastError());
return false;
}
WaitForSingleObject(pi.hProcess, 500);
DWORD dwExitCode;
GetExitCodeProcess(pi.hProcess, &dwExitCode);
if(dwExitCode != STILL_ACTIVE && dwExitCode > 0){
ErrorHandler(L"64-bit hook error", dwExitCode);
return false;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
MSG msg;
while(GetMessageW(&msg, NULL, 0, 0)){
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
delete nid;
DestroyMenu(hPopMenu);
if(currentProcess){
CloseHandle(currentProcess);
}
//UnhookWindowsHookEx(hook);
return (int)msg.wParam;
}
//LRESULT CALLBACK LowLevelMouseProc(
// _In_ int nCode,
// _In_ WPARAM wParam,
// _In_ LPARAM lParam
//){
// static bool bCaptured = false;
// if(nCode >= HC_ACTION){
// LPMSLLHOOKSTRUCT mss = (LPMSLLHOOKSTRUCT)lParam;
// if(g_bPinning){
// switch(wParam){
// case WM_LBUTTONDOWN:
// if(!bCaptured){
// //CallNextHookEx(NULL, nCode, WM_LBUTTONDOWN, lParam);
// //DefWindowProcW(hWndMain, WM_LBUTTONDOWN, 0, MAKELPARAM(mss->pt.x, mss->pt.y));
// //SetCursorPos(mss->pt.x, mss->pt.y);
// SetCursor(g_hPinCursor);
// SetCapture(hWndMain);
// bCaptured = true;
// return false;
// }
// //case WM_LBUTTONDOWN:
// //case WM_MOUSEMOVE:
// //SetCursorPos(100, 100);
//
// //SetCapture(hWndMain);
// //return true;
//
// }
// }
// }
// return CallNextHookEx(NULL, nCode, wParam, lParam);
//}
bool StartPin(HWND hWnd){
g_bPinning = true;
POINT pos;
GetCursorPos(&pos);
// Hacky solution to set mouse capture without clicking
SetWindowPos(hWnd, HWND_TOPMOST, pos.x - 10, pos.y - 10, 20, 20, SWP_SHOWWINDOW);
SetLayeredWindowAttributes(hWnd, RGB(255, 0, 0), 200, LWA_COLORKEY | LWA_ALPHA);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
SetCursor(LoadCursorW(hInst, MAKEINTRESOURCEW(IDI_PIN_CURSOR)));
SetCapture(hWnd);
SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_HIDEWINDOW);
return true;
}
bool EndPin(){
g_bPinning = false;
// Determine the window that lies underneath the mouse cursor.
POINT pt;
GetCursorPos(&pt);
HWND hWnd = FindParent(WindowFromPoint(pt));
ReleaseCapture();
InvalidateRect(NULL, NULL, FALSE);
if(CheckWindowValidity(hWnd)){
//WCHAR title[120];
//GetWindowTextW(hWnd, title, 120);
//WCHAR result[200];
//_snwprintf_s(result, 200, L"Handle: 0x%08X\nTitle: %s", (int)hWnd, title);
//MessageBoxW(NULL, result, L"Info", MB_ICONINFORMATION);
PinWindow(hWnd);
return true;
}
return false;
}
bool MovePin(){
static HWND lastWnd = NULL;
POINT pt;
GetCursorPos(&pt);
// Determine the window that lies underneath the mouse cursor.
HWND hWnd = FindParent(WindowFromPoint(pt));
if(lastWnd == hWnd){
return false;
}
// If there was a previously found window, we must instruct it to refresh itself.
if(lastWnd){
InvalidateRect(NULL, NULL, TRUE);
UpdateWindow(lastWnd);
RedrawWindow(lastWnd, NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
}
// Indicate that this found window is now the current found window.
lastWnd = hWnd;
// Check first for validity.
if(CheckWindowValidity(hWnd)){
return HighlightWindow(hWnd);
}
return false;
}
bool HighlightWindow(HWND hWnd){
HDC hdcScreen = GetWindowDC(NULL);
if(!hdcScreen){
TRACE(L"Highligt window failed - HDC is null");
return false;
}
RECT rcWnd;
if(FAILED(DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rcWnd, sizeof(rcWnd)))){
//TRACE(L"Highligt window failed - GetWindowAttr failed");
GetWindowRect(hWnd, &rcWnd);
}
HPEN hPen = CreatePen(PS_SOLID, 10, RGB(255, 0, 0));
HGDIOBJ oldBrush = SelectObject(hdcScreen, GetStockObject(HOLLOW_BRUSH));
HGDIOBJ oldPen = SelectObject(hdcScreen, hPen);
Rectangle(hdcScreen, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
// Cleanup
SelectObject(hdcScreen, oldBrush);
SelectObject(hdcScreen, oldPen);
DeleteObject(hPen);
ReleaseDC(NULL, hdcScreen);
return true;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){
if(message == WM_TASKBARCREATED){
Shell_NotifyIconW(NIM_ADD, (PNOTIFYICONDATAW)GetPropW(hWnd, L"trayIcon"));
}
switch(message){
case WM_COMMAND:
// Parse the menu selections:
switch(LOWORD(wParam)){
case IDM_PIN:
//PinActiveWindow(hWnd);
StartPin(hWnd);
break;
case IDM_UNPIN:
for(auto wnd : g_pinnedWnds){
UnpinWindow(wnd);
}
g_pinnedWnds.clear();
break;
case IDM_ABOUT:
return DialogBoxParamW(hInst, MAKEINTRESOURCEW(IDD_ABOUTBOX), hWnd, About, 0);
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProcW(hWnd, message, wParam, lParam);
}
break;
case WM_LBUTTONUP:
if(g_bPinning){
EndPin();
return false;
}
break;
case WM_MOUSEMOVE:
if(g_bPinning){
MovePin();
return false;
}
break;
case WM_USER_SHELLICON:
switch(LOWORD(lParam)){
case WM_RBUTTONUP:
{
POINT lpClickPoint;
UINT uFlag = MF_BYPOSITION | MF_STRING;
GetCursorPos(&lpClickPoint);
TrackPopupMenu((HMENU)GetPropW(hWnd, L"hPopMenu"), TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_BOTTOMALIGN, lpClickPoint.x, lpClickPoint.y, 0, hWnd, NULL);
return true;
}
case WM_LBUTTONUP:
StartPin(hWnd);
return false;
}
break;
case WM_DESTROY:
UnhookWindowsHookEx(hHook);
Shell_NotifyIconW(NIM_DELETE, (PNOTIFYICONDATAW)GetPropW(hWnd, L"trayIcon"));
PostQuitMessage(0);
break;
default:
return DefWindowProcW(hWnd, message, wParam, lParam);
}
return DefWindowProcW(hWnd, message, wParam, lParam);
}
bool PinWindow(HWND hWnd){
LONG dwExStyle = GetWindowLongW(hWnd, GWL_EXSTYLE);
dwExStyle |= WS_EX_TOPMOST;
SetWindowLongW(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW);
g_pinnedWnds.push_back(hWnd);
return true;
}
bool UnpinWindow(HWND hWnd){
LONG dwExStyle = GetWindowLongW(hWnd, GWL_EXSTYLE);
dwExStyle &= ~WS_EX_TOPMOST;
SetWindowLongW(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW);
return true;
}
NOTIFYICONDATAW* CreateTrayIcon(HWND hWnd){
// Create tray icon
NOTIFYICONDATAW* nidApp = new NOTIFYICONDATAW;
if(!nidApp) return nullptr;
nidApp->cbSize = sizeof(NOTIFYICONDATAW);
nidApp->hWnd = hWnd; //handle of the window which will process this app. messages
nidApp->uID = IDI_WINDOWSPIN; //ID of the icon that will appear in the system tray
nidApp->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nidApp->hIcon = LoadIconW(hInst, MAKEINTRESOURCEW(IDI_WINDOWSPIN));
nidApp->uCallbackMessage = WM_USER_SHELLICON;
LoadStringW(hInst, IDS_APPTOOLTIP, nidApp->szTip, _countof(nidApp->szTip));
SetPropW(hWnd, L"trayIcon", nidApp);
return nidApp;
}
bool CheckWindowValidity(HWND hWnd){
if(!hWnd || !IsWindow(hWnd) || hWnd == GetShellWindow() || hWnd == FindWindowW(L"Shell_TrayWnd", NULL)){
return false;
}
return true;
}
HWND FindParent(HWND hWnd){
DWORD dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
if(dwStyle & WS_CHILD){
return FindParent(GetParent(hWnd));
}
return hWnd;
}
bool Is64BitWindows(){
#if defined(_WIN64)
return true; // 64-bit programs run only on Win64
#elif defined(_WIN32)
// 32-bit programs run on both 32-bit and 64-bit Windows, so must sniff
BOOL f64 = FALSE;
return IsWow64Process(GetCurrentProcess(), &f64) && f64;
#else
return false; // Win64 does not support Win16
#endif
}
void ErrorHandler(LPCWSTR errMsg, DWORD errCode, DWORD dwType){
std::wstring msg(errMsg);
if(errCode){
msg.append(L"\nError code: " + std::to_wstring(errCode));
}
MessageBoxW(NULL, msg.c_str(), L"Windows Pin - Error", dwType | MB_OK);
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam){
UNREFERENCED_PARAMETER(lParam);
switch (message){
case WM_INITDIALOG:
return true;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL){
EndDialog(hDlg, LOWORD(wParam));
return true;
}
break;
}
return false;
}
//void PinActiveWindow(HWND hWndApp){
// HWND hwndWindow = GetWindow(GetDesktopWindow(), GW_HWNDFIRST);// GetForegroundWindow();
// LONG dwExStyle = GetWindowLongPtrW(hwndWindow, GWL_EXSTYLE);
// HWND hInsertAfter = NULL;
// if(dwExStyle & WS_EX_TOPMOST){
// dwExStyle &= ~WS_EX_TOPMOST;
// hInsertAfter = HWND_NOTOPMOST;
// ModifyMenuW((HMENU)GetPropW(hWndApp, L"hPopMenu"), IDM_PIN, MF_BYCOMMAND, IDM_PIN, L"Pin current window");
// }
// else{
// dwExStyle |= WS_EX_TOPMOST;
// hInsertAfter = HWND_TOPMOST;
// ModifyMenuW((HMENU)GetPropW(hWndApp, L"hPopMenu"), IDM_PIN, MF_BYCOMMAND, IDM_PIN, L"Unpin current window");
// }
// SetWindowLongPtrW(hwndWindow, GWL_EXSTYLE, dwExStyle);
// SetWindowPos(hwndWindow, hInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW);
//}
//---------------------------------------------------------------------------------------------InitInstance
//BOOL InitInstance(HINSTANCE hInstance){
// obtain msghook library functions
/*HINSTANCE g_hInstLib = LoadLibraryW(L"WindowPinDll.dll");
if(g_hInstLib == NULL){
return FALSE;
}
pfnSetMsgHook = (SetMsgHookT)GetProcAddress(g_hInstLib, "SetMsgHook");
if(NULL == pfnSetMsgHook){
FreeLibrary(g_hInstLib);
return FALSE;
}
pfnUnsetMsgHook = (UnsetMsgHookT)GetProcAddress(g_hInstLib, "UnsetMsgHook");
if(NULL == pfnUnsetMsgHook){
FreeLibrary(g_hInstLib);
return FALSE;
}
pfnSetMsgHook();*/
//(SetMsgHookT)GetProcAddress(g_hInstLib, "SetMsgHook");
//hHook = SetWindowsHookExW(WH_CALLWNDPROC, /*(HOOKPROC)*/HookProc/*GetProcAddress(g_hInstLib, "HookProc")*/, g_hInstLib/*GetModuleHandleW(L"WindowPinDll.dll")*/, 0);
//if(hHook == NULL){
// int error = GetLastError();
//}
//hHook64 = SetWindowsHookExW(WH_CALLWNDPROC, (HOOKPROC)HookProc, GetModuleHandleW(L"WindowPinDll64"), 0);
//hHookCbt = SetWindowsHookExW(WH_CBT, (HOOKPROC)/*CBTProc*/GetProcAddress(g_hInstLib, "CBTProc"), g_hInstLib/*GetModuleHandleW(L"WindowPinDll.dll")*/, 0);
//bPump = TRUE;
//MSG msg;
//while(bPump){
// // Keep pumping...
// PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE);
// TranslateMessage(&msg);
// DispatchMessageW(&msg);
// Sleep(10);
//}
//int error = GetLastError();
//WinExec("notepad.exe", 1);
//}
/*
bool HighlightWindow(HWND hWndIn){
HWND hWnd = hWndIn;//FindParent(hWndIn);
//OutputDebugStringW(std::format(L"Highlighting current window {}\n", (int)hWndIn).c_str());
HDC hdcScreen = GetWindowDC(NULL);
if(!hdcScreen){
ErrorHandler(L"DC is null", GetLastError());
return false;
}
RECT rcWnd;
//GetWindowRect(hWnd, &rcWnd);
DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rcWnd, sizeof(rcWnd));
//RECT rcScreen = {0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)};
//int scrW = GetSystemMetrics(SM_CXSCREEN);
//int scrH = GetSystemMetrics(SM_CYSCREEN);
//RedrawWindow(GetDesktopWindow(), NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
//if(bRefresh){
// InvalidateRect(NULL, NULL, false);
//}
//WCHAR ss[100];
//GetWindowTextW(hWnd, ss, 100);
//HDC tempDC = CreateCompatibleDC(NULL);
//BitBlt(tempDC, 0, 0, rcWnd.right - rcWnd.left, rcWnd.bottom - rcWnd.top, hdc, )
//ExcludeClipRect(hdc, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
//HDC tmpDC = CreateCompatibleDC(g_hdcScreen);
//HBITMAP hBmp = CreateCompatibleBitmap(tmpDC, scrW, scrH);
//SelectObject(tmpDC, hBmp);
//BitBlt(tmpDC, 0, 0, scrW, scrH, g_hdcScreen, 0, 0, SRCCOPY);
//FillRect(tmpDC, &rcWnd, (HBRUSH)CreateSolidBrush(RGB(255, 255, 255)));
//FillRect(tmpDC, &rcWnd, (HBRUSH)GetStockObject(HOLLOW_BRUSH));
HGDIOBJ oldBrush = SelectObject(hdcScreen, GetStockObject(HOLLOW_BRUSH));
HGDIOBJ oldPen = SelectObject(hdcScreen, CreatePen(PS_SOLID, 10, RGB(255, 0, 0)));
////Rectangle(hdc, 0, 0, scrW, scrH);
Rectangle(hdcScreen, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
//InvalidateRect(hWnd, NULL, FALSE);
//FillRect(hdc, &rcWnd, (HBRUSH)GetStockObject(HOLLOW_BRUSH));
//SelectObject(hdc, )
//FillRect(hdc, &rcScreen, );
//BLENDFUNCTION bf = {0};
//bf.SourceConstantAlpha = 200;
//bf.AlphaFormat = AC_SRC_ALPHA;
//if(!AlphaBlend(hdc, 0, 0, scrW, scrH, tmpDC, 0, 0, scrW, scrH, bf)){
// OutputDebugStringW(L"AplhaBlend failed");
//}
//TransparentBlt(hdcScreen, 0, 0, scrW, scrH, tmpDC, 0, 0, scrW, scrH, RGB(255, 255, 255));
SelectObject(hdcScreen, oldBrush);
SelectObject(hdcScreen, oldPen);
ReleaseDC(NULL, hdcScreen);
return true;
}
*/
// Create snapshot of current screen
//int sw = GetSystemMetrics(SM_CXSCREEN);
//int sy = GetSystemMetrics(SM_CYSCREEN);
//HDC hdc = GetWindowDC(NULL);
//g_hdcScreen = CreateCompatibleDC(hdc);
//HBITMAP hBmp = CreateCompatibleBitmap(hdc, sw, sy);
//SelectObject(g_hdcScreen, hBmp);
//BitBlt(g_hdcScreen, 0, 0, sw, sy, hdc, 0, 0, SRCCOPY);
//ReleaseDC(NULL, hdc);
//case WM_PAINT:
//{
// PAINTSTRUCT ps;
// HDC hdc = BeginPaint(hWnd, &ps);
// RECT rc;
// GetWindowRect(hWnd, &rc);
// FillRect(hdc, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH));
// EndPaint(hWnd, &ps);
// return false;
//}
| 29.253996
| 167
| 0.702975
|
barty32
|
4266219ebae7d643ef0606185beb79535329e25e
| 54
|
cpp
|
C++
|
source/framework/algorithm/src/local_operation/cos.cpp
|
computationalgeography/lue
|
71993169bae67a9863d7bd7646d207405dc6f767
|
[
"MIT"
] | 2
|
2021-02-26T22:45:56.000Z
|
2021-05-02T10:28:48.000Z
|
source/framework/algorithm/src/local_operation/cos.cpp
|
computationalgeography/lue
|
71993169bae67a9863d7bd7646d207405dc6f767
|
[
"MIT"
] | 131
|
2020-10-27T13:09:16.000Z
|
2022-03-29T10:24:26.000Z
|
source/framework/algorithm/src/local_operation/cos.cpp
|
computationalgeography/lue
|
71993169bae67a9863d7bd7646d207405dc6f767
|
[
"MIT"
] | null | null | null |
#include "lue/framework/algorithm/definition/cos.hpp"
| 27
| 53
| 0.814815
|
computationalgeography
|
4269de30fa7cfb72d6b42b76f5231eb530d0a6ee
| 12,518
|
cpp
|
C++
|
src/samples/aiff/aiff.cpp
|
eriser/hivetrekkr
|
bac051e587fb53fc47bbd18066059c2c402b5720
|
[
"BSD-2-Clause"
] | 1
|
2018-10-22T11:32:30.000Z
|
2018-10-22T11:32:30.000Z
|
src/samples/aiff/aiff.cpp
|
eriser/hivetrekkr
|
bac051e587fb53fc47bbd18066059c2c402b5720
|
[
"BSD-2-Clause"
] | null | null | null |
src/samples/aiff/aiff.cpp
|
eriser/hivetrekkr
|
bac051e587fb53fc47bbd18066059c2c402b5720
|
[
"BSD-2-Clause"
] | 1
|
2019-03-05T15:39:57.000Z
|
2019-03-05T15:39:57.000Z
|
// ------------------------------------------------------
// Protrekkr
// Based on Juan Antonio Arguelles Rius's NoiseTrekker.
//
// Copyright (C) 2008-2014 Franck Charlet.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 FRANCK CHARLET 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.
// ------------------------------------------------------
// TODO: add support for AIFC
// ------------------------------------------------------
// Includes
#include "include/aiff.h"
AIFFFile::AIFFFile()
{
file = NULL;
Base_Note = 0;
SustainLoop.PlayMode = NoLooping;
Use_Floats = 0;
Loop_Start = 0;
Loop_End = 0;
}
AIFFFile::~AIFFFile()
{
Close();
}
unsigned long AIFFFile::FourCC(const char *ChunkName)
{
long retbuf = 0x20202020; // four spaces (padding)
char *p = ((char *) &retbuf);
// Remember, this is Intel format!
// The first character goes in the LSB
for (int i = 0; i < 4 && ChunkName[i]; i++)
{
*p++ = ChunkName[i];
}
return retbuf;
}
// ------------------------------------------------------
// Look for a chunk inside the file
// Return it's length (with file pointing to it's data) or 0
int AIFFFile::SeekChunk(const char *ChunkName)
{
int Chunk;
int Chunk_To_Find_Lo;
int Chunk_To_Find = FourCC(ChunkName);
int i;
int size;
i = 0;
Chunk_To_Find_Lo = tolower(Chunk_To_Find & 0xff);
Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 8) & 0xff) << 8;
Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 16) & 0xff) << 16;
Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 24) & 0xff) << 24;
Seek(i);
while(!feof(file))
{
Chunk = 0;
Seek(i);
Read(&Chunk, 4);
if(Chunk == Chunk_To_Find ||
Chunk == Chunk_To_Find_Lo)
{
Read(&size, 4);
return(Mot_Swap_32(size));
}
// Skip the data part to speed up the process
if(Chunk == SoundDataID)
{
Read(&size, 4);
size = Mot_Swap_32(size);
i += size + 4 + 4 - 1;
}
i++;
}
return(0);
}
int AIFFFile::Open(const char *Filename)
{
int chunk_size;
int Padding;
int Phony_Byte;
short Phony_Short;
file = fopen(Filename, "rb");
if(file)
{
// Those compression schemes are not supported
chunk_size = SeekChunk("ALAW");
if(chunk_size) return 0;
chunk_size = SeekChunk("ULAW");
if(chunk_size) return 0;
chunk_size = SeekChunk("G722");
if(chunk_size) return 0;
chunk_size = SeekChunk("G726");
if(chunk_size) return 0;
chunk_size = SeekChunk("G728");
if(chunk_size) return 0;
chunk_size = SeekChunk("GSM ");
if(chunk_size) return 0;
chunk_size = SeekChunk("COMM");
if(chunk_size)
{
Read(&CommDat.numChannels, sizeof(short));
CommDat.numChannels = Mot_Swap_16(CommDat.numChannels);
Read(&CommDat.numSampleFrames, sizeof(unsigned long));
CommDat.numSampleFrames = Mot_Swap_32(CommDat.numSampleFrames);
Read(&CommDat.sampleSize, sizeof(short));
CommDat.sampleSize = Mot_Swap_16(CommDat.sampleSize);
chunk_size = SeekChunk("INST");
// (Not mandatory)
if(chunk_size)
{
Read(&Base_Note, sizeof(char));
Read(&Phony_Byte, sizeof(char)); // detune
Read(&Phony_Byte, sizeof(char)); // lowNote
Read(&Phony_Byte, sizeof(char)); // highNote
Read(&Phony_Byte, sizeof(char)); // lowVelocity
Read(&Phony_Byte, sizeof(char)); // highVelocity
Read(&Phony_Short, sizeof(short)); // gain
Read(&SustainLoop, sizeof(Loop)); // sustainLoop
SustainLoop.PlayMode = Mot_Swap_16(SustainLoop.PlayMode);
SustainLoop.beginLoop = Mot_Swap_16(SustainLoop.beginLoop);
SustainLoop.endLoop = Mot_Swap_16(SustainLoop.endLoop);
if(SustainLoop.beginLoop < SustainLoop.endLoop)
{
// Find loop points
Loop_Start = Get_Marker(SustainLoop.beginLoop);
Loop_End = Get_Marker(SustainLoop.endLoop);
// Messed up data
if(Loop_Start >= Loop_End)
{
SustainLoop.PlayMode = NoLooping;
}
}
else
{
// Doc specifies that begin must be smaller
// otherwise there's no loop
SustainLoop.PlayMode = NoLooping;
}
}
chunk_size = SeekChunk("FL32");
if(chunk_size) Use_Floats = 1;
chunk_size = SeekChunk("FL64");
if(chunk_size) Use_Floats = 1;
chunk_size = SeekChunk("SSND");
if(chunk_size)
{
// Dummy reads
Read(&Padding, sizeof(unsigned long));
Read(&Block_Size, sizeof(unsigned long));
Seek(CurrentFilePosition() + Padding);
// File pos now points on waveform data
return 1;
}
}
}
return 0;
}
long AIFFFile::CurrentFilePosition()
{
return ftell(file);
}
int AIFFFile::Seek(long offset)
{
fflush(file);
if(fseek(file, offset, SEEK_SET))
{
return(0);
}
else
{
return(1);
}
}
int AIFFFile::Read(void *Data, unsigned NumBytes)
{
return fread(Data, NumBytes, 1, file);
}
void AIFFFile::Close()
{
if(file) fclose(file);
file = NULL;
}
int AIFFFile::BitsPerSample()
{
return CommDat.sampleSize;
}
int AIFFFile::NumChannels()
{
return CommDat.numChannels;
}
unsigned long AIFFFile::LoopStart()
{
return Loop_Start;
}
unsigned long AIFFFile::LoopEnd()
{
return Loop_End;
}
unsigned long AIFFFile::NumSamples()
{
return CommDat.numSampleFrames;
}
int AIFFFile::BaseNote()
{
return Base_Note;
}
int AIFFFile::LoopType()
{
return SustainLoop.PlayMode;
}
int AIFFFile::ReadMonoSample(short *Sample)
{
int retcode;
float y;
double y64;
unsigned long int_y;
Uint64 int_y64;
switch(CommDat.sampleSize)
{
case 8:
unsigned char x;
retcode = Read(&x, 1);
*Sample = (short(x) << 8);
break;
case 12:
case 16:
retcode = Read(Sample, 2);
*Sample = Mot_Swap_16(*Sample);
break;
case 24:
int_y = 0;
retcode = Read(&int_y, 3);
int_y = Mot_Swap_32(int_y);
*Sample = (short) (int_y / 65536);
break;
case 32:
retcode = Read(&int_y, 4);
int_y = Mot_Swap_32(int_y);
if(Use_Floats)
{
IntToFloat((int *) &y, int_y);
*Sample = (short) (y * 32767.0f);
}
else
{
*Sample = (short) (int_y / 65536);
}
break;
case 64:
retcode = Read(&int_y64, 8);
int_y64 = Mot_Swap_64(int_y64);
Int64ToDouble((Uint64 *) &y64, int_y64);
*Sample = (short) (y64 * 32767.0);
break;
default:
retcode = 0;
}
return retcode;
}
int AIFFFile::ReadStereoSample(short *L, short *R)
{
int retcode = 0;
unsigned char x[2];
short y[2];
float z[2];
double z64[2];
long int_z[2];
Uint64 int_z64[2];
switch(CommDat.sampleSize)
{
case 8:
retcode = Read(x, 2);
*L = (short (x[0]) << 8);
*R = (short (x[1]) << 8);
break;
case 12:
case 16:
retcode = Read(y, 4);
y[0] = Mot_Swap_16(y[0]);
y[1] = Mot_Swap_16(y[1]);
*L = short(y[0]);
*R = short(y[1]);
break;
case 24:
int_z[0] = 0;
int_z[1] = 0;
retcode = Read(&int_z[0], 3);
retcode = Read(&int_z[1], 3);
int_z[0] = Mot_Swap_32(int_z[0]);
int_z[1] = Mot_Swap_32(int_z[1]);
*L = (short) (int_z[0] / 65536);
*R = (short) (int_z[1] / 65536);
break;
case 32:
retcode = Read(int_z, 8);
int_z[0] = Mot_Swap_32(int_z[0]);
int_z[1] = Mot_Swap_32(int_z[1]);
if(Use_Floats)
{
IntToFloat((int *) &z[0], int_z[0]);
IntToFloat((int *) &z[1], int_z[1]);
*L = (short) (z[0] * 32767.0f);
*R = (short) (z[1] * 32767.0f);
}
else
{
*L = (short) (int_z[0] / 65536);
*R = (short) (int_z[1] / 65536);
}
break;
case 64:
retcode = Read(int_z64, 16);
int_z64[0] = Mot_Swap_64(int_z64[0]);
int_z64[1] = Mot_Swap_64(int_z64[1]);
Int64ToDouble((Uint64 *) &z64[0], int_z64[0]);
Int64ToDouble((Uint64 *) &z64[1], int_z64[1]);
*L = (short) (z64[0] * 32767.0);
*R = (short) (z64[1] * 32767.0);
break;
default:
retcode = 0;
}
return retcode;
}
int AIFFFile::Get_Marker(int Marker_Id)
{
unsigned char string_size;
int i;
int chunk_size = SeekChunk("MARK");
if(chunk_size)
{
Read(&Markers.numMarkers, sizeof(unsigned short));
Markers.numMarkers = Mot_Swap_16(Markers.numMarkers);
for(i = 0 ; i < Markers.numMarkers; i++)
{
Read(&CurMarker.id, sizeof(unsigned short));
CurMarker.id = Mot_Swap_16(CurMarker.id);
Read(&CurMarker.position, sizeof(unsigned long));
CurMarker.position = Mot_Swap_32(CurMarker.position);
if(CurMarker.id == Marker_Id)
{
return(CurMarker.position);
}
else
{
Read(&string_size, sizeof(unsigned char));
string_size++;
Seek(CurrentFilePosition() + string_size);
}
}
// Couldn't find the specified marker so disable everything
SustainLoop.PlayMode = NoLooping;
return(-1);
}
else
{
// Everything is broken so disable looping
SustainLoop.PlayMode = NoLooping;
return(-1);
}
}
void AIFFFile::IntToFloat(int *Dest, int Source)
{
*Dest = Source;
}
void AIFFFile::Int64ToDouble(Uint64 *Dest, Uint64 Source)
{
*Dest = Source;
}
| 28.067265
| 81
| 0.506071
|
eriser
|
426d9e182fd082858b230aa1f5cd48f10aac8725
| 3,192
|
cc
|
C++
|
modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc
|
minstrelsy/webrtc-official
|
cfe75c12ee04d17e7898ebc0a8ad1051b6627e53
|
[
"BSD-3-Clause"
] | 305
|
2020-03-31T14:12:50.000Z
|
2022-03-19T16:45:49.000Z
|
modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc
|
daixy111040536/webrtc
|
7abfc990c00ab35090fff285fcf635d1d7892433
|
[
"BSD-3-Clause"
] | 23
|
2020-04-29T11:41:23.000Z
|
2021-09-07T02:07:57.000Z
|
modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc
|
daixy111040536/webrtc
|
7abfc990c00ab35090fff285fcf635d1d7892433
|
[
"BSD-3-Clause"
] | 122
|
2020-04-17T11:38:56.000Z
|
2022-03-25T15:48:42.000Z
|
/*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/congestion_controller/goog_cc/congestion_window_pushback_controller.h"
#include <memory>
#include "api/transport/field_trial_based_config.h"
#include "test/field_trial.h"
#include "test/gmock.h"
#include "test/gtest.h"
using ::testing::_;
namespace webrtc {
namespace test {
class CongestionWindowPushbackControllerTest : public ::testing::Test {
public:
CongestionWindowPushbackControllerTest() {
cwnd_controller_.reset(
new CongestionWindowPushbackController(&field_trial_config_));
}
protected:
FieldTrialBasedConfig field_trial_config_;
std::unique_ptr<CongestionWindowPushbackController> cwnd_controller_;
};
TEST_F(CongestionWindowPushbackControllerTest, FullCongestionWindow) {
cwnd_controller_->UpdateOutstandingData(100000);
cwnd_controller_->SetDataWindow(DataSize::bytes(50000));
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(72000u, bitrate_bps);
cwnd_controller_->SetDataWindow(DataSize::bytes(50000));
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(static_cast<uint32_t>(72000 * 0.9 * 0.9), bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, NormalCongestionWindow) {
cwnd_controller_->UpdateOutstandingData(199999);
cwnd_controller_->SetDataWindow(DataSize::bytes(200000));
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(80000u, bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, LowBitrate) {
cwnd_controller_->UpdateOutstandingData(100000);
cwnd_controller_->SetDataWindow(DataSize::bytes(50000));
uint32_t bitrate_bps = 35000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(static_cast<uint32_t>(35000 * 0.9), bitrate_bps);
cwnd_controller_->SetDataWindow(DataSize::bytes(20000));
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(30000u, bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, NoPushbackOnDataWindowUnset) {
cwnd_controller_->UpdateOutstandingData(1e8); // Large number
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(80000u, bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, PushbackOnInititialDataWindow) {
test::ScopedFieldTrials trials("WebRTC-CongestionWindow/InitWin:100000/");
cwnd_controller_.reset(
new CongestionWindowPushbackController(&field_trial_config_));
cwnd_controller_->UpdateOutstandingData(1e8); // Large number
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_GT(80000u, bitrate_bps);
}
} // namespace test
} // namespace webrtc
| 33.957447
| 88
| 0.794486
|
minstrelsy
|
f11737a8bdf71e8e728cc3403ef9cde13391f555
| 3,515
|
cpp
|
C++
|
gfx/region_pixman.cpp
|
clarfonthey/laf
|
305592194e3d89dfe6d16648bf84576a2f7b05a5
|
[
"MIT"
] | 186
|
2017-04-25T12:13:05.000Z
|
2022-03-30T08:06:47.000Z
|
gfx/region_pixman.cpp
|
clarfonthey/laf
|
305592194e3d89dfe6d16648bf84576a2f7b05a5
|
[
"MIT"
] | 34
|
2016-12-20T16:33:31.000Z
|
2022-03-29T21:07:52.000Z
|
gfx/region_pixman.cpp
|
clarfonthey/laf
|
305592194e3d89dfe6d16648bf84576a2f7b05a5
|
[
"MIT"
] | 47
|
2016-12-19T17:23:46.000Z
|
2022-03-30T19:45:55.000Z
|
// LAF Gfx Library
// Copyright (C) 2001-2015 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pixman.h"
#include "base/debug.h"
#include "gfx/point.h"
#include "gfx/region.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace gfx {
inline Rect to_rect(const pixman_box32& extends)
{
return Rect(
extends.x1, extends.y1,
extends.x2 - extends.x1,
extends.y2 - extends.y1);
}
Region::Region()
{
pixman_region32_init(&m_region);
}
Region::Region(const Region& copy)
{
pixman_region32_init(&m_region);
pixman_region32_copy(&m_region, ©.m_region);
}
Region::Region(const Rect& rect)
{
if (!rect.isEmpty())
pixman_region32_init_rect(&m_region, rect.x, rect.y, rect.w, rect.h);
else
pixman_region32_init(&m_region);
}
Region::~Region()
{
pixman_region32_fini(&m_region);
}
Region& Region::operator=(const Rect& rect)
{
if (!rect.isEmpty()) {
pixman_box32 box = { rect.x, rect.y, rect.x2(), rect.y2() };
pixman_region32_reset(&m_region, &box);
}
else
pixman_region32_clear(&m_region);
return *this;
}
Region& Region::operator=(const Region& copy)
{
pixman_region32_copy(&m_region, ©.m_region);
return *this;
}
Region::iterator Region::begin()
{
iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL);
return it;
}
Region::iterator Region::end()
{
iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL) + size();
return it;
}
Region::const_iterator Region::begin() const
{
const_iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL);
return it;
}
Region::const_iterator Region::end() const
{
const_iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL) + size();
return it;
}
bool Region::isEmpty() const
{
return (pixman_region32_not_empty(&m_region) ? false: true);
}
bool Region::isRect() const
{
return (size() == 1);
}
bool Region::isComplex() const
{
return (size() > 1);
}
std::size_t Region::size() const
{
return pixman_region32_n_rects(&m_region);
}
Rect Region::bounds() const
{
return to_rect(*pixman_region32_extents(&m_region));
}
void Region::clear()
{
pixman_region32_clear(&m_region);
}
void Region::offset(int dx, int dy)
{
pixman_region32_translate(&m_region, dx, dy);
}
void Region::offset(const PointT<int>& delta)
{
pixman_region32_translate(&m_region, delta.x, delta.y);
}
Region& Region::createIntersection(const Region& a, const Region& b)
{
pixman_region32_intersect(&m_region, &a.m_region, &b.m_region);
return *this;
}
Region& Region::createUnion(const Region& a, const Region& b)
{
pixman_region32_union(&m_region, &a.m_region, &b.m_region);
return *this;
}
Region& Region::createSubtraction(const Region& a, const Region& b)
{
pixman_region32_subtract(&m_region, &a.m_region, &b.m_region);
return *this;
}
bool Region::contains(const PointT<int>& pt) const
{
return pixman_region32_contains_point(&m_region, pt.x, pt.y, NULL) ? true: false;
}
Region::Overlap Region::contains(const Rect& rect) const
{
static_assert(
int(Out) == int(PIXMAN_REGION_OUT) &&
int(In) == int(PIXMAN_REGION_IN) &&
int(Part) == int(PIXMAN_REGION_PART), "Pixman constants have changed");
pixman_box32 box = { rect.x, rect.y, rect.x2(), rect.y2() };
return (Region::Overlap)pixman_region32_contains_rectangle(&m_region, &box);
}
} // namespace gfx
| 20.085714
| 83
| 0.702703
|
clarfonthey
|
f119ccfb9176845b806213b365af93a316cf0fff
| 6,870
|
cpp
|
C++
|
frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp
|
shillcock/dmz
|
02174b45089e12cd7f0840d5259a00403cd1ccff
|
[
"MIT"
] | 2
|
2015-11-05T03:03:40.000Z
|
2016-02-03T21:50:40.000Z
|
frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp
|
dmzgroup/dmz
|
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
|
[
"MIT"
] | null | null | null |
frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp
|
dmzgroup/dmz
|
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
|
[
"MIT"
] | null | null | null |
#include <dmzEntityConsts.h>
#include "dmzEntityPluginWheels.h"
#include <dmzObjectAttributeMasks.h>
#include <dmzObjectConsts.h>
#include <dmzObjectModule.h>
#include <dmzRuntimeConfig.h>
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzRuntimeObjectType.h>
#include <dmzTypesMatrix.h>
#include <dmzTypesVector.h>
/*!
\class dmz::EntityPluginWheels
\ingroup Entity
\brief Articulates an object's wheels based on velocity.
\details
\code
<dmz>
<runtime>
<object-type name="Type">
<wheels pairs="Int32" radius="Float64" root="String" modifier="Float64"/>
</object-type>
</runtime>
</dmz>
\endcode
Wheels are defined on a ObjectType basis.
- pairs: Number of wheel pairs. Defaults to 0.
- radius: Wheel radius in meters. Defaults to 0.25.
- root: Root of the wheel attribute name. Defaults to dmz::EntityWheelRootName.
- modifier: Defaults to 1.0
*/
//! \cond
dmz::EntityPluginWheels::EntityPluginWheels (const PluginInfo &Info, Config &local) :
Plugin (Info),
TimeSlice (Info),
ObjectObserverUtil (Info, local),
_log (Info),
_defs (Info),
_defaultAttr (0) {
_init (local);
}
dmz::EntityPluginWheels::~EntityPluginWheels () {
_wheelTable.empty ();
_objTable.empty ();
}
// Plugin Interface
void
dmz::EntityPluginWheels::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::EntityPluginWheels::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
}
else if (Mode == PluginDiscoverRemove) {
}
}
// Time Slice Interface
void
dmz::EntityPluginWheels::update_time_slice (const Float64 DeltaTime) {
ObjectModule *module = get_object_module ();
if (module) {
HashTableHandleIterator it;
ObjectStruct *os (0);
while (_objTable.get_next (it, os)) {
Matrix ori;
Vector vel;
module->lookup_velocity (os->Object, _defaultAttr, vel);
module->lookup_orientation (os->Object, _defaultAttr, ori);
Float64 speed = vel.magnitude ();
if (!is_zero64 (speed)) {
Vector dir (0.0, 0.0, -1.0);
ori.transform_vector (dir);
if (dir.get_angle (vel) > HalfPi64) { speed = -speed; }
const Float64 Distance = speed * DeltaTime;
WheelStruct *wheel (os->wheels);
while (wheel) {
Float64 value (0.0);
module->lookup_scalar (os->Object, wheel->Attr, value);
value -= (Distance * wheel->InvertRadius * wheel->Mod);
value = normalize_angle (value);
module->store_scalar (os->Object, wheel->Attr, value);
wheel = wheel->next;
}
}
}
}
}
// Object Observer Interface
void
dmz::EntityPluginWheels::create_object (
const UUID &Identity,
const Handle ObjectHandle,
const ObjectType &Type,
const ObjectLocalityEnum Locality) {
WheelStruct *ws = _lookup_wheels_def (Type);
if (ws) {
ObjectStruct *os = new ObjectStruct (ObjectHandle, ws);
if (os && !_objTable.store (ObjectHandle, os)) { delete os; os = 0; }
}
}
void
dmz::EntityPluginWheels::destroy_object (
const UUID &Identity,
const Handle ObjectHandle) {
ObjectStruct *os = _objTable.remove (ObjectHandle);
if (os) { delete os; os = 0; }
}
dmz::EntityPluginWheels::WheelStruct *
dmz::EntityPluginWheels::_lookup_wheels_def (const ObjectType &Type) {
WheelStruct *result (0);
ObjectType current (Type);
while (!result && current) {
result = _wheelTable.lookup (current.get_handle ());
if (!result) { result = _create_wheels_def (current); }
current.become_parent ();
}
return result;
}
namespace {
static const dmz::UInt32 FlipRight = 0x01;
static const dmz::UInt32 FlipLeft = 0x02;
};
dmz::EntityPluginWheels::WheelStruct *
dmz::EntityPluginWheels::_create_wheels_def (const ObjectType &Type) {
WheelStruct *result (0);
Config wheels;
if (Type.get_config ().lookup_all_config_merged ("wheels", wheels)) {
UInt32 flip (0);
const Float64 Radius = config_to_float64 ("radius", wheels, 0.25);
const Float64 Mod = config_to_float64 ("modifier", wheels, 1.0);
const String Root = config_to_string ("root", wheels, EntityWheelRootName);
const Int32 Pairs = config_to_int32 ("pairs", wheels, 0);
const String FlipString = config_to_string ("reverse", wheels, "none");
if (FlipString == "left") { flip = FlipLeft; }
else if (FlipString == "right") { flip = FlipRight; }
else if ((FlipString == "both") || (FlipString == "all")) {
flip = FlipLeft | FlipRight;
}
else if (FlipString == "none") { flip = 0; }
if (Radius > 0.0) {
const Float64 InvertRadius = 1.0 / Radius;
if (Pairs > 0) {
for (Int32 ix = 1; ix <= Pairs; ix++) {
Handle attr = _defs.create_named_handle (
create_wheel_attribute_name (Root, EntityWheelLeft, ix));
WheelStruct *ws = new WheelStruct (
attr,
InvertRadius,
Mod * (flip & FlipLeft ? -1.0 : 1.0));
if (ws) {
ws->next = result;
result = ws;
}
attr = _defs.create_named_handle (
create_wheel_attribute_name (Root, EntityWheelRight, ix));
ws = new WheelStruct (
attr,
InvertRadius,
Mod * (flip & FlipRight ? -1.0 : 1.0));
if (ws) {
ws->next = result;
result = ws;
}
}
}
else {
_log.error << "Must have at least one wheel pair in type: "
<< Type.get_name () << endl;
}
}
else {
_log.error << "Radius of wheel of type: " << Type.get_name ()
<< " is less than or equal to zero: " << Radius << endl;
}
}
return result;
}
void
dmz::EntityPluginWheels::_init (Config &local) {
_defaultAttr = _defs.create_named_handle (ObjectAttributeDefaultName);
activate_default_object_attribute (ObjectCreateMask | ObjectDestroyMask);
}
//! \endcond
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzEntityPluginWheels (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::EntityPluginWheels (Info, local);
}
};
| 22.82392
| 85
| 0.604658
|
shillcock
|
f11edf0045a11ad72e3bb5d8fd84b19f5e9060ea
| 977
|
cpp
|
C++
|
Engine/src/Traceability/Logger.cpp
|
LinMAD/Nibble
|
65a8d12810335d832512812740f86bd8df14feb0
|
[
"MIT"
] | null | null | null |
Engine/src/Traceability/Logger.cpp
|
LinMAD/Nibble
|
65a8d12810335d832512812740f86bd8df14feb0
|
[
"MIT"
] | null | null | null |
Engine/src/Traceability/Logger.cpp
|
LinMAD/Nibble
|
65a8d12810335d832512812740f86bd8df14feb0
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Logger.h"
#include "spdlog/sinks/stdout_color_sinks.h"
namespace Nibble {
std::shared_ptr<spdlog::logger> Logger::s_CoreLogger;
std::shared_ptr<spdlog::logger> Logger::s_ClientLogger;
Logger::Logger()
{
}
Logger::~Logger()
{
}
void Logger::Init()
{
// https://github.com/gabime/spdlog/wiki/3.-Custom-formatting
// %^ - Start color range (can be used only once)
// %$ - End color range (for example %^[+++]%$ %v) (can be used only once)
// %T - ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
// %l - The log level of the message
// %v - The actual text to log ("debug", "info", etc)
spdlog::set_pattern("%^[%l]|%T| %n: %v");
s_CoreLogger = spdlog::stdout_color_mt("Nibble");
s_ClientLogger = spdlog::stdout_color_mt("Application");
// TODO Add log level config loading
s_CoreLogger->set_level(spdlog::level::trace);
s_ClientLogger->set_level(spdlog::level::trace);
}
}
| 28.735294
| 77
| 0.64176
|
LinMAD
|
f121c81e2a556a26ce7c1dbda509bdc8ae36dcc9
| 1,344
|
hpp
|
C++
|
src/sensors/interface.hpp
|
Hyp-ed/hyped-2022
|
9cac4632b660f569629cf0ad4048787f6017905d
|
[
"Apache-2.0"
] | 9
|
2021-07-31T16:22:24.000Z
|
2022-01-19T18:14:31.000Z
|
src/sensors/interface.hpp
|
Hyp-ed/hyped-2022
|
9cac4632b660f569629cf0ad4048787f6017905d
|
[
"Apache-2.0"
] | 91
|
2021-07-29T18:21:30.000Z
|
2022-03-31T20:44:55.000Z
|
src/sensors/interface.hpp
|
Hyp-ed/hyped-2022
|
9cac4632b660f569629cf0ad4048787f6017905d
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <string>
#include <data/data.hpp>
namespace hyped {
using data::BatteryData;
using data::ImuData;
using data::NavigationVector;
using data::StripeCounter;
using data::TemperatureData;
namespace sensors {
class SensorInterface {
public:
/**
* @brief Check if sensor is responding, i.e. connected to the system
* @return true - if sensor is online
*/
virtual bool isOnline() = 0;
};
class ImuInterface : public SensorInterface {
public:
/**
* @brief Get IMU data
* @param imu - output pointer to be filled by this sensor
*/
virtual void getData(ImuData *imu) = 0;
};
class GpioInterface : public SensorInterface {
public:
/**
* @brief Get GPIO data
* @param stripe_counter - output pointer
*/
virtual void getData(StripeCounter *stripe_counter) = 0;
};
class BMSInterface : public SensorInterface {
public:
/**
* @brief Get Battery data
* @param battery - output pointer to be filled by this sensor
*/
virtual void getData(BatteryData *battery) = 0;
};
class TemperatureInterface {
public:
/**
* @brief not a thread, checks temperature
*/
virtual void run() = 0;
/**
* @brief returns int representation of temperature
* @return int temperature degrees C
*/
virtual int getData() = 0;
};
} // namespace sensors
} // namespace hyped
| 19.764706
| 71
| 0.680804
|
Hyp-ed
|
f1221f59c63a06cf4df50f1e2769796ba5ba222c
| 332
|
cpp
|
C++
|
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp
|
redcatbox/Instanced
|
347790e8ade0c6e6fb9b742afc78c764414ed36a
|
[
"MIT"
] | 1
|
2022-02-03T17:10:29.000Z
|
2022-02-03T17:10:29.000Z
|
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp
|
redcatbox/Instanced
|
347790e8ade0c6e6fb9b742afc78c764414ed36a
|
[
"MIT"
] | null | null | null |
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp
|
redcatbox/Instanced
|
347790e8ade0c6e6fb9b742afc78c764414ed36a
|
[
"MIT"
] | null | null | null |
// redbox, 2021
#include "Components/Operations/IPOperationAlignBase.h"
UIPOperationAlignBase::UIPOperationAlignBase()
{
#if WITH_EDITORONLY_DATA
bInstancesNumEditCondition = false;
bAlignToSurface = false;
OffsetInTraceDirection = 0.f;
bReverse = false;
bTraceComplex = false;
bIgnoreSelf = true;
DrawTime = 5.f;
#endif
}
| 19.529412
| 55
| 0.777108
|
redcatbox
|
f1226e2ec401b0be3b8b0af702bb3de980341b25
| 725
|
cpp
|
C++
|
dmoj/dmopc/2014/contest-2/deforestation.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | 1
|
2020-07-16T01:46:38.000Z
|
2020-07-16T01:46:38.000Z
|
dmoj/dmopc/2014/contest-2/deforestation.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | null | null | null |
dmoj/dmopc/2014/contest-2/deforestation.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | 1
|
2020-05-27T14:30:43.000Z
|
2020-05-27T14:30:43.000Z
|
#include <iostream>
#include <vector>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int trees;
cin >> trees;
vector<unsigned int> prefix_sums(trees + 1);
for (unsigned int i {1}; i <= trees; ++i)
{
unsigned int mass;
cin >> mass;
prefix_sums[i] = prefix_sums[i - 1] + mass;
}
unsigned int queries;
cin >> queries;
for (unsigned int i {0}; i < queries; ++i)
{
unsigned int from;
unsigned int to;
cin >> from >> to;
cout << prefix_sums[to + 1] - prefix_sums[from] << '\n';
}
return 0;
}
| 16.477273
| 64
| 0.56
|
Rkhoiwal
|
f124100905a0dd50b377e341d084a768cc278f82
| 1,151
|
cpp
|
C++
|
cref/10_enums.cpp
|
admantium-sg/learning-cpp
|
cc827a8d7eabceac32069bb7f5a64b3c0fe488f4
|
[
"BSD-3-Clause"
] | null | null | null |
cref/10_enums.cpp
|
admantium-sg/learning-cpp
|
cc827a8d7eabceac32069bb7f5a64b3c0fe488f4
|
[
"BSD-3-Clause"
] | null | null | null |
cref/10_enums.cpp
|
admantium-sg/learning-cpp
|
cc827a8d7eabceac32069bb7f5a64b3c0fe488f4
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* ---------------------------------------
* Copyright (c) Sebastian Günther 2021 |
* |
* devcon@admantium.com |
* |
* SPDX-License-Identifier: BSD-3-Clause |
* ---------------------------------------
*/
#include <stdio.h>
#include <stdexcept>
#include <iostream>
#include <cstddef>
using namespace std;
enum class Color {
Red,
Blue,
Green
};
class ColorFactory{
public:
static int getInstances() { return instances;}
static Color makeColor(Color c) { ColorFactory::instances++; return c;}
static int instances;
};
int ColorFactory::instances = 0;
int main(int argc, char* argv[]) {
cout << "Number of args: " << argc << endl;
for (int i=0; i < argc; i++) {
cout << "Arg " << i << ": " << argv[i] << endl;
}
ColorFactory paint;
Color r = paint.makeColor(Color::Red);
Color g = paint.makeColor(Color::Green);
cout << "Number of paints " << ColorFactory::getInstances() << endl;
if (r == Color::Red) {cout << "Beautifull Red" << endl;}
// if (r == 0) {cout << "Beautifull Red";} //throws error
}
| 24.489362
| 75
| 0.519548
|
admantium-sg
|
f1292ef8610d84e7d6c789af02652b45f680a893
| 573
|
cpp
|
C++
|
1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp
|
arpangoswami/LeetcodeSolutions
|
17a2450cacf0020c2626023012a5a354c8fee5da
|
[
"MIT"
] | null | null | null |
1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp
|
arpangoswami/LeetcodeSolutions
|
17a2450cacf0020c2626023012a5a354c8fee5da
|
[
"MIT"
] | null | null | null |
1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp
|
arpangoswami/LeetcodeSolutions
|
17a2450cacf0020c2626023012a5a354c8fee5da
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
int left = 0;
int n = nums.size();
multiset<int> windowElements;
int ans = 1;
for(int i=0;i<n;i++){
windowElements.insert(nums[i]);
while(left <= i && (*windowElements.rbegin() - *windowElements.begin()) > limit){
auto it = windowElements.find(nums[left]);
windowElements.erase(it);
left++;
}
ans = max(ans,i-left+1);
}
return ans;
}
};
| 30.157895
| 93
| 0.490401
|
arpangoswami
|
f12b3726fca9bd6e160b866808b266980538cc88
| 3,681
|
cpp
|
C++
|
Source/Framework/Core/GameComponentContainer.cpp
|
gabr1e11/cornerstone
|
bc696e22af350b867219ef3ac99840b3e8a3f20a
|
[
"MIT"
] | null | null | null |
Source/Framework/Core/GameComponentContainer.cpp
|
gabr1e11/cornerstone
|
bc696e22af350b867219ef3ac99840b3e8a3f20a
|
[
"MIT"
] | null | null | null |
Source/Framework/Core/GameComponentContainer.cpp
|
gabr1e11/cornerstone
|
bc696e22af350b867219ef3ac99840b3e8a3f20a
|
[
"MIT"
] | null | null | null |
//
// GameComponentContainer.cpp
//
// @author Roberto Cano
//
#include "GameComponentContainer.hpp"
using namespace Framework;
using namespace Framework::Core;
using namespace Framework::Types;
void GameComponentContainer::addComponent(Types::GameComponent::PtrType component)
{
const ComponentId& componentId = component->getComponentId();
const InstanceId& instanceId = component->getInstanceId();
_notStartedComponents.push(component);
// Dependency injection
Types::GameObject::PtrType gameObjectPtr = shared_from_this();
component->_setOwner(gameObjectPtr);
// Map by Instance Id
auto insertionIter = _componentsMapByInstanceId.insert(std::pair<InstanceId, Types::GameComponent::PtrType>(instanceId, std::move(component)));
assert(insertionIter.second);
// Map by Component Id
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
if (componentsMapIter != _componentsMapByComponentId.end())
{
componentsMapIter->second.emplace(instanceId);
}
else
{
_componentsMapByComponentId.emplace(componentId, std::set<InstanceId>{instanceId});
}
}
bool GameComponentContainer::removeComponent(const Core::GameComponent& component)
{
const InstanceId& instanceId = component.getInstanceId();
return removeComponent(instanceId);
}
bool GameComponentContainer::removeComponent(const InstanceId& instanceId)
{
bool retValue = true;
auto findIter = _componentsMapByInstanceId.find(instanceId);
if (findIter == _componentsMapByInstanceId.end())
{
return false;
}
const GameComponent& component = *(findIter->second);
const ComponentId& componentId = component.getComponentId();
// Map by Component Id
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
if (componentsMapIter != _componentsMapByComponentId.end())
{
componentsMapIter->second.erase(instanceId);
}
else
{
retValue = false;
}
// Map by Instance Id
_componentsMapByInstanceId.erase(findIter);
return retValue;
}
bool GameComponentContainer::hasComponent(const Core::GameComponent& component) const
{
const InstanceId& instanceId = component.getInstanceId();
return hasComponent(instanceId);
}
bool GameComponentContainer::hasComponents(const ComponentId& componentId) const
{
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
return componentsMapIter != _componentsMapByComponentId.end();
}
bool GameComponentContainer::hasComponent(const InstanceId& instanceId) const
{
auto instancesMapIter = _componentsMapByInstanceId.find(instanceId);
return instancesMapIter != _componentsMapByInstanceId.end();
}
const std::set<InstanceId>& GameComponentContainer::getComponentsIds(const ComponentId& componentId) const
{
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
assert(componentsMapIter != _componentsMapByComponentId.end());
return componentsMapIter->second;
}
void GameComponentContainer::internalInit()
{
for (auto& componentPair : _componentsMapByInstanceId)
{
componentPair.second->init();
}
}
void GameComponentContainer::internalStart()
{
for (auto& componentPair : _componentsMapByInstanceId)
{
componentPair.second->start();
}
}
void GameComponentContainer::internalUpdate(float dt)
{
for (auto& componentPair : _componentsMapByInstanceId)
{
componentPair.second->update(dt);
}
}
void GameComponentContainer::updateNotStarted()
{
if (_notStartedComponents.empty())
{
return;
}
while (!_notStartedComponents.empty())
{
Types::GameComponent::WeakPtrType gameComponentWPtr = _notStartedComponents.front();
_notStartedComponents.pop();
if (auto gameComponent = gameComponentWPtr.lock())
{
gameComponent->internalStart();
}
}
}
| 25.741259
| 144
| 0.784569
|
gabr1e11
|
f133409731a3a8155fbf3128a4b1e316847324c6
| 240
|
cpp
|
C++
|
src/trap_instances/SegmentLdr.cpp
|
DavidLudwig/executor
|
eddb527850af639b3ffe314e05d92a083ba47af6
|
[
"MIT"
] | 2
|
2019-09-16T15:51:39.000Z
|
2020-03-04T08:47:42.000Z
|
src/trap_instances/SegmentLdr.cpp
|
probonopd/executor
|
0fb82c09109ec27ae8707f07690f7325ee0f98e0
|
[
"MIT"
] | null | null | null |
src/trap_instances/SegmentLdr.cpp
|
probonopd/executor
|
0fb82c09109ec27ae8707f07690f7325ee0f98e0
|
[
"MIT"
] | null | null | null |
#define INSTANTIATE_TRAPS_SegmentLdr
#include <SegmentLdr.h>
// Function for preventing the linker from considering the static constructors in this module unused
namespace Executor {
namespace ReferenceTraps {
void SegmentLdr() {}
}
}
| 24
| 100
| 0.791667
|
DavidLudwig
|
f1368c3c646265606a2f4ca855cf81b325293b08
| 269
|
cpp
|
C++
|
cpp_algs/bst/test_new.cpp
|
vitalir2/AlgorithmsCpp
|
f9a1b7a0b51c6f122ff600008d2c0ef72a26502f
|
[
"MIT"
] | null | null | null |
cpp_algs/bst/test_new.cpp
|
vitalir2/AlgorithmsCpp
|
f9a1b7a0b51c6f122ff600008d2c0ef72a26502f
|
[
"MIT"
] | null | null | null |
cpp_algs/bst/test_new.cpp
|
vitalir2/AlgorithmsCpp
|
f9a1b7a0b51c6f122ff600008d2c0ef72a26502f
|
[
"MIT"
] | null | null | null |
#include <iostream>
void f(double* n) {
n = new double(4);
}
void g(double* n) {
delete n;
}
int main() {
double* x = new double(5);
f(x);
std::cout << *x << std::endl;
g(x);
std::cout << *x << std::endl;
int* m = nullptr;
delete m;
return 0;
}
| 12.227273
| 31
| 0.520446
|
vitalir2
|
f13712f5a4d5b34c049fdc782a7bbe51a4e909a6
| 9,958
|
cpp
|
C++
|
src/websocket/frame_websocket.cpp
|
hl4/da4qi4
|
9dfb8902427d40b392977b4fd706048ce3ee8828
|
[
"Apache-2.0"
] | 166
|
2019-04-15T03:19:31.000Z
|
2022-03-26T05:41:12.000Z
|
src/websocket/frame_websocket.cpp
|
YangKefan/da4qi4
|
9dfb8902427d40b392977b4fd706048ce3ee8828
|
[
"Apache-2.0"
] | 9
|
2019-07-18T06:09:59.000Z
|
2021-01-27T04:19:04.000Z
|
src/websocket/frame_websocket.cpp
|
YangKefan/da4qi4
|
9dfb8902427d40b392977b4fd706048ce3ee8828
|
[
"Apache-2.0"
] | 43
|
2019-07-03T05:41:57.000Z
|
2022-02-24T14:16:09.000Z
|
#include "daqi/websocket/frame_websocket.hpp"
#include <cstring>
namespace da4qi4
{
namespace Websocket
{
std::string FrameBuilder::Build(char const* data, size_t len)
{
std::string buffer;
size_t externded_payload_len = (len <= 125 ? 0 : (len <= 65535 ? 2 : 8));
size_t mask_key_len = ((len && _frame_header.MASK) ? 4 : 0);
auto frame_size = static_cast<size_t>(2 + externded_payload_len + mask_key_len + len);
buffer.resize(frame_size);
uint8_t* ptr = reinterpret_cast<uint8_t*>(buffer.data());
uint64_t offset = 0;
ptr[0] |= _frame_header.FIN;
ptr[0] |= _frame_header.OPCODE;
if (len)
{
ptr[1] |= _frame_header.MASK;
}
++offset;
if (len <= 125)
{
ptr[offset++] |= static_cast<unsigned char>(len);
}
else if (len <= 65535)
{
ptr[offset++] |= 126;
ptr[offset++] = static_cast<unsigned char>((len >> 8) & 0xFF);
ptr[offset++] = len & 0xFF;
}
else
{
ptr[offset++] |= 127;
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 56) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 48) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 40) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 32) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 24) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 16) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 8) & 0xff));
ptr[offset++] = static_cast<unsigned char>((static_cast<uint64_t>(len) & 0xff));
}
if (!len || !data)
{
return buffer;
}
if (_frame_header.MASK)
{
int mask_key = static_cast<int>(_frame_header.MASKING_KEY);
ptr[offset++] = static_cast<unsigned char>(((mask_key >> 24) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((mask_key >> 16) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((mask_key >> 8) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((mask_key) & 0xff));
unsigned char* mask = ptr + offset - 4;
for (uint32_t i = 0; i < len; ++i)
{
ptr[offset++] = static_cast<uint8_t>(data[i] ^ mask[i % 4]);
}
}
else
{
std::copy(data, data + len, reinterpret_cast<char*>(ptr + offset));
offset += len;
}
assert(offset == frame_size);
return buffer;
}
void FrameParser::reset()
{
_parser_step = e_fixed_header;
_masking_key_pos = 0;
_payload_len_offset = 0;
_payload.clear();
memset(&_frame_header, 0, sizeof(_frame_header));
}
void FrameParser::move_reset(FrameParser&& parser)
{
if (&parser == this)
{
return;
}
_parser_step = parser._parser_step;
_payload_len_offset = parser._payload_len_offset;
_masking_key_pos = parser._masking_key_pos;
_payload = std::move(parser._payload);
_frame_header = std::move(parser._frame_header);
_msb_cb = std::move(parser._msb_cb);
}
uint32_t FrameParser::parse_fixed_header(const char* data)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
memset(&_frame_header, 0, sizeof(_frame_header));
_payload_len_offset = 0;
_frame_header.FIN = ptr[0] & 0xf0;
_frame_header.RSV1 = ptr[0] & 0x40;
_frame_header.RSV2 = ptr[0] & 0x20;
_frame_header.RSV3 = ptr[0] & 0x10;
_frame_header.OPCODE = static_cast<FrameType>(ptr[0] & 0x0f);
_parser_step = e_payload_len;
return 1U;
}
uint32_t FrameParser::parse_payload_len(const char* data)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
_frame_header.MASK = ptr[0] & 0x80;
_frame_header.PAYLOAD_LEN = ptr[0] & (0x7f);
if (_frame_header.PAYLOAD_LEN <= 125)
{
_frame_header.PAYLOAD_REALY_LEN = _frame_header.PAYLOAD_LEN;
if (_frame_header.MASK)
{
_parser_step = e_masking_key;
}
else
{
_parser_step = e_payload_data;
}
}
else if (_frame_header.PAYLOAD_LEN > 125)
{
_parser_step = e_extened_payload_len;
}
if (_frame_header.PAYLOAD_LEN == 0)
{
assert(_msb_cb);
_msb_cb("", _frame_header.OPCODE, !!_frame_header.FIN);
reset();
}
return 1U;
}
uint32_t FrameParser::parse_extened_payload_len(const char* data, uint32_t len)
{
uint32_t offset = 0;
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
if (_frame_header.PAYLOAD_LEN == 126)
{
//Extended payload length is 16bit!
uint32_t min_len = std::min<uint32_t>
(2 - _payload_len_offset, len - offset);
memcpy(&_frame_header.EXT_PAYLOAD_LEN_16,
ptr + offset, min_len);
offset += min_len;
_payload_len_offset += min_len;
if (_payload_len_offset == 2)
{
decode_extened_payload_len();
}
}
else if (_frame_header.PAYLOAD_LEN == 127)
{
//Extended payload length is 64bit!
auto min_len = std::min<uint32_t>(8 - _payload_len_offset, len - offset);
memcpy(&_frame_header.EXT_PAYLOAD_LEN_64, ptr + offset, static_cast<size_t>(min_len));
offset += min_len;
_payload_len_offset += min_len;
if (_payload_len_offset == 8)
{
decode_extened_payload_len();
}
}
return offset;
}
void FrameParser::decode_extened_payload_len()
{
if (_frame_header.PAYLOAD_LEN == 126)
{
uint16_t tmp = _frame_header.EXT_PAYLOAD_LEN_16;
uint8_t* buffer_ = reinterpret_cast<uint8_t*>(&tmp);
_frame_header.PAYLOAD_REALY_LEN =
static_cast<uint64_t>(
(static_cast<uint16_t>(buffer_[0]) << 8) | static_cast<uint16_t>(buffer_[1]));
}
else if (_frame_header.PAYLOAD_LEN == 127)
{
uint64_t tmp = _frame_header.EXT_PAYLOAD_LEN_64;
uint8_t* buffer_ = reinterpret_cast<uint8_t*>(&tmp);
_frame_header.PAYLOAD_REALY_LEN =
(static_cast<uint64_t>(buffer_[0]) << 56) |
(static_cast<uint64_t>(buffer_[1]) << 48) |
(static_cast<uint64_t>(buffer_[2]) << 40) |
(static_cast<uint64_t>(buffer_[3]) << 32) |
(static_cast<uint64_t>(buffer_[4]) << 24) |
(static_cast<uint64_t>(buffer_[5]) << 16) |
(static_cast<uint64_t>(buffer_[6]) << 8) |
static_cast<uint64_t>(buffer_[7]);
}
if (_frame_header.MASK)
{
_parser_step = e_masking_key;
}
else
{
_parser_step = e_payload_data;
}
}
uint32_t FrameParser::parse_masking_key(const char* data, uint32_t len)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
auto min = std::min<uint32_t>(4 - _masking_key_pos, len);
if (_parser_step == e_masking_key)
{
memcpy(&_frame_header.MASKING_KEY, ptr, static_cast<size_t>(min));
_masking_key_pos += min;
if (_masking_key_pos == 4)
{
_parser_step = e_payload_data;
}
}
return min;
}
uint32_t FrameParser::parse_payload(const char* data, uint32_t len)
{
if (_payload.empty() && _frame_header.PAYLOAD_REALY_LEN > 0)
{
_payload.reserve(static_cast<size_t>(_frame_header.PAYLOAD_REALY_LEN));
}
auto remain = static_cast<uint32_t>(_frame_header.PAYLOAD_REALY_LEN) - static_cast<uint32_t>(_payload.size());
auto min_len = std::min<uint32_t>(remain, len);
if (_frame_header.MASK)
{
unsigned char* mask = reinterpret_cast<unsigned char*>(&_frame_header.MASKING_KEY);
for (size_t i = 0; i < min_len; i++)
{
_payload.push_back(static_cast<char>(data[i] ^ mask[i % 4]));
}
}
else
{
_payload.append(data, min_len);
}
if (_payload.size() == _frame_header.PAYLOAD_REALY_LEN)
{
assert(_msb_cb);
_msb_cb(std::move(_payload), _frame_header.OPCODE, !!_frame_header.FIN);
reset();
}
return min_len;
}
std::pair<bool, std::string> FrameParser::Parse(void const* data, uint32_t len)
{
assert(data != nullptr && len > 0);
uint32_t offset = 0;
uint32_t remain_len = len;
try
{
do
{
if (_parser_step == e_fixed_header && remain_len)
{
offset += parse_fixed_header(static_cast<char const*>(data) + offset);
remain_len = len - offset;
}
if (_parser_step == e_payload_len && remain_len)
{
offset += parse_payload_len(static_cast<char const*>(data) + offset);
remain_len = len - offset;
}
if (_parser_step == e_extened_payload_len && remain_len)
{
offset += parse_extened_payload_len(static_cast<char const*>(data) + offset, remain_len);
remain_len = len - offset;
}
if (_parser_step == e_masking_key && remain_len)
{
offset += parse_masking_key(static_cast<char const*>(data) + offset, remain_len);
remain_len = len - offset;
}
if (_parser_step == e_payload_data && remain_len)
{
offset += parse_payload(static_cast<char const*>(data) + offset, remain_len);
remain_len = len - offset;
}
}
while (offset < len);
}
catch (std::exception const& e)
{
return {false, e.what()};
}
catch (...)
{
return {false, "unknown exception."};
}
return {true, ""};
}
} // namespace Websocket
} // namespace da4qi4
| 28.37037
| 114
| 0.586463
|
hl4
|
f137c5d4c66f20fd9810d8e5203c0a323e4e585e
| 2,893
|
cpp
|
C++
|
lib/src/agents/proximity_sensor.cpp
|
eidelen/maf
|
759b4b4a21962de8ec53dd198bc5bf66c19ee017
|
[
"MIT"
] | null | null | null |
lib/src/agents/proximity_sensor.cpp
|
eidelen/maf
|
759b4b4a21962de8ec53dd198bc5bf66c19ee017
|
[
"MIT"
] | null | null | null |
lib/src/agents/proximity_sensor.cpp
|
eidelen/maf
|
759b4b4a21962de8ec53dd198bc5bf66c19ee017
|
[
"MIT"
] | null | null | null |
/****************************************************************************
** Copyright (c) 2021 Adrian Schneider
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
**
*****************************************************************************/
#include "proximity_sensor.h"
std::shared_ptr<ProximitySensor> ProximitySensor::createProxSensor(unsigned int id, double range)
{
return std::shared_ptr<ProximitySensor>(new ProximitySensor(id, range));
}
ProximitySensor::ProximitySensor(unsigned int id, double range): Agent::Agent(id), m_range(range)
{
}
ProximitySensor::~ProximitySensor()
{
}
void ProximitySensor::update(double time)
{
// update first sub agents
updateSubAgents(time);
assert(hasEnvironment());
// update agents in range
m_agentsInRange.clear();
EnvironmentInterface::DistanceQueue q = m_environment.lock()->getAgentDistancesToAllOtherAgents(id());
while(!q.empty())
{
const auto& d = q.top();
// if target is not on ignore list and target is in range
if( d.dist < m_range )
{
if( m_ignoreAgentIds.find(d.targetId) == m_ignoreAgentIds.end() )
{
m_agentsInRange.push_back(d);
}
q.pop();
}
else
{
// DistanceQueue is ordered -> next agent is out of range too
break;
}
}
performMove(time);
}
AgentType ProximitySensor::type() const
{
return AgentType::EProxSensor;
}
double ProximitySensor::range() const
{
return m_range;
}
void ProximitySensor::setRange(double newRange)
{
m_range = newRange;
}
std::vector<EnvironmentInterface::Distance> ProximitySensor::getAgentsInSensorRange() const
{
return m_agentsInRange;
}
void ProximitySensor::addIgnoreAgentId(unsigned int agentId)
{
m_ignoreAgentIds.insert(agentId);
}
| 28.93
| 106
| 0.663671
|
eidelen
|
f137ef2add0af378ea99b08270988355bd06f43b
| 212
|
cpp
|
C++
|
TestProject/Source/TestProject/TestProject.cpp
|
1Gokul/TestProject
|
e732c65440537252bd02b9b527ac9a084f4ce44c
|
[
"MIT"
] | 3
|
2020-07-06T19:46:42.000Z
|
2021-12-06T11:23:17.000Z
|
TestProject/Source/TestProject/TestProject.cpp
|
1Gokul/TestProject
|
e732c65440537252bd02b9b527ac9a084f4ce44c
|
[
"MIT"
] | null | null | null |
TestProject/Source/TestProject/TestProject.cpp
|
1Gokul/TestProject
|
e732c65440537252bd02b9b527ac9a084f4ce44c
|
[
"MIT"
] | 1
|
2021-12-06T11:23:48.000Z
|
2021-12-06T11:23:48.000Z
|
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "TestProject.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE(FDefaultGameModuleImpl, TestProject, "TestProject");
| 30.285714
| 83
| 0.783019
|
1Gokul
|
f138a7c9b24826789f4657efba62850bfafede9b
| 3,047
|
cpp
|
C++
|
go/runtime/cgosymbolizer/symbolizer.cpp
|
searKing/golang
|
b386053582e223fc1f4c4ab3c2d73ab423cefef2
|
[
"MIT"
] | 37
|
2019-11-19T15:42:09.000Z
|
2022-03-27T07:55:42.000Z
|
go/runtime/cgosymbolizer/symbolizer.cpp
|
searKing/golang
|
b386053582e223fc1f4c4ab3c2d73ab423cefef2
|
[
"MIT"
] | 5
|
2020-10-28T06:55:54.000Z
|
2021-06-19T05:25:46.000Z
|
go/runtime/cgosymbolizer/symbolizer.cpp
|
searKing/golang
|
b386053582e223fc1f4c4ab3c2d73ab423cefef2
|
[
"MIT"
] | 8
|
2019-12-17T05:56:18.000Z
|
2021-08-17T20:36:41.000Z
|
// Copyright 2021 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "symbolizer.h"
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <boost/stacktrace/frame.hpp>
#include <boost/stacktrace/stacktrace.hpp>
#include "traceback.h"
static int append_pc_info_to_symbolizer_list(cgoSymbolizerArg* arg);
static int append_entry_to_symbolizer_list(cgoSymbolizerArg* arg);
// For the details of how this is called see runtime.SetCgoTraceback.
void cgoSymbolizer(cgoSymbolizerArg* arg) {
cgoSymbolizerMore* more = arg->data;
if (more != NULL) {
arg->file = more->file;
arg->lineno = more->lineno;
arg->func = more->func;
// set non-zero if more info for this PC
arg->more = more->more != NULL;
arg->data = more->more;
// If returning the last file/line, we can set the
// entry point field.
if (!arg->more) { // no more info
append_entry_to_symbolizer_list(arg);
}
return;
}
arg->file = NULL;
arg->lineno = 0;
arg->func = NULL;
arg->more = 0;
if (arg->pc == 0) {
return;
}
append_pc_info_to_symbolizer_list(arg);
// If returning only one file/line, we can set the entry point field.
if (!arg->more) {
append_entry_to_symbolizer_list(arg);
}
}
void prepare_syminfo(const boost::stacktrace::detail::native_frame_ptr_t addr,
std::string& file, std::size_t& line, std::string& func) {
auto frame = boost::stacktrace::frame(addr);
file = frame.source_file();
line = frame.source_line();
func = frame.name();
if (!func.empty()) {
func = boost::core::demangle(func.c_str());
} else {
func = boost::stacktrace::detail::to_hex_array(addr).data();
}
if (file.empty() || file.find_first_of("?") == 0) {
boost::stacktrace::detail::location_from_symbol loc(addr);
if (!loc.empty()) {
file = loc.name();
}
}
}
static int append_pc_info_to_symbolizer_list(cgoSymbolizerArg* arg) {
std::string file;
std::size_t line = 0;
std::string func;
prepare_syminfo(boost::stacktrace::frame::native_frame_ptr_t(arg->pc), file,
line, func);
// init head with current stack
if (arg->file == NULL) {
arg->file = strdup(file.c_str());
arg->lineno = line;
arg->func = strdup(func.c_str());
return 0;
}
cgoSymbolizerMore* more = (cgoSymbolizerMore*)malloc(sizeof(*more));
if (more == NULL) {
return 1;
}
// append current stack to the tail
more->more = NULL;
more->file = strdup(file.c_str());
more->lineno = line;
more->func = strdup(func.c_str());
cgoSymbolizerMore** pp = NULL;
for (pp = &arg->data; *pp != NULL; pp = &(*pp)->more) {
}
*pp = more;
arg->more = 1;
return 0;
}
static int append_entry_to_symbolizer_list(cgoSymbolizerArg* arg) {
auto frame = boost::stacktrace::frame(
boost::stacktrace::frame::native_frame_ptr_t(arg->pc));
arg->entry = (uintptr_t)strdup(frame.name().c_str());
return 0;
}
| 27.954128
| 79
| 0.653758
|
searKing
|
f13ca97b2f05ebd5a61231499adceea695401023
| 7,774
|
cpp
|
C++
|
unique_paths.cpp
|
artureganyan/algorithms
|
98cd0048162b3cb1c79712a884261cd3fe31063c
|
[
"MIT"
] | null | null | null |
unique_paths.cpp
|
artureganyan/algorithms
|
98cd0048162b3cb1c79712a884261cd3fe31063c
|
[
"MIT"
] | null | null | null |
unique_paths.cpp
|
artureganyan/algorithms
|
98cd0048162b3cb1c79712a884261cd3fe31063c
|
[
"MIT"
] | null | null | null |
// Problem: https://leetcode.com/problems/unique-paths/
#include <vector>
#include "utils.h"
namespace unique_paths {
// Note: All solutions return int as required by the initial problem, but
// 32-bit signed integer can hold the result for at most the 17x18 grid.
// The straightforward solution, recursively counting paths from the start
// cell to the target
class Solution1 {
public:
// Time: O(C(n + m, m)), Space: O(n + m), Recursion depth < n + m
// n - number of rows, m - number of columns,
// C(n + m, m) - binomial coefficient (n + m)! / (m! * n!)
//
// Note: Time complexity is estimated by the number of paths, which is
// the binomial coefficient as shown in the Solution3. Space complexity
// depends on the recursion depth, which is determined by the path
// length n + m - 1.
//
int run(int rows_count, int cols_count)
{
if (rows_count <= 0 || cols_count <= 0)
return 0;
if (rows_count == 1 || cols_count == 1)
return 1;
// Go right + go down
return run(rows_count, cols_count - 1) +
run(rows_count - 1, cols_count);
}
};
// Non-recursive solution, counting paths from the target cell to the start
class Solution2 {
public:
// Time: O(n * m), Space: O(n * m), n - number of rows, m - number of columns
//
// Note: It calculates all cells, but 1) we need only the (0, 0), 2) the
// results are symmetrical: count(n, m) == count(m, n). So it could be
// optimized.
//
int run(int rows_count, int cols_count)
{
if (rows_count <= 0 || cols_count <= 0)
return 0;
// Idea:
// Count paths in reverse order, moving the start from the target cell to (0, 0):
// 1. Put the start to the target cell (t = rows_count - 1, l = cols_count - 1).
// Then there is only 1 path, i.e. the cell itself.
// 2. Go to the outer rectangle, which top-left corner is (t - 1, l - 1) if this
// is a square.
// 3. Calculate counts for the top and left borders of the outer rectangle. For
// each cell (r, c), the count is a sum of counts for (r + 1, c) and (r, c + 1),
// because we can step only right or down.
// 4. Repeat 2 and 3 until we reach (0, 0).
//
// 0 0 0 0 0 0 6 3 1
// 0 0 0 -> 0 2 1 -> 3 2 1
// 0 0 1 0 1 1 1 1 1
// Allocate one more row and column with zeros to avoid excessive range checks
std::vector<std::vector<int>> count(rows_count + 1, std::vector<int>(cols_count + 1, 0));
// Start from the target cell
int t = rows_count - 1;
int l = cols_count - 1;
int b = t;
int r = l;
count[t][l] = 1;
do {
// Go up and left. If not possible, decrease the right/bottom border
// because everything at the right/bottom is already counted.
if (t > 0) {
t -= 1;
} else {
r = l - 1;
}
if (l > 0) {
l -= 1;
} else {
b = t - 1;
}
// Count top border of the outer rectangle
for (int ci = r, ri = t; ci > l; ci--) {
calculateCount(count, ri, ci);
}
// Count left border of the outer rectangle
for (int ri = b, ci = l; ri > t; ri--) {
calculateCount(count, ri, ci);
}
// Count top-left corner of the outer rectangle
calculateCount(count, t, l);
} while (t != 0 || l != 0);
return count[0][0];
}
private:
inline void calculateCount(std::vector<std::vector<int>>& count, int r, int c) const
{
int& cell = count[r][c];
cell += count[r + 1][c];
cell += count[r][c + 1];
}
};
// This solution just calculates the binomial coefficient
class Solution3 {
public:
// Time: O(n - m), Space: O(1), n - number of rows, m - number of columns
//
// Warning: This implementation uses floating-point calculation and produces
// rounding error for large grids (e.g. test for 15x18 returned 1 path less
// than expected).
//
int run(int rows_count, int cols_count)
{
// Idea:
// If we look at the numbers of paths from each cell to the right-bottom
// corner, we may notice that they are binomial coefficients
// C(n, m) = n! / (m! * (n - m)!), written by diagonals:
//
// Numbers of paths. n n, excluding
// They are C(n, m). trivial cases
//
// 70 35 15 5 1 8 7 6 5 4 8 7 6 5 *
// 35 20 10 4 1 7 6 5 4 3 7 6 5 4 *
// 15 10 6 3 1 6 5 4 3 2 6 5 4 3 *
// 5 4 3 2 1 5 4 3 2 1 5 4 3 2 *
// 1 1 1 1 1 4 3 2 1 1 * * * * *
//
// For all cells except the right and bottom borders (which correspond
// to trivial cases nx1 and 1xn):
// n = (rows_count - 1) + (cols_count - 1)
// m = (cols_count - 1)
//
// Finally, to reduce the number of multiplications, we can simplify
// C(n, m) to ((m+1) * (m+2) * ... * n) / (n - m)! and swap rows_count
// and cols_count if rows_count > cols_count (the result is the same,
// but both the dividend and divisor are lesser).
if (rows_count <= 0 || cols_count <= 0)
return 0;
if (rows_count == 1 || cols_count == 1)
return 1;
if (rows_count > cols_count)
std::swap(rows_count, cols_count);
// Calculate C(n, m) = n! / (m! * (n - m)!)
// n, m
const int n = rows_count - 1 + cols_count - 1;
const int m = cols_count - 1;
// n! / m! = (m + 1) * (m + 2) * ... * n
double nf_div_mf = 1;
for (int i = m + 1; i <= n; i++)
nf_div_mf *= i;
// (n - m)!
double n_minus_m_f = 1;
for (int i = 2; i <= (n - m); i++)
n_minus_m_f *= i;
// C(n, m)
const double C_n_m = nf_div_mf / n_minus_m_f;
return static_cast<int>(C_n_m);
}
};
template <typename Solution>
void test(bool large_grid = false)
{
auto test_symmetrical = [](int rows_count, int cols_count, int expected)
{
if (Solution().run(rows_count, cols_count) != expected)
return false;
if (rows_count != cols_count) {
if (Solution().run(cols_count, rows_count) != expected)
return false;
}
return true;
};
ASSERT( test_symmetrical(-1, -1, 0) );
ASSERT( test_symmetrical(-1, 0, 0) );
ASSERT( test_symmetrical(-1, 1, 0) );
ASSERT( test_symmetrical(0, 0, 0) );
ASSERT( test_symmetrical(1, 0, 0) );
ASSERT( test_symmetrical(1, 1, 1) );
ASSERT( test_symmetrical(1, 2, 1) );
ASSERT( test_symmetrical(1, 3, 1) );
ASSERT( test_symmetrical(2, 2, 2) );
ASSERT( test_symmetrical(2, 3, 3) );
ASSERT( test_symmetrical(2, 4, 4) );
ASSERT( test_symmetrical(2, 5, 5) );
ASSERT( test_symmetrical(3, 3, 6) );
ASSERT( test_symmetrical(3, 4, 10) );
ASSERT( test_symmetrical(3, 5, 15) );
ASSERT( test_symmetrical(4, 4, 20) );
ASSERT( test_symmetrical(4, 5, 35) );
ASSERT( test_symmetrical(5, 5, 70) );
ASSERT( test_symmetrical(10, 10, 48620) );
if (large_grid)
ASSERT( test_symmetrical(17, 18, 1166803110) );
}
int main()
{
// Do not test large grid because of time complexity
test<Solution1>();
test<Solution2>(true);
// Do not test large grid because of rounding error
test<Solution3>();
return 0;
}
}
| 32.123967
| 97
| 0.531515
|
artureganyan
|
f13e6e63b73ef115d8ca7a445339307d0a7f6eca
| 176,331
|
cpp
|
C++
|
GCG_Source.build/module.django.utils._os.cpp
|
Pckool/GCG
|
cee786d04ea30f3995e910bca82635f442b2a6a8
|
[
"MIT"
] | null | null | null |
GCG_Source.build/module.django.utils._os.cpp
|
Pckool/GCG
|
cee786d04ea30f3995e910bca82635f442b2a6a8
|
[
"MIT"
] | null | null | null |
GCG_Source.build/module.django.utils._os.cpp
|
Pckool/GCG
|
cee786d04ea30f3995e910bca82635f442b2a6a8
|
[
"MIT"
] | null | null | null |
/* Generated code for Python source for module 'django.utils._os'
* created by Nuitka version 0.5.28.2
*
* This code is in part copyright 2017 Kay Hayen.
*
* 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 "nuitka/prelude.h"
#include "__helpers.h"
/* The _module_django$utils$_os is a Python object pointer of module type. */
/* Note: For full compatibility with CPython, every module variable access
* needs to go through it except for cases where the module cannot possibly
* have changed in the mean time.
*/
PyObject *module_django$utils$_os;
PyDictObject *moduledict_django$utils$_os;
/* The module constants used, if any. */
extern PyObject *const_str_plain_force_text;
static PyObject *const_str_digest_a2f4bfb7897945f1cc69848924f0cb55;
extern PyObject *const_str_plain_remove;
extern PyObject *const_str_plain_PY2;
extern PyObject *const_str_plain_ModuleSpec;
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain___package__;
extern PyObject *const_str_plain_sys;
extern PyObject *const_tuple_str_plain_SuspiciousFileOperation_tuple;
extern PyObject *const_str_plain_decode;
extern PyObject *const_str_plain_unicode_literals;
extern PyObject *const_str_plain_nt;
extern PyObject *const_str_plain_sep;
static PyObject *const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8;
extern PyObject *const_str_plain_text_type;
static PyObject *const_str_plain_final_path;
extern PyObject *const_tuple_str_plain_path_tuple;
static PyObject *const_str_plain_symlink_path;
static PyObject *const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e;
extern PyObject *const_dict_empty;
extern PyObject *const_str_digest_842dfd4744c6e20ce39943a1591eb59d;
extern PyObject *const_str_plain___file__;
static PyObject *const_str_digest_e333b5c27f64858ace2064722679d143;
extern PyObject *const_str_digest_e3393b2e61653c3df2c7d436c253bbee;
static PyObject *const_tuple_d68c618138c0feb94dce5f32faa81863_tuple;
extern PyObject *const_tuple_str_plain_force_text_tuple;
extern PyObject *const_str_digest_e399ba4554180f37de594a6743234f17;
extern PyObject *const_int_0;
extern PyObject *const_str_plain_path;
extern PyObject *const_str_angle_listcontraction;
extern PyObject *const_str_plain_safe_join;
extern PyObject *const_str_plain_encode;
static PyObject *const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple;
extern PyObject *const_str_plain_six;
extern PyObject *const_str_plain_p;
extern PyObject *const_str_plain_tempfile;
extern PyObject *const_str_plain_abspathu;
static PyObject *const_str_digest_b3b92bc7aa9804266ff219682e3d0112;
static PyObject *const_str_plain_mkdtemp;
extern PyObject *const_str_plain_normpath;
extern PyObject *const_str_plain_abspath;
static PyObject *const_str_plain_rmdir;
static PyObject *const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5;
extern PyObject *const_str_plain_normcase;
static PyObject *const_str_plain_getdefaultencoding;
static PyObject *const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple;
extern PyObject *const_str_digest_dfb6e1abbed3113ee07234fdc458a320;
static PyObject *const_str_digest_d92a79f74db4468ebeba34a6c933cb11;
extern PyObject *const_tuple_str_plain_six_tuple;
extern PyObject *const_str_plain_os;
static PyObject *const_str_digest_5c892843b642786d8376f7cd7a9ec574;
static PyObject *const_str_plain_getfilesystemencoding;
static PyObject *const_str_plain_symlink;
extern PyObject *const_str_plain_original;
extern PyObject *const_tuple_empty;
extern PyObject *const_str_plain_getcwdu;
extern PyObject *const_str_plain_SuspiciousFileOperation;
extern PyObject *const_str_digest_467c9722f19d9d40d148689532cdc0b1;
extern PyObject *const_str_plain_base;
extern PyObject *const_str_plain_tmpdir;
extern PyObject *const_str_plain_upath;
extern PyObject *const_str_plain_npath;
extern PyObject *const_str_plain_paths;
static PyObject *const_str_plain_base_path;
extern PyObject *const_str_plain_makedirs;
static PyObject *const_str_plain_original_path;
extern PyObject *const_str_plain___loader__;
extern PyObject *const_str_plain_format;
extern PyObject *const_str_plain_join;
extern PyObject *const_str_plain_name;
static PyObject *const_str_plain_symlinks_supported;
extern PyObject *const_str_plain_startswith;
static PyObject *const_str_plain_supported;
extern PyObject *const_str_plain_dirname;
static PyObject *const_str_plain_fs_encoding;
static PyObject *const_tuple_str_plain_p_str_plain_paths_tuple;
extern PyObject *const_str_plain_PY3;
extern PyObject *const_str_plain___doc__;
extern PyObject *const_str_plain___cached__;
static PyObject *const_str_plain_isabs;
static PyObject *module_filename_obj;
static bool constants_created = false;
static void createModuleConstants( void )
{
const_str_digest_a2f4bfb7897945f1cc69848924f0cb55 = UNSTREAM_STRING( &constant_bin[ 1141471 ], 19, 0 );
const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8 = UNSTREAM_STRING( &constant_bin[ 1141490 ], 257, 0 );
const_str_plain_final_path = UNSTREAM_STRING( &constant_bin[ 1141747 ], 10, 1 );
const_str_plain_symlink_path = UNSTREAM_STRING( &constant_bin[ 1141757 ], 12, 1 );
const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e = UNSTREAM_STRING( &constant_bin[ 1141769 ], 39, 0 );
const_str_digest_e333b5c27f64858ace2064722679d143 = UNSTREAM_STRING( &constant_bin[ 1141808 ], 71, 0 );
const_tuple_d68c618138c0feb94dce5f32faa81863_tuple = PyTuple_New( 4 );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 0, const_str_plain_tmpdir ); Py_INCREF( const_str_plain_tmpdir );
const_str_plain_original_path = UNSTREAM_STRING( &constant_bin[ 1141879 ], 13, 1 );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 1, const_str_plain_original_path ); Py_INCREF( const_str_plain_original_path );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 2, const_str_plain_symlink_path ); Py_INCREF( const_str_plain_symlink_path );
const_str_plain_supported = UNSTREAM_STRING( &constant_bin[ 1262 ], 9, 1 );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 3, const_str_plain_supported ); Py_INCREF( const_str_plain_supported );
const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple = PyTuple_New( 4 );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 0, const_str_plain_base ); Py_INCREF( const_str_plain_base );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 1, const_str_plain_paths ); Py_INCREF( const_str_plain_paths );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 2, const_str_plain_final_path ); Py_INCREF( const_str_plain_final_path );
const_str_plain_base_path = UNSTREAM_STRING( &constant_bin[ 1141892 ], 9, 1 );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 3, const_str_plain_base_path ); Py_INCREF( const_str_plain_base_path );
const_str_digest_b3b92bc7aa9804266ff219682e3d0112 = UNSTREAM_STRING( &constant_bin[ 1141901 ], 183, 0 );
const_str_plain_mkdtemp = UNSTREAM_STRING( &constant_bin[ 1142084 ], 7, 1 );
const_str_plain_rmdir = UNSTREAM_STRING( &constant_bin[ 1142091 ], 5, 1 );
const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5 = UNSTREAM_STRING( &constant_bin[ 1142096 ], 25, 0 );
const_str_plain_getdefaultencoding = UNSTREAM_STRING( &constant_bin[ 1142121 ], 18, 1 );
const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple = PyTuple_New( 7 );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 0, const_str_plain_abspath ); Py_INCREF( const_str_plain_abspath );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 1, const_str_plain_dirname ); Py_INCREF( const_str_plain_dirname );
const_str_plain_isabs = UNSTREAM_STRING( &constant_bin[ 1142139 ], 5, 1 );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 2, const_str_plain_isabs ); Py_INCREF( const_str_plain_isabs );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 3, const_str_plain_join ); Py_INCREF( const_str_plain_join );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 4, const_str_plain_normcase ); Py_INCREF( const_str_plain_normcase );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 5, const_str_plain_normpath ); Py_INCREF( const_str_plain_normpath );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 6, const_str_plain_sep ); Py_INCREF( const_str_plain_sep );
const_str_digest_d92a79f74db4468ebeba34a6c933cb11 = UNSTREAM_STRING( &constant_bin[ 1142144 ], 213, 0 );
const_str_digest_5c892843b642786d8376f7cd7a9ec574 = UNSTREAM_STRING( &constant_bin[ 1142357 ], 98, 0 );
const_str_plain_getfilesystemencoding = UNSTREAM_STRING( &constant_bin[ 1142455 ], 21, 1 );
const_str_plain_symlink = UNSTREAM_STRING( &constant_bin[ 1141757 ], 7, 1 );
const_str_plain_symlinks_supported = UNSTREAM_STRING( &constant_bin[ 1142476 ], 18, 1 );
const_str_plain_fs_encoding = UNSTREAM_STRING( &constant_bin[ 1142494 ], 11, 1 );
const_tuple_str_plain_p_str_plain_paths_tuple = PyTuple_New( 2 );
PyTuple_SET_ITEM( const_tuple_str_plain_p_str_plain_paths_tuple, 0, const_str_plain_p ); Py_INCREF( const_str_plain_p );
PyTuple_SET_ITEM( const_tuple_str_plain_p_str_plain_paths_tuple, 1, const_str_plain_paths ); Py_INCREF( const_str_plain_paths );
constants_created = true;
}
#ifndef __NUITKA_NO_ASSERT__
void checkModuleConstants_django$utils$_os( void )
{
// The module may not have been used at all.
if (constants_created == false) return;
}
#endif
// The module code objects.
static PyCodeObject *codeobj_f795cf1a4736e33c5a5152c4aef12ba3;
static PyCodeObject *codeobj_e3f2225c4277cee0cd5878c353c5494a;
static PyCodeObject *codeobj_8338c887cffee3f6624948b93fdb5cad;
static PyCodeObject *codeobj_f5eb817954879f203f472ef76832ad97;
static PyCodeObject *codeobj_519eab41ce47fa2590f6a99ccc08067a;
static PyCodeObject *codeobj_7f1d67953d1486ada0ef5501b0312cae;
static PyCodeObject *codeobj_786e20e096923522b138dc8044ece5a9;
static void createModuleCodeObjects(void)
{
module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_a2f4bfb7897945f1cc69848924f0cb55 );
codeobj_f795cf1a4736e33c5a5152c4aef12ba3 = MAKE_CODEOBJ( module_filename_obj, const_str_angle_listcontraction, 63, const_tuple_str_plain_p_str_plain_paths_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_e3f2225c4277cee0cd5878c353c5494a = MAKE_CODEOBJ( module_filename_obj, const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5, 1, const_tuple_empty, 0, 0, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_8338c887cffee3f6624948b93fdb5cad = MAKE_CODEOBJ( module_filename_obj, const_str_plain_abspathu, 24, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_f5eb817954879f203f472ef76832ad97 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_npath, 44, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_519eab41ce47fa2590f6a99ccc08067a = MAKE_CODEOBJ( module_filename_obj, const_str_plain_safe_join, 54, const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARARGS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_7f1d67953d1486ada0ef5501b0312cae = MAKE_CODEOBJ( module_filename_obj, const_str_plain_symlinks_supported, 82, const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 0, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_786e20e096923522b138dc8044ece5a9 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_upath, 35, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
}
// The module function declarations.
NUITKA_CROSS_MODULE PyObject *impl___internal__$$$function_12_complex_call_helper_pos_star_list( PyObject **python_pars );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_2_upath( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_3_npath( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( );
// The module function definitions.
static PyObject *impl_django$utils$_os$$$function_1_abspathu( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_path = python_pars[ 0 ];
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_assign_source_1;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_return_value;
static struct Nuitka_FrameObject *cache_frame_8338c887cffee3f6624948b93fdb5cad = NULL;
struct Nuitka_FrameObject *frame_8338c887cffee3f6624948b93fdb5cad;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_8338c887cffee3f6624948b93fdb5cad, codeobj_8338c887cffee3f6624948b93fdb5cad, module_django$utils$_os, sizeof(void *) );
frame_8338c887cffee3f6624948b93fdb5cad = cache_frame_8338c887cffee3f6624948b93fdb5cad;
// Push the new frame as the currently active one.
pushFrameStack( frame_8338c887cffee3f6624948b93fdb5cad );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_8338c887cffee3f6624948b93fdb5cad ) == 2 ); // Frame stack
// Framed code:
tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_isabs );
if (unlikely( tmp_called_name_1 == NULL ))
{
tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_isabs );
}
if ( tmp_called_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "isabs" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 30;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = par_path;
CHECK_OBJECT( tmp_args_element_name_1 );
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 30;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_cond_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 30;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 30;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_no_1;
}
else
{
goto branch_yes_1;
}
branch_yes_1:;
tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join );
if (unlikely( tmp_called_name_2 == NULL ))
{
tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_join );
}
if ( tmp_called_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "join" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 31;
tmp_args_element_name_2 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_getcwdu );
if ( tmp_args_element_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_3 = par_path;
if ( tmp_args_element_name_3 == NULL )
{
Py_DECREF( tmp_args_element_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 31;
{
PyObject *call_args[] = { tmp_args_element_name_2, tmp_args_element_name_3 };
tmp_assign_source_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args );
}
Py_DECREF( tmp_args_element_name_2 );
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
{
PyObject *old = par_path;
par_path = tmp_assign_source_1;
Py_XDECREF( old );
}
branch_no_1:;
tmp_called_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normpath );
if (unlikely( tmp_called_name_3 == NULL ))
{
tmp_called_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normpath );
}
if ( tmp_called_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normpath" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 32;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_4 = par_path;
if ( tmp_args_element_name_4 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 32;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 32;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args );
}
if ( tmp_return_value == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 32;
type_description_1 = "o";
goto frame_exception_exit_1;
}
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_8338c887cffee3f6624948b93fdb5cad, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_8338c887cffee3f6624948b93fdb5cad->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_8338c887cffee3f6624948b93fdb5cad, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_8338c887cffee3f6624948b93fdb5cad,
type_description_1,
par_path
);
// Release cached frame.
if ( frame_8338c887cffee3f6624948b93fdb5cad == cache_frame_8338c887cffee3f6624948b93fdb5cad )
{
Py_DECREF( frame_8338c887cffee3f6624948b93fdb5cad );
}
cache_frame_8338c887cffee3f6624948b93fdb5cad = NULL;
assertFrameObject( frame_8338c887cffee3f6624948b93fdb5cad );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_1_abspathu );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_path );
par_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_path );
par_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_1_abspathu );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_2_upath( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_path = python_pars[ 0 ];
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
int tmp_and_left_truth_1;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_right_value_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_called_name_1;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_isinstance_cls_1;
PyObject *tmp_isinstance_inst_1;
PyObject *tmp_operand_name_1;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
static struct Nuitka_FrameObject *cache_frame_786e20e096923522b138dc8044ece5a9 = NULL;
struct Nuitka_FrameObject *frame_786e20e096923522b138dc8044ece5a9;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_786e20e096923522b138dc8044ece5a9, codeobj_786e20e096923522b138dc8044ece5a9, module_django$utils$_os, sizeof(void *) );
frame_786e20e096923522b138dc8044ece5a9 = cache_frame_786e20e096923522b138dc8044ece5a9;
// Push the new frame as the currently active one.
pushFrameStack( frame_786e20e096923522b138dc8044ece5a9 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_786e20e096923522b138dc8044ece5a9 ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 );
if ( tmp_and_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 );
if ( tmp_and_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_and_left_value_1 );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_1 == 1 )
{
goto and_right_1;
}
else
{
goto and_left_1;
}
and_right_1:;
Py_DECREF( tmp_and_left_value_1 );
tmp_isinstance_inst_1 = par_path;
if ( tmp_isinstance_inst_1 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_isinstance_cls_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_text_type );
if ( tmp_isinstance_cls_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_operand_name_1 = BUILTIN_ISINSTANCE( tmp_isinstance_inst_1, tmp_isinstance_cls_1 );
Py_DECREF( tmp_isinstance_cls_1 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 );
if ( tmp_and_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_and_right_value_1 );
tmp_cond_value_1 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
tmp_cond_value_1 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_source_name_3 = par_path;
if ( tmp_source_name_3 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_decode );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding );
if (unlikely( tmp_args_element_name_1 == NULL ))
{
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_fs_encoding );
}
if ( tmp_args_element_name_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "fs_encoding" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_786e20e096923522b138dc8044ece5a9->m_frame.f_lineno = 40;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_return_value == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
goto frame_return_exit_1;
branch_no_1:;
tmp_return_value = par_path;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 41;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_786e20e096923522b138dc8044ece5a9, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_786e20e096923522b138dc8044ece5a9->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_786e20e096923522b138dc8044ece5a9, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_786e20e096923522b138dc8044ece5a9,
type_description_1,
par_path
);
// Release cached frame.
if ( frame_786e20e096923522b138dc8044ece5a9 == cache_frame_786e20e096923522b138dc8044ece5a9 )
{
Py_DECREF( frame_786e20e096923522b138dc8044ece5a9 );
}
cache_frame_786e20e096923522b138dc8044ece5a9 = NULL;
assertFrameObject( frame_786e20e096923522b138dc8044ece5a9 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_2_upath );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_path );
par_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_path );
par_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_2_upath );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_3_npath( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_path = python_pars[ 0 ];
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
int tmp_and_left_truth_1;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_right_value_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_called_name_1;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_isinstance_cls_1;
PyObject *tmp_isinstance_inst_1;
PyObject *tmp_operand_name_1;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
static struct Nuitka_FrameObject *cache_frame_f5eb817954879f203f472ef76832ad97 = NULL;
struct Nuitka_FrameObject *frame_f5eb817954879f203f472ef76832ad97;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_f5eb817954879f203f472ef76832ad97, codeobj_f5eb817954879f203f472ef76832ad97, module_django$utils$_os, sizeof(void *) );
frame_f5eb817954879f203f472ef76832ad97 = cache_frame_f5eb817954879f203f472ef76832ad97;
// Push the new frame as the currently active one.
pushFrameStack( frame_f5eb817954879f203f472ef76832ad97 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_f5eb817954879f203f472ef76832ad97 ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 );
if ( tmp_and_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 );
if ( tmp_and_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_and_left_value_1 );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_1 == 1 )
{
goto and_right_1;
}
else
{
goto and_left_1;
}
and_right_1:;
Py_DECREF( tmp_and_left_value_1 );
tmp_isinstance_inst_1 = par_path;
if ( tmp_isinstance_inst_1 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_isinstance_cls_1 = (PyObject *)&PyBytes_Type;
tmp_operand_name_1 = BUILTIN_ISINSTANCE( tmp_isinstance_inst_1, tmp_isinstance_cls_1 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 );
if ( tmp_and_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_and_right_value_1 );
tmp_cond_value_1 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
tmp_cond_value_1 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_source_name_2 = par_path;
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_encode );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding );
if (unlikely( tmp_args_element_name_1 == NULL ))
{
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_fs_encoding );
}
if ( tmp_args_element_name_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "fs_encoding" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_f5eb817954879f203f472ef76832ad97->m_frame.f_lineno = 50;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_return_value == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
goto frame_return_exit_1;
branch_no_1:;
tmp_return_value = par_path;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 51;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_f5eb817954879f203f472ef76832ad97, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_f5eb817954879f203f472ef76832ad97->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_f5eb817954879f203f472ef76832ad97, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_f5eb817954879f203f472ef76832ad97,
type_description_1,
par_path
);
// Release cached frame.
if ( frame_f5eb817954879f203f472ef76832ad97 == cache_frame_f5eb817954879f203f472ef76832ad97 )
{
Py_DECREF( frame_f5eb817954879f203f472ef76832ad97 );
}
cache_frame_f5eb817954879f203f472ef76832ad97 = NULL;
assertFrameObject( frame_f5eb817954879f203f472ef76832ad97 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_3_npath );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_path );
par_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_path );
par_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_3_npath );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_4_safe_join( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_base = python_pars[ 0 ];
PyObject *par_paths = python_pars[ 1 ];
PyObject *var_final_path = NULL;
PyObject *var_base_path = NULL;
PyObject *outline_0_var_p = NULL;
PyObject *tmp_listcontraction_1__$0 = NULL;
PyObject *tmp_listcontraction_1__contraction = NULL;
PyObject *tmp_listcontraction_1__iter_value_0 = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
int tmp_and_left_truth_1;
int tmp_and_left_truth_2;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_left_value_2;
PyObject *tmp_and_right_value_1;
PyObject *tmp_and_right_value_2;
PyObject *tmp_append_list_1;
PyObject *tmp_append_value_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
PyObject *tmp_args_element_name_7;
PyObject *tmp_args_element_name_8;
PyObject *tmp_args_element_name_9;
PyObject *tmp_args_element_name_10;
PyObject *tmp_args_element_name_11;
PyObject *tmp_args_element_name_12;
PyObject *tmp_args_element_name_13;
PyObject *tmp_args_element_name_14;
PyObject *tmp_args_element_name_15;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_called_name_4;
PyObject *tmp_called_name_5;
PyObject *tmp_called_name_6;
PyObject *tmp_called_name_7;
PyObject *tmp_called_name_8;
PyObject *tmp_called_name_9;
PyObject *tmp_called_name_10;
PyObject *tmp_called_name_11;
PyObject *tmp_called_name_12;
PyObject *tmp_called_name_13;
PyObject *tmp_called_name_14;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_left_2;
PyObject *tmp_compexpr_right_1;
PyObject *tmp_compexpr_right_2;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_dircall_arg1_1;
PyObject *tmp_dircall_arg2_1;
PyObject *tmp_dircall_arg3_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_left_name_1;
PyObject *tmp_next_source_1;
PyObject *tmp_operand_name_1;
PyObject *tmp_outline_return_value_1;
PyObject *tmp_raise_type_1;
int tmp_res;
PyObject *tmp_return_value;
PyObject *tmp_right_name_1;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_tuple_element_1;
static struct Nuitka_FrameObject *cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = NULL;
struct Nuitka_FrameObject *frame_f795cf1a4736e33c5a5152c4aef12ba3_2;
static struct Nuitka_FrameObject *cache_frame_519eab41ce47fa2590f6a99ccc08067a = NULL;
struct Nuitka_FrameObject *frame_519eab41ce47fa2590f6a99ccc08067a;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
NUITKA_MAY_BE_UNUSED char const *type_description_2 = NULL;
tmp_return_value = NULL;
tmp_outline_return_value_1 = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_519eab41ce47fa2590f6a99ccc08067a, codeobj_519eab41ce47fa2590f6a99ccc08067a, module_django$utils$_os, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_519eab41ce47fa2590f6a99ccc08067a = cache_frame_519eab41ce47fa2590f6a99ccc08067a;
// Push the new frame as the currently active one.
pushFrameStack( frame_519eab41ce47fa2590f6a99ccc08067a );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_519eab41ce47fa2590f6a99ccc08067a ) == 2 ); // Frame stack
// Framed code:
tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text );
if (unlikely( tmp_called_name_1 == NULL ))
{
tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_force_text );
}
if ( tmp_called_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "force_text" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 62;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = par_base;
CHECK_OBJECT( tmp_args_element_name_1 );
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 62;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_assign_source_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 62;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
{
PyObject *old = par_base;
par_base = tmp_assign_source_1;
Py_XDECREF( old );
}
// Tried code:
tmp_iter_arg_1 = par_paths;
if ( tmp_iter_arg_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "free variable '%s' referenced before assignment in enclosing scope", "paths" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_1 = "oooo";
goto try_except_handler_2;
}
tmp_assign_source_3 = MAKE_ITERATOR( tmp_iter_arg_1 );
if ( tmp_assign_source_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_1 = "oooo";
goto try_except_handler_2;
}
assert( tmp_listcontraction_1__$0 == NULL );
tmp_listcontraction_1__$0 = tmp_assign_source_3;
tmp_assign_source_4 = PyList_New( 0 );
assert( tmp_listcontraction_1__contraction == NULL );
tmp_listcontraction_1__contraction = tmp_assign_source_4;
MAKE_OR_REUSE_FRAME( cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2, codeobj_f795cf1a4736e33c5a5152c4aef12ba3, module_django$utils$_os, sizeof(void *)+sizeof(void *) );
frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2;
// Push the new frame as the currently active one.
pushFrameStack( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ) == 2 ); // Frame stack
// Framed code:
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_listcontraction_1__$0;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_5 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_5 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_2 = "oo";
exception_lineno = 63;
goto try_except_handler_3;
}
}
{
PyObject *old = tmp_listcontraction_1__iter_value_0;
tmp_listcontraction_1__iter_value_0 = tmp_assign_source_5;
Py_XDECREF( old );
}
tmp_assign_source_6 = tmp_listcontraction_1__iter_value_0;
CHECK_OBJECT( tmp_assign_source_6 );
{
PyObject *old = outline_0_var_p;
outline_0_var_p = tmp_assign_source_6;
Py_INCREF( outline_0_var_p );
Py_XDECREF( old );
}
tmp_append_list_1 = tmp_listcontraction_1__contraction;
CHECK_OBJECT( tmp_append_list_1 );
tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text );
if (unlikely( tmp_called_name_2 == NULL ))
{
tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_force_text );
}
if ( tmp_called_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "force_text" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
tmp_args_element_name_2 = outline_0_var_p;
CHECK_OBJECT( tmp_args_element_name_2 );
frame_f795cf1a4736e33c5a5152c4aef12ba3_2->m_frame.f_lineno = 63;
{
PyObject *call_args[] = { tmp_args_element_name_2 };
tmp_append_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_2, call_args );
}
if ( tmp_append_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
assert( PyList_Check( tmp_append_list_1 ) );
tmp_res = PyList_Append( tmp_append_list_1, tmp_append_value_1 );
Py_DECREF( tmp_append_value_1 );
if ( tmp_res == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
goto loop_start_1;
loop_end_1:;
tmp_outline_return_value_1 = tmp_listcontraction_1__contraction;
CHECK_OBJECT( tmp_outline_return_value_1 );
Py_INCREF( tmp_outline_return_value_1 );
goto try_return_handler_3;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
// Return handler code:
try_return_handler_3:;
Py_XDECREF( tmp_listcontraction_1__$0 );
tmp_listcontraction_1__$0 = NULL;
Py_XDECREF( tmp_listcontraction_1__contraction );
tmp_listcontraction_1__contraction = NULL;
Py_XDECREF( tmp_listcontraction_1__iter_value_0 );
tmp_listcontraction_1__iter_value_0 = NULL;
goto frame_return_exit_2;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_listcontraction_1__$0 );
tmp_listcontraction_1__$0 = NULL;
Py_XDECREF( tmp_listcontraction_1__contraction );
tmp_listcontraction_1__contraction = NULL;
Py_XDECREF( tmp_listcontraction_1__iter_value_0 );
tmp_listcontraction_1__iter_value_0 = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_2;
// End of try:
#if 0
RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_2:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_2;
frame_exception_exit_2:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_f795cf1a4736e33c5a5152c4aef12ba3_2, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_f795cf1a4736e33c5a5152c4aef12ba3_2->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_f795cf1a4736e33c5a5152c4aef12ba3_2, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_f795cf1a4736e33c5a5152c4aef12ba3_2,
type_description_2,
outline_0_var_p,
par_paths
);
// Release cached frame.
if ( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 == cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 )
{
Py_DECREF( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
}
cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = NULL;
assertFrameObject( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto nested_frame_exit_1;
frame_no_exception_1:;
goto skip_nested_handling_1;
nested_frame_exit_1:;
type_description_1 = "oooo";
goto try_except_handler_2;
skip_nested_handling_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
// Return handler code:
try_return_handler_2:;
Py_XDECREF( outline_0_var_p );
outline_0_var_p = NULL;
goto outline_result_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( outline_0_var_p );
outline_0_var_p = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto outline_exception_1;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
outline_exception_1:;
exception_lineno = 63;
goto frame_exception_exit_1;
outline_result_1:;
tmp_assign_source_2 = tmp_outline_return_value_1;
{
PyObject *old = par_paths;
par_paths = tmp_assign_source_2;
Py_XDECREF( old );
}
tmp_called_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu );
if (unlikely( tmp_called_name_3 == NULL ))
{
tmp_called_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspathu );
}
if ( tmp_called_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspathu" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_dircall_arg1_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join );
if (unlikely( tmp_dircall_arg1_1 == NULL ))
{
tmp_dircall_arg1_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_join );
}
if ( tmp_dircall_arg1_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "join" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_dircall_arg2_1 = PyTuple_New( 1 );
tmp_tuple_element_1 = par_base;
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_dircall_arg2_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_dircall_arg2_1, 0, tmp_tuple_element_1 );
tmp_dircall_arg3_1 = par_paths;
CHECK_OBJECT( tmp_dircall_arg3_1 );
Py_INCREF( tmp_dircall_arg1_1 );
Py_INCREF( tmp_dircall_arg3_1 );
{
PyObject *dir_call_args[] = {tmp_dircall_arg1_1, tmp_dircall_arg2_1, tmp_dircall_arg3_1};
tmp_args_element_name_3 = impl___internal__$$$function_12_complex_call_helper_pos_star_list( dir_call_args );
}
if ( tmp_args_element_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 64;
{
PyObject *call_args[] = { tmp_args_element_name_3 };
tmp_assign_source_7 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args );
}
Py_DECREF( tmp_args_element_name_3 );
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_final_path == NULL );
var_final_path = tmp_assign_source_7;
tmp_called_name_4 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu );
if (unlikely( tmp_called_name_4 == NULL ))
{
tmp_called_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspathu );
}
if ( tmp_called_name_4 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspathu" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 65;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_4 = par_base;
if ( tmp_args_element_name_4 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 65;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 65;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_assign_source_8 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args );
}
if ( tmp_assign_source_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 65;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_base_path == NULL );
var_base_path = tmp_assign_source_8;
tmp_called_name_6 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_6 == NULL ))
{
tmp_called_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_6 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = var_final_path;
if ( tmp_args_element_name_5 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73;
{
PyObject *call_args[] = { tmp_args_element_name_5 };
tmp_source_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args );
}
if ( tmp_source_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_startswith );
Py_DECREF( tmp_source_name_1 );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_7 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_7 == NULL ))
{
tmp_called_name_7 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_7 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_left_name_1 = var_base_path;
if ( tmp_left_name_1 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_right_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sep );
if (unlikely( tmp_right_name_1 == NULL ))
{
tmp_right_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sep );
}
if ( tmp_right_name_1 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sep" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_7 = BINARY_OPERATION_ADD( tmp_left_name_1, tmp_right_name_1 );
if ( tmp_args_element_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_5 );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73;
{
PyObject *call_args[] = { tmp_args_element_name_7 };
tmp_args_element_name_6 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_args_element_name_7 );
if ( tmp_args_element_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_5 );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73;
{
PyObject *call_args[] = { tmp_args_element_name_6 };
tmp_operand_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_5, call_args );
}
Py_DECREF( tmp_called_name_5 );
Py_DECREF( tmp_args_element_name_6 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 );
Py_DECREF( tmp_operand_name_1 );
if ( tmp_and_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 );
if ( tmp_and_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_1 == 1 )
{
goto and_right_1;
}
else
{
goto and_left_1;
}
and_right_1:;
tmp_called_name_8 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_8 == NULL ))
{
tmp_called_name_8 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_8 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_8 = var_final_path;
if ( tmp_args_element_name_8 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 74;
{
PyObject *call_args[] = { tmp_args_element_name_8 };
tmp_compexpr_left_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_8, call_args );
}
if ( tmp_compexpr_left_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_9 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_9 == NULL ))
{
tmp_called_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_9 == NULL )
{
Py_DECREF( tmp_compexpr_left_1 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_9 = var_base_path;
if ( tmp_args_element_name_9 == NULL )
{
Py_DECREF( tmp_compexpr_left_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 74;
{
PyObject *call_args[] = { tmp_args_element_name_9 };
tmp_compexpr_right_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_9, call_args );
}
if ( tmp_compexpr_right_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compexpr_left_1 );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_value_2 = RICH_COMPARE_NE( tmp_compexpr_left_1, tmp_compexpr_right_1 );
Py_DECREF( tmp_compexpr_left_1 );
Py_DECREF( tmp_compexpr_right_1 );
if ( tmp_and_left_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_truth_2 = CHECK_IF_TRUE( tmp_and_left_value_2 );
if ( tmp_and_left_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_and_left_value_2 );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_2 == 1 )
{
goto and_right_2;
}
else
{
goto and_left_2;
}
and_right_2:;
Py_DECREF( tmp_and_left_value_2 );
tmp_called_name_10 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_dirname );
if (unlikely( tmp_called_name_10 == NULL ))
{
tmp_called_name_10 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_dirname );
}
if ( tmp_called_name_10 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "dirname" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_11 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_11 == NULL ))
{
tmp_called_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_11 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_11 = var_base_path;
if ( tmp_args_element_name_11 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75;
{
PyObject *call_args[] = { tmp_args_element_name_11 };
tmp_args_element_name_10 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_11, call_args );
}
if ( tmp_args_element_name_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75;
{
PyObject *call_args[] = { tmp_args_element_name_10 };
tmp_compexpr_left_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_10, call_args );
}
Py_DECREF( tmp_args_element_name_10 );
if ( tmp_compexpr_left_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_12 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_12 == NULL ))
{
tmp_called_name_12 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_12 == NULL )
{
Py_DECREF( tmp_compexpr_left_2 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_12 = var_base_path;
if ( tmp_args_element_name_12 == NULL )
{
Py_DECREF( tmp_compexpr_left_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75;
{
PyObject *call_args[] = { tmp_args_element_name_12 };
tmp_compexpr_right_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_12, call_args );
}
if ( tmp_compexpr_right_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compexpr_left_2 );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_right_value_2 = RICH_COMPARE_NE( tmp_compexpr_left_2, tmp_compexpr_right_2 );
Py_DECREF( tmp_compexpr_left_2 );
Py_DECREF( tmp_compexpr_right_2 );
if ( tmp_and_right_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = tmp_and_right_value_2;
goto and_end_2;
and_left_2:;
tmp_and_right_value_1 = tmp_and_left_value_2;
and_end_2:;
tmp_cond_value_1 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
Py_INCREF( tmp_and_left_value_1 );
tmp_cond_value_1 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_called_name_13 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation );
if (unlikely( tmp_called_name_13 == NULL ))
{
tmp_called_name_13 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation );
}
if ( tmp_called_name_13 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "SuspiciousFileOperation" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 76;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_source_name_2 = const_str_digest_e333b5c27f64858ace2064722679d143;
tmp_called_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_format );
assert( tmp_called_name_14 != NULL );
tmp_args_element_name_14 = var_final_path;
if ( tmp_args_element_name_14 == NULL )
{
Py_DECREF( tmp_called_name_14 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 78;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_15 = var_base_path;
if ( tmp_args_element_name_15 == NULL )
{
Py_DECREF( tmp_called_name_14 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 78;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 77;
{
PyObject *call_args[] = { tmp_args_element_name_14, tmp_args_element_name_15 };
tmp_args_element_name_13 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_14, call_args );
}
Py_DECREF( tmp_called_name_14 );
if ( tmp_args_element_name_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 77;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 76;
{
PyObject *call_args[] = { tmp_args_element_name_13 };
tmp_raise_type_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_13, call_args );
}
Py_DECREF( tmp_args_element_name_13 );
if ( tmp_raise_type_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 76;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_1;
exception_lineno = 76;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooo";
goto frame_exception_exit_1;
branch_no_1:;
tmp_return_value = var_final_path;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 79;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_2;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_519eab41ce47fa2590f6a99ccc08067a, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_519eab41ce47fa2590f6a99ccc08067a->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_519eab41ce47fa2590f6a99ccc08067a, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_519eab41ce47fa2590f6a99ccc08067a,
type_description_1,
par_base,
par_paths,
var_final_path,
var_base_path
);
// Release cached frame.
if ( frame_519eab41ce47fa2590f6a99ccc08067a == cache_frame_519eab41ce47fa2590f6a99ccc08067a )
{
Py_DECREF( frame_519eab41ce47fa2590f6a99ccc08067a );
}
cache_frame_519eab41ce47fa2590f6a99ccc08067a = NULL;
assertFrameObject( frame_519eab41ce47fa2590f6a99ccc08067a );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_2:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_base );
par_base = NULL;
Py_XDECREF( par_paths );
par_paths = NULL;
Py_XDECREF( var_final_path );
var_final_path = NULL;
Py_XDECREF( var_base_path );
var_base_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_base );
par_base = NULL;
Py_XDECREF( par_paths );
par_paths = NULL;
Py_XDECREF( var_final_path );
var_final_path = NULL;
Py_XDECREF( var_base_path );
var_base_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_5_symlinks_supported( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *var_tmpdir = NULL;
PyObject *var_original_path = NULL;
PyObject *var_symlink_path = NULL;
PyObject *var_supported = NULL;
PyObject *tmp_try_except_1__unhandled_indicator = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
PyObject *exception_keeper_type_4;
PyObject *exception_keeper_value_4;
PyTracebackObject *exception_keeper_tb_4;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4;
PyObject *exception_keeper_type_5;
PyObject *exception_keeper_value_5;
PyTracebackObject *exception_keeper_tb_5;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_5;
PyObject *exception_keeper_type_6;
PyObject *exception_keeper_value_6;
PyTracebackObject *exception_keeper_tb_6;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_6;
PyObject *exception_preserved_type_1;
PyObject *exception_preserved_value_1;
PyTracebackObject *exception_preserved_tb_1;
PyObject *exception_preserved_type_2;
PyObject *exception_preserved_value_2;
PyTracebackObject *exception_preserved_tb_2;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
PyObject *tmp_args_element_name_7;
PyObject *tmp_args_element_name_8;
PyObject *tmp_args_element_name_9;
PyObject *tmp_args_element_name_10;
PyObject *tmp_args_element_name_11;
PyObject *tmp_args_element_name_12;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_called_name_4;
PyObject *tmp_called_name_5;
PyObject *tmp_called_name_6;
PyObject *tmp_called_name_7;
PyObject *tmp_called_name_8;
PyObject *tmp_called_name_9;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_left_2;
PyObject *tmp_compare_right_1;
PyObject *tmp_compare_right_2;
int tmp_exc_match_exception_match_1;
bool tmp_is_1;
bool tmp_result;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
PyObject *tmp_source_name_4;
PyObject *tmp_source_name_5;
PyObject *tmp_source_name_6;
PyObject *tmp_source_name_7;
PyObject *tmp_source_name_8;
PyObject *tmp_source_name_9;
PyObject *tmp_source_name_10;
PyObject *tmp_source_name_11;
PyObject *tmp_tuple_element_1;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_7f1d67953d1486ada0ef5501b0312cae = NULL;
struct Nuitka_FrameObject *frame_7f1d67953d1486ada0ef5501b0312cae;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_7f1d67953d1486ada0ef5501b0312cae, codeobj_7f1d67953d1486ada0ef5501b0312cae, module_django$utils$_os, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_7f1d67953d1486ada0ef5501b0312cae = cache_frame_7f1d67953d1486ada0ef5501b0312cae;
// Push the new frame as the currently active one.
pushFrameStack( frame_7f1d67953d1486ada0ef5501b0312cae );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_7f1d67953d1486ada0ef5501b0312cae ) == 2 ); // Frame stack
// Framed code:
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_tempfile );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_tempfile );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "tempfile" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 88;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 88;
tmp_assign_source_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_mkdtemp );
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 88;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_tmpdir == NULL );
var_tmpdir = tmp_assign_source_1;
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_source_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_path );
if ( tmp_source_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_join );
Py_DECREF( tmp_source_name_1 );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = var_tmpdir;
if ( tmp_args_element_name_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_2 = const_str_plain_original;
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 89;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_assign_source_2 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_assign_source_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_original_path == NULL );
var_original_path = tmp_assign_source_2;
tmp_source_name_4 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_4 == NULL ))
{
tmp_source_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_4 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_source_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_path );
if ( tmp_source_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_join );
Py_DECREF( tmp_source_name_3 );
if ( tmp_called_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_3 = var_tmpdir;
if ( tmp_args_element_name_3 == NULL )
{
Py_DECREF( tmp_called_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_4 = const_str_plain_symlink;
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 90;
{
PyObject *call_args[] = { tmp_args_element_name_3, tmp_args_element_name_4 };
tmp_assign_source_3 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args );
}
Py_DECREF( tmp_called_name_2 );
if ( tmp_assign_source_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_symlink_path == NULL );
var_symlink_path = tmp_assign_source_3;
tmp_source_name_5 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_5 == NULL ))
{
tmp_source_name_5 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_5 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_makedirs );
if ( tmp_called_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = var_original_path;
if ( tmp_args_element_name_5 == NULL )
{
Py_DECREF( tmp_called_name_3 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 91;
{
PyObject *call_args[] = { tmp_args_element_name_5 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args );
}
Py_DECREF( tmp_called_name_3 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_assign_source_4 = Py_True;
assert( tmp_try_except_1__unhandled_indicator == NULL );
Py_INCREF( tmp_assign_source_4 );
tmp_try_except_1__unhandled_indicator = tmp_assign_source_4;
// Tried code:
// Tried code:
// Tried code:
tmp_source_name_6 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_6 == NULL ))
{
tmp_source_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_6 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_symlink );
if ( tmp_called_name_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
tmp_args_element_name_6 = var_original_path;
if ( tmp_args_element_name_6 == NULL )
{
Py_DECREF( tmp_called_name_4 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
tmp_args_element_name_7 = var_symlink_path;
if ( tmp_args_element_name_7 == NULL )
{
Py_DECREF( tmp_called_name_4 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "symlink_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 93;
{
PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_4, call_args );
}
Py_DECREF( tmp_called_name_4 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
Py_DECREF( tmp_unused );
tmp_assign_source_5 = Py_True;
assert( var_supported == NULL );
Py_INCREF( tmp_assign_source_5 );
var_supported = tmp_assign_source_5;
goto try_end_1;
// Exception handler code:
try_except_handler_4:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
tmp_assign_source_6 = Py_False;
{
PyObject *old = tmp_try_except_1__unhandled_indicator;
tmp_try_except_1__unhandled_indicator = tmp_assign_source_6;
Py_INCREF( tmp_try_except_1__unhandled_indicator );
Py_XDECREF( old );
}
// Preserve existing published exception.
exception_preserved_type_1 = PyThreadState_GET()->exc_type;
Py_XINCREF( exception_preserved_type_1 );
exception_preserved_value_1 = PyThreadState_GET()->exc_value;
Py_XINCREF( exception_preserved_value_1 );
exception_preserved_tb_1 = (PyTracebackObject *)PyThreadState_GET()->exc_traceback;
Py_XINCREF( exception_preserved_tb_1 );
if ( exception_keeper_tb_1 == NULL )
{
exception_keeper_tb_1 = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_1 );
}
else if ( exception_keeper_lineno_1 != 0 )
{
exception_keeper_tb_1 = ADD_TRACEBACK( exception_keeper_tb_1, frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_1 );
}
NORMALIZE_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 );
PyException_SetTraceback( exception_keeper_value_1, (PyObject *)exception_keeper_tb_1 );
PUBLISH_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 );
// Tried code:
tmp_compare_left_1 = PyThreadState_GET()->exc_type;
tmp_compare_right_1 = PyTuple_New( 3 );
tmp_tuple_element_1 = PyExc_OSError;
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_compare_right_1, 0, tmp_tuple_element_1 );
tmp_tuple_element_1 = PyExc_NotImplementedError;
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_compare_right_1, 1, tmp_tuple_element_1 );
tmp_tuple_element_1 = PyExc_AttributeError;
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_compare_right_1, 2, tmp_tuple_element_1 );
tmp_exc_match_exception_match_1 = EXCEPTION_MATCH_BOOL( tmp_compare_left_1, tmp_compare_right_1 );
if ( tmp_exc_match_exception_match_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compare_right_1 );
exception_lineno = 95;
type_description_1 = "oooo";
goto try_except_handler_5;
}
Py_DECREF( tmp_compare_right_1 );
if ( tmp_exc_match_exception_match_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_assign_source_7 = Py_False;
assert( var_supported == NULL );
Py_INCREF( tmp_assign_source_7 );
var_supported = tmp_assign_source_7;
goto branch_end_1;
branch_no_1:;
tmp_result = RERAISE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
if (unlikely( tmp_result == false ))
{
exception_lineno = 92;
}
if (exception_tb && exception_tb->tb_frame == &frame_7f1d67953d1486ada0ef5501b0312cae->m_frame) frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = exception_tb->tb_lineno;
type_description_1 = "oooo";
goto try_except_handler_5;
branch_end_1:;
goto try_end_2;
// Exception handler code:
try_except_handler_5:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 );
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto try_except_handler_3;
// End of try:
try_end_2:;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 );
goto try_end_1;
// exception handler codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
// End of try:
try_end_1:;
tmp_compare_left_2 = tmp_try_except_1__unhandled_indicator;
CHECK_OBJECT( tmp_compare_left_2 );
tmp_compare_right_2 = Py_True;
tmp_is_1 = ( tmp_compare_left_2 == tmp_compare_right_2 );
if ( tmp_is_1 )
{
goto branch_yes_2;
}
else
{
goto branch_no_2;
}
branch_yes_2:;
tmp_source_name_7 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_7 == NULL ))
{
tmp_source_name_7 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_7 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_remove );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
tmp_args_element_name_8 = var_symlink_path;
if ( tmp_args_element_name_8 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "symlink_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 98;
{
PyObject *call_args[] = { tmp_args_element_name_8 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_5, call_args );
}
Py_DECREF( tmp_called_name_5 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
Py_DECREF( tmp_unused );
branch_no_2:;
goto try_end_3;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_try_except_1__unhandled_indicator );
tmp_try_except_1__unhandled_indicator = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto try_except_handler_2;
// End of try:
try_end_3:;
goto try_end_4;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_4 = exception_type;
exception_keeper_value_4 = exception_value;
exception_keeper_tb_4 = exception_tb;
exception_keeper_lineno_4 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Preserve existing published exception.
exception_preserved_type_2 = PyThreadState_GET()->exc_type;
Py_XINCREF( exception_preserved_type_2 );
exception_preserved_value_2 = PyThreadState_GET()->exc_value;
Py_XINCREF( exception_preserved_value_2 );
exception_preserved_tb_2 = (PyTracebackObject *)PyThreadState_GET()->exc_traceback;
Py_XINCREF( exception_preserved_tb_2 );
if ( exception_keeper_tb_4 == NULL )
{
exception_keeper_tb_4 = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_4 );
}
else if ( exception_keeper_lineno_4 != 0 )
{
exception_keeper_tb_4 = ADD_TRACEBACK( exception_keeper_tb_4, frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_4 );
}
NORMALIZE_EXCEPTION( &exception_keeper_type_4, &exception_keeper_value_4, &exception_keeper_tb_4 );
PyException_SetTraceback( exception_keeper_value_4, (PyObject *)exception_keeper_tb_4 );
PUBLISH_EXCEPTION( &exception_keeper_type_4, &exception_keeper_value_4, &exception_keeper_tb_4 );
// Tried code:
tmp_source_name_8 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_8 == NULL ))
{
tmp_source_name_8 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_8 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_called_name_6 = LOOKUP_ATTRIBUTE( tmp_source_name_8, const_str_plain_rmdir );
if ( tmp_called_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_args_element_name_9 = var_original_path;
if ( tmp_args_element_name_9 == NULL )
{
Py_DECREF( tmp_called_name_6 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 100;
{
PyObject *call_args[] = { tmp_args_element_name_9 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args );
}
Py_DECREF( tmp_called_name_6 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
Py_DECREF( tmp_unused );
tmp_source_name_9 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_9 == NULL ))
{
tmp_source_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_9 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_called_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_9, const_str_plain_rmdir );
if ( tmp_called_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_args_element_name_10 = var_tmpdir;
if ( tmp_args_element_name_10 == NULL )
{
Py_DECREF( tmp_called_name_7 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 101;
{
PyObject *call_args[] = { tmp_args_element_name_10 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_called_name_7 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
Py_DECREF( tmp_unused );
tmp_return_value = var_supported;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "supported" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 102;
type_description_1 = "oooo";
goto try_except_handler_6;
}
Py_INCREF( tmp_return_value );
goto try_return_handler_6;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
// Return handler code:
try_return_handler_6:;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_2, exception_preserved_value_2, exception_preserved_tb_2 );
goto frame_return_exit_1;
// Exception handler code:
try_except_handler_6:;
exception_keeper_type_5 = exception_type;
exception_keeper_value_5 = exception_value;
exception_keeper_tb_5 = exception_tb;
exception_keeper_lineno_5 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_2, exception_preserved_value_2, exception_preserved_tb_2 );
// Re-raise.
exception_type = exception_keeper_type_5;
exception_value = exception_keeper_value_5;
exception_tb = exception_keeper_tb_5;
exception_lineno = exception_keeper_lineno_5;
goto frame_exception_exit_1;
// End of try:
// End of try:
try_end_4:;
Py_XDECREF( tmp_try_except_1__unhandled_indicator );
tmp_try_except_1__unhandled_indicator = NULL;
tmp_source_name_10 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_10 == NULL ))
{
tmp_source_name_10 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_10 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_10, const_str_plain_rmdir );
if ( tmp_called_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_11 = var_original_path;
if ( tmp_args_element_name_11 == NULL )
{
Py_DECREF( tmp_called_name_8 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 100;
{
PyObject *call_args[] = { tmp_args_element_name_11 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_8, call_args );
}
Py_DECREF( tmp_called_name_8 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_11 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_11 == NULL ))
{
tmp_source_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_11 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_11, const_str_plain_rmdir );
if ( tmp_called_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_12 = var_tmpdir;
if ( tmp_args_element_name_12 == NULL )
{
Py_DECREF( tmp_called_name_9 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 101;
{
PyObject *call_args[] = { tmp_args_element_name_12 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_9, call_args );
}
Py_DECREF( tmp_called_name_9 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_return_value = var_supported;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "supported" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 102;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 1
RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_7f1d67953d1486ada0ef5501b0312cae->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_7f1d67953d1486ada0ef5501b0312cae, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_7f1d67953d1486ada0ef5501b0312cae,
type_description_1,
var_tmpdir,
var_original_path,
var_symlink_path,
var_supported
);
// Release cached frame.
if ( frame_7f1d67953d1486ada0ef5501b0312cae == cache_frame_7f1d67953d1486ada0ef5501b0312cae )
{
Py_DECREF( frame_7f1d67953d1486ada0ef5501b0312cae );
}
cache_frame_7f1d67953d1486ada0ef5501b0312cae = NULL;
assertFrameObject( frame_7f1d67953d1486ada0ef5501b0312cae );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( var_tmpdir );
var_tmpdir = NULL;
Py_XDECREF( var_original_path );
var_original_path = NULL;
Py_XDECREF( var_symlink_path );
var_symlink_path = NULL;
Py_XDECREF( var_supported );
var_supported = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_6 = exception_type;
exception_keeper_value_6 = exception_value;
exception_keeper_tb_6 = exception_tb;
exception_keeper_lineno_6 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( var_tmpdir );
var_tmpdir = NULL;
Py_XDECREF( var_original_path );
var_original_path = NULL;
Py_XDECREF( var_symlink_path );
var_symlink_path = NULL;
Py_XDECREF( var_supported );
var_supported = NULL;
// Re-raise.
exception_type = exception_keeper_type_6;
exception_value = exception_keeper_value_6;
exception_tb = exception_keeper_tb_6;
exception_lineno = exception_keeper_lineno_6;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_1_abspathu,
const_str_plain_abspathu,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_8338c887cffee3f6624948b93fdb5cad,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_d92a79f74db4468ebeba34a6c933cb11,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_2_upath( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_2_upath,
const_str_plain_upath,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_786e20e096923522b138dc8044ece5a9,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_3_npath( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_3_npath,
const_str_plain_npath,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_f5eb817954879f203f472ef76832ad97,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_5c892843b642786d8376f7cd7a9ec574,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_4_safe_join,
const_str_plain_safe_join,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_519eab41ce47fa2590f6a99ccc08067a,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_5_symlinks_supported,
const_str_plain_symlinks_supported,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_7f1d67953d1486ada0ef5501b0312cae,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_b3b92bc7aa9804266ff219682e3d0112,
0
);
return (PyObject *)result;
}
#if PYTHON_VERSION >= 300
static struct PyModuleDef mdef_django$utils$_os =
{
PyModuleDef_HEAD_INIT,
"django.utils._os", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
NULL, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
#if PYTHON_VERSION >= 300
extern PyObject *metapath_based_loader;
#endif
#if PYTHON_VERSION >= 330
extern PyObject *const_str_plain___loader__;
#endif
extern void _initCompiledCellType();
extern void _initCompiledGeneratorType();
extern void _initCompiledFunctionType();
extern void _initCompiledMethodType();
extern void _initCompiledFrameType();
#if PYTHON_VERSION >= 350
extern void _initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
extern void _initCompiledAsyncgenTypes();
#endif
// The exported interface to CPython. On import of the module, this function
// gets called. It has to have an exact function name, in cases it's a shared
// library export. This is hidden behind the MOD_INIT_DECL.
MOD_INIT_DECL( django$utils$_os )
{
#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300
static bool _init_done = false;
// Modules might be imported repeatedly, which is to be ignored.
if ( _init_done )
{
return MOD_RETURN_VALUE( module_django$utils$_os );
}
else
{
_init_done = true;
}
#endif
#ifdef _NUITKA_MODULE
// In case of a stand alone extension module, need to call initialization
// the init here because that's the first and only time we are going to get
// called here.
// Initialize the constant values used.
_initBuiltinModule();
createGlobalConstants();
/* Initialize the compiled types of Nuitka. */
_initCompiledCellType();
_initCompiledGeneratorType();
_initCompiledFunctionType();
_initCompiledMethodType();
_initCompiledFrameType();
#if PYTHON_VERSION >= 350
_initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
_initCompiledAsyncgenTypes();
#endif
#if PYTHON_VERSION < 300
_initSlotCompare();
#endif
#if PYTHON_VERSION >= 270
_initSlotIternext();
#endif
patchBuiltinModule();
patchTypeComparison();
// Enable meta path based loader if not already done.
setupMetaPathBasedLoader();
#if PYTHON_VERSION >= 300
patchInspectModule();
#endif
#endif
/* The constants only used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("django.utils._os: Calling createModuleConstants().");
#endif
createModuleConstants();
/* The code objects used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("django.utils._os: Calling createModuleCodeObjects().");
#endif
createModuleCodeObjects();
// puts( "in initdjango$utils$_os" );
// Create the module object first. There are no methods initially, all are
// added dynamically in actual code only. Also no "__doc__" is initially
// set at this time, as it could not contain NUL characters this way, they
// are instead set in early module code. No "self" for modules, we have no
// use for it.
#if PYTHON_VERSION < 300
module_django$utils$_os = Py_InitModule4(
"django.utils._os", // Module Name
NULL, // No methods initially, all are added
// dynamically in actual module code only.
NULL, // No __doc__ is initially set, as it could
// not contain NUL this way, added early in
// actual code.
NULL, // No self for modules, we don't use it.
PYTHON_API_VERSION
);
#else
module_django$utils$_os = PyModule_Create( &mdef_django$utils$_os );
#endif
moduledict_django$utils$_os = MODULE_DICT( module_django$utils$_os );
CHECK_OBJECT( module_django$utils$_os );
// Seems to work for Python2.7 out of the box, but for Python3, the module
// doesn't automatically enter "sys.modules", so do it manually.
#if PYTHON_VERSION >= 300
{
int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_842dfd4744c6e20ce39943a1591eb59d, module_django$utils$_os );
assert( r != -1 );
}
#endif
// For deep importing of a module we need to have "__builtins__", so we set
// it ourselves in the same way than CPython does. Note: This must be done
// before the frame object is allocated, or else it may fail.
if ( GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL )
{
PyObject *value = (PyObject *)builtin_module;
// Check if main module, not a dict then but the module itself.
#if !defined(_NUITKA_EXE) || !0
value = PyModule_GetDict( value );
#endif
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___builtins__, value );
}
#if PYTHON_VERSION >= 330
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader );
#endif
// Temp variables if any
PyObject *tmp_import_from_1__module = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_assign_source_9;
PyObject *tmp_assign_source_10;
PyObject *tmp_assign_source_11;
PyObject *tmp_assign_source_12;
PyObject *tmp_assign_source_13;
PyObject *tmp_assign_source_14;
PyObject *tmp_assign_source_15;
PyObject *tmp_assign_source_16;
PyObject *tmp_assign_source_17;
PyObject *tmp_assign_source_18;
PyObject *tmp_assign_source_19;
PyObject *tmp_assign_source_20;
PyObject *tmp_assign_source_21;
PyObject *tmp_assign_source_22;
PyObject *tmp_assign_source_23;
PyObject *tmp_assign_source_24;
PyObject *tmp_assign_source_25;
PyObject *tmp_assign_source_26;
PyObject *tmp_assign_source_27;
PyObject *tmp_assign_source_28;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_instance_2;
PyObject *tmp_called_name_1;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_right_1;
int tmp_cond_truth_1;
int tmp_cond_truth_2;
PyObject *tmp_cond_value_1;
PyObject *tmp_cond_value_2;
PyObject *tmp_fromlist_name_1;
PyObject *tmp_fromlist_name_2;
PyObject *tmp_fromlist_name_3;
PyObject *tmp_fromlist_name_4;
PyObject *tmp_fromlist_name_5;
PyObject *tmp_fromlist_name_6;
PyObject *tmp_fromlist_name_7;
PyObject *tmp_globals_name_1;
PyObject *tmp_globals_name_2;
PyObject *tmp_globals_name_3;
PyObject *tmp_globals_name_4;
PyObject *tmp_globals_name_5;
PyObject *tmp_globals_name_6;
PyObject *tmp_globals_name_7;
PyObject *tmp_import_name_from_1;
PyObject *tmp_import_name_from_2;
PyObject *tmp_import_name_from_3;
PyObject *tmp_import_name_from_4;
PyObject *tmp_import_name_from_5;
PyObject *tmp_import_name_from_6;
PyObject *tmp_import_name_from_7;
PyObject *tmp_import_name_from_8;
PyObject *tmp_import_name_from_9;
PyObject *tmp_import_name_from_10;
PyObject *tmp_import_name_from_11;
PyObject *tmp_level_name_1;
PyObject *tmp_level_name_2;
PyObject *tmp_level_name_3;
PyObject *tmp_level_name_4;
PyObject *tmp_level_name_5;
PyObject *tmp_level_name_6;
PyObject *tmp_level_name_7;
PyObject *tmp_locals_name_1;
PyObject *tmp_locals_name_2;
PyObject *tmp_locals_name_3;
PyObject *tmp_locals_name_4;
PyObject *tmp_locals_name_5;
PyObject *tmp_locals_name_6;
PyObject *tmp_locals_name_7;
PyObject *tmp_name_name_1;
PyObject *tmp_name_name_2;
PyObject *tmp_name_name_3;
PyObject *tmp_name_name_4;
PyObject *tmp_name_name_5;
PyObject *tmp_name_name_6;
PyObject *tmp_name_name_7;
int tmp_or_left_truth_1;
int tmp_or_left_truth_2;
PyObject *tmp_or_left_value_1;
PyObject *tmp_or_left_value_2;
PyObject *tmp_or_right_value_1;
PyObject *tmp_or_right_value_2;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
struct Nuitka_FrameObject *frame_e3f2225c4277cee0cd5878c353c5494a;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
// Module code.
tmp_assign_source_1 = Py_None;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );
tmp_assign_source_2 = module_filename_obj;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );
tmp_assign_source_3 = metapath_based_loader;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 );
// Frame without reuse.
frame_e3f2225c4277cee0cd5878c353c5494a = MAKE_MODULE_FRAME( codeobj_e3f2225c4277cee0cd5878c353c5494a, module_django$utils$_os );
// Push the new frame as the currently active one, and we should be exclusively
// owning it.
pushFrameStack( frame_e3f2225c4277cee0cd5878c353c5494a );
assert( Py_REFCNT( frame_e3f2225c4277cee0cd5878c353c5494a ) == 2 );
// Framed code:
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1;
{
PyObject *module = PyImport_ImportModule("importlib._bootstrap");
if (likely( module != NULL ))
{
tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec );
}
else
{
tmp_called_name_1 = NULL;
}
}
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = const_str_digest_842dfd4744c6e20ce39943a1591eb59d;
tmp_args_element_name_2 = metapath_based_loader;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 );
tmp_assign_source_5 = Py_None;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 );
tmp_assign_source_6 = const_str_digest_467c9722f19d9d40d148689532cdc0b1;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 );
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1;
tmp_import_name_from_1 = PyImport_ImportModule("__future__");
assert( tmp_import_name_from_1 != NULL );
tmp_assign_source_7 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_unicode_literals );
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_7 );
tmp_name_name_1 = const_str_plain_os;
tmp_globals_name_1 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_1 = Py_None;
tmp_fromlist_name_1 = Py_None;
tmp_level_name_1 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 3;
tmp_assign_source_8 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 );
if ( tmp_assign_source_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 3;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os, tmp_assign_source_8 );
tmp_name_name_2 = const_str_plain_sys;
tmp_globals_name_2 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_2 = Py_None;
tmp_fromlist_name_2 = Py_None;
tmp_level_name_2 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 4;
tmp_assign_source_9 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 );
assert( tmp_assign_source_9 != NULL );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys, tmp_assign_source_9 );
tmp_name_name_3 = const_str_plain_tempfile;
tmp_globals_name_3 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_3 = Py_None;
tmp_fromlist_name_3 = Py_None;
tmp_level_name_3 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 5;
tmp_assign_source_10 = IMPORT_MODULE5( tmp_name_name_3, tmp_globals_name_3, tmp_locals_name_3, tmp_fromlist_name_3, tmp_level_name_3 );
if ( tmp_assign_source_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 5;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_tempfile, tmp_assign_source_10 );
tmp_name_name_4 = const_str_digest_e399ba4554180f37de594a6743234f17;
tmp_globals_name_4 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_4 = Py_None;
tmp_fromlist_name_4 = const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple;
tmp_level_name_4 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 6;
tmp_assign_source_11 = IMPORT_MODULE5( tmp_name_name_4, tmp_globals_name_4, tmp_locals_name_4, tmp_fromlist_name_4, tmp_level_name_4 );
if ( tmp_assign_source_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto frame_exception_exit_1;
}
assert( tmp_import_from_1__module == NULL );
tmp_import_from_1__module = tmp_assign_source_11;
// Tried code:
tmp_import_name_from_2 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_2 );
tmp_assign_source_12 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_abspath );
if ( tmp_assign_source_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspath, tmp_assign_source_12 );
tmp_import_name_from_3 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_3 );
tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_dirname );
if ( tmp_assign_source_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_dirname, tmp_assign_source_13 );
tmp_import_name_from_4 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_4 );
tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_isabs );
if ( tmp_assign_source_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_isabs, tmp_assign_source_14 );
tmp_import_name_from_5 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_5 );
tmp_assign_source_15 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_join );
if ( tmp_assign_source_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join, tmp_assign_source_15 );
tmp_import_name_from_6 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_6 );
tmp_assign_source_16 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_normcase );
if ( tmp_assign_source_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase, tmp_assign_source_16 );
tmp_import_name_from_7 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_7 );
tmp_assign_source_17 = IMPORT_NAME( tmp_import_name_from_7, const_str_plain_normpath );
if ( tmp_assign_source_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normpath, tmp_assign_source_17 );
tmp_import_name_from_8 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_8 );
tmp_assign_source_18 = IMPORT_NAME( tmp_import_name_from_8, const_str_plain_sep );
if ( tmp_assign_source_18 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sep, tmp_assign_source_18 );
goto try_end_1;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
tmp_name_name_5 = const_str_digest_dfb6e1abbed3113ee07234fdc458a320;
tmp_globals_name_5 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_5 = Py_None;
tmp_fromlist_name_5 = const_tuple_str_plain_SuspiciousFileOperation_tuple;
tmp_level_name_5 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 8;
tmp_import_name_from_9 = IMPORT_MODULE5( tmp_name_name_5, tmp_globals_name_5, tmp_locals_name_5, tmp_fromlist_name_5, tmp_level_name_5 );
if ( tmp_import_name_from_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 8;
goto frame_exception_exit_1;
}
tmp_assign_source_19 = IMPORT_NAME( tmp_import_name_from_9, const_str_plain_SuspiciousFileOperation );
Py_DECREF( tmp_import_name_from_9 );
if ( tmp_assign_source_19 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 8;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation, tmp_assign_source_19 );
tmp_name_name_6 = const_str_digest_467c9722f19d9d40d148689532cdc0b1;
tmp_globals_name_6 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_6 = Py_None;
tmp_fromlist_name_6 = const_tuple_str_plain_six_tuple;
tmp_level_name_6 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 9;
tmp_import_name_from_10 = IMPORT_MODULE5( tmp_name_name_6, tmp_globals_name_6, tmp_locals_name_6, tmp_fromlist_name_6, tmp_level_name_6 );
if ( tmp_import_name_from_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto frame_exception_exit_1;
}
tmp_assign_source_20 = IMPORT_NAME( tmp_import_name_from_10, const_str_plain_six );
Py_DECREF( tmp_import_name_from_10 );
if ( tmp_assign_source_20 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six, tmp_assign_source_20 );
tmp_name_name_7 = const_str_digest_e3393b2e61653c3df2c7d436c253bbee;
tmp_globals_name_7 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_7 = Py_None;
tmp_fromlist_name_7 = const_tuple_str_plain_force_text_tuple;
tmp_level_name_7 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 10;
tmp_import_name_from_11 = IMPORT_MODULE5( tmp_name_name_7, tmp_globals_name_7, tmp_locals_name_7, tmp_fromlist_name_7, tmp_level_name_7 );
if ( tmp_import_name_from_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 10;
goto frame_exception_exit_1;
}
tmp_assign_source_21 = IMPORT_NAME( tmp_import_name_from_11, const_str_plain_force_text );
Py_DECREF( tmp_import_name_from_11 );
if ( tmp_assign_source_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 10;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text, tmp_assign_source_21 );
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 12;
goto frame_exception_exit_1;
}
tmp_cond_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 );
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 12;
goto frame_exception_exit_1;
}
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 12;
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sys );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sys" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 13;
goto frame_exception_exit_1;
}
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 13;
tmp_or_left_value_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_getfilesystemencoding );
if ( tmp_or_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
tmp_or_left_truth_1 = CHECK_IF_TRUE( tmp_or_left_value_1 );
if ( tmp_or_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_or_left_value_1 );
exception_lineno = 13;
goto frame_exception_exit_1;
}
if ( tmp_or_left_truth_1 == 1 )
{
goto or_left_1;
}
else
{
goto or_right_1;
}
or_right_1:;
Py_DECREF( tmp_or_left_value_1 );
tmp_called_instance_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys );
if (unlikely( tmp_called_instance_2 == NULL ))
{
tmp_called_instance_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sys );
}
if ( tmp_called_instance_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sys" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 13;
goto frame_exception_exit_1;
}
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 13;
tmp_or_right_value_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_2, const_str_plain_getdefaultencoding );
if ( tmp_or_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
tmp_assign_source_22 = tmp_or_right_value_1;
goto or_end_1;
or_left_1:;
tmp_assign_source_22 = tmp_or_left_value_1;
or_end_1:;
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding, tmp_assign_source_22 );
branch_no_1:;
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_or_left_value_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_PY3 );
if ( tmp_or_left_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_or_left_truth_2 = CHECK_IF_TRUE( tmp_or_left_value_2 );
if ( tmp_or_left_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_or_left_value_2 );
exception_lineno = 21;
goto frame_exception_exit_1;
}
if ( tmp_or_left_truth_2 == 1 )
{
goto or_left_2;
}
else
{
goto or_right_2;
}
or_right_2:;
Py_DECREF( tmp_or_left_value_2 );
tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_3 == NULL ))
{
tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_compexpr_left_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_name );
if ( tmp_compexpr_left_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_compexpr_right_1 = const_str_plain_nt;
tmp_or_right_value_2 = RICH_COMPARE_EQ_NORECURSE( tmp_compexpr_left_1, tmp_compexpr_right_1 );
Py_DECREF( tmp_compexpr_left_1 );
if ( tmp_or_right_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_cond_value_2 = tmp_or_right_value_2;
goto or_end_2;
or_left_2:;
tmp_cond_value_2 = tmp_or_left_value_2;
or_end_2:;
tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_2 );
exception_lineno = 21;
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == 1 )
{
goto branch_yes_2;
}
else
{
goto branch_no_2;
}
branch_yes_2:;
tmp_assign_source_23 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspath );
if (unlikely( tmp_assign_source_23 == NULL ))
{
tmp_assign_source_23 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspath );
}
if ( tmp_assign_source_23 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspath" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 22;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu, tmp_assign_source_23 );
goto branch_end_2;
branch_no_2:;
tmp_assign_source_24 = MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu, tmp_assign_source_24 );
branch_end_2:;
// Restore frame exception if necessary.
#if 0
RESTORE_FRAME_EXCEPTION( frame_e3f2225c4277cee0cd5878c353c5494a );
#endif
popFrameStack();
assertFrameObject( frame_e3f2225c4277cee0cd5878c353c5494a );
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_e3f2225c4277cee0cd5878c353c5494a );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_e3f2225c4277cee0cd5878c353c5494a, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_e3f2225c4277cee0cd5878c353c5494a->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_e3f2225c4277cee0cd5878c353c5494a, exception_lineno );
}
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto module_exception_exit;
frame_no_exception_1:;
tmp_assign_source_25 = MAKE_FUNCTION_django$utils$_os$$$function_2_upath( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_upath, tmp_assign_source_25 );
tmp_assign_source_26 = MAKE_FUNCTION_django$utils$_os$$$function_3_npath( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_npath, tmp_assign_source_26 );
tmp_assign_source_27 = MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_safe_join, tmp_assign_source_27 );
tmp_assign_source_28 = MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_symlinks_supported, tmp_assign_source_28 );
return MOD_RETURN_VALUE( module_django$utils$_os );
module_exception_exit:
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return MOD_RETURN_VALUE( NULL );
}
| 33.741102
| 255
| 0.714514
|
Pckool
|
f149c82d43c60e6684a451990867bad9a9cb791c
| 866
|
cpp
|
C++
|
InAirState.cpp
|
thomasvt/stuck
|
eb590f4218d8eb00199518c8f0c1d3225216d412
|
[
"MIT"
] | 1
|
2022-03-13T09:02:50.000Z
|
2022-03-13T09:02:50.000Z
|
InAirState.cpp
|
thomasvt/stuck
|
eb590f4218d8eb00199518c8f0c1d3225216d412
|
[
"MIT"
] | 1
|
2022-03-13T09:04:33.000Z
|
2022-03-13T18:56:32.000Z
|
InAirState.cpp
|
thomasvt/stuck
|
eb590f4218d8eb00199518c8f0c1d3225216d412
|
[
"MIT"
] | null | null | null |
#include <InAirState.h>
#include <Hero.h>
#include "HeroAnimations.h"
namespace actors
{
namespace hero
{
void InAirState::update(Hero& hero)
{
if (hero.rigid_body.is_on_floor())
hero.fsm_.change_state(HeroFsm::hero_state::on_floor);
if (hero.rigid_body.is_on_ladder() && !hero.rigid_body.is_going_up())
hero.fsm_.change_state(HeroFsm::hero_state::on_ladder);
const auto throttle8_x = hero.get_throttle8_x();
hero.rigid_body.set_velocity8_x(throttle8_x); // no inertia, classic feel
// bit dirty. can only do this because these animations are only 1 frame.
hero.animation_player_.set_animation(hero.rigid_body.is_going_up() ? &animations::hero::jump : &animations::hero::fall);
}
void InAirState::on_enter(Hero& hero)
{
hero.rigid_body.is_gravity_enabled = true;
}
void InAirState::on_exit(Hero& hero)
{
}
}
}
| 26.242424
| 123
| 0.720554
|
thomasvt
|
f14b22aad4767d594ef33df2293217cfc40f5233
| 4,355
|
cc
|
C++
|
video.cc
|
SolraBizna/teg
|
05a307f2f3b359f3462cba23e15dbda8d6af66fc
|
[
"Zlib"
] | null | null | null |
video.cc
|
SolraBizna/teg
|
05a307f2f3b359f3462cba23e15dbda8d6af66fc
|
[
"Zlib"
] | null | null | null |
video.cc
|
SolraBizna/teg
|
05a307f2f3b359f3462cba23e15dbda8d6af66fc
|
[
"Zlib"
] | null | null | null |
#include "video.hh"
#include "config.hh"
#include "xgl.hh"
using namespace Video;
const uint32_t Video::uninitialized_context_cookie = 0;
uint32_t Video::opengl_context_cookie = uninitialized_context_cookie;
#ifndef DEFAULT_WINDOWED_WIDTH
#define DEFAULT_WINDOWED_WIDTH 640
#endif
#ifndef DEFAULT_WINDOWED_HEIGHT
#define DEFAULT_WINDOWED_HEIGHT 480
#endif
int32_t Video::fullscreen_width = 0, Video::fullscreen_height = 0;
int32_t Video::windowed_width = DEFAULT_WINDOWED_WIDTH,
Video::windowed_height = DEFAULT_WINDOWED_HEIGHT;
bool Video::fullscreen_mode = true;
bool Video::vsync = false;
static const char* video_config_file = "Video Configuration.utxt";
static const Config::Element video_config_elements[] = {
Config::Element("fullscreen_width", fullscreen_width),
Config::Element("fullscreen_height", fullscreen_height),
Config::Element("windowed_width", windowed_width),
Config::Element("windowed_height", windowed_height),
Config::Element("fullscreen_mode", fullscreen_mode),
Config::Element("vsync", vsync),
};
static SDL_Window* window = NULL;
static SDL_GLContext glcontext = NULL;
static bool inited = false;
static bool window_visible = true, window_minimized = false;
void Video::Kill() {
if(inited) {
SDL_Quit();
inited = false;
}
}
void Video::Init() {
if(!inited) {
if(SDL_Init(SDL_INIT_VIDEO))
die("Couldn't initialize SDL!");
inited = true;
}
if(glcontext) SDL_GL_DeleteContext(glcontext);
if(window) SDL_DestroyWindow(window);
int target_w, target_h;
Uint32 flags = SDL_WINDOW_OPENGL;
if(fullscreen_mode) {
target_w = fullscreen_width;
target_h = fullscreen_height;
if(target_w == 0 || target_h == 0)
flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
else
flags |= SDL_WINDOW_FULLSCREEN;
}
else {
target_w = windowed_width;
target_h = windowed_height;
}
do {
/* sanity */
if(target_w < 320) target_w = 320;
else if(target_h < 240) target_h = 240;
window = SDL_CreateWindow(GAME_WINDOW_TITLE,
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
target_w, target_h, flags);
if(window) break;
else if(flags & SDL_WINDOW_FULLSCREEN) {
fprintf(stderr, "Fullscreen mode %i x %i failed. Trying a window.\n",
target_w, target_h);
flags &= ~(SDL_WINDOW_FULLSCREEN_DESKTOP);
target_w = windowed_width;
target_h = windowed_height;
}
else
die("Could not create a window no matter how hard we tried. The last reason SDL gave was: %s", SDL_GetError());
} while(1);
/* TODO: set minimized/visible state? */
dprintf("SDL_CreateWindow(..., %i, %i, 0x%x) succeeded.\n",
target_w, target_h, flags);
glcontext = SDL_GL_CreateContext(window);
if(!glcontext)
die("Could not create an OpenGL context. The reason SDL gave was: %s", SDL_GetError());
++opengl_context_cookie;
dprintf("OpenGL initialized. Context cookie is %i.\n",
opengl_context_cookie);
xgl::Initialize();
/* OpenGL context setup */
glPixelStorei(GL_PACK_ALIGNMENT, TEG_PIXEL_PACK);
glPixelStorei(GL_UNPACK_ALIGNMENT, TEG_PIXEL_PACK);
}
void Video::ReadConfig() {
Config::Read(video_config_file, video_config_elements, elementcount(video_config_elements));
}
void Video::WriteConfig() {
Config::Write(video_config_file, video_config_elements, elementcount(video_config_elements));
}
uint32_t Video::GetScreenWidth() {
int w, h;
SDL_GL_GetDrawableSize(window, &w, &h);
return w;
}
uint32_t Video::GetScreenHeight() {
int w, h;
SDL_GL_GetDrawableSize(window, &w, &h);
return h;
}
double Video::GetAspect() {
int w, h;
SDL_GL_GetDrawableSize(window, &w, &h);
return (double)w / h;
}
void Video::Swap() {
SDL_GL_SwapWindow(window);
}
bool Video::IsScreenActive() {
return window_visible && !window_minimized;
}
bool Video::HandleEvent(SDL_Event& evt) {
switch(evt.type) {
case SDL_WINDOWEVENT:
switch(evt.window.event) {
case SDL_WINDOWEVENT_SHOWN:
window_visible = true;
break;
case SDL_WINDOWEVENT_HIDDEN:
window_visible = false;
break;
case SDL_WINDOWEVENT_MINIMIZED:
window_minimized = true;
break;
case SDL_WINDOWEVENT_RESTORED:
window_minimized = false;
break;
}
return true;
}
return false;
}
| 27.738854
| 117
| 0.702181
|
SolraBizna
|
f14c2349718a37f8d01d88242163e8662d181f54
| 14,692
|
cpp
|
C++
|
OgreMain/src/OgreASTCCodec.cpp
|
resttime/ogre-next
|
7435e60bd6df422d2fb4c742a493c3f37ef9a7a9
|
[
"MIT"
] | 701
|
2019-09-08T15:56:41.000Z
|
2022-03-31T05:51:26.000Z
|
OgreMain/src/OgreASTCCodec.cpp
|
resttime/ogre-next
|
7435e60bd6df422d2fb4c742a493c3f37ef9a7a9
|
[
"MIT"
] | 204
|
2019-09-01T23:02:32.000Z
|
2022-03-28T14:58:39.000Z
|
OgreMain/src/OgreASTCCodec.cpp
|
resttime/ogre-next
|
7435e60bd6df422d2fb4c742a493c3f37ef9a7a9
|
[
"MIT"
] | 188
|
2019-09-05T05:14:46.000Z
|
2022-03-22T21:51:39.000Z
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreASTCCodec.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
namespace Ogre {
const uint32 ASTC_MAGIC = 0x5CA1AB13;
typedef struct
{
uint8 magic[4];
uint8 blockdim_x;
uint8 blockdim_y;
uint8 blockdim_z;
uint8 xsize[3]; // x-size = xsize[0] + xsize[1] + xsize[2]
uint8 ysize[3]; // x-size, y-size and z-size are given in texels;
uint8 zsize[3]; // block count is inferred
} ASTCHeader;
float ASTCCodec::getBitrateForPixelFormat(PixelFormatGpu fmt)
{
switch (fmt)
{
case PFG_ASTC_RGBA_UNORM_4X4_LDR:
return 8.00;
case PFG_ASTC_RGBA_UNORM_5X4_LDR:
return 6.40;
case PFG_ASTC_RGBA_UNORM_5X5_LDR:
return 5.12;
case PFG_ASTC_RGBA_UNORM_6X5_LDR:
return 4.27;
case PFG_ASTC_RGBA_UNORM_6X6_LDR:
return 3.56;
case PFG_ASTC_RGBA_UNORM_8X5_LDR:
return 3.20;
case PFG_ASTC_RGBA_UNORM_8X6_LDR:
return 2.67;
case PFG_ASTC_RGBA_UNORM_8X8_LDR:
return 2.00;
case PFG_ASTC_RGBA_UNORM_10X5_LDR:
return 2.56;
case PFG_ASTC_RGBA_UNORM_10X6_LDR:
return 2.13;
case PFG_ASTC_RGBA_UNORM_10X8_LDR:
return 1.60;
case PFG_ASTC_RGBA_UNORM_10X10_LDR:
return 1.28;
case PFG_ASTC_RGBA_UNORM_12X10_LDR:
return 1.07;
case PFG_ASTC_RGBA_UNORM_12X12_LDR:
return 0.89;
default:
return 0;
}
}
// Utility function to determine 2D block dimensions from a target bitrate. Used for 3D textures.
// Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec
void ASTCCodec::getClosestBlockDim2d(float targetBitrate, int *x, int *y) const
{
int blockdims[6] = { 4, 5, 6, 8, 10, 12 };
float best_error = 1000;
float aspect_of_best = 1;
int i, j;
// Y dimension
for (i = 0; i < 6; i++)
{
// X dimension
for (j = i; j < 6; j++)
{
// NxN MxN 8x5 10x5 10x6
int is_legal = (j==i) || (j==i+1) || (j==3 && i==1) || (j==4 && i==1) || (j==4 && i==2);
if(is_legal)
{
float bitrate = 128.0f / (blockdims[i] * blockdims[j]);
float bitrate_error = fabs(bitrate - targetBitrate);
float aspect = (float)blockdims[j] / blockdims[i];
if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best))
{
*x = blockdims[j];
*y = blockdims[i];
best_error = bitrate_error;
aspect_of_best = aspect;
}
}
}
}
}
// Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec
void ASTCCodec::getClosestBlockDim3d(float targetBitrate, int *x, int *y, int *z)
{
int blockdims[4] = { 3, 4, 5, 6 };
float best_error = 1000;
float aspect_of_best = 1;
int i, j, k;
for (i = 0; i < 4; i++) // Z
{
for (j = i; j < 4; j++) // Y
{
for (k = j; k < 4; k++) // X
{
// NxNxN MxNxN MxMxN
int is_legal = ((k==j)&&(j==i)) || ((k==j+1)&&(j==i)) || ((k==j)&&(j==i+1));
if(is_legal)
{
float bitrate = 128.0f / (blockdims[i] * blockdims[j] * blockdims[k]);
float bitrate_error = fabs(bitrate - targetBitrate);
float aspect = (float)blockdims[k] / blockdims[j] + (float)blockdims[j] / blockdims[i] + (float)blockdims[k] / blockdims[i];
if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best))
{
*x = blockdims[k];
*y = blockdims[j];
*z = blockdims[i];
best_error = bitrate_error;
aspect_of_best = aspect;
}
}
}
}
}
}
size_t ASTCCodec::getMemorySize( uint32 width, uint32 height, uint32 depth,
int32 xdim, int32 ydim, PixelFormatGpu fmt )
{
float bitrate = getBitrateForPixelFormat(fmt);
int32 zdim = 1;
if(depth > 1)
{
getClosestBlockDim3d(bitrate, &xdim, &ydim, &zdim);
}
int xblocks = (width + xdim - 1) / xdim;
int yblocks = (height + ydim - 1) / ydim;
int zblocks = (depth + zdim - 1) / zdim;
return xblocks * yblocks * zblocks * 16;
}
//---------------------------------------------------------------------
ASTCCodec* ASTCCodec::msInstance = 0;
//---------------------------------------------------------------------
void ASTCCodec::startup()
{
if (!msInstance)
{
msInstance = OGRE_NEW ASTCCodec();
Codec::registerCodec(msInstance);
}
LogManager::getSingleton().logMessage(LML_NORMAL,
"ASTC codec registering");
}
//---------------------------------------------------------------------
void ASTCCodec::shutdown()
{
if(msInstance)
{
Codec::unregisterCodec(msInstance);
OGRE_DELETE msInstance;
msInstance = 0;
}
}
//---------------------------------------------------------------------
ASTCCodec::ASTCCodec():
mType("astc")
{
}
//---------------------------------------------------------------------
DataStreamPtr ASTCCodec::encode(MemoryDataStreamPtr& input, Codec::CodecDataPtr& pData) const
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"ASTC encoding not supported",
"ASTCCodec::encode" ) ;
}
//---------------------------------------------------------------------
void ASTCCodec::encodeToFile(MemoryDataStreamPtr& input,
const String& outFileName, Codec::CodecDataPtr& pData) const
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"ASTC encoding not supported",
"ASTCCodec::encodeToFile" ) ;
}
//---------------------------------------------------------------------
Codec::DecodeResult ASTCCodec::decode(DataStreamPtr& stream) const
{
ASTCHeader header;
// Read the ASTC header
stream->read(&header, sizeof(ASTCHeader));
if( memcmp( &ASTC_MAGIC, &header.magic, sizeof(uint32) ) != 0 )
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This is not a valid ASTC file!", "ASTCCodec::decode");
}
int xdim = header.blockdim_x;
int ydim = header.blockdim_y;
int zdim = header.blockdim_z;
int xsize = header.xsize[0] + 256 * header.xsize[1] + 65536 * header.xsize[2];
int ysize = header.ysize[0] + 256 * header.ysize[1] + 65536 * header.ysize[2];
int zsize = header.zsize[0] + 256 * header.zsize[1] + 65536 * header.zsize[2];
ImageData2 *imgData = OGRE_NEW ImageData2();
imgData->box.width = xsize;
imgData->box.height = ysize;
imgData->box.depth = zsize;
imgData->box.numSlices = 1u; //Always one face, cubemaps are not currently supported
imgData->numMipmaps = 1u; // Always 1 mip level per file (ASTC file restriction)
if( zsize <= 1 )
imgData->textureType = TextureTypes::Type2D;
else
imgData->textureType = TextureTypes::Type3D;
// For 3D we calculate the bitrate then find the nearest 2D block size.
if(zdim > 1)
{
float bitrate = 128.0f / (xdim * ydim * zdim);
getClosestBlockDim2d(bitrate, &xdim, &ydim);
}
if(xdim == 4)
{
imgData->format = PFG_ASTC_RGBA_UNORM_4X4_LDR;
}
else if(xdim == 5)
{
if(ydim == 4)
imgData->format = PFG_ASTC_RGBA_UNORM_5X4_LDR;
else if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_5X5_LDR;
}
else if(xdim == 6)
{
if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_6X5_LDR;
else if(ydim == 6)
imgData->format = PFG_ASTC_RGBA_UNORM_6X6_LDR;
}
else if(xdim == 8)
{
if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_8X5_LDR;
else if(ydim == 6)
imgData->format = PFG_ASTC_RGBA_UNORM_8X6_LDR;
else if(ydim == 8)
imgData->format = PFG_ASTC_RGBA_UNORM_8X8_LDR;
}
else if(xdim == 10)
{
if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_10X5_LDR;
else if(ydim == 6)
imgData->format = PFG_ASTC_RGBA_UNORM_10X6_LDR;
else if(ydim == 8)
imgData->format = PFG_ASTC_RGBA_UNORM_10X8_LDR;
else if(ydim == 10)
imgData->format = PFG_ASTC_RGBA_UNORM_10X10_LDR;
}
else if(xdim == 12)
{
if(ydim == 10)
imgData->format = PFG_ASTC_RGBA_UNORM_12X10_LDR;
else if(ydim == 12)
imgData->format = PFG_ASTC_RGBA_UNORM_12X12_LDR;
}
const uint32 rowAlignment = 4u;
// imgData->box.bytesPerPixel = PixelFormatGpuUtils::getBytesPerPixel( imgData->format );
imgData->box.setCompressedPixelFormat( imgData->format );
imgData->box.bytesPerRow = PixelFormatGpuUtils::getSizeBytes( imgData->box.width,
1u, 1u, 1u,
imgData->format,
rowAlignment );
imgData->box.bytesPerImage = PixelFormatGpuUtils::getSizeBytes( imgData->box.width,
imgData->box.height,
1u, 1u,
imgData->format,
rowAlignment );
const size_t requiredBytes = PixelFormatGpuUtils::calculateSizeBytes( imgData->box.width,
imgData->box.height,
imgData->box.depth,
imgData->box.numSlices,
imgData->format,
imgData->numMipmaps,
rowAlignment );
// Bind output buffer
imgData->box.data = OGRE_MALLOC_SIMD( requiredBytes, MEMCATEGORY_RESOURCE );
// Now deal with the data
stream->read( imgData->box.data, requiredBytes );
DecodeResult ret;
ret.first.reset();
ret.second = CodecDataPtr( imgData );
return ret;
}
//---------------------------------------------------------------------
String ASTCCodec::getType() const
{
return mType;
}
//---------------------------------------------------------------------
void ASTCCodec::flipEndian(void * pData, size_t size, size_t count) const
{
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
for(unsigned int index = 0; index < count; index++)
{
flipEndian((void *)((long)pData + (index * size)), size);
}
#endif
}
//---------------------------------------------------------------------
void ASTCCodec::flipEndian(void * pData, size_t size) const
{
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
char swapByte;
for(unsigned int byteIndex = 0; byteIndex < size/2; byteIndex++)
{
swapByte = *(char *)((long)pData + byteIndex);
*(char *)((long)pData + byteIndex) = *(char *)((long)pData + size - byteIndex - 1);
*(char *)((long)pData + size - byteIndex - 1) = swapByte;
}
#endif
}
//---------------------------------------------------------------------
String ASTCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const
{
if (maxbytes >= sizeof(uint32))
{
uint32 fileType;
memcpy(&fileType, magicNumberPtr, sizeof(uint32));
flipEndian(&fileType, sizeof(uint32), 1);
if (ASTC_MAGIC == fileType)
return String("astc");
}
return BLANKSTRING;
}
}
| 37.865979
| 148
| 0.487953
|
resttime
|
f14ccaa4af8babd8f33583d2a19d07f1d66fe96b
| 1,409
|
hh
|
C++
|
include/Activia/ActGuiInput.hh
|
UniversityofWarwick/ACTIVIA
|
bbd0dfa71337602f94d911fa5101a440e8c16606
|
[
"BSL-1.0"
] | 1
|
2020-11-04T08:32:23.000Z
|
2020-11-04T08:32:23.000Z
|
include/Activia/ActGuiInput.hh
|
UniversityofWarwick/ACTIVIA
|
bbd0dfa71337602f94d911fa5101a440e8c16606
|
[
"BSL-1.0"
] | null | null | null |
include/Activia/ActGuiInput.hh
|
UniversityofWarwick/ACTIVIA
|
bbd0dfa71337602f94d911fa5101a440e8c16606
|
[
"BSL-1.0"
] | 1
|
2020-11-04T08:32:30.000Z
|
2020-11-04T08:32:30.000Z
|
#ifdef ACT_USE_QT
#ifndef ACT_GUI_INPUT_HH
#define ACT_GUI_INPUT_HH
#include "Activia/ActAbsInput.hh"
#include "Activia/ActOutputSelection.hh"
#include "Activia/ActGuiWindow.hh"
#include <iostream>
#include <fstream>
#include <string>
/// \brief Define the inputs (target, products, spectrum, algorithms) for the code via a GUI
class ActGuiInput : public ActAbsInput {
public:
/// Default constructor
ActGuiInput();
/// Constructor
ActGuiInput(ActOutputSelection* outputSelection, ActGuiWindow* theGui);
/// Destructor
virtual ~ActGuiInput();
/// Define the target isotopes
virtual void defineTarget();
/// Specify the calculation mode
virtual void defineCalcMode();
/// Define the product isotopes
virtual void defineNuclides();
/// Define the input beam spectrum
virtual void defineSpectrum();
/// Specify the cross-section algorithm
virtual void specifyXSecAlgorithm();
/// Define the exposure and decay times for radioactive decay yield calculations
virtual void defineTime();
/// Specify the decay yield calculation algorithm
virtual void specifyDecayAlgorithm();
/// Define the output file names, format and level of detail.
virtual void specifyOutput();
/// Print out the available calculation options.
virtual void printOptions(std::ofstream&) {;}
protected:
private:
void printIntro() {;}
ActGuiWindow* _theGui;
};
#endif
#endif
| 23.483333
| 92
| 0.74237
|
UniversityofWarwick
|
f14dd9ea676999232cb222f6795a7e021eb553e4
| 488
|
cpp
|
C++
|
Leetcode/Leaf-Similar Trees.cpp
|
Lucifermaniraj/Hacktoberfest2021
|
ec62edfad0d483e4b65874f37c0142d7154adb7b
|
[
"MIT"
] | null | null | null |
Leetcode/Leaf-Similar Trees.cpp
|
Lucifermaniraj/Hacktoberfest2021
|
ec62edfad0d483e4b65874f37c0142d7154adb7b
|
[
"MIT"
] | null | null | null |
Leetcode/Leaf-Similar Trees.cpp
|
Lucifermaniraj/Hacktoberfest2021
|
ec62edfad0d483e4b65874f37c0142d7154adb7b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<int> v;
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> v1, v2;
leaves(root1, v1);
leaves(root2, v2);
return v1==v2;
}
void leaves(TreeNode* root, vector<int>& v) {
if(!root)
return;
if(!root->left && !root->right)
v.push_back(root->val);
leaves(root->left, v);
leaves(root->right, v);
}
};
| 21.217391
| 56
| 0.471311
|
Lucifermaniraj
|
f14f99a466eaf87278065fade561b9f0e0ae7cae
| 1,097
|
hpp
|
C++
|
libraries/include/Engine/Shader.hpp
|
kermado/Total-Resistance
|
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
|
[
"MIT"
] | 3
|
2015-04-25T22:57:58.000Z
|
2019-11-05T18:36:31.000Z
|
libraries/include/Engine/Shader.hpp
|
kermado/Total-Resistance
|
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
|
[
"MIT"
] | 1
|
2016-06-23T15:22:41.000Z
|
2016-06-23T15:22:41.000Z
|
libraries/include/Engine/Shader.hpp
|
kermado/Total-Resistance
|
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
|
[
"MIT"
] | null | null | null |
#ifndef SHADER_H
#define SHADER_H
#include <string>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <Engine/NonCopyable.hpp>
namespace Engine
{
class Shader : private NonCopyable
{
public:
/**
* Shader types.
*/
enum Type
{
VertexShader = GL_VERTEX_SHADER,
FragmentShader = GL_FRAGMENT_SHADER
};
/**
* Constructor.
*
* @param shaderType Type of shader.
*/
Shader(Type shaderType);
/**
* Destructor.
*/
~Shader();
/**
* Initializes the shader from the specified source code file and
* attempts to compile it.
*
* @param filename Path to the shader source code file.
* @return True if shader was initialized successfully.
*/
bool LoadFromFile(std::string filename);
/**
* Returns the type of the shader.
*
* @return Shader type.
*/
Type GetShaderType() const;
/**
* Returns the shader object identifier.
*
* @return Shader ID.
*/
GLuint GetId() const;
private:
/**
* Shader object identifier.
*/
GLuint m_id;
/**
* Shader type.
*/
Type m_type;
};
}
#endif
| 14.824324
| 67
| 0.621696
|
kermado
|
f150a727cad6a3e7269e4ced9a2a70305180e5ea
| 6,816
|
hpp
|
C++
|
include/intent/utils/Logger.hpp
|
open-intent-io/open-intent
|
57d8c4fc89c038f51138d51e776880e728152194
|
[
"MIT"
] | 47
|
2016-07-05T15:20:33.000Z
|
2021-08-06T05:38:33.000Z
|
include/intent/utils/Logger.hpp
|
open-intent-io/open-intent
|
57d8c4fc89c038f51138d51e776880e728152194
|
[
"MIT"
] | 30
|
2016-07-03T22:42:11.000Z
|
2017-11-17T15:58:10.000Z
|
include/intent/utils/Logger.hpp
|
open-intent-io/open-intent
|
57d8c4fc89c038f51138d51e776880e728152194
|
[
"MIT"
] | 8
|
2016-07-22T20:07:58.000Z
|
2017-11-05T10:40:29.000Z
|
/*
|---------------------------------------------------------|
| ___ ___ _ _ |
| / _ \ _ __ ___ _ __ |_ _|_ __ | |_ ___ _ __ | |_ |
| | | | | '_ \ / _ \ '_ \ | || '_ \| __/ _ \ '_ \| __| |
| | |_| | |_) | __/ | | || || | | | || __/ | | | |_ |
| \___/| .__/ \___|_| |_|___|_| |_|\__\___|_| |_|\__| |
| |_| |
| |
| - The users first... |
| |
| Authors: |
| - Clement Michaud |
| - Sergei Kireev |
| |
| Version: 1.0.0 |
| |
|---------------------------------------------------------|
The MIT License (MIT)
Copyright (c) 2016 - Clement Michaud, Sergei Kireev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef INTENT_LOGGER_HPP
#define INTENT_LOGGER_HPP
#include <iostream>
#include "spdlog/spdlog.h"
#include <string>
#include <sstream>
namespace intent {
namespace log {
class Logger {
public:
/**
* \brief The severity levels handled by the logger
*/
struct SeverityLevel {
enum type { TRACE, DEBUG, INFO, WARNING, ERROR, FATAL };
};
/**
* @brief Initialize the logging system with the maximum severity level to
* use.
* \param severityLevel The maximum severity level to use.
*/
static void initialize(SeverityLevel::type severityLevel);
/**
* @brief Return the severity type for string. Return FATAL if nothing is
* matching.
* @param severity The string to convert into severity level
* @return the severity level
*/
static SeverityLevel::type severityLevelFromString(
const std::string& severity);
/**
* @brief Get the static instance of the logger
* \return The logger instance
*/
static Logger& getInstance() {
static Logger* logger = NULL;
if (logger == NULL) {
logger = new Logger();
SeverityLevel::type initialLevel = SeverityLevel::FATAL;
if (const char* env_p = std::getenv("LOG_LEVEL")) {
initialLevel = Logger::severityLevelFromString(env_p);
}
initialize(initialLevel);
}
return *logger;
}
template <int v>
struct Int2Type {
enum { value = v };
};
/**
* \brief Logger by level of severity.
*/
template <SeverityLevel::type LogLevel>
class LoggerWithLevel {
public:
/**
* \brief Log a message from a string stream.
*/
LoggerWithLevel& operator<<(const std::stringstream& message) {
//*this << message;
return *this;
}
/**
* \brief Log a message from an object that supports the stream operator.
*/
template <typename T>
LoggerWithLevel& operator<<(const T& message) {
std::stringstream ss;
ss << message;
log(ss.str(), Int2Type<LogLevel>());
return *this;
}
private:
void log(const std::string& message, Int2Type<SeverityLevel::TRACE>) {
spdlog::get("console")->trace(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::DEBUG>) {
spdlog::get("console")->debug(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::INFO>) {
spdlog::get("console")->info(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::WARNING>) {
spdlog::get("console")->warn(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::ERROR>) {
spdlog::get("console")->error(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::FATAL>) {
spdlog::get("console")->critical(message);
}
};
/**
* @brief Get the trace logger
* \return the trace logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::TRACE>& trace() {
return m_loggerTrace;
}
/**
* @brief Get the debug logger
* \return the debug logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::DEBUG>& debug() {
return m_loggerDebug;
}
/**
* @brief Get the info logger
* \return the info logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::INFO>& info() {
return m_loggerInfo;
}
/**
* @brief Get the warning logger
* \return the warning logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::WARNING>& warning() {
return m_loggerWarning;
}
/**
* @brief Get the error logger
* \return the error logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::ERROR>& error() {
return m_loggerError;
}
/**
* @brief Get the fatal logger
* \return the fatal logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::FATAL>& fatal() {
return m_loggerFatal;
}
private:
Logger() {}
LoggerWithLevel<Logger::SeverityLevel::TRACE> m_loggerTrace;
LoggerWithLevel<Logger::SeverityLevel::DEBUG> m_loggerDebug;
LoggerWithLevel<Logger::SeverityLevel::INFO> m_loggerInfo;
LoggerWithLevel<Logger::SeverityLevel::WARNING> m_loggerWarning;
LoggerWithLevel<Logger::SeverityLevel::ERROR> m_loggerError;
LoggerWithLevel<Logger::SeverityLevel::FATAL> m_loggerFatal;
};
}
}
#define INTENT_LOG_TRACE() intent::log::Logger::getInstance().trace()
#define INTENT_LOG_DEBUG() intent::log::Logger::getInstance().debug()
#define INTENT_LOG_INFO() intent::log::Logger::getInstance().info()
#define INTENT_LOG_WARNING() intent::log::Logger::getInstance().warning()
#define INTENT_LOG_ERROR() intent::log::Logger::getInstance().error()
#define INTENT_LOG_FATAL() intent::log::Logger::getInstance().fatal()
#endif
| 30.841629
| 79
| 0.606808
|
open-intent-io
|
f15150a1d26756736ba76e08aba31173a98f6fe0
| 1,631
|
hpp
|
C++
|
PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp
|
jodavis42/PhysicsSandbox
|
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
|
[
"MIT"
] | 1
|
2022-03-26T21:08:19.000Z
|
2022-03-26T21:08:19.000Z
|
PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp
|
jodavis42/PhysicsSandbox
|
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
|
[
"MIT"
] | null | null | null |
PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp
|
jodavis42/PhysicsSandbox
|
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Common/CommonStandard.hpp"
#include "Physics2dCore/Detection/Broadphase/BroadphaseLayerType.hpp"
namespace SandboxGeometry
{
class Ray2d;
class RayResult2d;
}//SandboxBroadphase2d
namespace SandboxBroadphase2d
{
class IBroadphase2d;
}//SandboxBroadphase2d
namespace Physics2dCore
{
class RigidBody2d;
class Collider2d;
class Physics2dEffect;
class PropertyChangedEvent;
class Collider2dPair;
class ContactManifold2d;
class IBroadphase2dManager;
class Collider2dRaycastResult;
class IConstraint2dSolver;
class SimpleConstraint2dSolver;
}//namespace Physics2dCore
namespace Physics2dTCS
{
using Math::Vector2;
using Math::Vector3;
using Math::Vector4;
using Math::Matrix2;
using Math::Matrix3;
using Math::Matrix4;
using Math::Quaternion;
using Ray2d = SandboxGeometry::Ray2d;
using RayResult2d = SandboxGeometry::RayResult2d;
using IBroadphase2d = SandboxBroadphase2d::IBroadphase2d;
using RigidBody2d = Physics2dCore::RigidBody2d;
using Collider2d = Physics2dCore::Collider2d;
using Physics2dEffect = Physics2dCore::Physics2dEffect;
using Collider2dRaycastResult = Physics2dCore::Collider2dRaycastResult;
using PropertyChangedEvent = Physics2dCore::PropertyChangedEvent;
using IBroadphase2dManager = Physics2dCore::IBroadphase2dManager;
using IConstraint2dSolver = Physics2dCore::IConstraint2dSolver;
using SimpleConstraint2dSolver = Physics2dCore::SimpleConstraint2dSolver;
namespace BroadphaseLayerType = Physics2dCore::BroadphaseLayerType;
template <typename T>
using Array = Zero::Array<T>;
class PhysicsSpace2dTCS;
class RigidBody2dTCS;
class Collider2dTCS;
}//namespace Physics2dTCS
| 22.652778
| 73
| 0.83691
|
jodavis42
|
f1593e60eb478e7426da26ba59ec367786c7a7c7
| 18,733
|
cpp
|
C++
|
Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp
|
leowind/accelbyte-unreal-sdk-plugin
|
73a7bf289abbba8141767eb16005aaf8293f8a63
|
[
"MIT"
] | null | null | null |
Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp
|
leowind/accelbyte-unreal-sdk-plugin
|
73a7bf289abbba8141767eb16005aaf8293f8a63
|
[
"MIT"
] | null | null | null |
Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp
|
leowind/accelbyte-unreal-sdk-plugin
|
73a7bf289abbba8141767eb16005aaf8293f8a63
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2018 - 2020 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
#include "Api/AccelByteEntitlementApi.h"
#include "Core/AccelByteError.h"
#include "Core/AccelByteRegistry.h"
#include "Core/AccelByteReport.h"
#include "Core/AccelByteHttpRetryScheduler.h"
#include "JsonUtilities.h"
#include "EngineMinimal.h"
#include "Core/AccelByteSettings.h"
namespace AccelByte
{
namespace Api
{
Entitlement::Entitlement(const AccelByte::Credentials& Credentials, const AccelByte::Settings& Setting) : Credentials(Credentials), Settings(Setting){}
Entitlement::~Entitlement(){}
void Entitlement::QueryUserEntitlements(const FString& EntitlementName, const FString& ItemId, const int32& Offset, const int32& Limit, const THandler<FAccelByteModelsEntitlementPagingSlicedResult>& OnSuccess, const FErrorHandler& OnError, EAccelByteEntitlementClass EntitlementClass = EAccelByteEntitlementClass::NONE, EAccelByteAppType AppType = EAccelByteAppType::NONE )
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId());
FString Query = TEXT("");
if (!EntitlementName.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementName=%s"), *EntitlementName));
}
if (!ItemId.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("itemId=%s"), *ItemId));
}
if (Offset>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("offset=%d"), Offset));
}
if (Limit>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("limit=%d"), Limit));
}
if (EntitlementClass != EAccelByteEntitlementClass::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementClazz=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteEntitlementClass"), true)->GetNameStringByValue((int32)EntitlementClass)));
}
if (AppType != EAccelByteAppType::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("appType=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteAppType"), true)->GetNameStringByValue((int32)AppType)));
}
Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query));
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::QueryUserEntitlements(const FString& EntitlementName, const TArray<FString>& ItemIds,
const int32& Offset, const int32& Limit, const THandler<FAccelByteModelsEntitlementPagingSlicedResult>& OnSuccess,
const FErrorHandler& OnError, EAccelByteEntitlementClass EntitlementClass, EAccelByteAppType AppType)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId());
FString Query = TEXT("");
if (!EntitlementName.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementName=%s"), *EntitlementName));
}
for (const FString& ItemId : ItemIds)
{
if (!ItemId.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("itemId=%s"), *ItemId));
}
}
if (Offset>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("offset=%d"), Offset));
}
if (Limit>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("limit=%d"), Limit));
}
if (EntitlementClass != EAccelByteEntitlementClass::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementClazz=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteEntitlementClass"), true)->GetNameStringByValue((int32)EntitlementClass)));
}
if (AppType != EAccelByteAppType::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("appType=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteAppType"), true)->GetNameStringByValue((int32)AppType)));
}
Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query));
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementById(const FString& Entitlementid, const THandler<FAccelByteModelsEntitlementInfo>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *Entitlementid);
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementOwnershipByAppId(const FString& AppId, const THandler<FAccelByteModelsEntitlementOwnership>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/byAppId?appId=%s"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace, *AppId);
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementOwnershipBySku(const FString& Sku, const THandler<FAccelByteModelsEntitlementOwnership>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/bySku?sku=%s"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace, *Sku);
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementOwnershipAny(const TArray<FString> ItemIds, const TArray<FString> AppIds, const TArray<FString> Skus,
const THandler<FAccelByteModelsEntitlementOwnership> OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
if (ItemIds.Num() < 1
&& AppIds.Num() < 1
&& Skus.Num() < 1)
{
OnError.ExecuteIfBound(EHttpResponseCodes::NotFound, TEXT("Please provide at least one itemId, AppId or Sku."));
}
else
{
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/any"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace);
int paramCount = 0;
for (int i = 0; i < ItemIds.Num(); i++)
{
Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("itemIds=")).Append(ItemIds[i]);
paramCount++;
}
for (int i = 0; i < AppIds.Num(); i++)
{
Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("appIds=")).Append(AppIds[i]);
paramCount++;
}
for (int i = 0; i < Skus.Num(); i++)
{
Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("skus=")).Append(Skus[i]);
paramCount++;
}
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
}
void Entitlement::ConsumeUserEntitlement(const FString& EntitlementId, const int32& UseCount, const THandler<FAccelByteModelsEntitlementInfo>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FAccelByteModelsConsumeUserEntitlementRequest ConsumeUserEntitlementRequest;
ConsumeUserEntitlementRequest.UseCount = UseCount;
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/%s/decrement"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *EntitlementId);
FString Verb = TEXT("PUT");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FJsonObjectConverter::UStructToJsonObjectString(ConsumeUserEntitlementRequest, Content);
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::CreateDistributionReceiver(const FString& ExtUserId, const FAccelByteModelsAttributes Attributes, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *ExtUserId);
FAccelByteModelsDistributionAttributes DistributionAttributes;
DistributionAttributes.Attributes = Attributes;
FString Verb = TEXT("POST");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FJsonObjectConverter::UStructToJsonObjectString(DistributionAttributes, Content);
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::DeleteDistributionReceiver(const FString& ExtUserId, const FString& UserId, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *UserId, *ExtUserId);
FString Verb = TEXT("DELETE");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetDistributionReceiver(const FString& PublisherNamespace, const FString& PublisherUserId, const THandler<TArray<FAccelByteModelsDistributionReceiver>>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers"), *Settings.PlatformServerUrl, *PublisherNamespace, *PublisherUserId);
FString Query = TEXT("");
if (!Credentials.GetNamespace().IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("targetNamespace=%s"), *Credentials.GetNamespace()));
}
Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query));
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::UpdateDistributionReceiver(const FString& ExtUserId, const FAccelByteModelsAttributes Attributes, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *ExtUserId);
FAccelByteModelsDistributionAttributes DistributionAttributes;
DistributionAttributes.Attributes = Attributes;
FString Verb = TEXT("PUT");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FJsonObjectConverter::UStructToJsonObjectString(DistributionAttributes, Content);
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::SyncPlatformPurchase(EAccelBytePlatformSync PlatformType, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString PlatformText = TEXT("");
FString Content = TEXT("{}");
FString platformUserId = Credentials.GetPlatformUserId();
switch (PlatformType)
{
case EAccelBytePlatformSync::STEAM:
PlatformText = TEXT("steam");
if (platformUserId.IsEmpty()) {
OnError.ExecuteIfBound(static_cast<int32>(ErrorCodes::IsNotLoggedIn), TEXT("User not logged in with 3rd Party Platform"));
return;
}
Content = FString::Printf(TEXT("{\"steamId\": \"%s\", \"appId\": %s}"), *Credentials.GetPlatformUserId(), *Settings.AppId);
break;
case EAccelBytePlatformSync::XBOX_LIVE:
PlatformText = TEXT("xbl");
break;
case EAccelBytePlatformSync::PLAYSTATION:
PlatformText = TEXT("psn");
break;
default:
OnError.ExecuteIfBound(static_cast<int32>(ErrorCodes::InvalidRequest), TEXT("Platform Sync Type is not found"));
return;
}
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/iap/%s/sync"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *PlatformText);
FString Verb = TEXT("PUT");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
} // Namespace Api
}
| 43.363426
| 373
| 0.746917
|
leowind
|
f15f88b741604ccfffcee89d8b457a4d06de6c7f
| 949
|
cpp
|
C++
|
src/logic/role/role_manager.cpp
|
lanhuanjun/game_server
|
64fb7ca39db776fa9471f4c71a76c31759ace7a4
|
[
"MIT"
] | null | null | null |
src/logic/role/role_manager.cpp
|
lanhuanjun/game_server
|
64fb7ca39db776fa9471f4c71a76c31759ace7a4
|
[
"MIT"
] | 1
|
2020-01-15T12:46:05.000Z
|
2020-01-15T12:46:05.000Z
|
src/logic/role/role_manager.cpp
|
lanhuanjun/game_server
|
64fb7ca39db776fa9471f4c71a76c31759ace7a4
|
[
"MIT"
] | null | null | null |
#include "role_manager.h"
#include "role_rmi.h"
#include <third-party/coroutine/gs_co.h>
#include <core/tools/gs_random.h>
MNG_IMPL(role, IRoleManager, CRoleManager)
CRoleManager::CRoleManager()
: m_last_call(0)
{
}
CRoleManager::~CRoleManager()
{
}
void CRoleManager::Init()
{
}
void CRoleManager::Update()
{
if (svc_run_msec() - m_last_call > 1000) {
m_last_call = svc_run_msec();
START_TASK(&CRoleManager::TestCall, this);
}
}
void CRoleManager::TestCall()
{
Rmi<IRoleManager> svc_lobby(__ANY_LOBBY__);
int32_t a = gs::rand(1, 1000);
int32_t b = gs::rand(1, 1000);
int32_t res = svc_lobby.RmiTest_Add(a, b);
LOG(INFO) << a << " + " << b << " = " << res;
if (rmi_last_err() != RMI_CODE_OK) {
rmi_clear_err();
}
}
void CRoleManager::Destroy()
{
}
int CRoleManager::RmiTest_Add(int a, int b)
{
LOG(INFO) << "call: a:" << a << " b:" << b;
return a + b;
}
| 19.367347
| 50
| 0.610116
|
lanhuanjun
|
f161a296a2b14adc45ae38221a97574055384874
| 1,449
|
hpp
|
C++
|
ufora/BackendGateway/ComputedGraph/Typedefs.hpp
|
ufora/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571
|
2015-11-05T20:07:07.000Z
|
2022-01-24T22:31:09.000Z
|
ufora/BackendGateway/ComputedGraph/Typedefs.hpp
|
timgates42/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218
|
2015-11-05T20:37:55.000Z
|
2021-05-30T03:53:50.000Z
|
ufora/BackendGateway/ComputedGraph/Typedefs.hpp
|
timgates42/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40
|
2015-11-07T21:42:19.000Z
|
2021-05-23T03:48:19.000Z
|
/***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#pragma once
#include "../../FORA/Core/Type.hppml"
#include "../../core/PolymorphicSharedPtr.hpp"
#include <boost/python.hpp>
#include <map>
#include <string>
#define COMPUTED_GRAPH_TIMING 1
namespace ComputedGraph {
typedef boost::python::list py_list;
typedef unsigned long id_type;
typedef std::pair<id_type, id_type> class_id_type;
typedef enum {
attrKey,
attrMutable,
attrProperty,
attrFunction,
attrNotCached,
attrClassAttribute,
attrUnknown
} attr_type;
class Graph;
class Location;
class LocationProperty;
class Root;
class LocationType;
class PropertyStorage;
class InstanceStorage;
typedef PolymorphicSharedPtr<Root> RootPtr;
typedef PolymorphicSharedWeakPtr<Root> WeakRootPtr;
}
| 23.370968
| 77
| 0.6853
|
ufora
|
f16775511f36e93433292026986065f31f690529
| 1,683
|
hpp
|
C++
|
lib/fizzy/leb128.hpp
|
imapp-pl/fizzy
|
69e154ad7b910809f2219839d328b93168020135
|
[
"Apache-2.0"
] | null | null | null |
lib/fizzy/leb128.hpp
|
imapp-pl/fizzy
|
69e154ad7b910809f2219839d328b93168020135
|
[
"Apache-2.0"
] | null | null | null |
lib/fizzy/leb128.hpp
|
imapp-pl/fizzy
|
69e154ad7b910809f2219839d328b93168020135
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "types.hpp"
#include <cstdint>
#include <stdexcept>
namespace fizzy
{
template <typename T>
std::pair<T, const uint8_t*> leb128u_decode(const uint8_t* input)
{
static_assert(!std::numeric_limits<T>::is_signed);
T result = 0;
int result_shift = 0;
for (; result_shift < std::numeric_limits<T>::digits; ++input, result_shift += 7)
{
// TODO this ignores the bits in the last byte other than the least significant one
// So would not reject some invalid encoding with those bits set.
result |= static_cast<T>((static_cast<T>(*input) & 0x7F) << result_shift);
if ((*input & 0x80) == 0)
return {result, input + 1};
}
throw std::runtime_error("Invalid LEB128 encoding: too many bytes.");
}
template <typename T>
std::pair<T, const uint8_t*> leb128s_decode(const uint8_t* input)
{
static_assert(std::numeric_limits<T>::is_signed);
using T_unsigned = typename std::make_unsigned<T>::type;
T_unsigned result = 0;
int result_shift = 0;
for (; result_shift < std::numeric_limits<T_unsigned>::digits; ++input, result_shift += 7)
{
result |= static_cast<T_unsigned>((static_cast<T_unsigned>(*input) & 0x7F) << result_shift);
if ((*input & 0x80) == 0)
{
// sign extend
if ((*input & 0x40) != 0)
{
auto const mask = static_cast<T_unsigned>(~T_unsigned{0} << (result_shift + 7));
result |= mask;
}
return {static_cast<T>(result), input + 1};
}
}
throw std::runtime_error("Invalid LEB128 encoding: too many bytes.");
}
} // namespace fizzy
| 30.053571
| 100
| 0.612002
|
imapp-pl
|
f16cff1e25753675382ed1c15ea4d3165627f0a0
| 1,794
|
cpp
|
C++
|
graph-source-code/141-E/3793087.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/141-E/3793087.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/141-E/3793087.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: GNU C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstdio>
using namespace std;
const int nmax = 1010;
int n,m;
int se[nmax][nmax],me[nmax][nmax],u,v;
int color_s[nmax],color[nmax];
int nc=1;
vector < int > res;
void dfs(int u,int c){
color_s[u] = c;
for(int j = 1;j<=n;j++)
if(color_s[j]==0 && me[u][j]>0)
dfs(j,c);
}
void uni(int u,int v){
int c = color[u];
for(int i=1;i<=n;i++)
if(color[i]==c)
color[i] = color[v];
}
int main() {
int u,v; char c;
scanf("%d%d", &n, &m);
for(int i=1;i<=m;i++){
scanf("%d %d %c",&u,&v,&c);
if(c == 'S') se[u][v] = i; else me[u][v] = i;
if(c == 'S') se[v][u] = i; else me[v][u] = i;
}
for(int i=1;i<=n;i++)
if(color_s[i]==0)
dfs(i,nc++);
if(n%2==0){ cout << -1 << endl; return 0; }
if(n == 1 ){ cout << 0 << endl; return 0; }
u = (n-1)/2;
for(int i=1;i<=n;i++) color[i] = i;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(se[i][j]>0 && color_s[i]!=color_s[j] && color[i]!=color[j] && u!=0)
{
uni(i,j); res.push_back(se[i][j]); u--;}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(se[i][j]>0 && color_s[i]==color_s[j] && color[i]!=color[j] && u!=0)
{
uni(i,j); res.push_back(se[i][j]); u--;}
if(u!=0){
cout << -1 << endl; return 0;
}
u = (n-1) / 2;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(me[i][j]>0 && color[i]!=color[j] && u!=0)
{
uni(i,j); res.push_back(me[i][j]); u--;}
if(res.size()!=n-1){
cout << -1 << endl; return 0;
}
cout << n-1 << endl;
for(int i=0;i<n-1;i++)
cout << res[i] << ' ';
cout << endl;
return 0;
}
| 24.243243
| 77
| 0.444259
|
AmrARaouf
|
f16d1cdb27f16e68f138487b6cdb79fe5e7f8f74
| 5,858
|
hpp
|
C++
|
rpc_examples/RpcServer.hpp
|
cd606/tm_examples
|
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
|
[
"Apache-2.0"
] | 1
|
2020-05-22T08:47:00.000Z
|
2020-05-22T08:47:00.000Z
|
rpc_examples/RpcServer.hpp
|
cd606/tm_examples
|
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
|
[
"Apache-2.0"
] | null | null | null |
rpc_examples/RpcServer.hpp
|
cd606/tm_examples
|
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
|
[
"Apache-2.0"
] | null | null | null |
#ifndef RPC_SERVER_HPP_
#define RPC_SERVER_HPP_
#include <tm_kit/infra/GenericLift.hpp>
#include <unordered_map>
#include "RpcInterface.hpp"
namespace rpc_examples {
template <class R>
auto simpleFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using namespace dev::cd606::tm;
using GL = typename infra::GenericLift<typename R::AppType>;
return GL::lift(infra::LiftAsFacility{}, [](Input &&input) -> Output {
return {input.y+":"+std::to_string(input.x)};
});
}
template <class R>
auto clientStreamFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using M = typename R::AppType;
class Facility final : public M::template AbstractOnOrderFacility<Input,Output> {
private:
struct PerIDData {
std::string res;
int remainingCount;
};
std::unordered_map<typename M::EnvironmentType::IDType, PerIDData> remainingInputs_;
public:
Facility() : remainingInputs_() {}
virtual ~Facility() = default;
virtual void handle(typename M::template InnerData<
typename M::template Key<Input>
> &&input) override final {
auto id = input.timedData.value.id();
auto const &realInput = input.timedData.value.key();
auto iter = remainingInputs_.find(id);
if (iter == remainingInputs_.end()) {
iter = remainingInputs_.insert({
id, PerIDData {
realInput.y+":"+std::to_string(realInput.x)
, realInput.x-1
}
}).first;
} else {
iter->second.res += ","+realInput.y+":"+std::to_string(realInput.x);
--iter->second.remainingCount;
}
if (iter->second.remainingCount <= 0) {
this->publish(
input.environment
, typename M::template Key<Output> {
id, {std::move(iter->second.res)}
}
, true //this is the last (and only) one output for this input
);
remainingInputs_.erase(iter);
}
}
};
return M::template fromAbstractOnOrderFacility(new Facility());
}
template <class R>
auto serverStreamFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using M = typename R::AppType;
class Facility final : public M::template AbstractOnOrderFacility<Input,Output> {
public:
Facility() {}
virtual ~Facility() = default;
virtual void handle(typename M::template InnerData<
typename M::template Key<Input>
> &&input) override final {
auto id = input.timedData.value.id();
auto const &realInput = input.timedData.value.key();
int resultCount = std::max(1,realInput.x);
Output o {realInput.y+":"+std::to_string(realInput.x)};
for (int ii=1; ii<=resultCount; ++ii) {
this->publish(
input.environment
, typename M::template Key<Output> {
id, o
}
, (ii == resultCount)
);
}
}
};
return M::template fromAbstractOnOrderFacility(new Facility());
}
template <class R>
auto bothStreamFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using M = typename R::AppType;
class Facility final : public M::template AbstractOnOrderFacility<Input,Output> {
private:
struct PerIDData {
std::vector<Output> res;
int remainingCount;
};
std::unordered_map<typename M::EnvironmentType::IDType, PerIDData> remainingInputs_;
public:
Facility() : remainingInputs_() {}
virtual ~Facility() = default;
virtual void handle(typename M::template InnerData<
typename M::template Key<Input>
> &&input) override final {
auto id = input.timedData.value.id();
auto const &realInput = input.timedData.value.key();
auto iter = remainingInputs_.find(id);
if (iter == remainingInputs_.end()) {
iter = remainingInputs_.insert({
id, PerIDData {
{Output {realInput.y+":"+std::to_string(realInput.x)}}
, realInput.x-1
}
}).first;
} else {
iter->second.res.push_back(Output {realInput.y+":"+std::to_string(realInput.x)});
--iter->second.remainingCount;
}
if (iter->second.remainingCount <= 0) {
int sz = iter->second.res.size();
for (int ii=0; ii<sz; ++ii) {
this->publish(
input.environment
, typename M::template Key<Output> {
id, std::move(iter->second.res[ii])
}
, (ii==sz-1)
);
}
remainingInputs_.erase(iter);
}
}
};
return M::template fromAbstractOnOrderFacility(new Facility());
}
}
#endif
| 40.123288
| 101
| 0.485831
|
cd606
|
f16de14756fc2d2d5852a7a7a9a4b907937f8e5d
| 1,348
|
cpp
|
C++
|
Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp
|
summonFox/unified
|
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
|
[
"MIT"
] | 111
|
2018-01-16T18:49:19.000Z
|
2022-03-13T12:33:54.000Z
|
Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp
|
summonFox/unified
|
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
|
[
"MIT"
] | 636
|
2018-01-17T10:05:31.000Z
|
2022-03-28T20:06:03.000Z
|
Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp
|
summonFox/unified
|
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
|
[
"MIT"
] | 110
|
2018-01-16T19:05:54.000Z
|
2022-03-28T03:44:16.000Z
|
#include "nwnx.hpp"
#include "API/CNWRules.hpp"
#include "API/CNWSCreature.hpp"
#include "API/CNWSCreatureStats.hpp"
#include "API/CNWSInventory.hpp"
#include "API/CNWSItem.hpp"
#include "API/CTwoDimArrays.hpp"
namespace Tweaks {
using namespace NWNXLib;
using namespace NWNXLib::API;
void FixArmorDexBonusUnderOne() __attribute__((constructor));
void FixArmorDexBonusUnderOne()
{
if (!Config::Get<bool>("FIX_ARMOR_DEX_BONUS_UNDER_ONE", false))
return;
LOG_INFO("Allowing armors with max DEX bonus under 1.");
static Hooks::Hook s_ReplacedFunc = Hooks::HookFunction(Functions::_ZN17CNWSCreatureStats9GetDEXModEi,
(void*)+[](CNWSCreatureStats *pThis, int32_t bArmorDexCap) -> uint8_t
{
auto nDexAC = pThis->m_nDexterityModifier;
if (bArmorDexCap)
{
auto pArmor = pThis->m_pBaseCreature->m_pInventory->GetItemInSlot(Constants::EquipmentSlot::Chest);
int nTempValue = 0;
if (pArmor && (nTempValue = pArmor->ComputeArmorClass()) > 0)
{
Globals::Rules()->m_p2DArrays->m_pArmorTable->GetINTEntry(nTempValue, CExoString("DEXBONUS"), &nTempValue);
if (nTempValue < nDexAC)
nDexAC = static_cast<char>(nTempValue);
}
}
return nDexAC;
}, Hooks::Order::Final);
}
}
| 28.680851
| 123
| 0.660237
|
summonFox
|
f16e00fb02c76edea15ca84b7c9d391418773adc
| 159
|
cpp
|
C++
|
character/Character.cpp
|
iliam-12/Bomberman
|
62c688704e34bf1ec762adc76390a545b056e0cc
|
[
"MIT"
] | null | null | null |
character/Character.cpp
|
iliam-12/Bomberman
|
62c688704e34bf1ec762adc76390a545b056e0cc
|
[
"MIT"
] | null | null | null |
character/Character.cpp
|
iliam-12/Bomberman
|
62c688704e34bf1ec762adc76390a545b056e0cc
|
[
"MIT"
] | null | null | null |
/*
** EPITECH PROJECT, 2021
** Projects
** File description:
** Character
*/
#include "Character.hpp"
Character::Character()
{
}
Character::~Character()
{
}
| 9.9375
| 24
| 0.660377
|
iliam-12
|
f17333fa914f67298836ac2d09f1dc1d58bbd82f
| 12,350
|
cpp
|
C++
|
tests/string.tests.cpp
|
dynamic-static/dynamic_static.string
|
ea28d847e97d5f83c2051b722f6b4e4f508e55a6
|
[
"MIT"
] | null | null | null |
tests/string.tests.cpp
|
dynamic-static/dynamic_static.string
|
ea28d847e97d5f83c2051b722f6b4e4f508e55a6
|
[
"MIT"
] | null | null | null |
tests/string.tests.cpp
|
dynamic-static/dynamic_static.string
|
ea28d847e97d5f83c2051b722f6b4e4f508e55a6
|
[
"MIT"
] | null | null | null |
/*
==========================================
Copyright (c) 2016-2021 dynamic_static
Licensed under the MIT license
http://opensource.org/licenses/MIT
==========================================
*/
#include "dynamic_static/string.hpp"
#include "catch2/catch.hpp"
namespace dst {
namespace tests {
static const std::string TheQuickBrownFox { "The quick brown fox jumps over the lazy dog!" };
/**
Validates that string::Proxy constructs correctly
*/
TEST_CASE("string::Proxy::Proxy()", "[string]")
{
SECTION("string::Proxy::Proxy(char)")
{
string::Proxy proxy('c');
CHECK(proxy == "c");
}
SECTION("string::Proxy::Proxy(std::string)")
{
string::Proxy proxy(TheQuickBrownFox);
CHECK(proxy == TheQuickBrownFox);
}
SECTION("string::Proxy::Proxy(const char*) (valid)")
{
string::Proxy proxy(TheQuickBrownFox.c_str());
CHECK(proxy == TheQuickBrownFox);
}
SECTION("string::Proxy::Proxy(const char*) (invalid)")
{
char* pStr = nullptr;
string::Proxy proxy(pStr);
CHECK(proxy == std::string());
}
}
/**
Validates string::contains()
*/
TEST_CASE("string::contains()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::contains(TheQuickBrownFox, "fox"));
REQUIRE(string::contains(TheQuickBrownFox, "rown fox ju"));
REQUIRE(string::contains(TheQuickBrownFox, 'j'));
REQUIRE(string::contains(TheQuickBrownFox, '!'));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::contains(TheQuickBrownFox, "bat"));
REQUIRE_FALSE(string::contains(TheQuickBrownFox, '7'));
REQUIRE_FALSE(string::contains(TheQuickBrownFox, '?'));
}
SECTION("Empty str true")
{
REQUIRE(string::contains(TheQuickBrownFox, std::string()));
REQUIRE(string::contains(std::string(), std::string()));
}
SECTION("Empty str false")
{
REQUIRE_FALSE(string::contains(std::string(), TheQuickBrownFox));
}
}
/**
Validates string::starts_with()
*/
TEST_CASE("string::starts_with()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::starts_with(TheQuickBrownFox, 'T'));
REQUIRE(string::starts_with(TheQuickBrownFox, "The"));
REQUIRE(string::starts_with(TheQuickBrownFox, "The quick"));
REQUIRE(string::starts_with(TheQuickBrownFox, TheQuickBrownFox));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, "he quick brown fox"));
REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, "the"));
REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, '8'));
}
SECTION("Empty str true")
{
REQUIRE(string::starts_with(TheQuickBrownFox, std::string()));
REQUIRE(string::starts_with(std::string(), std::string()));
}
SECTION("Empty str false")
{
REQUIRE_FALSE(string::starts_with(std::string(), TheQuickBrownFox));
}
}
/**
Validates string::ends_with()
*/
TEST_CASE("string::ends_with()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::ends_with(TheQuickBrownFox, '!'));
REQUIRE(string::ends_with(TheQuickBrownFox, "dog!"));
REQUIRE(string::ends_with(TheQuickBrownFox, "lazy dog!"));
REQUIRE(string::ends_with(TheQuickBrownFox, TheQuickBrownFox));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, "he quick brown fox"));
REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, "the"));
REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, '8'));
}
SECTION("Empty str true")
{
REQUIRE(string::ends_with(TheQuickBrownFox, std::string()));
REQUIRE(string::ends_with(std::string(), std::string()));
}
SECTION("Empty str false")
{
REQUIRE_FALSE(string::ends_with(std::string(), TheQuickBrownFox));
}
}
/**
Validates string::replace()
*/
TEST_CASE("string::replace()", "[string]")
{
SECTION("Successful replace")
{
auto str = TheQuickBrownFox;
str = string::replace(str, '!', '.');
str = string::replace(str, "quick", "slow");
str = string::replace(str, "jumps", "trips");
str = string::replace(str, "lazy", "sleeping");
REQUIRE(str == "The slow brown fox trips over the sleeping dog.");
}
SECTION("Unsuccessful replace")
{
auto str = TheQuickBrownFox;
str = string::replace(str, "fox", "fox");
str = string::replace(str, std::string(), "bird");
str = string::replace(str, "cat", "dog");
str = string::replace(str, "frog", std::string());
REQUIRE(str == TheQuickBrownFox);
}
SECTION("Empty str replace")
{
auto str = std::string();
str = string::replace(str, '!', '.');
str = string::replace(str, "quick", "slow");
str = string::replace(str, "jumps", "trips");
str = string::replace(str, "lazy", "sleeping");
REQUIRE(str == std::string());
}
SECTION("Successful multi Replacement")
{
auto str = string::replace(
TheQuickBrownFox,
{
{ '!', '.' },
{ "quick", "slow" },
{ "jumps", "trips" },
{ "lazy", "sleeping" },
}
);
REQUIRE(str == "The slow brown fox trips over the sleeping dog.");
}
SECTION("Unsuccessful multi Replacement")
{
auto str = string::replace(
TheQuickBrownFox,
{
{ "fox", "fox" },
{ std::string(), "bird" },
{ "cat", "dog" },
{ "frog", std::string() },
}
);
REQUIRE(str == TheQuickBrownFox);
}
SECTION("Empty str multi Replacement")
{
auto str = string::replace(
std::string(),
{
{ "!", "." },
{ "quick", "slow" },
{ "jumps", "trips" },
{ "lazy", "sleeping" },
}
);
REQUIRE(str == std::string());
}
}
/**
Validates string::remove()
*/
TEST_CASE("string::remove()", "[string]")
{
SECTION("Successful remove")
{
auto str = TheQuickBrownFox;
str = string::remove(str, "The ");
str = string::remove(str, '!');
str = string::remove(str, "brown ");
str = string::remove(str, "lazy ");
REQUIRE(str == "quick fox jumps over the dog");
}
SECTION("Unsuccessful remove")
{
auto str = TheQuickBrownFox;
str = string::remove(str, '9');
str = string::remove(str, "antelope");
str = string::remove(str, "The ");
str = string::remove(str, " fox ");
REQUIRE(str == TheQuickBrownFox);
}
}
/**
Validates string::reduce_sequence()
*/
TEST_CASE("string::reduce_sequence()", "[string]")
{
std::string str = "some\\ugly\\/\\//\\path\\with\\a/////broken\\\\extension.....ext";
str = string::replace(str, '\\', "/");
str = string::reduce_sequence(str, '/');
str = string::reduce_sequence(str, ".");
str = string::replace(str, "ugly", "nice");
str = string::replace(str, "broken", "decent");
REQUIRE(str == "some/nice/path/with/a/decent/extension.ext");
}
/**
Validates string::scrub_path()
*/
TEST_CASE("string::scrub_path()", "[string]")
{
std::string str = "some//file/\\path/with\\various\\//conventions.txt";
REQUIRE(string::scrub_path(str) == "some/file/path/with/various/conventions.txt");
}
/**
Validates string::scrub_path()
*/
TEST_CASE("string::is_whitespace()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::is_whitespace(' '));
REQUIRE(string::is_whitespace('\f'));
REQUIRE(string::is_whitespace('\n'));
REQUIRE(string::is_whitespace('\r'));
REQUIRE(string::is_whitespace('\t'));
REQUIRE(string::is_whitespace('\v'));
REQUIRE(string::is_whitespace(" \f\n\r\t\v"));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::is_whitespace('0'));
REQUIRE_FALSE(string::is_whitespace(" \f\n\r text \t\v"));
}
}
/**
Validates string::trim_leading_whitespace()
*/
TEST_CASE("string::trim_leading_whitespace()", "[string]")
{
auto str = " " + TheQuickBrownFox + " ";
REQUIRE(string::trim_leading_whitespace(str) == TheQuickBrownFox + " ");
}
/**
Validates string::trim_trailing_whitespace()
*/
TEST_CASE("string::trim_trailing_whitespace()", "[string]")
{
auto str = " " + TheQuickBrownFox + " ";
REQUIRE(string::trim_trailing_whitespace(str) == " " + TheQuickBrownFox);
}
/**
Validates string::trim_whitespace()
*/
TEST_CASE("string::trim_whitespace()", "[string]")
{
auto str = " " + TheQuickBrownFox + " ";
REQUIRE(string::trim_whitespace(str) == TheQuickBrownFox);
}
/**
Validates string::is_upper()
*/
TEST_CASE("string::is_upper()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::is_upper('Z'));
REQUIRE(string::is_upper("THE"));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::is_upper('z'));
REQUIRE_FALSE(string::is_upper(TheQuickBrownFox));
}
}
/**
Validates string::to_upper()
*/
TEST_CASE("string::to_upper()", "[string]")
{
REQUIRE(string::to_upper(TheQuickBrownFox) == "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!");
}
/**
Validates string::is_lower()
*/
TEST_CASE("string::is_lower()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::is_lower('z'));
REQUIRE(string::is_lower("the"));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::is_lower('Z'));
REQUIRE_FALSE(string::is_lower(TheQuickBrownFox));
}
}
/**
Validates string::to_lower()
*/
TEST_CASE("string::to_lower()", "[string]")
{
REQUIRE(string::to_lower("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!") == "the quick brown fox jumps over the lazy dog!");
}
/**
Validates string::get_line()
*/
TEST_CASE("string::get_line()", "[string]")
{
std::vector<std::string> lines {
{ "The quick\n" },
{ "brown fox\n" },
{ "jumps over\n" },
{ "the lazy\n" },
{ "dog." },
};
std::string str;
for (auto const& line : lines) {
str += line;
}
CHECK(string::get_line(str, str.find("quick")) == lines[0]);
CHECK(string::get_line(str, str.find("brown")) == lines[1]);
CHECK(string::get_line(str, str.find("over")) == lines[2]);
CHECK(string::get_line(str, str.find("lazy")) == lines[3]);
CHECK(string::get_line(str, str.find("dog")) == lines[4]);
}
/**
Validates string::split()
*/
TEST_CASE("string::split()", "[string]")
{
const std::vector<std::string> Tokens { "The", "quick", "brown", "fox" };
SECTION("Empty str")
{
REQUIRE(string::split(std::string(), " ").empty());
}
SECTION("char delimiter")
{
REQUIRE(string::split("The;quick;brown;fox", ';') == Tokens);
}
SECTION("char delimiter (prefix)")
{
REQUIRE(string::split(";The;quick;brown;fox", ';') == Tokens);
}
SECTION("char delimiter (postfix)")
{
REQUIRE(string::split("The;quick;brown;fox;", ';') == Tokens);
}
SECTION("char delimiter (prefix and postfix)")
{
REQUIRE(string::split(";The;quick;brown;fox;", ';') == Tokens);
}
SECTION("std::string delimiter")
{
REQUIRE(string::split("The COW quick COW brown COW fox COW ", " COW ") == Tokens);
}
}
/**
Validates string::split_snake_case()
*/
TEST_CASE("string::split_snake_case()", "[string]")
{
const std::vector<std::string> Tokens { "the", "quick", "brown", "fox" };
REQUIRE(string::split_snake_case("the_quick_brown_fox") == Tokens);
}
/**
Validates string::split_camel_case()
*/
TEST_CASE("string::split_camel_case()", "[string]")
{
const std::vector<std::string> Tokens { "The", "Quick", "Brown", "FOX" };
REQUIRE(string::split_camel_case("TheQuickBrownFOX") == Tokens);
}
/**
Validates string::to_hex_string()
*/
TEST_CASE("to_hex_string()", "[string]")
{
REQUIRE(to_hex_string(3735928559) == "0xdeadbeef");
REQUIRE(to_hex_string(3735928559, false) == "deadbeef");
}
} // namespace tests
} // namespace dst
| 28.196347
| 128
| 0.576923
|
dynamic-static
|
f176b8bcd1d2f3be8e21be281432fc659e9960be
| 7,059
|
cpp
|
C++
|
src/lab_extra/compute_shaders/compute_shaders.cpp
|
MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator
|
6f6cc6645d036cf4997f9e8028389cdbb1bb6a56
|
[
"MIT",
"BSD-3-Clause"
] | 6
|
2016-10-10T14:27:17.000Z
|
2020-10-09T09:31:37.000Z
|
src/lab_extra/compute_shaders/compute_shaders.cpp
|
MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator
|
6f6cc6645d036cf4997f9e8028389cdbb1bb6a56
|
[
"MIT",
"BSD-3-Clause"
] | 9
|
2021-10-05T11:03:59.000Z
|
2022-02-25T19:01:53.000Z
|
src/lab_extra/compute_shaders/compute_shaders.cpp
|
MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator
|
6f6cc6645d036cf4997f9e8028389cdbb1bb6a56
|
[
"MIT",
"BSD-3-Clause"
] | 23
|
2016-11-05T12:55:01.000Z
|
2021-05-13T16:55:40.000Z
|
#include "lab_extra/compute_shaders/compute_shaders.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
using namespace extra;
static inline GLuint NumGroupSize(int dataSize, int groupSize)
{
return (dataSize + groupSize - 1) / groupSize;
}
static void DispatchCompute(unsigned int sizeX, unsigned int sizeY, unsigned int sizeZ, unsigned int workGroupSize, bool synchronize = true)
{
glDispatchCompute(NumGroupSize(sizeX, workGroupSize), NumGroupSize(sizeY, workGroupSize), NumGroupSize(sizeZ, workGroupSize));
if (synchronize) {
glMemoryBarrier(GL_ALL_BARRIER_BITS);
}
CheckOpenGLError();
}
/*
* To find out more about `FrameStart`, `Update`, `FrameEnd`
* and the order in which they are called, see `world.cpp`.
*/
ComputeShaders::ComputeShaders()
{
}
ComputeShaders::~ComputeShaders()
{
delete frameBuffer;
delete texture1;
delete texture2;
}
void ComputeShaders::Init()
{
auto camera = GetSceneCamera();
camera->SetPositionAndRotation(glm::vec3(0, 5, 4), glm::quat(glm::vec3(-30 * TO_RADIANS, 0, 0)));
camera->Update();
// Load a mesh from file into GPU memory
{
Mesh* mesh = new Mesh("sphere");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "sphere.obj");
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("bamboo");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "vegetation", "bamboo"), "bamboo.obj");
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("quad");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "quad.obj");
mesh->UseMaterials(false);
meshes[mesh->GetMeshID()] = mesh;
}
const string shaderPath = PATH_JOIN(window->props.selfDir, SOURCE_PATH::EXTRA, "compute_shaders", "shaders");
// Create a shader program for rendering to texture
{
Shader *shader = new Shader("ComputeShaders");
shader->AddShader(PATH_JOIN(shaderPath, "VertexShader.glsl"), GL_VERTEX_SHADER);
shader->AddShader(PATH_JOIN(shaderPath, "FragmentShader.glsl"), GL_FRAGMENT_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
{
Shader *shader = new Shader("FullScreenPass");
shader->AddShader(PATH_JOIN(shaderPath, "FullScreenPass.VS.glsl"), GL_VERTEX_SHADER);
shader->AddShader(PATH_JOIN(shaderPath, "FullScreenPass.FS.glsl"), GL_FRAGMENT_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
{
Shader *shader = new Shader("ComputeShader");
shader->AddShader(PATH_JOIN(shaderPath, "ComputeShader.CS.glsl"), GL_COMPUTE_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
auto resolution = window->GetResolution();
frameBuffer = new FrameBuffer();
frameBuffer->Generate(resolution.x, resolution.y, 3);
texture1 = new Texture2D();
texture1->Create(nullptr, resolution.x, resolution.y, 4);
texture2 = new Texture2D();
texture2->Create(nullptr, resolution.x, resolution.y, 4);
}
void ComputeShaders::FrameStart()
{
}
void ComputeShaders::Update(float deltaTimeSeconds)
{
angle += 0.5f * deltaTimeSeconds;
ClearScreen();
{
frameBuffer->Bind();
DrawScene();
}
// Run compute shader
{
auto shader = shaders["ComputeShader"];
shader->Use();
glm::ivec2 resolution = frameBuffer->GetResolution();
glBindImageTexture(0, frameBuffer->GetTextureID(0), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(1, texture1->GetTextureID(), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
DispatchCompute(resolution.x, resolution.y, 1, 16, true);
}
// Render the scene normaly
FrameBuffer::BindDefault();
if (fullScreenPass)
{
{
auto shader = shaders["FullScreenPass"];
shader->Use();
{
int locTexture = shader->GetUniformLocation("texture_1");
glUniform1i(locTexture, 0);
frameBuffer->BindTexture(0, GL_TEXTURE0);
}
{
int locTexture = shader->GetUniformLocation("texture_2");
glUniform1i(locTexture, 1);
frameBuffer->BindTexture(1, GL_TEXTURE0 + 1);
}
{
int locTexture = shader->GetUniformLocation("texture_3");
glUniform1i(locTexture, 2);
frameBuffer->BindTexture(2, GL_TEXTURE0 + 2);
}
{
int locTexture = shader->GetUniformLocation("texture_4");
glUniform1i(locTexture, 3);
glActiveTexture(GL_TEXTURE0 + 3);
glBindTexture(GL_TEXTURE_2D, texture1->GetTextureID());
}
int locTextureID = shader->GetUniformLocation("textureID");
glUniform1i(locTextureID, textureID);
glm::mat4 modelMatrix(1);
RenderMesh(meshes["quad"], shader, modelMatrix);
}
}
}
void ComputeShaders::DrawScene()
{
for (int i = 0; i < 16; i++)
{
float rotateAngle = (angle + i) * ((i % 2) * 2 - 1);
glm::vec3 position = glm::vec3(-4 + (i % 4) * 2.5, 0, -2 + (i / 4) * 2.5);
glm::mat4 modelMatrix = glm::translate(glm::mat4(1), position);
modelMatrix = glm::rotate(modelMatrix, rotateAngle, glm::vec3(0, 1, 0));
modelMatrix = glm::scale(modelMatrix, glm::vec3(0.1f));
RenderMesh(meshes["bamboo"], shaders["ComputeShaders"], modelMatrix);
}
}
void ComputeShaders::FrameEnd()
{
DrawCoordinateSystem();
}
/*
* These are callback functions. To find more about callbacks and
* how they behave, see `input_controller.h`.
*/
void ComputeShaders::OnInputUpdate(float deltaTime, int mods)
{
// Treat continuous update based on input
}
void ComputeShaders::OnKeyPress(int key, int mods)
{
// Add key press event
if (key == GLFW_KEY_F)
{
fullScreenPass = !fullScreenPass;
}
for (int i = 1; i < 9; i++)
{
if (key == GLFW_KEY_0 + i)
{
textureID = i - 1;
}
}
}
void ComputeShaders::OnKeyRelease(int key, int mods)
{
// Add key release event
}
void ComputeShaders::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// Add mouse move event
}
void ComputeShaders::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button press event
}
void ComputeShaders::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button release event
}
void ComputeShaders::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
// Treat mouse scroll event
}
void ComputeShaders::OnWindowResize(int width, int height)
{
frameBuffer->Resize(width, height, 32);
// Treat window resize event
}
| 26.04797
| 140
| 0.627568
|
MihaiAnghel07
|
f17ba655540cfb9782ec5e74f3f052b3f38ac763
| 1,261
|
cc
|
C++
|
aiks/paint_pass_delegate.cc
|
eyebrowsoffire/impeller
|
bdb74c046327bf1203b4293806399ccf57bf1c6e
|
[
"BSD-3-Clause"
] | null | null | null |
aiks/paint_pass_delegate.cc
|
eyebrowsoffire/impeller
|
bdb74c046327bf1203b4293806399ccf57bf1c6e
|
[
"BSD-3-Clause"
] | 2
|
2022-03-16T05:29:37.000Z
|
2022-03-31T05:35:03.000Z
|
aiks/paint_pass_delegate.cc
|
eyebrowsoffire/impeller
|
bdb74c046327bf1203b4293806399ccf57bf1c6e
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/aiks/paint_pass_delegate.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/contents/texture_contents.h"
namespace impeller {
PaintPassDelegate::PaintPassDelegate(Paint paint, std::optional<Rect> coverage)
: paint_(std::move(paint)), coverage_(std::move(coverage)) {}
// |EntityPassDelgate|
PaintPassDelegate::~PaintPassDelegate() = default;
// |EntityPassDelgate|
std::optional<Rect> PaintPassDelegate::GetCoverageRect() {
return coverage_;
}
// |EntityPassDelgate|
bool PaintPassDelegate::CanElide() {
return paint_.color.IsTransparent();
}
// |EntityPassDelgate|
bool PaintPassDelegate::CanCollapseIntoParentPass() {
return paint_.color.IsOpaque();
}
// |EntityPassDelgate|
std::shared_ptr<Contents> PaintPassDelegate::CreateContentsForSubpassTarget(
std::shared_ptr<Texture> target) {
auto contents = std::make_shared<TextureContents>();
contents->SetTexture(target);
contents->SetSourceRect(IRect::MakeSize(target->GetSize()));
contents->SetOpacity(paint_.color.alpha);
return contents;
}
} // namespace impeller
| 28.659091
| 79
| 0.762887
|
eyebrowsoffire
|
f17e3fa2dd08809c92c8eb600fd8d011d386bf9f
| 1,664
|
cpp
|
C++
|
src/xray/editor/world/sources/property_integer_values_value_getter.cpp
|
ixray-team/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 3
|
2021-10-30T09:36:14.000Z
|
2022-03-26T17:00:06.000Z
|
src/xray/editor/world/sources/property_integer_values_value_getter.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | null | null | null |
src/xray/editor/world/sources/property_integer_values_value_getter.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:08.000Z
|
2022-03-26T17:00:08.000Z
|
////////////////////////////////////////////////////////////////////////////
// Created : 09.01.2008
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "property_integer_values_value_getter.h"
using System::Collections::IList;
using System::Collections::ArrayList;
using System::Object;
using System::String;
property_integer_values_value_getter::property_integer_values_value_getter (
integer_getter_type^ getter,
integer_setter_type^ setter,
string_collection_getter_type^ collection_getter,
string_collection_size_getter_type^ collection_size_getter
) :
inherited (getter, setter),
m_collection_getter (collection_getter),
m_collection_size_getter(collection_size_getter)
{
}
Object ^property_integer_values_value_getter::get_value ()
{
int value = safe_cast<int>(inherited::get_value());
if (value < 0)
value = 0;
int count = collection()->Count;
if (value >= count)
value = count - 1;
return (value);
}
void property_integer_values_value_getter::set_value (Object ^object)
{
String^ string_value = dynamic_cast<String^>(object);
int index = collection()->IndexOf(string_value);
ASSERT ((index >= 0));
inherited::set_value (index);
}
IList^ property_integer_values_value_getter::collection ()
{
ArrayList^ collection = gcnew ArrayList();
u32 count = m_collection_size_getter();
for (u32 i=0; i<count; ++i)
{
collection->Add (m_collection_getter(i));
}
return (collection);
}
| 28.20339
| 77
| 0.631611
|
ixray-team
|
f18e4b27b552d210e912eaf35ef4a0d5efb20573
| 1,030
|
cpp
|
C++
|
Source/GUI/Submenus/HUD.cpp
|
HatchesPls/GrandTheftAutoV-Cheat
|
f06011362a0a8297439b260a670f5091118ef5de
|
[
"curl",
"MIT"
] | 31
|
2021-07-13T21:24:58.000Z
|
2022-03-31T13:04:38.000Z
|
Source/GUI/Submenus/HUD.cpp
|
HatchesPls/GrandTheftAutoV-Cheat
|
f06011362a0a8297439b260a670f5091118ef5de
|
[
"curl",
"MIT"
] | 12
|
2021-07-28T16:53:58.000Z
|
2022-03-31T22:51:03.000Z
|
Source/GUI/Submenus/HUD.cpp
|
HowYouDoinMate/GrandTheftAutoV-Cheat
|
1a345749fc676b7bf2c5cd4df63ed6c9b80ff377
|
[
"curl",
"MIT"
] | 12
|
2020-08-16T15:57:52.000Z
|
2021-06-23T13:08:53.000Z
|
#include "../Header/Cheat Functions/FiberMain.h"
using namespace Cheat;
int HUDColorRed, HUDColorGreen, HUDColorBlue, HUDColorAlpha;
void GUI::Submenus::HUD()
{
GUI::Title("HUD");
GUI::Toggle("Disable HUD", CheatFeatures::DisableHUDBool, "Prevents all HUD elements from being visible");
GUI::Toggle("Hide Minimap", CheatFeatures::HideMinimapBool, "Not needed when Disable HUD is enabled");
GUI::Break("Color", SELECTABLE_CENTER_TEXT);
GUI::Int("Red", HUDColorRed, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
GUI::Int("Green", HUDColorGreen, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
GUI::Int("Blue", HUDColorBlue, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
GUI::Int("Alpha", HUDColorAlpha, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
if (GUI::Option("Change", ""))
{
for (int i = 0; i <= 223; i++)
{
UI::_SET_HUD_COLOUR(i, HUDColorRed, HUDColorGreen, HUDColorBlue, HUDColorAlpha);
}
}
}
| 46.818182
| 107
| 0.73301
|
HatchesPls
|
f1939d344d0611eefaf236413473731281bb235f
| 15,136
|
cpp
|
C++
|
DotGenerator2.cpp
|
PollyP/TraceVizPintool
|
0c76e660834c6b77ffe944169d4afbd04e16ed0a
|
[
"MIT"
] | 6
|
2020-04-25T12:45:52.000Z
|
2021-12-15T01:24:54.000Z
|
DotGenerator2.cpp
|
PollyP/TraceVizPintool
|
0c76e660834c6b77ffe944169d4afbd04e16ed0a
|
[
"MIT"
] | 5
|
2020-04-17T21:03:30.000Z
|
2020-04-24T20:17:28.000Z
|
DotGenerator2.cpp
|
PollyP/TraceVizPintool
|
0c76e660834c6b77ffe944169d4afbd04e16ed0a
|
[
"MIT"
] | null | null | null |
/***
Copyright 2020 P.S.Powledge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this softwareand 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 noticeand this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***/
#include <algorithm>
#include <assert.h>
#include <fstream>
#include <sstream>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "DotGenerator2.h"
using namespace std;
extern ofstream logfile;
extern string get_filename(string pathplusfname);
extern string truncate_string(string inputs, int new_length);;
extern void find_and_replace_all(string& data, string replacee, string replacer);
/**********************************************************************************************************************************
* *
* Section2Color: map section indexes to colors *
* *
/*********************************************************************************************************************************/
Section2ColorPtr Section2Color::inst = NULL;
const string Section2Color::colors[] = { "yellow", "pink", "lightblue", "orange", "green", "tan", };
Section2Color *Section2Color::getInstance()
{
if (Section2Color::inst == NULL)
{
Section2Color::inst = new Section2Color();
}
return Section2Color::inst;
}
string Section2Color::getColor(int section_idx)
{
int idx = section_idx % Section2Color::colors->length();
return Section2Color::inst->colors[idx];
}
/**********************************************************************************************************************************
* *
* NodeItem: class to hold info about nodes *
* *
/*********************************************************************************************************************************/
ostream& operator<<(ostream& os, const DotNodeItem& n)
{
os << " nodeid: " << n.nodeid << " label " << n.label << " color: " << n.color ;
return os;
}
/**********************************************************************************************************************************
* *
* NodeManager: class to manage nodes *
* *
/*********************************************************************************************************************************/
DotNodeManager::DotNodeManager()
{
this->node_counter = 0;
}
DotNodeManager::~DotNodeManager()
{
this->node_counter = 0;
// clean up the heap from all the internally-created (ie placeholder) nodes
// note: the class that added nodes via addNode() is responsible for reclaiming that heap.
for (auto n : this->placeholder_nodes)
{
delete n;
}
}
vector<int> DotNodeManager::getTids()
{
vector<int> ret;
for (map<int, string>::iterator it = this->tidlist.begin(); it != this->tidlist.end(); ++it)
{
ret.push_back(it->first);
}
sort(ret.begin(), ret.end());
return ret;
}
void DotNodeManager::addNode(DotNodeItemPtr n)
{
this->tidlist[n->tid] = "";
this->node_map[this->node_counter] = n;
this->node_counter++;
}
vector<DotNodeItemPtr> DotNodeManager::getNodes()
{
vector<DotNodeItemPtr> ret;
for (pair<int, DotNodeItemPtr> element : this->node_map)
{
DotNodeItemPtr n = element.second;
ret.push_back(n);
}
return ret;
}
vector<DotNodeItemPtr> DotNodeManager::getNodesForTid(int tid)
{
vector<DotNodeItemPtr> ret;
for (pair<int, DotNodeItemPtr> element : this->node_map)
{
int node_idx = element.first;
DotNodeItemPtr n = element.second;
// does this node come from this tid?
if (n->tid != tid)
{
// no, generate a placeholder node first
n = this->getPlaceholderNode(tid, node_idx);
}
ret.push_back(n);
}
return ret;
}
vector<pair<DotNodeItemPtr,DotNodeItemPtr>> DotNodeManager::getNodesThatJumpTids()
{
vector<pair<DotNodeItemPtr,DotNodeItemPtr>> ret;
for (pair<int, DotNodeItemPtr> kv : this->node_map)
{
int i = kv.first;
DotNodeItemPtr n = kv.second;
if (this->node_map.find(i + 1) != this->node_map.end())
{
DotNodeItemPtr nextnode = this->node_map[i + 1];
if (n->tid != nextnode->tid)
{
pair<DotNodeItemPtr, DotNodeItemPtr> apair = { n, nextnode };
ret.push_back(apair);
}
}
}
return ret;
}
DotNodeItemPtr DotNodeManager::getPlaceholderNode(int tid, int node_idx)
{
// build unique node id
stringstream ss;
ss << "cluster_" << tid << "_node_" << node_idx;
// create the nodeitem
// heap management is in class dtor
DotNodeItemPtr ret = new DotNodeItem(tid, ss.str(), "placeholder", "red");
ret->isplaceholder = true;
// add the placeholder node on a list so we can reclaim the heap
this->placeholder_nodes.push_back(ret);
return ret;
}
ostream& operator<<(ostream& os, DotNodeManager& nm)
{
os << "nm state:\n";
os << "\tnode counter: " << nm.node_counter << "\n";
vector<int> tids = nm.getTids();
os << "\ttid count = " << tids.size() << "\n";
for (auto t : tids)
{
os << "\ttid = " << t << "\n";
vector<DotNodeItemPtr> nodes = nm.getNodesForTid(t);
for (auto n : nodes)
{
os << "\t\t" << *n << "\n";
}
}
return os;
}
/**********************************************************************************************************************************
* *
* DotGenerator2: class to generate the dot file *
* *
/*********************************************************************************************************************************/
DotGenerator::DotGenerator(const char * fname, const char *comment)
{
this->fname = fname;
this->file_output.open(this->fname.c_str(), ios::out | ios::trunc);
if (this->file_output.is_open() != true)
{
logfile << "could not open " << fname << endl;
return;
}
this->node_manager = new DotNodeManager();
assert(this->node_manager != NULL);
this->sections2colors = Section2Color::getInstance();
this->file_output << "digraph {" << endl;
this->file_output << "\t# " << comment << endl;
this->file_output << "\tlabel=\"" << comment << "\";" << endl;
this->file_output << "\tcompound=true;" << endl;
this->file_output << "\tedge[style=\"invis\"];" << endl;
this->file_output << "\tnode [shape=rectangle, style=filled, height=1.5, width=6.0, fixedsize=true, margin=.25]; # units=inches" << endl;
this->file_output << endl;
}
DotGenerator::~DotGenerator()
{
// finish writing output file
this->closeOutputFile();
// clean up heap'ed memory
vector<DotNodeItemPtr> nodes = this->node_manager->getNodes();
for (auto n : nodes)
{
delete n;
}
// clean up heap'ed memory, part two
delete this->node_manager;
}
void DotGenerator::addNewImage(int tid, string imgname, int secidx, ADDRINT start_address )
{
// build a unique node id
string node_id = this->buildNodeId(tid);
// build a label for the node
string filename = get_filename(imgname);
find_and_replace_all(imgname, "\\", "\\\\");
string trunc_imgname = truncate_string(imgname, max_imgname_len);
stringstream ss2;
ss2 << "image load: mapped " << filename << " to " << hex << showbase << start_address << "\\lfull path: " << trunc_imgname << "\\l";
string label = ss2.str();
// turn this into a node and add it to our nodemanager
DotNodeItemPtr n = new DotNodeItem(tid, node_id, label, "lightgray");
assert(n != NULL);
this->addImageLoadNode(n);
}
void DotGenerator::addNewLibCall(int tid, string symbol, string imgname, int secidx, ADDRINT addr, string calling_address, string details)
{
// if there's a lot of text, make the node larger
bool needsLargeNode = false;
if (details != "")
{
needsLargeNode = true;
}
// build a unique node id
string node_id = this->buildNodeId(tid);
// build a label for the node
string filename = get_filename(imgname);
find_and_replace_all(imgname, "\\", "\\\\");
string trunc_imgname = truncate_string(imgname, max_imgname_len);
string trunc_symbol = truncate_string(symbol, max_symbol_len);
stringstream ss2;
ss2 << "library call from " << calling_address << " \\l" << trunc_symbol << " (" << hex << showbase << addr << ", " << filename << ") \\l" << "full path: " << trunc_imgname << " \\l";
ss2 << details;
string label = ss2.str();
// map the section idx to a background color
string color = this->sections2colors->getColor(secidx);
// turn this into a node and add it to our nodemanager
DotNodeItemPtr n = new DotNodeItem(tid, node_id, label, color);
assert(n != NULL);
if (needsLargeNode)
{
this->addLargeLibCallNode(n);
}
else
{
this->addLibCallNode(n);
}
}
string DotGenerator::formatDetailsLines(vector<string> input_strings)
{
stringstream ss;
for (auto is : input_strings)
{
ss << is << "\\l";
}
return ss.str();
}
void DotGenerator::closeOutputFile()
{
if (this->file_output.is_open())
{
this->buildClusters();
this->file_output << "}" << endl;
this->file_output.close();
}
}
void DotGenerator::buildClusters()
{
// for every thread we saw ...
vector<int> tids = this->node_manager->getTids();
for (const auto tid : tids)
{
// get the nodes associated with that thread
vector<DotNodeItemPtr> nodes = this->node_manager->getNodesForTid(tid);
if (nodes.size() == 0)
{
continue;
}
// turn the nodes into a cluster
// step 1. build cluster header
stringstream ss;
ss << "cluster_" << tid;
string cluster_id = ss.str();
this->file_output << endl;
this->file_output << "\tsubgraph " << cluster_id << " {" << endl;
this->file_output << "\t\t# " << cluster_id << endl;
this->file_output << "\t\tlabel=\"thread #" << tid << "\"" << endl;
// step 2. xdot doesn't give you a way to line up the nodes
// as a grid, so I create placeholder nodes to get things to
// line up. yes, it's a horrible hack. :( anyway, i need to first
// define the placeholder nodes in the cluster.
this->file_output << "\t\t# placeholder nodes" << endl;
for (int i = 0; i < (int)nodes.size(); i++)
{
if (nodes[i]->isplaceholder)
{
this->file_output << "\t\tnode [label=\"" << nodes[i]->label << "\", style=invis, fillcolor=\"" << nodes[i]->color << "\", height=1.25] " << nodes[i]->nodeid << ";" << endl;
}
}
// step 3. link up the nodes in this cluster.
stringstream ss2;
ss2 << "\t\t" << nodes.front()->nodeid;
for ( int i = 1 ; i < (int)nodes.size() ; i++ )
{
ss2 << " -> " << nodes[i]->nodeid << " ";
}
// step 4. build cluster tail
this->file_output << ss2.str() << ";" << endl;
this->file_output << "\t} # subgraph for " << cluster_id << endl;
}
// is the application multithreaded? If so make the various threads line us nicely in the output
// by building links for each node in thread x that is followed by a node in thread y
vector<pair<DotNodeItemPtr,DotNodeItemPtr>> jumppairs = this->node_manager->getNodesThatJumpTids();
if ( jumppairs.size() > 0 )
{
this->file_output << "\n\n\t# thread jumps" << endl;
for (const auto jumppair : jumppairs)
{
// xdot builds really strange diagrams when you have descendent clusters linking back to ancestor clusters. leave them out.
//if (true)
if (jumppair.first->nodeid < jumppair.second->nodeid)
{
this->file_output << "\t" << jumppair.first->nodeid << " -> " << jumppair.second->nodeid << ";" << endl;
}
}
}
}
// build a unique node id
string DotGenerator::buildNodeId(int tid)
{
stringstream ss;
ss << "cluster_" << tid << "_node_" << this->node_manager->node_counter;
return ss.str();
}
// write this node to file output and add it to the node manager for later clustering/linking.
void DotGenerator::addImageLoadNode(DotNodeItemPtr n)
{
this->file_output << "\tnode [label=\"" << n->label << "\", style=\"filled, rounded\", fillcolor=\"" << n->color << "\", height=0.75] " << n->nodeid << ";" << endl;
this->node_manager->addNode(n);
}
// write this node to file output and add it to the node manager for later clustering/linking.
void DotGenerator::addLargeLibCallNode(DotNodeItemPtr n)
{
this->file_output << "\tnode [label=\"" << n->label << "\", style=filled, fillcolor=\"" << n->color << "\", height=1.25] " << n->nodeid << ";" << endl;
this->node_manager->addNode(n);
}
// write this node to file output and add it to the node manager for later clustering/linking.
void DotGenerator::addLibCallNode(DotNodeItemPtr n)
{
this->file_output << "\tnode [label=\"" << n->label << "\", style=filled, fillcolor=\"" << n->color << "\", height=1.0] " << n->nodeid << ";" << endl;
this->node_manager->addNode(n);
}
// dump the state to an ostream
inline ostream& operator<<(ostream& os, const DotGenerator& dg)
{
os << "dg state:\n";
os << "\tfname: " << dg.fname;
os << "\tnm: " << *(dg.node_manager);
return os;
}
| 34.636156
| 185
| 0.544662
|
PollyP
|
f1968e5e82d78cd2ab6a7204e17c7b55d9f51753
| 202
|
cpp
|
C++
|
ue4_c++/1/bp2/bp2.cpp
|
mohamadem60mdem/a5
|
c6f53364cc148862129acd1c6334d104f5e6bef3
|
[
"MIT"
] | null | null | null |
ue4_c++/1/bp2/bp2.cpp
|
mohamadem60mdem/a5
|
c6f53364cc148862129acd1c6334d104f5e6bef3
|
[
"MIT"
] | null | null | null |
ue4_c++/1/bp2/bp2.cpp
|
mohamadem60mdem/a5
|
c6f53364cc148862129acd1c6334d104f5e6bef3
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "bp2.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, bp2, "bp2" );
| 28.857143
| 78
| 0.787129
|
mohamadem60mdem
|
1af940e1d38d3161c5216d6fae8d230388d44cce
| 18,618
|
cpp
|
C++
|
hi_snex/unit_test/snex_jit_IndexTest.cpp
|
Matt-Dub/HISE
|
ae2dd1653e1c8d749a9088edcd573de6252b0b96
|
[
"Intel"
] | null | null | null |
hi_snex/unit_test/snex_jit_IndexTest.cpp
|
Matt-Dub/HISE
|
ae2dd1653e1c8d749a9088edcd573de6252b0b96
|
[
"Intel"
] | null | null | null |
hi_snex/unit_test/snex_jit_IndexTest.cpp
|
Matt-Dub/HISE
|
ae2dd1653e1c8d749a9088edcd573de6252b0b96
|
[
"Intel"
] | null | null | null |
/* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option any later version.
*
* HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licences for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licencing:
*
* http://www.hartinstruments.net/hise/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace snex {
namespace jit {
using namespace juce;
#define TEST_ALL_INDEXES 1
template <typename IndexType> struct IndexTester
{
using Type = typename IndexType::Type;
static constexpr int Limit = IndexType::LogicType::getUpperLimit();
static constexpr bool isLoopTest()
{
return std::is_same<index::looped_logic<Limit>, typename IndexType::LogicType>();
}
IndexTester(UnitTest* test_, StringArray opt, int dynamicSize = 0) :
test(*test_),
indexName(IndexType::toString()),
optimisations(opt),
ArraySize(Limit != 0 ? Limit : dynamicSize)
{
test.beginTest("Testing " + indexName);
runTest();
}
private:
const int ArraySize;
const String indexName;
void runTest()
{
testLoopRange(0.0, 0.0);
testLoopRange(0.0, 1.0);
testLoopRange(0.5, 1.0);
testLoopRange(0.3, 0.6);
#if TEST_ALL_INDEXES
testIncrementors(FunctionClass::SpecialSymbols::IncOverload);
testIncrementors(FunctionClass::SpecialSymbols::DecOverload);
testIncrementors(FunctionClass::SpecialSymbols::PostIncOverload);
testIncrementors(FunctionClass::SpecialSymbols::PostDecOverload);
testAssignAndCast();
testFloatAlphaAndIndex();
testSpanAccess();
testDynAccess();
#endif
testInterpolators();
}
Range<int> getLoopRange(double nStart, double nEnd)
{
auto s = roundToInt(jlimit(0.0, 1.0, nStart) * (double)Limit);
auto e = roundToInt(jlimit(0.0, 1.0, nEnd) * (double)Limit);
return Range<int>(s, e);
}
String getLoopRangeCode(double start, double end)
{
auto l = getLoopRange(start, end);
String c;
c << ".setLoopRange(" << l.getStart() << ", " << l.getEnd() << ");";
return c;
}
void testLoopRange(double normalisedStart, double normalisedEnd)
{
if constexpr (isLoopTest() && IndexType::LogicType::hasBoundCheck())
{
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
span<Type, Limit> data;
String spanCode;
initialiseSpan(spanCode, data);
c << indexName << " i;";
c << spanCode;
c << "T test(T input)";
{
cppgen::StatementBlock sb(c);
c << "i" << getLoopRangeCode(normalisedStart, normalisedEnd);
c << "i = input;";
c << "return data[i];";
}
test.logMessage("Testing loop range " + indexName + getLoopRangeCode(normalisedStart, normalisedEnd));
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
IndexType i;
auto lr = getLoopRange(normalisedStart, normalisedEnd);
i.setLoopRange(lr.getStart(), lr.getEnd());
i = testValue;
auto expected = data[i];
auto actual = obj["test"].template call<Type>(testValue);
String message = indexName;
message << " with value " << String(testValue);
test.expectWithinAbsoluteError(actual, expected, Type(0.0001), message);
};
// Test List =======================================================
testWithValue(0.5);
#if SNEX_WRAP_ALL_NEGATIVE_INDEXES
testWithValue(-1.5);
#endif
testWithValue(20.0);
testWithValue(-1);
testWithValue(Limit * 0.99);
testWithValue(Limit * 1.2);
testWithValue(Limit * 141.2);
testWithValue(Limit * 8141.92);
testWithValue(0.3);
testWithValue(8.0);
testWithValue(Limit / 3);
}
}
void testInterpolators()
{
if constexpr (!IndexType::canReturnReference() && IndexType::LogicType::hasBoundCheck())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
span<Type, Limit> data;
String spanCode;
initialiseSpan(spanCode, data);
c << indexName + " i;";
c << spanCode;
c << "T test(T input)";
{
cppgen::StatementBlock sb(c);
c << "i = input;";
c << "i.setLoopRange(0, 0);";
c << "return data[i];";
}
test.logMessage("Testing interpolator " + indexName);
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
IndexType i;
i = testValue;
auto expected = data[i];
auto actual = obj["test"].template call<Type>(testValue);
String message = indexName;
message << " with value " << String(testValue);
test.expectWithinAbsoluteError(actual, expected, Type(0.0001), message);
};
// Test List =======================================================
testWithValue(0.5);
#if SNEX_WRAP_ALL_NEGATIVE_INDEXES
testWithValue(-1.5);
#endif
testWithValue(20.0);
testWithValue(Limit * 0.99);
testWithValue(Limit * 1.2);
testWithValue(0.3);
testWithValue(8.0);
testWithValue(Limit / 3);
}
}
void testSpanAccess()
{
if constexpr (Limit != 0 && !isInterpolator())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
span<int, Limit> data;
String spanCode;
initialiseSpan(spanCode, data);
c << spanCode;
c << indexName + " i;";
c << "int test(T input)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return data[i];");
}
c << "int test2(T input)";
{
cppgen::StatementBlock sb(c);
c << "i = input;";
c << "data[i] = (T)50;";
c << "return data[i];";
}
test.logMessage("Testing " + indexName + " span[]");
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
if (IndexType::LogicType::hasBoundCheck())
{
IndexType i;
i = testValue;
auto expectedValue = data[i];
auto actualValue = obj["test"].template call<int>(testValue);
String m = indexName;
m << "::operator[]";
m << " with value " << String(testValue);
test.expectEquals(actualValue, expectedValue, m);
data[i] = Type(50);
auto e2 = data[i];
auto a2 = obj["test2"].template call<int>(testValue);
m << "(write access)";
test.expectEquals(e2, a2, m);
}
else
{
test.logMessage("skip [] access for unsafe index");
}
};
// Test List =======================================================
if (std::is_floating_point<Type>())
{
testWithValue(0.5);
testWithValue(Limit + 0.5);
testWithValue(Limit / 3.f);
testWithValue(-0.5 * Limit);
}
else
{
testWithValue(80);
testWithValue(Limit);
testWithValue(Limit - 1);
testWithValue(-1);
testWithValue(0);
testWithValue(1);
testWithValue(Limit + 1);
testWithValue(-Limit + 1);
}
}
}
void testDynAccess()
{
if constexpr (!isInterpolator())
{
// Test Code ===================================================
heap<int> data;
data.setSize(ArraySize);
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
String spanCode;
initialiseSpan(spanCode, data);
dyn<int> d;
d.referTo(data);
c << spanCode;
c << "dyn<int> d;";
c << indexName + " i;";
c << "int test(XXX input)";
{
cppgen::StatementBlock sb(c);
c << "d.referTo(data);";
c << "i = input;";
c << "return d[i];";
}
test.logMessage("Testing " + indexName + " dyn[]");
c.replaceWildcard("XXX", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
if (IndexType::LogicType::hasBoundCheck())
{
IndexType i;
i = testValue;
auto expectedValue = d[i];
auto actualValue = obj["test"].template call<int>(testValue);
String m = indexName;
m << "::operator[]";
m << "(dyn) with value " << String(testValue);
test.expectEquals(actualValue, expectedValue, m);
}
else
{
test.logMessage("skip [] access for unsafe index");
}
};
// Test List =======================================================
if (std::is_floating_point<Type>())
{
testWithValue(0.5);
testWithValue(Limit + 0.5);
testWithValue(Limit / 3.f);
#if SNEX_WRAP_ALL_NEGATIVE_INDEXES
testWithValue(-12.215 * Limit);
#endif
}
else
{
testWithValue(80);
testWithValue(Limit);
testWithValue(Limit - 1);
testWithValue(-1);
testWithValue(0);
testWithValue(1);
testWithValue(Limit + 1);
testWithValue(-Limit + 1);
}
}
}
template <typename Container> void initialiseSpan(String& asCode, Container& data)
{
auto elementType = Types::Helpers::getTypeFromTypeId<typename Container::DataType>();
asCode << "span<" << Types::Helpers::getTypeName(elementType) << ", " << ArraySize << "> data = { ";
for (int i = 0; i < ArraySize; i++)
{
asCode << Types::Helpers::getCppValueString(var(i), elementType) << ", ";
data[i] = (typename Container::DataType)i;
}
asCode = asCode.upToLastOccurrenceOf(", ", false, false);
asCode << " };";
}
static constexpr bool isInterpolator()
{
return !IndexType::canReturnReference();
}
static constexpr bool hasDynamicBounds()
{
return IndexType::LogicType::hasDynamicBounds();
}
void testFloatAlphaAndIndex()
{
if constexpr (std::is_floating_point<Type>() && !isInterpolator())
{
if constexpr (hasDynamicBounds())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "T testAlpha(T input, int limit)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getAlpha(limit);");
}
c << "int testIndex(T input, int delta, int limit)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getIndex(limit, delta);");
}
test.logMessage("Testing " + indexName + "::getAlpha");
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue, int deltaValue, int limit)
{
IndexType i;
i = testValue;
auto expectedAlpha = i.getAlpha(limit);
auto actualAlpha = obj["testAlpha"].template call<Type>(testValue, limit);
String am = indexName;
am << "::getAlpha()";
am << " with value " << String(testValue);
test.expectWithinAbsoluteError(actualAlpha, expectedAlpha, Type(0.00001), am);
auto expectedIndex = i.getIndex(limit, deltaValue);
auto actualIndex = obj["testIndex"].template call<int>(testValue, deltaValue, limit);
String im = indexName;
im << "::getIndex()";
im << " with value " << String(testValue) << " and delta " << String(deltaValue);
test.expectEquals(actualIndex, expectedIndex, im);
};
// Test List =======================================================
testWithValue(0.51, 0, 48);
testWithValue(12.3, 0, 64);
testWithValue(-0.52, -1, 91);
testWithValue(Limit - 0.44, 2, 10);
testWithValue(Limit + 25.2, 1, 16);
testWithValue(Limit / 0.325 - 1, 9, 1);
testWithValue(Limit * 9.029, 4, 2);
testWithValue(Limit * -0.42, Limit + 2, 32);
testWithValue(324.42, -Limit + 2, 57);
}
else
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "T testAlpha(T input)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getAlpha(0);");
}
c << "int testIndex(T input, int delta)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getIndex(0, delta);");
}
test.logMessage("Testing " + indexName + "::getAlpha");
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue, int deltaValue)
{
IndexType i;
i = testValue;
auto expectedAlpha = i.getAlpha(0);
auto actualAlpha = obj["testAlpha"].template call<Type>(testValue);
String am = indexName;
am << "::getAlpha()";
am << " with value " << String(testValue);
test.expectWithinAbsoluteError(actualAlpha, expectedAlpha, Type(0.00001), am);
auto expectedIndex = i.getIndex(0, deltaValue);
auto actualIndex = obj["testIndex"].template call<int>(testValue, deltaValue);
String im = indexName;
im << "::getIndex()";
im << " with value " << String(testValue) << " and delta " << String(deltaValue);
test.expectEquals(actualIndex, expectedIndex, im);
};
// Test List =======================================================
testWithValue(0.51, 0);
testWithValue(12.3, 0);
testWithValue(-0.52, -1);
testWithValue(Limit - 0.44, 2);
testWithValue(Limit + 25.2, 1);
testWithValue(Limit / 0.325 - 1, 9);
testWithValue(Limit * 9.029, 4);
testWithValue(Limit * 0.42, Limit + 2);
testWithValue(324.42, -Limit + 2);
}
}
}
void testIncrementors(FunctionClass::SpecialSymbols incType)
{
if constexpr (std::is_integral<Type>() && !IndexType::LogicType::hasDynamicBounds())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "int test(int input)";
String op;
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input");
switch (incType)
{
case FunctionClass::IncOverload: op = "++i;"; break;
case FunctionClass::PostIncOverload: op = "i++;"; break;
case FunctionClass::DecOverload: op = "--i;"; break;
case FunctionClass::PostDecOverload: op = "i--;"; break;
default: op = ""; break;
}
c.addWithSemicolon("return (int)" + op);
}
test.logMessage("Testing " + indexName + "::" + FunctionClass::getSpecialSymbol({}, incType).toString());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](int testValue)
{
IndexType i;
i = testValue;
int expected;
switch (incType)
{
case FunctionClass::IncOverload: expected = (int)++i; break;
case FunctionClass::PostIncOverload: expected = (int)i++; break;
case FunctionClass::DecOverload: expected = (int)--i; break;
case FunctionClass::PostDecOverload: expected = (int)i--; break;
default: expected = 0; break;
}
auto actual = obj["test"].template call<int>(testValue);
String message = indexName;
message << ": " << op;
message << " with value " << String(testValue);
test.expectEquals(actual, expected, message);
};
// Test List =======================================================
testWithValue(0);
testWithValue(-1);
testWithValue(Limit - 1);
testWithValue(Limit + 1);
testWithValue(Limit);
testWithValue(Limit * 2);
testWithValue(-Limit);
testWithValue(Limit / 3);
}
}
void testAssignAndCast()
{
if constexpr (Limit != 0)
{
test.logMessage("Testing assignment and type cast ");
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "T test(T input)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input");
c.addWithSemicolon("return (T)i");
}
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
IndexType i;
i = testValue;
auto expected = (Type)i;
auto actual = obj["test"].template call<Type>(testValue);
String message = indexName;
message << " with value " << String(testValue);
test.expectWithinAbsoluteError(actual, expected, Type(0.00001), message);
};
// Test List =======================================================
if constexpr (std::is_floating_point<Type>())
{
testWithValue(Type(Limit - 0.4));
testWithValue(Type(Limit + 0.1));
testWithValue(Type(Limit + 2.4));
testWithValue(Type(-0.2));
testWithValue(Type(-80.2));
}
else
{
testWithValue(Type(0));
testWithValue(Type(Limit - 1));
testWithValue(Type(Limit));
testWithValue(Type(Limit + 1));
testWithValue(Type(-1));
testWithValue(Type(-Limit - 2));
testWithValue(Type(Limit * 32 + 9));
}
}
}
JitObject compile(const String& code)
{
for (auto& o : optimisations)
s.addOptimization(o);
Compiler compiler(s);
SnexObjectDatabase::registerObjects(compiler, 2);
auto obj = compiler.compileJitObject(code);
test.expect(compiler.getCompileResult().wasOk(), compiler.getCompileResult().getErrorMessage());
return obj;
}
GlobalScope s;
UnitTest& test;
StringArray optimisations;
};
}
}
| 25.786704
| 108
| 0.58422
|
Matt-Dub
|
1afcabee2775407f5e2b23d38e2ba2e62705fa63
| 1,013
|
hh
|
C++
|
include/distro/semver.hh
|
mbits-libs/libdistro
|
350f94ba004b21c30eb9a1a345a92b94eacf6ae6
|
[
"MIT"
] | null | null | null |
include/distro/semver.hh
|
mbits-libs/libdistro
|
350f94ba004b21c30eb9a1a345a92b94eacf6ae6
|
[
"MIT"
] | null | null | null |
include/distro/semver.hh
|
mbits-libs/libdistro
|
350f94ba004b21c30eb9a1a345a92b94eacf6ae6
|
[
"MIT"
] | null | null | null |
// Copyright 2021 midnightBITS
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#pragma once
#include <optional>
#include <string>
#include <variant>
#include <vector>
namespace distro {
class semver {
public:
class comp {
std::variant<unsigned, std::string> value;
public:
comp() = default;
comp(unsigned val) : value{val} {}
comp(std::string const& val) : value{val} {}
comp(std::string&& val) : value{std::move(val)} {}
std::string to_string() const;
bool operator<(comp const& rhs) const;
bool operator==(comp const& rhs) const;
static comp from_string(std::string_view comp);
};
unsigned major;
unsigned minor;
unsigned patch;
std::vector<comp> prerelease;
std::vector<std::string> meta;
std::string to_string() const;
bool operator<(semver const& rhs) const;
bool operator==(semver const& rhs) const;
static std::optional<semver> from_string(std::string_view view);
};
} // namespace distro
| 24.707317
| 73
| 0.687068
|
mbits-libs
|
2101331a0292dcc4225c749946f0ebf7e07afd9b
| 7,052
|
cpp
|
C++
|
cali-linker/modules/ipc_module.cpp
|
cali-library-isolation/Cali-library-isolation
|
550893293f66b0428a7b66e1ab80d9f5b7a4bbf4
|
[
"Apache-2.0"
] | 7
|
2021-03-26T06:52:31.000Z
|
2022-03-11T09:42:57.000Z
|
cali-linker/modules/ipc_module.cpp
|
cali-library-isolation/Cali-library-isolation
|
550893293f66b0428a7b66e1ab80d9f5b7a4bbf4
|
[
"Apache-2.0"
] | null | null | null |
cali-linker/modules/ipc_module.cpp
|
cali-library-isolation/Cali-library-isolation
|
550893293f66b0428a7b66e1ab80d9f5b7a4bbf4
|
[
"Apache-2.0"
] | 1
|
2022-02-25T06:57:17.000Z
|
2022-02-25T06:57:17.000Z
|
#include <memory>
#include <stdexcept>
#include <memory>
#include <iostream>
#include <llvm/IR/Module.h>
#include <llvm/Linker/Linker.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/IR/Verifier.h>
#include "ipc_module.h"
#include "llvm_module.h"
#include "../stdlib-is-shit.h"
#include "../cali_linker/archive-wrapper.h"
#include "../cali_linker/debug.h"
#include "../cali_linker/linker_replacement.h"
#include "../cali_linker/randomness.h"
namespace ipcrewriter {
std::shared_ptr<IpcModule>
IpcModule::newIpcModuleFromFile(const std::string &filename, bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig) {
if (endsWith(filename, ".bc") || endsWith(filename, ".ll") || endsWith(filename, ".o")) {
return std::shared_ptr<IpcModule>(new LlvmIpcModule(filename, isMainModule, config, contextConfig));
}
if (endsWith(filename, ".so") || endsWith(filename, ".a")) {
return std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig));
}
throw std::invalid_argument("No supported extension");
}
const std::set<std::string> &IpcModule::getImports() const {
return imports;
}
const std::set<std::string> &IpcModule::getExports() const {
return exports;
}
const std::string &IpcModule::getSource() const {
return source;
}
const std::vector<std::string> &IpcModule::getLogEntries() {
return logEntries;
}
static int linked_things = 0;
std::shared_ptr<IpcModule>
CompositeIpcModule::newIpcModulesFromFiles(std::vector<std::string> &files, bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig,
const std::string &output_filename) {
std::vector<std::shared_ptr<IpcModule>> binary_modules;
std::set<std::string> seen_files;
std::set<std::string> ignored;
// Prepare LLVM linker
LlvmIpcModule::context.enableDebugTypeODRUniquing();
// Load initial llvm bitcode file, containing some libc stubs
filesystem::path stubsFilename = applicationPath;
stubsFilename.append("libc-stubs.bc");
llvm::SMDiagnostic error;
auto composite_module = parseIRFile(stubsFilename.string(), error, LlvmIpcModule::context);
composite_module->setModuleIdentifier("llvm-linked-things_" + output_filename + "_" + std::to_string(linked_things++) + '-' + getRandomString() + ".bc");
// Prepare linker
llvm::Linker L(*composite_module);
int linked_modules = 0;
auto linkerflags = config->linkerOverride ? llvm::Linker::Flags::OverrideFromSrc : llvm::Linker::Flags::None;
// Helper function - link an additional LLVM file to the unique LLVM module
auto addLlvmModule = [&linked_modules, &L, linkerflags](std::unique_ptr<llvm::Module> module) {
if (L.linkInModule(std::move(module), linkerflags))
throw std::runtime_error("Could not link module");
linked_modules++;
};
for (const auto &filename: files) {
// file missing?
if (!exists(filename)) {
std::cerr << "Warning: file not found (" << filename << ")" << std::endl;
continue;
}
// Check if file has already been loaded
if (!seen_files.insert(absolute(filename)).second) {
std::cerr << "Already seen: " << filename << std::endl;
continue;
}
// Shared libraries
if (endsWith(filename, ".so")) {
binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig)));
continue;
}
// LLVM files
if (endsWith(filename, ".bc") || endsWith(filename, ".ll")) {
auto m = llvm::parseIRFile(filename, error, LlvmIpcModule::context);
if (filename.find("libstdc++") != std::string::npos)
for (auto &g: m->functions())
if (g.hasName()) ignored.insert(g.getName());
addLlvmModule(std::move(m));
}
// object files
if (endsWith(filename, ".o")) {
auto header = read_file_limit(filename, 4);
if (header == "BC\xc0\xde") {
addLlvmModule(llvm::parseIRFile(filename, error, LlvmIpcModule::context));
} else if (header == "\x7f""ELF") {
binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig)));
} else {
std::cerr << "Can\'t determine type of file " + filename << std::endl;
}
}
// static libraries
if (endsWith(filename, ".a")) {
bool binary_added = false;
dbg_cout << "Open archive " << filename << std::endl;
libarchive::Archive archive(filename);
int i = 0;
for (auto it: archive) {
//if (it.name() != "magick_libMagickCore_6_Q16_la-ps.o" && it.name() != "magick_libMagickCore_6_Q16_la-string.o")
// continue; //TODO hack
// if (i++ == 3)
// break; //TODO hack
if (endsWith(it.name(), ".o") || endsWith(it.name(), ".bc") || endsWith(it.name(), ".lo")) {
dbg_cout << "- Archive entry: " << it.name() << std::endl;
std::string buffer = it.read();
if (buffer.substr(0, 4) == "BC\xc0\xde") {
auto buffer2 = llvm::MemoryBuffer::getMemBufferCopy(buffer);
auto m = llvm::parseIR(buffer2->getMemBufferRef(), error, LlvmIpcModule::context);
if (!m)
error.print(it.name().c_str(), llvm::errs());
if (filename.find("libstdc++") != std::string::npos)
for (auto &g: m->functions())
if (g.hasName()) ignored.insert(g.getName());
addLlvmModule(std::move(m));
} else if (buffer.substr(0, 4) == "\x7f""ELF") {
if (!binary_added) {
binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig, true)));
binary_added = true;
}
} else {
std::cerr << "Can\'t determine type of file " + it.name() << " in archive " << filename << std::endl;
}
}
}
}
}
if (llvm::verifyModule(*composite_module, &llvm::errs())) {
throw std::runtime_error("linked module is broken!");
}
// build composite
if (linked_modules == 0 && binary_modules.size() == 1)
return binary_modules[0];
if (linked_modules == 1 && binary_modules.empty())
return std::shared_ptr<IpcModule>(new LlvmIpcModule(std::move(composite_module), isMainModule, config, contextConfig));
auto m = std::make_shared<CompositeIpcModule>(isMainModule, config, contextConfig);
if (linked_modules > 0) {
auto llvmModule = std::shared_ptr<IpcModule>(new LlvmIpcModule(std::move(composite_module), isMainModule, config, contextConfig));
dbg_cout << ignored.size() << " ignored symbols" << std::endl;
llvmModule->ignored = std::move(ignored);
m->add(llvmModule);
}
for (const auto &bm: binary_modules)
m->add(bm);
return m;
}
CompositeIpcModule::CompositeIpcModule(bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig)
: IpcModule("", isMainModule, config, contextConfig) {}
const std::vector<std::string> &CompositeIpcModule::getLogEntries() {
logEntries.clear();
for (auto &m: modules) {
for (auto &s: m->getLogEntries())
logEntries.push_back(s);
}
return logEntries;
}
}
| 36.729167
| 155
| 0.671583
|
cali-library-isolation
|
21041a67704d748cb24c61d6086c7bb68d188097
| 2,329
|
hpp
|
C++
|
includes/matrix.hpp
|
TheLandfill/tsp
|
ae2b90c8a44f4521373259a587d4c91c5bc318a3
|
[
"MIT"
] | null | null | null |
includes/matrix.hpp
|
TheLandfill/tsp
|
ae2b90c8a44f4521373259a587d4c91c5bc318a3
|
[
"MIT"
] | null | null | null |
includes/matrix.hpp
|
TheLandfill/tsp
|
ae2b90c8a44f4521373259a587d4c91c5bc318a3
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
template<typename T>
class Matrix {
public:
Matrix();
Matrix(const std::filesystem::path& path);
template<typename Func>
Matrix(size_t num_rows, size_t num_cols, Func rng);
void write_to_file(const std::filesystem::path& path) const;
T at(size_t row, size_t col) const;
T& at(size_t row, size_t col);
size_t get_num_rows() const;
size_t get_num_cols() const;
private:
size_t num_rows, num_cols;
std::vector<T> data;
};
template<typename T>
Matrix<T>::Matrix() : num_rows(0), num_cols(0), data() {}
template<typename T>
Matrix<T>::Matrix(const std::filesystem::path& path) {
std::ifstream reader{path};
if (!reader.is_open()) {
std::string error_message;
error_message.reserve(1024);
error_message += "File `";
error_message += path;
error_message += "` not found!";
throw std::runtime_error(error_message);
}
reader >> num_rows >> num_cols;
data.resize(num_rows * num_cols);
for (size_t row = 0; row < num_rows; row++) {
for (size_t col = 0; col < num_cols; col++) {
if(!(reader >> at(row, col))) {
std::cerr << "Could not read element at (" << row << ", " << col << ")!\n";
throw std::runtime_error("Error Reading Element!");
}
}
}
}
template<typename T>
template<typename Func>
Matrix<T>::Matrix(size_t nr, size_t nc, Func rng) :
num_rows(nr),
num_cols(nc)
{
data.reserve(nr * nc);
for (size_t row = 0; row < num_rows; row++) {
for (size_t col = 0; col < num_cols; col++) {
data.emplace_back(rng());
}
}
}
template<typename T>
void Matrix<T>::write_to_file(const std::filesystem::path& path) const {
std::ofstream writer{path};
writer << num_rows << " " << num_cols << "\n";
for (size_t row = 0; row < num_rows; row++) {
for (size_t col = 0; col < num_cols - 1; col++) {
writer << at(row, col) << " ";
}
writer << at(row, num_cols - 1) << "\n";
}
}
template<typename T>
T Matrix<T>::at(size_t row, size_t col) const {
return data.at(row * num_cols + col);
}
template<typename T>
T& Matrix<T>::at(size_t row, size_t col) {
return data.at(row * num_cols + col);
}
template<typename T>
size_t Matrix<T>::get_num_rows() const {
return num_rows;
}
template<typename T>
size_t Matrix<T>::get_num_cols() const {
return num_cols;
}
| 23.29
| 79
| 0.656934
|
TheLandfill
|
21132bbe7dbd51afb2918827974fcddfdb3c2dcb
| 269
|
cpp
|
C++
|
Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp
|
ferp132/math
|
96f765b93554a2ad3a279575d6c60b1107b0bf35
|
[
"MIT"
] | null | null | null |
Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp
|
ferp132/math
|
96f765b93554a2ad3a279575d6c60b1107b0bf35
|
[
"MIT"
] | null | null | null |
Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp
|
ferp132/math
|
96f765b93554a2ad3a279575d6c60b1107b0bf35
|
[
"MIT"
] | null | null | null |
#include "CNode.h"
CNode::CNode()
{
}
void CNode::SetData(int iData)
{
data = iData;
}
int CNode::GetData() const
{
return data;
}
void CNode::SetNextNode(CNode *newnextNode)
{
nextNode = newnextNode;
}
CNode * CNode::GetNextNode() const
{
return nextNode;
}
| 9.962963
| 43
| 0.672862
|
ferp132
|
2115560a3bd1e622ef0aad2f7fa0b18a961e5632
| 4,829
|
cpp
|
C++
|
src/brdf/LitSphereWindow.cpp
|
davidlee80/GI
|
820ccba1323daaff3453e61f679ee04ed36a91b9
|
[
"MS-PL"
] | 1
|
2022-03-16T01:41:13.000Z
|
2022-03-16T01:41:13.000Z
|
src/brdf/LitSphereWindow.cpp
|
davidlee80/GI
|
820ccba1323daaff3453e61f679ee04ed36a91b9
|
[
"MS-PL"
] | null | null | null |
src/brdf/LitSphereWindow.cpp
|
davidlee80/GI
|
820ccba1323daaff3453e61f679ee04ed36a91b9
|
[
"MS-PL"
] | null | null | null |
/*
Copyright Disney Enterprises, Inc. All rights reserved.
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have
the same meaning here as under U.S. copyright law. A "contribution" is the original
software, or any additions or changes to the software. A "contributor" is any person
that distributes its contribution under this license. "Licensed patents" are a
contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license
conditions and limitations in section 3, each contributor grants you a non-exclusive,
worldwide, royalty-free copyright license to reproduce its contribution, prepare
derivative works of its contribution, and distribute its contribution or any derivative
works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license
conditions and limitations in section 3, each contributor grants you a non-exclusive,
worldwide, royalty-free license under its licensed patents to make, have made,
use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the
software or derivative works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any
contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim
are infringed by the software, your patent license from such contributor to the
software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright,
patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do
so only under this license by including a complete copy of this license with your
distribution. If you distribute any portion of the software in compiled or object code
form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors
give no express warranties, guarantees or conditions. You may have additional
consumer rights under your local laws which this license cannot change.
To the extent permitted under your local laws, the contributors exclude the
implied warranties of merchantability, fitness for a particular purpose and non-
infringement.
*/
#include <QtGui>
#include <QCheckBox>
#include "LitSphereWindow.h"
#include "LitSphereWidget.h"
#include "ParameterWindow.h"
#include "FloatVarWidget.h"
LitSphereWindow::LitSphereWindow( ParameterWindow* paramWindow )
{
glWidget = new LitSphereWidget( this, paramWindow->getBRDFList() );
// so we can tell the parameter window when the incident vector changes (from dragging on the sphere)
connect( glWidget, SIGNAL(incidentVectorChanged( float, float )), paramWindow, SLOT(incidentVectorChanged( float, float )) );
connect( paramWindow, SIGNAL(incidentDirectionChanged(float,float)), glWidget, SLOT(incidentDirectionChanged(float,float)) );
connect( paramWindow, SIGNAL(brdfListChanged(std::vector<brdfPackage>)), glWidget, SLOT(brdfListChanged(std::vector<brdfPackage>)) );
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(glWidget);
QHBoxLayout *buttonLayout = new QHBoxLayout;
mainLayout->addLayout(buttonLayout);
doubleTheta = new QCheckBox( "Double theta" );
doubleTheta->setChecked( true );
connect( doubleTheta, SIGNAL(stateChanged(int)), glWidget, SLOT(doubleThetaChanged(int)) );
buttonLayout->addWidget(doubleTheta);
useNDotL = new QCheckBox( "Multiply by N . L" );
useNDotL->setChecked( true );
connect( useNDotL, SIGNAL(stateChanged(int)), glWidget, SLOT(useNDotLChanged(int)) );
buttonLayout->addWidget(useNDotL);
FloatVarWidget* fv;
#if 0
fv = new FloatVarWidget("Brightness", 0, 100.0, 1.0);
connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(brightnessChanged(float)));
mainLayout->addWidget(fv);
#endif
fv = new FloatVarWidget("Gamma", 1.0, 5.0, 2.2);
connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(gammaChanged(float)));
mainLayout->addWidget(fv);
fv = new FloatVarWidget("Exposure", -6.0, 6.0, 0.0);
connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(exposureChanged(float)));
mainLayout->addWidget(fv);
setLayout(mainLayout);
setWindowTitle( "Lit Sphere" );
}
void LitSphereWindow::setShowing( bool s )
{
if( glWidget )
glWidget->setShowing( s );
}
| 44.302752
| 137
| 0.75937
|
davidlee80
|
2115d2997d7bdca32560608377c3a692242d4c9c
| 1,404
|
cpp
|
C++
|
shader.cpp
|
a12n/rematrix
|
e539a5573a99665ba7b21e1c2114508060dcd163
|
[
"MIT"
] | 2
|
2022-01-15T16:27:05.000Z
|
2022-01-15T16:48:03.000Z
|
shader.cpp
|
a12n/rematrix
|
e539a5573a99665ba7b21e1c2114508060dcd163
|
[
"MIT"
] | null | null | null |
shader.cpp
|
a12n/rematrix
|
e539a5573a99665ba7b21e1c2114508060dcd163
|
[
"MIT"
] | null | null | null |
#include "shader.hpp"
namespace rematrix {
shader::shader(GLenum type) :
id{glCreateShader(type)}
{
if (id == 0) {
throw runtime_error("couldn't create shader");
}
}
shader::shader(shader&& other) noexcept :
id{other.id}
{
const_cast<GLuint&>(other.id) = 0;
}
shader::~shader()
{
glDeleteShader(id);
}
shader&
shader::operator=(shader&& other) noexcept
{
const_cast<GLuint&>(id) = other.id;
const_cast<GLuint&>(other.id) = 0;
return *this;
}
void
shader::compile(const char* src)
{
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
GLint ok;
glGetShaderiv(id, GL_COMPILE_STATUS, &ok);
if (! ok) {
GLint length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
string log(length, '\0');
glGetShaderInfoLog(id, length, nullptr, log.data());
throw runtime_error(log);
}
}
//----------------------------------------------------------------------------
vertex_shader::vertex_shader() :
shader{GL_VERTEX_SHADER}
{
}
vertex_shader::vertex_shader(const char* src) :
vertex_shader()
{
compile(src);
}
//----------------------------------------------------------------------------
fragment_shader::fragment_shader() :
shader{GL_FRAGMENT_SHADER}
{
}
fragment_shader::fragment_shader(const char* src) :
fragment_shader()
{
compile(src);
}
} // namespace rematrix
| 18.72
| 78
| 0.569088
|
a12n
|
2118ad4c107117fafa59610627f5627cff57c214
| 1,409
|
hpp
|
C++
|
include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 11
|
2019-11-27T00:40:43.000Z
|
2020-01-29T14:31:52.000Z
|
include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7
|
2019-11-27T00:29:08.000Z
|
2020-01-08T18:53:39.000Z
|
include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7
|
2019-11-27T10:27:40.000Z
|
2020-01-15T17:43:33.000Z
|
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Vulkan renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP
#define NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp>
namespace Nz
{
namespace Vk
{
class Semaphore : public DeviceObject<Semaphore, VkSemaphore, VkSemaphoreCreateInfo, VK_OBJECT_TYPE_SEMAPHORE>
{
friend DeviceObject;
public:
Semaphore() = default;
Semaphore(const Semaphore&) = delete;
Semaphore(Semaphore&&) = default;
~Semaphore() = default;
using DeviceObject::Create;
inline bool Create(Device& device, VkSemaphoreCreateFlags flags = 0, const VkAllocationCallbacks* allocator = nullptr);
Semaphore& operator=(const Semaphore&) = delete;
Semaphore& operator=(Semaphore&&) = delete;
private:
static inline VkResult CreateHelper(Device& device, const VkSemaphoreCreateInfo* createInfo, const VkAllocationCallbacks* allocator, VkSemaphore* handle);
static inline void DestroyHelper(Device& device, VkSemaphore handle, const VkAllocationCallbacks* allocator);
};
}
}
#include <Nazara/VulkanRenderer/Wrapper/Semaphore.inl>
#endif // NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP
| 32.767442
| 158
| 0.771469
|
jayrulez
|
2118d9f3e23256b269fc4834c33f50650dc05636
| 5,646
|
cc
|
C++
|
deps/autodock/bestpdb.cc
|
neonious/Neonious-Node
|
2859e60ca3f1303127d589d0f50c2aa2b281bc95
|
[
"MIT"
] | null | null | null |
deps/autodock/bestpdb.cc
|
neonious/Neonious-Node
|
2859e60ca3f1303127d589d0f50c2aa2b281bc95
|
[
"MIT"
] | null | null | null |
deps/autodock/bestpdb.cc
|
neonious/Neonious-Node
|
2859e60ca3f1303127d589d0f50c2aa2b281bc95
|
[
"MIT"
] | null | null | null |
/*
$Id: bestpdb.cc,v 1.11 2014/06/12 01:44:07 mp Exp $
AutoDock
Copyright (C) 2009 The Scripps Research Institute. All rights reserved.
AutoDock is a Trade Mark of The Scripps Research Institute.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* bestpdb.cc */
#include <stdio.h>
#include <string.h>
#include "constants.h"
#include "print_rem.h"
#include "strindex.h"
#include "print_avsfld.h"
#include "bestpdb.h"
extern int keepresnum;
extern char dock_param_fn[];
void bestpdb( const int ncluster,
const int num_in_clu[MAX_RUNS],
const int cluster[MAX_RUNS][MAX_RUNS],
const Real econf[MAX_RUNS],
const Real crd[MAX_RUNS][MAX_ATOMS][SPACE],
const char atomstuff[MAX_ATOMS][MAX_CHARS],
const int natom,
const Boole B_write_all_clusmem,
const Real ref_rms[MAX_RUNS],
const int outlev,
FILE *const logFile)
{
register int i=0,
j=0,
k=0,
confnum=0;
int c = 0,
kmax = 0,
/* imol = 0, */
indpf = 0,
off[7],
nframes = 0,
stride = 0,
c1 = 1,
i1 = 1;
char filnm[PATH_MAX],
label[MAX_CHARS];
char AtmNamResNamNumInsCode[20]; /* PDB record 0-origin indices 11-29 (from blank after serial_number to just before xcrd */
pr( logFile, "\n\tLOWEST ENERGY DOCKED CONFORMATION from EACH CLUSTER");
pr( logFile, "\n\t___________________________________________________\n\n\n" );
if (keepresnum > 0 ) {
pr( logFile, "\nKeeping original residue number (specified in the input PDBQ file) for outputting.\n\n");
} else {
pr( logFile, "\nResidue number will be the conformation's rank.\n\n");
}
for (i = 0; i < ncluster; i++) {
i1 = i + 1;
if (B_write_all_clusmem) {
kmax = num_in_clu[i];
} else {
kmax = 1; /* write lowest-energy only */
}
for ( k = 0; k < kmax; k++ ) {
c = cluster[i][k];
c1 = c + 1;
fprintf( logFile, "USER DPF = %s\n", dock_param_fn);
fprintf( logFile, "USER Conformation Number = %d\n", ++confnum);
print_rem(logFile, i1, num_in_clu[i], c1, ref_rms[c]);
if (keepresnum > 0) {
fprintf( logFile, "USER x y z Rank Run Energy RMS\n");
for (j = 0; j < natom; j++) {
sprintf(AtmNamResNamNumInsCode, "%-19.19s", &atomstuff[j][11]);
// retain original residue number (in fact, all fields
// from blank after atom serial number to start of coords)
// replace occupancy by cluster index,
// tempfactor by conformation index within cluster,
// add two non-standard fields with energy and RMSD from reference
#define FORMAT_PDBQT_ATOM_RANKRUN_STR "ATOM %5d%-19.19s%8.3f%8.3f%8.3f%6d%6d %+6.2f %8.3f\n"
fprintf(logFile, FORMAT_PDBQT_ATOM_RANKRUN_STR, j+1, AtmNamResNamNumInsCode,
crd[c][j][X], crd[c][j][Y], crd[c][j][Z], i1, c1, econf[c], ref_rms[c] );
} /* j */
} else {
fprintf( logFile, "USER Rank x y z Run Energy RMS\n");
for (j = 0; j < natom; j++) {
sprintf(AtmNamResNamNumInsCode, "%-11.11s%4d%-4.4s", &atomstuff[j][11],
i1, &atomstuff[j][26]);
// replace original residue number by cluster index
// replace occupancy by conformation index within cluster
// tempfactor by energy
// add one non-standard field with RMSD from reference
#define FORMAT_PDBQT_ATOM_RANKRUN_NUM "ATOM %5d%-19.19s%8.3f%8.3f%8.3f%6d%+6.2f %6.3f\n"
fprintf(logFile, FORMAT_PDBQT_ATOM_RANKRUN_NUM, j+1, AtmNamResNamNumInsCode,
crd[c][j][X], crd[c][j][Y], crd[c][j][Z], c1, econf[c], ref_rms[c] );
} /* j */
}
fprintf( logFile, "TER\n" );
fprintf( logFile, "ENDMDL\n" );
fflush( logFile );
nframes++;
} /* for k */
} /* for i */
fprintf( logFile, "\n" );
strcpy(label, "x y z Rank Run Energy RMS\0" );
if (keepresnum > 0) {
off[0]=5; off[1]=6; off[2]=7; off[3]=8; off[4]=9; off[5]=10; off[6]=11;
stride=12;
} else {
off[0]=5; off[1]=6; off[2]=7; off[3]=4; off[4]=8; off[5]=9; off[6]=10;
stride=11;
} /* if */
indpf = strindex( dock_param_fn, ".dpf" );
strncpy( filnm, dock_param_fn, (size_t)indpf );
filnm[ indpf ] = '\0';
strcat( filnm, ".dlg.pdb\0" );
print_avsfld( logFile, 7, natom, nframes, off, stride, label, filnm );
}
/* EOF */
| 34.851852
| 128
| 0.559511
|
neonious
|
211b8423298a8334dde179387b9288bb7e847119
| 68,192
|
cpp
|
C++
|
source/game/guis/UserInterfaceLocal.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | 2
|
2021-05-02T18:37:48.000Z
|
2021-07-18T16:18:14.000Z
|
source/game/guis/UserInterfaceLocal.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | null | null | null |
source/game/guis/UserInterfaceLocal.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | null | null | null |
// Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "UserInterfaceLocal.h"
#include "UserInterfaceExpressions.h"
#include "UserInterfaceManagerLocal.h"
#include "UIWindow.h"
#include "../../sys/sys_local.h"
using namespace sdProperties;
idCVar sdUserInterfaceLocal::g_debugGUIEvents( "g_debugGUIEvents", "0", CVAR_GAME | CVAR_INTEGER, "Show the results of events" );
idCVar sdUserInterfaceLocal::g_debugGUI( "g_debugGUI", "0", CVAR_GAME | CVAR_INTEGER, "1 - Show GUI window outlines\n2 - Show GUI window names\n3 - Only show visible windows" );
idCVar sdUserInterfaceLocal::g_debugGUITextRect( "g_debugGUITextRect", "0", CVAR_GAME | CVAR_BOOL, "Show windows' text rectangle outlines" );
idCVar sdUserInterfaceLocal::g_debugGUITextScale( "g_debugGUITextScale", "24", CVAR_GAME | CVAR_FLOAT, "Size that the debug GUI info font is drawn in." );
idCVar sdUserInterfaceLocal::s_volumeMusic_dB( "s_volumeMusic_dB", "0", CVAR_GAME | CVAR_SOUND | CVAR_ARCHIVE | CVAR_FLOAT, "music volume in dB" );
#ifdef SD_PUBLIC_BETA_BUILD
idCVar sdUserInterfaceLocal::g_skipIntro( "g_skipIntro", "1", CVAR_GAME | CVAR_BOOL | CVAR_ROM, "skip the opening intro movie" );
#else
idCVar sdUserInterfaceLocal::g_skipIntro( "g_skipIntro", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "skip the opening intro movie" );
#endif
// Crosshair
idCVar sdUserInterfaceLocal::gui_crosshairDef( "gui_crosshairDef", "crosshairs", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "name of def containing crosshair" );
idCVar sdUserInterfaceLocal::gui_crosshairKey( "gui_crosshairKey", "pin_01", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "name of crosshair key in def specified by gui_crosshairDef" );
idCVar sdUserInterfaceLocal::gui_crosshairAlpha( "gui_crosshairAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of crosshair" );
idCVar sdUserInterfaceLocal::gui_crosshairSpreadAlpha( "gui_crosshairSpreadAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of spread components" );
idCVar sdUserInterfaceLocal::gui_crosshairStatsAlpha( "gui_crosshairStatsAlpha", "0", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of health/ammo/reload components" );
idCVar sdUserInterfaceLocal::gui_crosshairGrenadeAlpha( "gui_crosshairGrenadeAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of grenade timer components" );
idCVar sdUserInterfaceLocal::gui_crosshairSpreadScale( "gui_crosshairSpreadScale", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "amount to scale the spread indicator movement" );
idCVar sdUserInterfaceLocal::gui_crosshairColor( "gui_crosshairColor", "1 1 1 1", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "RGB color tint for crosshair elements" );
// HUD
idCVar sdUserInterfaceLocal::gui_chatAlpha( "gui_chatAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of chat text" );
idCVar sdUserInterfaceLocal::gui_fireTeamAlpha( "gui_fireTeamAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of fireteam list" );
idCVar sdUserInterfaceLocal::gui_commandMapAlpha( "gui_commandMapAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of command map" );
idCVar sdUserInterfaceLocal::gui_objectiveListAlpha( "gui_objectiveListAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of objective list" );
idCVar sdUserInterfaceLocal::gui_personalBestsAlpha( "gui_personalBestsAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of personal bests display list" );
idCVar sdUserInterfaceLocal::gui_objectiveStatusAlpha( "gui_objectiveStatusAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of objective status" );
idCVar sdUserInterfaceLocal::gui_obitAlpha( "gui_obitAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of obituaries" );
idCVar sdUserInterfaceLocal::gui_voteAlpha( "gui_voteAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vote" );
idCVar sdUserInterfaceLocal::gui_tooltipAlpha( "gui_tooltipAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of tooltips" );
idCVar sdUserInterfaceLocal::gui_vehicleAlpha( "gui_vehicleAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vehicle information" );
idCVar sdUserInterfaceLocal::gui_vehicleDirectionAlpha( "gui_vehicleDirectionAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vehicle direction indicators" );
idCVar sdUserInterfaceLocal::gui_showRespawnText( "gui_showRespawnText", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "show text about respawning when in limbo or dead" );
idCVar sdUserInterfaceLocal::gui_tooltipDelay( "gui_tooltipDelay", "0.7", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Delay in seconds before tooltips pop up." );
idCVar sdUserInterfaceLocal::gui_doubleClickTime( "gui_doubleClickTime", "0.2", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Delay in seconds between considering two mouse clicks a double-click" );
idStrList sdUserInterfaceLocal::parseStack;
const int sdUserInterfaceLocal::TOOLTIP_MOVE_TOLERANCE = 2;
idBlockAlloc< uiCachedMaterial_t, 64 > sdUserInterfaceLocal::materialCacheAllocator;
const char* sdUserInterfaceLocal::partNames[ FP_MAX ] = {
"tl",
"t",
"tr",
"l",
"r",
"bl",
"b",
"br",
"c",
};
/*
===============================================================================
sdPropertyBinder
===============================================================================
*/
/*
================
sdPropertyBinder::ClearPropertyExpression
================
*/
void sdPropertyBinder::ClearPropertyExpression( int propertyKey, int propertyIndex ) {
boundProperty_t& bp = indexedProperties[ propertyKey ];
int index = bp.second + propertyIndex;
if ( !propertyExpressions[ index ] ) {
return;
}
int count = sdProperties::CountForPropertyType( propertyExpressions[ index ]->GetType() );
int i;
for ( i = 0; i < count; i++ ) {
if ( !propertyExpressions[ index + i ] ) {
continue;
}
propertyExpressions[ index + i ]->Detach();
propertyExpressions[ index + i ] = NULL;
}
}
/*
================
sdPropertyBinder::Clear
================
*/
void sdPropertyBinder::Clear( void ) {
indexedProperties.Clear();
propertyExpressions.Clear();
}
/*
================
sdPropertyBinder::IndexForProperty
================
*/
int sdPropertyBinder::IndexForProperty( sdProperties::sdProperty* property ) {
int i;
for ( i = 0; i < indexedProperties.Num(); i++ ) {
if ( indexedProperties[ i ].first == property ) {
return i;
}
}
boundProperty_t& bp = indexedProperties.Alloc();
bp.first = property;
bp.second = propertyExpressions.Num();
int count = CountForPropertyType( property->GetValueType() );
if ( count == -1 ) {
gameLocal.Error( "sdPropertyBinder::IndexForProperty Property has Invalid Field Count" );
}
for ( i = 0; i < count; i++ ) {
propertyExpressions.Append( NULL );
}
return indexedProperties.Num() - 1;
}
/*
================
sdPropertyBinder::SetPropertyExpression
================
*/
void sdPropertyBinder::SetPropertyExpression( int propertyKey, int propertyIndex, sdUIExpression* expression, sdUserInterfaceScope* scope ) {
boundProperty_t& bp = indexedProperties[ propertyKey ];
int index = bp.second + propertyIndex;
int count = sdProperties::CountForPropertyType( expression->GetType() );
int i;
for ( i = 0; i < count; i++ ) {
if ( propertyExpressions[ index + i ] ) {
propertyExpressions[ index + i ]->Detach();
propertyExpressions[ index + i ] = NULL;
}
}
propertyExpressions[ index ] = expression;
propertyExpressions[ index ]->SetProperty( bp.first, propertyIndex, propertyKey, scope );
}
/*
===============================================================================
sdUserInterfaceState
===============================================================================
*/
/*
================
sdUserInterfaceState::~sdUserInterfaceState
================
*/
sdUserInterfaceState::~sdUserInterfaceState( void ) {
for ( int i = 0; i < expressions.Num(); i++ ) {
expressions[ i ]->Free();
}
expressions.Clear();
}
/*
============
sdUserInterfaceState::GetName
============
*/
const char* sdUserInterfaceState::GetName() const {
return ui->GetName();
}
/*
============
sdUserInterfaceState::GetSubScope
============
*/
sdUserInterfaceScope* sdUserInterfaceState::GetSubScope( const char* name ) {
if ( !idStr::Icmp( name, "module" ) ) {
return ( ui->GetModule() != NULL ) ? ui->GetModule()->GetScope() : NULL;
}
if( !idStr::Icmp( name, "gui" ) ) {
return this;
}
if( !idStr::Icmp( name, "timeline" ) ) {
return ui->GetTimelineManager();
}
sdUIObject* window = ui->GetWindow( name );
if ( window ) {
return &window->GetScope();
}
return NULL;
}
/*
================
sdUserInterfaceState::GetProperty
================
*/
sdProperties::sdProperty* sdUserInterfaceState::GetProperty( const char* name ) {
return properties.GetProperty( name, PT_INVALID, false );
}
/*
============
sdUserInterfaceState::GetProperty
============
*/
sdProperties::sdProperty* sdUserInterfaceState::GetProperty( const char* name, sdProperties::ePropertyType type ) {
sdProperties::sdProperty* prop = properties.GetProperty( name, PT_INVALID, false );
if ( prop && prop->GetValueType() != type && type != PT_INVALID ) {
gameLocal.Error( "sdUserInterfaceState::GetProperty: type mismatch for property '%s'", name );
}
return prop;
}
/*
================
sdUserInterfaceState::SetPropertyExpression
================
*/
void sdUserInterfaceState::SetPropertyExpression( int propertyKey, int propertyIndex, sdUIExpression* expression ) {
boundProperties.SetPropertyExpression( propertyKey, propertyIndex, expression, this );
}
/*
================
sdUserInterfaceState::ClearPropertyExpression
================
*/
void sdUserInterfaceState::ClearPropertyExpression( int propertyKey, int propertyIndex ) {
boundProperties.ClearPropertyExpression( propertyKey, propertyIndex );
}
/*
================
sdUserInterfaceState::RunFunction
================
*/
void sdUserInterfaceState::RunFunction( int expressionIndex ) {
expressions[ expressionIndex ]->Evaluate();
}
/*
================
sdUserInterfaceState::IndexForProperty
================
*/
int sdUserInterfaceState::IndexForProperty( sdProperties::sdProperty* property ) {
return boundProperties.IndexForProperty( property );
}
/*
============
sdUserInterfaceState::GetEvent
============
*/
sdUIEventHandle sdUserInterfaceState::GetEvent( const sdUIEventInfo& info ) const {
return ui->GetEvent( info );
}
/*
============
sdUserInterfaceState::AddEvent
============
*/
void sdUserInterfaceState::AddEvent( const sdUIEventInfo& info, sdUIEventHandle scriptHandle ) {
ui->AddEvent( info, scriptHandle );
}
/*
============
sdUserInterfaceState::ClearExpressions
============
*/
void sdUserInterfaceState::ClearExpressions() {
for ( int i = 0; i < expressions.Num(); i++ ) {
expressions[ i ]->Free();
}
expressions.Clear();
}
/*
============
sdUserInterfaceState::Clear
============
*/
void sdUserInterfaceState::Clear() {
properties.Clear();
transitionExpressions.Clear();
boundProperties.Clear();
}
/*
============
sdUserInterfaceState::GetFunction
============
*/
sdUIFunctionInstance* sdUserInterfaceState::GetFunction( const char* name ) {
return ui->GetFunction( name );
}
/*
============
sdUserInterfaceState::RunNamedFunction
============
*/
bool sdUserInterfaceState::RunNamedFunction( const char* name, sdUIFunctionStack& stack ) {
const sdUserInterfaceLocal::uiFunction_t* func = sdUserInterfaceLocal::FindFunction( name );
if ( !func ) {
return false;
}
CALL_MEMBER_FN_PTR( ui, func->GetFunction() )( stack );
return true;
}
/*
============
sdUserInterfaceState::FindPropertyName
============
*/
const char* sdUserInterfaceState::FindPropertyName( sdProperties::sdProperty* property, sdUserInterfaceScope*& scope ) {
scope = this;
const char* name = properties.NameForProperty( property );
if ( name != NULL ) {
return name;
}
for ( int i = 0 ; i < ui->GetNumWindows(); i++ ) {
sdUIObject* obj = ui->GetWindow( i );
name = obj->GetScope().FindPropertyName( property, scope );
if ( name != NULL ) {
return name;
}
}
return NULL;
}
/*
============
sdUserInterfaceState::GetEvaluator
============
*/
sdUIEvaluatorTypeBase* sdUserInterfaceState::GetEvaluator( const char* name ) {
return GetUI()->GetEvaluator( name );
}
/*
============
sdUserInterfaceState::Update
============
*/
void sdUserInterfaceState::Update( void ) {
int i;
for ( i = 0; i < transitionExpressions.Num(); ) {
sdUIExpression* expression = transitionExpressions[ i ];
if ( !expression->UpdateValue() ) {
transitionExpressions.RemoveIndex( i );
} else {
i++;
}
}
}
/*
================
sdUserInterfaceState::AddTransition
================
*/
void sdUserInterfaceState::AddTransition( sdUIExpression* expression ) {
transitionExpressions.AddUnique( expression );
}
/*
================
sdUserInterfaceState::RemoveTransition
================
*/
void sdUserInterfaceState::RemoveTransition( sdUIExpression* expression ) {
transitionExpressions.Remove( expression );
}
/*
============
sdUserInterfaceState::OnSnapshotHitch
============
*/
void sdUserInterfaceState::OnSnapshotHitch( int delta ) {
for( int i = 0; i < transitionExpressions.Num(); i++ ) {
transitionExpressions[ i ]->OnSnapshotHitch( delta );
}
}
/*
===============================================================================
sdUserInterfaceLocal
===============================================================================
*/
idHashMap< sdUserInterfaceLocal::uiFunction_t* > sdUserInterfaceLocal::uiFunctions;
idList< sdUIEvaluatorTypeBase* > sdUserInterfaceLocal::uiEvaluators;
SD_UI_PUSH_CLASS_TAG( sdUserInterfaceLocal )
const char* sdUserInterfaceLocal::eventNames[ GE_NUM_EVENTS ] = {
SD_UI_EVENT_TAG( "onCreate", "", "Called on window creation" ),
SD_UI_EVENT_TAG( "onActivate", "", "This happens when the GUI is activated." ),
SD_UI_EVENT_TAG( "onDeactivate", "", "This happens when the GUI is activated." ),
SD_UI_EVENT_TAG( "onNamedEvent", "[Event ...]", "Called when one of the events specified occurs" ),
SD_UI_EVENT_TAG( "onPropertyChanged", "[Property ...]", "Called when one of the properties specified occurs" ),
SD_UI_EVENT_TAG( "onCVarChanged", "[CVar ...]", "Called when one of the CVars' value changes" ),
SD_UI_EVENT_TAG( "onCancel", "", "Called when any key bound to the _menuCancel is pressed" ),
SD_UI_EVENT_TAG( "onCancel", "", "Called when any key bound to the _menuCancel is pressed" ),
SD_UI_EVENT_TAG( "onToolTipEvent", "", "Called when a tooltip event occurs" ),
};
SD_UI_POP_CLASS_TAG
/*
================
sdUserInterfaceLocal::sdUserInterfaceLocal
================
*/
sdUserInterfaceLocal::sdUserInterfaceLocal( int _spawnId, bool _isUnique, bool _isPermanent, sdHudModule* _module ) :
spawnId( _spawnId ),
desktop( NULL ),
focusedWindow( NULL ),
entity( NULL ),
guiTime( 0.0f ){
guiDecl = NULL;
theme = NULL;
module = _module;
bindContext = NULL;
shaderParms.SetNum( MAX_ENTITY_SHADER_PARMS - 4 );
for( int i = 0 ; i < shaderParms.Num(); i++ ) {
shaderParms[ i ] = 0.0f;
}
flags.isActive = false;
flags.isUnique = _isUnique;
flags.isPermanent = _isPermanent;
flags.shouldUpdate = true;
currentTime = 0;
scriptState.Init( this );
UI_ADD_STR_CALLBACK( cursorMaterialName, sdUserInterfaceLocal, OnCursorMaterialNameChanged )
UI_ADD_STR_CALLBACK( postProcessMaterialName,sdUserInterfaceLocal, OnPostProcessMaterialNameChanged )
UI_ADD_STR_CALLBACK( focusedWindowName, sdUserInterfaceLocal, OnFocusedWindowNameChanged )
UI_ADD_STR_CALLBACK( screenSaverName, sdUserInterfaceLocal, OnScreenSaverMaterialNameChanged )
UI_ADD_STR_CALLBACK( themeName, sdUserInterfaceLocal, OnThemeNameChanged )
UI_ADD_STR_CALLBACK( bindContextName, sdUserInterfaceLocal, OnBindContextChanged )
UI_ADD_VEC2_CALLBACK( screenDimensions, sdUserInterfaceLocal, OnScreenDimensionChanged )
postProcessMaterial = NULL;
screenSaverMaterial = NULL;
lastMouseMoveTime = 0;
nextAllowToolTipTime = 0;
generalStacks.SetGranularity( 1 );
}
/*
============
sdUserInterfaceLocal::Init
============
*/
void sdUserInterfaceLocal::Init() {
scriptState.GetPropertyHandler().RegisterProperty( "cursorMaterial", cursorMaterialName );
scriptState.GetPropertyHandler().RegisterProperty( "cursorSize", cursorSize );
scriptState.GetPropertyHandler().RegisterProperty( "cursorColor", cursorColor );
scriptState.GetPropertyHandler().RegisterProperty( "cursorPos", cursorPos );
scriptState.GetPropertyHandler().RegisterProperty( "postProcessMaterial", postProcessMaterialName );
scriptState.GetPropertyHandler().RegisterProperty( "focusedWindow", focusedWindowName );
scriptState.GetPropertyHandler().RegisterProperty( "screenDimensions", screenDimensions );
scriptState.GetPropertyHandler().RegisterProperty( "screenCenter", screenCenter );
scriptState.GetPropertyHandler().RegisterProperty( "screenSaverName", screenSaverName );
scriptState.GetPropertyHandler().RegisterProperty( "time", guiTime );
scriptState.GetPropertyHandler().RegisterProperty( "theme", themeName );
scriptState.GetPropertyHandler().RegisterProperty( "bindContext", bindContextName );
scriptState.GetPropertyHandler().RegisterProperty( "flags", scriptFlags );
scriptState.GetPropertyHandler().RegisterProperty( "inputScale", inputScale );
scriptState.GetPropertyHandler().RegisterProperty( "blankWStr", blankWStr );
inputScale = 1.0f;
cursorSize = idVec2( 32.0f, 32.0f );
cursorColor = GetColor( "system/cursor" );
screenSaverName = "system/screensaver";
cursorMaterialName = "system/cursor";
scriptFlags = GUI_INTERACTIVE | GUI_SCREENSAVER;
screenDimensions = idVec2( SCREEN_WIDTH, SCREEN_HEIGHT );
screenDimensions .SetReadOnly( true );
screenCenter = idVec2( SCREEN_WIDTH * 0.5f, SCREEN_HEIGHT * 0.5f );
screenCenter .SetReadOnly( true );
guiTime.SetReadOnly( true );
blankWStr.SetReadOnly( true );
cursorPos = screenCenter;
focusedWindow = NULL;
focusedWindowName = "";
flags.ignoreLocalCursorUpdates = false;
flags.shouldUpdate = true;
toolTipWindow = NULL;
toolTipSource = NULL;
tooltipAnchor = vec2_origin;
postProcessMaterialName = "";
themeName = "default";
generalStacks.Clear();
scriptStack.Clear();
colorStack.Clear();
colorStack.SetGranularity( 1 );
currentColor = colorWhite;
}
/*
================
sdUserInterfaceLocal::~sdUserInterfaceLocal
================
*/
sdUserInterfaceLocal::~sdUserInterfaceLocal( void ) {
parseStack.Clear();
Clear();
}
/*
============
sdUserInterfaceLocal::PushTrace
============
*/
void sdUserInterfaceLocal::PushTrace( const char* info ) {
parseStack.Append( info );
}
/*
============
sdUserInterfaceLocal::PopTrace
============
*/
void sdUserInterfaceLocal::PopTrace() {
if( parseStack.Num() == 0 ) {
gameLocal.Warning( "sdUserInterfaceLocal::PopTrace: Stack underflow" );
return;
}
parseStack.RemoveIndex( parseStack.Num() - 1 );
}
/*
============
sdUserInterfaceLocal::PrintStackTrace
============
*/
void sdUserInterfaceLocal::PrintStackTrace() {
if( parseStack.Num() == 0 ) {
return;
}
gameLocal.Printf( "^3===============================================\n" );
for( int i = parseStack.Num() - 1; i >= 0; i-- ) {
gameLocal.Printf( "%s\n", parseStack[ i ].c_str() );
}
gameLocal.Printf( "^3===============================================\n" );
parseStack.Clear();
}
/*
================
sdUserInterfaceLocal::Load
================
*/
bool sdUserInterfaceLocal::Load( const char* name ) {
if ( guiDecl ) {
assert( false );
return false;
}
guiDecl = gameLocal.declGUIType[ name ];
if ( guiDecl == NULL ) {
gameLocal.Warning( "sdUserInterfaceLocal::Load Invalid GUI '%s'", name );
return false;
}
Init();
PushTrace( va( "Loading %s", GetName() ) );
scriptStack.SetID( GetName() );
const sdDeclGUITheme* theme = gameLocal.declGUIThemeType.LocalFind( "default" );
declManager->AddDependency( GetDecl(), theme );
idTokenCache& tokenCache = declManager->GetGlobalTokenCache();
try {
sdUIWindow::SetupProperties( scriptState.GetPropertyHandler(), guiDecl->GetProperties(), this, tokenCache );
int i;
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
const sdDeclGUIWindow* windowDecl = guiDecl->GetWindow( i );
PushTrace( windowDecl->GetName() );
sdUIObject* object = uiManager->CreateWindow( windowDecl->GetTypeName() );
if ( !object ) {
gameLocal.Error( "sdUserInterfaceLocal::Load Invalid Window Type '%s'", windowDecl->GetTypeName() );
}
object->CreateProperties( this, windowDecl, tokenCache );
object->CreateTimelines( this, windowDecl, tokenCache );
if( windows.Find( object->GetName() ) != windows.End() ) {
gameLocal.Error( "Window named '%s' already exists", object->GetName() );
}
windows.Set( object->GetName(), object );
PopTrace();
}
CreateEvents( guiDecl, tokenCache );
assert( windows.Num() == guiDecl->GetNumWindows() );
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->InitEvents();
}
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->CreateEvents( this, guiDecl->GetWindow( i ), tokenCache );
}
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->CacheEvents();
}
desktop = GetWindow( "desktop" )->Cast< sdUIWindow >();
if( desktop == NULL ) {
gameLocal.Warning( "sdUserInterfaceLocal::Load: could not find 'desktop' in '%s'", name );
}
toolTipWindow = GetWindow( "toolTip" )->Cast< sdUIWindow >();
// parent all the nested windows
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
const sdDeclGUIWindow* windowDecl = guiDecl->GetWindow( i );
const idStrList& children = windowDecl->GetChildren();
PushTrace( windowDecl->GetName() );
windowHash_t::Iterator parentIter = windows.Find( windowDecl->GetName() );
if( parentIter == windows.End() ) {
gameLocal.Error( "sdUserInterfaceLocal::Could not find window '%s'", windowDecl->GetName() );
}
for( int childIndex = 0; childIndex < children.Num(); childIndex++ ) {
windowHash_t::Iterator iter = windows.Find( children[ childIndex ] );
if( iter == windows.End() ) {
gameLocal.Error( "sdUserInterfaceLocal::Could not find window '%s'", children[ childIndex ].c_str() );
}
iter->second->SetParent( parentIter->second );
}
PopTrace();
}
// run constructors now that everything is parented
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->RunEvent( sdUIEventInfo( sdUIObject::OE_CREATE, 0 ) );
GetWindow( i )->OnCreate();
}
} catch ( idException& exception ) {
PrintStackTrace();
throw exception;
}
PopTrace();
return true;
}
/*
================
sdUserInterfaceLocal::Draw
================
*/
void sdUserInterfaceLocal::Draw() {
#ifdef _DEBUG
if( guiDecl && guiDecl->GetBreakOnDraw() ) {
assert( !"BREAK_ON_DRAW" );
}
#endif // _DEBUG
if ( !desktop ) {
return;
}
deviceContext->SetRegisters( shaderParms.Begin() );
bool allowScreenSaver = TestGUIFlag( GUI_SCREENSAVER ) && !TestGUIFlag( GUI_FULLSCREEN );
if ( IsActive() || !allowScreenSaver ) {
desktop->ApplyLayout();
desktop->Draw();
desktop->FinalDraw();
if ( TestGUIFlag( GUI_SHOWCURSOR ) ) {
deviceContext->DrawMaterial( cursorPos.GetValue().x, cursorPos.GetValue().y, cursorSize.GetValue().x, cursorSize.GetValue().y, cursorMaterial, cursorColor );
}
} else if ( screenSaverMaterial != NULL && allowScreenSaver ) {
deviceContext->DrawMaterial( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, screenSaverMaterial, colorWhite );
}
if( g_debugGUI.GetBool() ) {
sdBounds2D rect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
deviceContext->SetColor( colorWhite );
deviceContext->SetFontSize( g_debugGUITextScale.GetFloat() );
deviceContext->DrawText( va( L"%hs", guiDecl->GetName() ), rect, DTF_CENTER | DTF_VCENTER | DTF_SINGLELINE );
}
UpdateToolTip();
if ( postProcessMaterial != NULL ) {
deviceContext->DrawMaterial( 0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, postProcessMaterial, colorWhite );
}
assert( colorStack.Num() == 0 );
}
/*
============
sdUserInterfaceLocal::UpdateToolTip
============
*/
void sdUserInterfaceLocal::UpdateToolTip() {
if( TestGUIFlag( GUI_TOOLTIPS ) ) {
if( toolTipWindow == NULL ) {
gameLocal.Warning( "%s: could not find windowDef 'tooltip' for updating", GetName() );
ClearGUIFlag( GUI_TOOLTIPS );
return;
}
if( toolTipSource == NULL && GetCurrentTime() >= nextAllowToolTipTime ) {
if( !keyInputManager->AnyKeysDown() ) {
// try to spawn a new tool-tip
if( toolTipSource = desktop->UpdateToolTip( cursorPos ) ) {
tooltipAnchor = cursorPos;
} else {
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
}
} else if( toolTipSource != NULL ) {
bool keepWindow = false;
if( sdUIWindow* window = toolTipSource->Cast< sdUIWindow >() ) {
// see if the cursor has moved outside of the tool-tip window
sdBounds2D bounds( window->GetWorldRect() );
keepWindow = bounds.ContainsPoint( cursorPos );
}
if( !keepWindow ) {
toolTipSource = NULL;
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
}
if( !toolTipSource ) {
CancelToolTip();
return;
}
if( idMath::Fabs( cursorPos.GetValue().x - tooltipAnchor.x ) >= TOOLTIP_MOVE_TOLERANCE ||
idMath::Fabs( cursorPos.GetValue().y - tooltipAnchor.y ) >= TOOLTIP_MOVE_TOLERANCE ) {
CancelToolTip();
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
return;
}
sdProperties::sdProperty* toolText = toolTipSource->GetScope().GetProperty( "toolTipText", PT_WSTRING );
sdProperties::sdProperty* active = toolTipWindow->GetScope().GetProperty( "active", PT_FLOAT );
sdProperties::sdProperty* tipText = toolTipWindow->GetScope().GetProperty( "tipText", PT_WSTRING );
sdProperties::sdProperty* rect = toolTipWindow->GetScope().GetProperty( "rect", PT_VEC4 );
if( toolText && tipText && active ) {
*tipText->value.wstringValue = *toolText->value.wstringValue;
*active->value.floatValue = 1.0f;
}
if( rect != NULL ) {
idVec4 temp = *rect->value.vec4Value;
temp.x = cursorPos.GetValue().x;
temp.y = cursorPos.GetValue().y + cursorSize.GetValue().y * 0.5f;
if( temp.x + temp.z >= screenDimensions.GetValue().x ) {
temp.x -= temp.z;
}
if( temp.y + temp.w >= screenDimensions.GetValue().y ) {
temp.y -= temp.w + cursorSize.GetValue().y * 0.5f;;
}
*rect->value.vec4Value = temp;
}
tooltipAnchor = cursorPos;
nextAllowToolTipTime = 0;
}
}
/*
============
sdUserInterfaceLocal::CancelToolTip
============
*/
void sdUserInterfaceLocal::CancelToolTip() {
if( !toolTipWindow ) {
return;
}
sdProperties::sdProperty* active = toolTipWindow->GetScope().GetProperty( "active" );
if( active ) {
*active->value.floatValue = 0.0f;
}
toolTipSource = NULL;
}
/*
================
sdUserInterfaceLocal::GetWindow
================
*/
sdUIObject* sdUserInterfaceLocal::GetWindow( const char* name ) {
windowHash_t::Iterator iter = windows.Find( name );
if( iter == windows.End() ) {
return NULL;
}
return iter->second;
}
/*
================
sdUserInterfaceLocal::GetWindow
================
*/
const sdUIObject* sdUserInterfaceLocal::GetWindow( const char* name ) const {
windowHash_t::ConstIterator iter = windows.Find( name );
if( iter == windows.End() ) {
return NULL;
}
return iter->second;
}
/*
============
sdUserInterfaceLocal::Clear
============
*/
void sdUserInterfaceLocal::Clear() {
scriptState.ClearExpressions();
// we must do this before we destroy any windows, since a window could be watching other windows' properties
DisconnectGlobalCallbacks();
windowHash_t::Iterator iter = windows.Begin();
while( iter != windows.End() ) {
iter->second->DisconnectGlobalCallbacks();
++iter;
}
for( int i = 0; i < materialCache.Num(); i++ ) {
uiMaterialCache_t::Iterator entry = materialCache.FindIndex( i );
entry->second->material.Clear();
materialCacheAllocator.Free( entry->second );
}
materialCache.Clear();
timelineWindows.Clear();
windows.DeleteValues();
windows.Clear();
externalProperties.DeleteContents( true );
scriptState.Clear();
script.Clear();
scriptStack.Clear();
if( timelines.Get() != NULL ) {
timelines->Clear();
}
focusedWindow = NULL;
desktop = NULL;
guiDecl = NULL;
toolTipSource = NULL;
toolTipWindow = NULL;
themeName = "";
focusedWindowName = "";
cursorMaterialName = "";
cursorSize = vec2_zero;
cursorColor = vec4_zero;
screenSaverName = "";
postProcessMaterialName = "";
}
/*
============
sdUserInterfaceLocal::RegisterTimelineWindow
============
*/
void sdUserInterfaceLocal::RegisterTimelineWindow( sdUIObject* window ) {
timelineWindows.Alloc() = window;
}
idCVar sdUserInterfaceLocal::gui_invertMenuPitch( "gui_invertMenuPitch", "0", CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "invert mouse movement in in-game menus" );
/*
============
sdUserInterfaceLocal::PostEvent
============
*/
bool sdUserInterfaceLocal::PostEvent( const sdSysEvent* event ) {
if ( !desktop || !IsInteractive() ) {
return false;
}
if ( event->IsControllerButtonEvent() || event->IsKeyEvent() ) {
if ( bindContext != NULL ) {
bool down;
sdKeyCommand* cmd = keyInputManager->GetCommand( bindContext, *keyInputManager->GetKeyForEvent( *event, down ) );
if ( cmd != NULL ) {
keyInputManager->ProcessUserCmdEvent( *event );
return true;
}
}
}
// save these off for the events
if ( !flags.ignoreLocalCursorUpdates && event->IsMouseEvent() ) {
idVec2 pos = cursorPos;
idVec2 scaledDelta( event->GetXCoord(), event->GetYCoord() );
scaledDelta *= inputScale;
if ( TestGUIFlag( GUI_FULLSCREEN ) ) {
scaledDelta.x *= ( 1.0f / deviceContext->GetAspectRatioCorrection() );
}
pos.x += scaledDelta.x;
if ( TestGUIFlag( GUI_USE_MOUSE_PITCH ) && gui_invertMenuPitch.GetBool() ) {
pos.y -= scaledDelta.y;
} else {
pos.y += scaledDelta.y;
}
pos.x = idMath::ClampFloat( 0.0f, screenDimensions.GetValue().x, pos.x );
pos.y = idMath::ClampFloat( 0.0f, screenDimensions.GetValue().y, pos.y );
cursorPos = pos;
}
bool retVal = false;
if ( !TestGUIFlag( GUI_SHOWCURSOR ) &&
( event->IsMouseEvent() || ( event->IsMouseButtonEvent() && event->GetMouseButton() >= M_MOUSE1 && event->GetMouseButton() <= M_MOUSE12 ) && !TestGUIFlag( GUI_NON_FOCUSED_MOUSE_EVENTS ) )) {
retVal = false;
} else {
if ( event->IsMouseButtonEvent() && event->IsButtonDown() ) {
if( focusedWindow ) {
retVal |= focusedWindow->HandleFocus( event );
}
if( !retVal ) {
retVal |= desktop->HandleFocus( event );
}
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
if( ( ( event->IsMouseButtonEvent() || event->IsKeyEvent() ) && event->IsButtonDown() ) || event->IsGuiEvent() ) {
CancelToolTip();
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
if ( focusedWindow == NULL && focusedWindowName.GetValue().Length() ) {
SetFocus( GetWindow( focusedWindowName.GetValue().c_str() )->Cast< sdUIWindow >() );
}
if ( focusedWindow ) {
bool focusedRetVal = focusedWindow->PostEvent( event );
retVal |= focusedRetVal;
if( !focusedRetVal ) {
// give immediate parents that capture key events a crack
if( !retVal && event->IsKeyEvent() || event->IsGuiEvent() ) {
sdUIObject* parent = focusedWindow->GetNode().GetParent();
while( parent != NULL && retVal == false ) {
if( sdUIWindow* window = parent->Cast< sdUIWindow >() ) {
if( window->TestFlag( sdUIWindow::WF_CAPTURE_KEYS ) ) {
retVal |= parent->PostEvent( event );
}
}
parent = parent->GetNode().GetParent();
}
}
}
}
if( !retVal ) {
retVal |= desktop->PostEvent( event );
}
}
// eat everything but the F-Keys
if ( TestGUIFlag( GUI_CATCH_ALL_EVENTS ) ) {
keyNum_t keyNum;
if ( event->IsKeyEvent() ) {
keyNum = event->GetKey();
} else {
keyNum = K_INVALID;
}
if ( ( keyNum != K_INVALID && ( keyNum < K_F1 || keyNum > K_F15 ) ) || ( event->IsControllerButtonEvent() ) ) {
retVal = true;
}
}
if( TestGUIFlag( GUI_TOOLTIPS ) && event->IsMouseEvent() ) {
lastMouseMoveTime = GetCurrentTime();
}
return retVal;
}
/*
============
sdUserInterfaceLocal::Shutdown
============
*/
void sdUserInterfaceLocal::Shutdown( void ) {
uiFunctions.DeleteContents();
uiEvaluators.DeleteContents( true );
}
/*
============
sdUserInterfaceLocal::FindFunction
============
*/
sdUserInterfaceLocal::uiFunction_t* sdUserInterfaceLocal::FindFunction( const char* name ) {
sdUserInterfaceLocal::uiFunction_t** ptr;
return uiFunctions.Get( name, &ptr ) ? *ptr : NULL;
}
/*
============
sdUserInterfaceLocal::GetFunction
============
*/
sdUIFunctionInstance* sdUserInterfaceLocal::GetFunction( const char* name ) {
uiFunction_t* function = FindFunction( name );
if ( function == NULL ) {
return NULL;
}
return new sdUITemplateFunctionInstance< sdUserInterfaceLocal, sdUITemplateFunctionInstance_Identifier >( this, function );
}
/*
============
sdUserInterfaceLocal::GetEvaluator
============
*/
sdUIEvaluatorTypeBase* sdUserInterfaceLocal::GetEvaluator( const char* name ) {
int i;
for ( i = 0; i < uiEvaluators.Num(); i++ ) {
if ( !idStr::Cmp( uiEvaluators[ i ]->GetName(), name ) ) {
return uiEvaluators[ i ];
}
}
return NULL;
}
/*
================
sdUserInterfaceLocal::CreateEvents
================
*/
void sdUserInterfaceLocal::CreateEvents( const sdDeclGUI* guiDecl, idTokenCache& tokenCache ) {
parseStack.Clear();
const idList< sdDeclGUIProperty* >& guiProperties = guiDecl->GetProperties();
events.Clear();
events.SetNumEvents( GE_NUM_EVENTS );
namedEvents.Clear();
sdUserInterfaceLocal::PushTrace( va( "sdUserInterfaceLocal::CreateEvents for gui '%s'", guiDecl->GetName() ));
idList<unsigned short> constructorTokens;
bool hasValues = sdDeclGUI::CreateConstructor( guiDecl->GetProperties(), constructorTokens, tokenCache );
if( hasValues ) {
sdUserInterfaceLocal::PushTrace( "<constructor>" );
idLexer parser( sdDeclGUI::LEXER_FLAGS );
parser.LoadTokenStream( constructorTokens, tokenCache, "sdUserInterfaceLocal::CreateEvents" );
sdUIEventInfo constructionEvent( GE_CONSTRUCTOR, 0 );
GetScript().ParseEvent( &parser, constructionEvent, &scriptState );
RunEvent( constructionEvent );
sdUserInterfaceLocal::PopTrace();
}
if( guiDecl->GetTimelines().GetNumTimelines() > 0 ) {
timelines.Reset( new sdUITimelineManager( *this, scriptState, script ));
timelines->CreateTimelines( guiDecl->GetTimelines(), guiDecl );
timelines->CreateProperties( guiDecl->GetTimelines(), guiDecl, tokenCache );
}
const idList< sdDeclGUIEvent* >& guiEvents = guiDecl->GetEvents();
idList< sdUIEventInfo > eventList;
for ( int i = 0; i < guiEvents.Num(); i++ ) {
const sdDeclGUIEvent* eventInfo = guiEvents[ i ];
sdUserInterfaceLocal::PushTrace( tokenCache[ eventInfo->GetName() ] );
eventList.Clear();
EnumerateEvents( tokenCache[ eventInfo->GetName() ], eventInfo->GetFlags(), eventList, tokenCache );
for ( int j = 0; j < eventList.Num(); j++ ) {
idLexer parser( sdDeclGUI::LEXER_FLAGS );
parser.LoadTokenStream( eventInfo->GetTokenIndices(), tokenCache, tokenCache[ eventInfo->GetName() ] );
GetScript().ParseEvent( &parser, eventList[ j ], &scriptState );
}
sdUserInterfaceLocal::PopTrace();
}
if( timelines.Get() != NULL ) {
timelines->CreateEvents( guiDecl->GetTimelines(), guiDecl, tokenCache );
}
RunEvent( sdUIEventInfo( GE_CREATE, 0 ) );
}
/*
================
sdUserInterfaceLocal::EnumerateEvents
================
*/
void sdUserInterfaceLocal::EnumerateEvents( const char* name, const idList<unsigned short>& flags, idList< sdUIEventInfo >& events, const idTokenCache& tokenCache ) {
if ( !idStr::Icmp( name, "onActivate" ) ) {
events.Append( sdUIEventInfo( GE_ACTIVATE, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onDeactivate" ) ) {
events.Append( sdUIEventInfo( GE_DEACTIVATE, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onCancel" ) ) {
events.Append( sdUIEventInfo( GE_CANCEL, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onNamedEvent" ) ) {
int i;
for ( i = 0; i < flags.Num(); i++ ) {
events.Append( sdUIEventInfo( GE_NAMED, NamedEventHandleForString( tokenCache[ flags[ i ] ] ) ) );
}
return;
}
if( !idStr::Icmp( name, "onCVarChanged" ) ) {
int i;
for( i = 0; i < flags.Num(); i++ ) {
const idToken& name = tokenCache[ flags[ i ] ];
idCVar* cvar = cvarSystem->Find( name.c_str() );
if( cvar == NULL ) {
gameLocal.Error( "Event 'onCVarChanged' could not find cvar '%s'", name.c_str() );
return;
}
int eventHandle = NamedEventHandleForString( name.c_str() );
cvarCallback_t* callback = new cvarCallback_t( *this, *cvar, eventHandle );
cvarCallbacks.Append( callback );
events.Append( sdUIEventInfo( GE_CVARCHANGED, eventHandle ) );
}
return;
}
if ( !idStr::Icmp( name, "onToolTipEvent" ) ) {
events.Append( sdUIEventInfo( GE_TOOLTIPEVENT, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onPropertyChanged" ) ) {
int i;
for ( i = 0; i < flags.Num(); i++ ) {
const idToken& name = tokenCache[ flags[ i ] ];
// do a proper lookup, so windows can watch guis and vice-versa
idLexer p( sdDeclGUI::LEXER_FLAGS );
p.LoadMemory( name, name.Length(), "onPropertyChanged event handler" );
sdUserInterfaceScope* propertyScope = gameLocal.GetUserInterfaceScope( GetState(), &p );
idToken token;
p.ReadToken( &token );
sdProperty* prop = propertyScope->GetProperty( token );
if( !prop ) {
gameLocal.Error( "sdUserInterfaceLocal::EnumerateEvents: event 'onPropertyChanged' could not find property '%s'", name.c_str() );
return;
}
int eventHandle = NamedEventHandleForString( name.c_str() );
int cbHandle = -1;
switch( prop->GetValueType() ) {
case PT_VEC4:
cbHandle = prop->value.vec4Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec4&, const idVec4& >( &sdUserInterfaceLocal::OnVec4PropertyChanged, this , eventHandle ) );
break;
case PT_VEC3:
cbHandle = prop->value.vec3Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec3&, const idVec3& >( &sdUserInterfaceLocal::OnVec3PropertyChanged, this , eventHandle ) );
break;
case PT_VEC2:
cbHandle = prop->value.vec2Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec2&, const idVec2& >( &sdUserInterfaceLocal::OnVec2PropertyChanged, this , eventHandle ) );
break;
case PT_INT:
cbHandle = prop->value.intValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const int, const int >( &sdUserInterfaceLocal::OnIntPropertyChanged, this , eventHandle ) );
break;
case PT_FLOAT:
cbHandle = prop->value.floatValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const float, const float >( &sdUserInterfaceLocal::OnFloatPropertyChanged, this , eventHandle ) );
break;
case PT_STRING:
cbHandle = prop->value.stringValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idStr&, const idStr& >( &sdUserInterfaceLocal::OnStringPropertyChanged, this , eventHandle ) );
break;
case PT_WSTRING:
cbHandle = prop->value.wstringValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idWStr&, const idWStr& >( &sdUserInterfaceLocal::OnWStringPropertyChanged, this , eventHandle ) );
break;
}
toDisconnect.Append( callbackHandler_t( prop, cbHandle ));
events.Append( sdUIEventInfo( GE_PROPCHANGED, eventHandle ) );
}
return;
}
gameLocal.Error( "sdUserInterfaceLocal::EnumerateEvents: unknown event '%s'", name );
}
/*
================
sdUserInterfaceLocal::Activate
================
*/
void sdUserInterfaceLocal::Activate( void ) {
if( !guiDecl ) {
return;
}
if ( flags.isActive ) {
return;
}
flags.isActive = true;
CancelToolTip();
if ( NonGameGui() ) {
SetCurrentTime( sys->Milliseconds() );
} else {
SetCurrentTime( gameLocal.time + gameLocal.timeOffset );
}
Update();
if( timelines.Get() != NULL ) {
timelines->ResetAllTimelines();
}
int i;
for ( i = 0; i < windows.Num(); i++ ) {
sdUIObject* object = windows.FindIndex( i )->second;
if( sdUIWindow* window = object->Cast< sdUIWindow >() ) {
window->OnActivate();
}
}
RunEvent( sdUIEventInfo( GE_ACTIVATE, 0 ) );
}
/*
================
sdUserInterfaceLocal::Deactivate
================
*/
void sdUserInterfaceLocal::Deactivate( bool forceDeactivate ) {
if( !guiDecl ) {
return;
}
if ( !flags.isActive || ( !forceDeactivate && !TestGUIFlag( GUI_SCREENSAVER ) )) {
return;
}
flags.isActive = false;
if( timelines.Get() != NULL ) {
timelines->ClearAllTimelines();
}
RunEvent( sdUIEventInfo( GE_DEACTIVATE, 0 ) );
}
/*
================
sdUserInterfaceLocal::Update
================
*/
void sdUserInterfaceLocal::Update( void ) {
if ( !IsActive() ) {
return;
}
guiTime.SetReadOnly( false );
guiTime = currentTime;
guiTime.SetReadOnly( true );
screenDimensions.SetReadOnly( false );
screenCenter.SetReadOnly( false );
if ( TestGUIFlag( GUI_FULLSCREEN ) ) {
float adjustedWidth = idMath::Ceil( SCREEN_WIDTH * ( 1.0f / deviceContext->GetAspectRatioCorrection() ) );
screenDimensions.SetIndex( 0, adjustedWidth );
} else {
screenDimensions.SetIndex( 0, SCREEN_WIDTH );
}
screenCenter.SetIndex( 0 , screenDimensions.GetValue().x / 2.0f );
screenCenter.SetReadOnly( true );
screenDimensions.SetReadOnly( true );
if ( timelines.Get() != NULL ) {
timelines->Run( currentTime );
}
for ( int i = 0; i < timelineWindows.Num(); i++ ) {
sdUITimelineManager* manager = timelineWindows[ i ]->GetTimelineManager();
manager->Run( currentTime );
}
scriptState.Update();
}
/*
================
sdUserInterfaceLocal::AddEvent
================
*/
void sdUserInterfaceLocal::AddEvent( const sdUIEventInfo& info, sdUIEventHandle scriptHandle ) {
events.AddEvent( info, scriptHandle );
}
/*
================
sdUserInterfaceLocal::GetEvent
================
*/
sdUIEventHandle sdUserInterfaceLocal::GetEvent( const sdUIEventInfo& info ) const {
return events.GetEvent( info );
}
/*
============
sdUserInterfaceLocal::RunEvent
============
*/
bool sdUserInterfaceLocal::RunEvent( const sdUIEventInfo& info ) {
return GetScript().RunEventHandle( GetEvent( info ), &scriptState );
}
/*
============
sdUserInterfaceLocal::SetFocus
============
*/
void sdUserInterfaceLocal::SetFocus( sdUIWindow* focus ) {
if( focusedWindow == focus ) {
return;
}
if( focusedWindow ) {
focusedWindow->OnLoseFocus();
}
focusedWindow = focus;
if( focusedWindow ) {
focusedWindow->OnGainFocus();
}
}
/*
============
sdUserInterfaceLocal::OnCursorMaterialNameChanged
============
*/
void sdUserInterfaceLocal::OnCursorMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.Length() ) {
cursorMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue ));
if( cursorMaterial && cursorMaterial->GetSort() < SS_POST_PROCESS ) {
if ( cursorMaterial->GetSort() != SS_GUI && cursorMaterial->GetSort() != SS_NEAREST ) {
gameLocal.Warning( "sdUserInterfaceLocal::OnCursorMaterialNameChanged: material %s used in gui '%s' without proper sort", cursorMaterial->GetName(), GetName() );
}
}
} else {
cursorMaterial = NULL;
}
}
/*
============
sdUserInterfaceLocal::OnPostProcessMaterialNameChanged
============
*/
void sdUserInterfaceLocal::OnPostProcessMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.Length() ) {
postProcessMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue ));
} else {
postProcessMaterial = NULL;
}
}
/*
============
sdUserInterfaceLocal::OnFocusedWindowNameChanged
============
*/
void sdUserInterfaceLocal::OnFocusedWindowNameChanged( const idStr& oldValue, const idStr& newValue ) {
SetFocus( GetWindow( newValue )->Cast< sdUIWindow >() );
if( newValue.Length() && !focusedWindow ) {
gameLocal.Warning( "sdUserInterfaceLocal::OnFocusedWindowNameChanged: '%s' could not find windowDef '%s' for focus", GetName(), newValue.c_str() );
}
}
/*
============
sdUserInterfaceLocal::OnOnScreenSaverMaterialNameChanged
============
*/
void sdUserInterfaceLocal::OnScreenSaverMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.Length() ) {
screenSaverMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue ));
} else {
screenSaverMaterial = NULL;
}
}
/*
============
sdUserInterfaceLocal::SetRenderCallback
============
*/
void sdUserInterfaceLocal::SetRenderCallback( const char* objectName, uiRenderCallback_t callback, uiRenderCallbackType_t type ) {
sdUIWindow* object = GetWindow( objectName )->Cast< sdUIWindow >();
if( object == NULL ) {
gameLocal.Error( "sdUserInterfaceLocal::SetRenderCallback: could not find window '%s'", objectName );
}
object->SetRenderCallback( callback, type );
}
/*
============
sdUserInterfaceLocal::PostNamedEvent
============
*/
bool sdUserInterfaceLocal::PostNamedEvent( const char* event, bool allowMissing ) {
assert( event );
int index = namedEvents.FindIndex( event );
if( index == -1 ) {
if( !allowMissing ) {
gameLocal.Error( "sdUserInterfaceLocal::PostNamedEvent: could not find event '%s' in '%s'", event, guiDecl != NULL ? guiDecl->GetName() : "unknown GUI" );
}
return false;
}
if( g_debugGUIEvents.GetBool() ) {
gameLocal.Printf( "GUI '%s': named event '%s'\n", GetName(), event );
}
return RunEvent( sdUIEventInfo( GE_NAMED, index ) );
}
/*
============
sdUserInterfaceLocal::NamedEventHandleForString
============
*/
int sdUserInterfaceLocal::NamedEventHandleForString( const char* name ) {
int index = namedEvents.FindIndex( name );
if( index == -1 ) {
index = namedEvents.Append( name ) ;
}
return index;
}
/*
============
sdUserInterfaceLocal::OnStringPropertyChanged
============
*/
void sdUserInterfaceLocal::OnStringPropertyChanged( int event, const idStr& oldValue, const idStr& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnWStringPropertyChanged
============
*/
void sdUserInterfaceLocal::OnWStringPropertyChanged( int event, const idWStr& oldValue, const idWStr& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnIntPropertyChanged
============
*/
void sdUserInterfaceLocal::OnIntPropertyChanged( int event, const int oldValue, const int newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnFloatPropertyChanged
============
*/
void sdUserInterfaceLocal::OnFloatPropertyChanged( int event, const float oldValue, const float newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnVec4PropertyChanged
============
*/
void sdUserInterfaceLocal::OnVec4PropertyChanged( int event, const idVec4& oldValue, const idVec4& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnVec3PropertyChanged
============
*/
void sdUserInterfaceLocal::OnVec3PropertyChanged( int event, const idVec3& oldValue, const idVec3& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnVec2PropertyChanged
============
*/
void sdUserInterfaceLocal::OnVec2PropertyChanged( int event, const idVec2& oldValue, const idVec2& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::SetCursor
============
*/
void sdUserInterfaceLocal::SetCursor( const int x, const int y ) {
idVec2 pos( idMath::ClampInt( 0, SCREEN_WIDTH, x ), idMath::ClampInt( 0, SCREEN_HEIGHT, y ) );
cursorPos = pos;
}
/*
============
sdUserInterfaceLocal::SetTheme
============
*/
void sdUserInterfaceLocal::SetTheme( const char* theme ) {
const sdDeclGUITheme* newTheme = gameLocal.declGUIThemeType.LocalFind( theme, false );
if( !newTheme ) {
newTheme = gameLocal.declGUIThemeType.LocalFind( "default", true );
}
if( this->theme != newTheme ) {
bool isActive = IsActive();
if ( isActive ) {
Deactivate( true );
}
this->theme = newTheme;
if ( guiDecl != NULL ) {
declManager->AddDependency( GetDecl(), newTheme );
// regenerate
idStr name = guiDecl->GetName();
guiDecl = NULL;
Clear();
Load( name );
}
if ( isActive ) {
Activate();
}
}
}
/*
============
sdUserInterfaceLocal::GetMaterial
============
*/
const char* sdUserInterfaceLocal::GetMaterial( const char* key ) const {
if( key[ 0 ] == '\0' ) {
return "";
}
const char* out = GetDecl() ? GetDecl()->GetMaterials().GetString( key, "" ) : "";
if( out[ 0 ] == '\0' && GetTheme() ) {
out = GetTheme()->GetMaterial( key );
}
return out;
}
/*
============
sdUserInterfaceLocal::GetSound
============
*/
const char* sdUserInterfaceLocal::GetSound( const char* key ) const {
if( key[ 0 ] == '\0' ) {
return "";
}
if( idStr::Icmpn( key, "::", 2 ) == 0 ) {
return key + 2;
}
const char* out = GetDecl() ? GetDecl()->GetSounds().GetString( key, "" ) : "";
if( out[ 0 ] == '\0' && GetTheme() ) {
out = GetTheme()->GetSound( key );
}
return out;
}
/*
============
sdUserInterfaceLocal::GetColor
============
*/
idVec4 sdUserInterfaceLocal::GetColor( const char* key ) const {
if( key[ 0 ] == '\0' ) {
return colorWhite;
}
idVec4 out;
if( !GetDecl() || !GetDecl()->GetColors().GetVec4( key, "1 1 1 1", out ) && GetTheme() ) {
out = GetTheme()->GetColor( key );
}
return out;
}
/*
============
sdUserInterfaceLocal::ApplyLatchedTheme
============
*/
void sdUserInterfaceLocal::ApplyLatchedTheme() {
if ( latchedTheme.Length() > 0 ) {
SetTheme( latchedTheme );
latchedTheme.Clear();
}
}
/*
============
sdUserInterfaceLocal::OnThemeNameChanged
============
*/
void sdUserInterfaceLocal::OnThemeNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.IsEmpty() ) {
latchedTheme = "default";
} else {
latchedTheme = newValue;
}
}
/*
============
sdUserInterfaceLocal::OnBindContextChanged
============
*/
void sdUserInterfaceLocal::OnBindContextChanged( const idStr& oldValue, const idStr& newValue ) {
if ( newValue.IsEmpty() ) {
bindContext = NULL;
} else {
bindContext = keyInputManager->AllocBindContext( newValue.c_str() );
}
}
/*
============
sdUserInterfaceLocal::OnScreenDimensionChanged
============
*/
void sdUserInterfaceLocal::OnScreenDimensionChanged( const idVec2& oldValue, const idVec2& newValue ) {
windowHash_t::Iterator iter = windows.Begin();
while( iter != windows.End() ) {
if( sdUIWindow* window = iter->second->Cast< sdUIWindow >() ) {
window->MakeLayoutDirty();
}
++iter;
}
}
/*
============
sdUserInterfaceLocal::Translate
============
*/
bool sdUserInterfaceLocal::Translate( const idKey& key, sdKeyCommand** cmd ) {
if ( bindContext == NULL ) {
return false;
}
*cmd = keyInputManager->GetCommand( bindContext, key );
return *cmd != NULL;
}
/*
============
sdUserInterfaceLocal::EndLevelLoad
============
*/
void sdUserInterfaceLocal::EndLevelLoad() {
uiMaterialCache_t::Iterator cacheIter= materialCache.Begin();
while( cacheIter != materialCache.End() ) {
uiCachedMaterial_t& cached = *( cacheIter->second );
LookupPartSizes( cached.parts.Begin(), cached.parts.Num() );
SetupMaterialInfo( cached.material );
++cacheIter;
}
windowHash_t::Iterator iter = windows.Begin();
while( iter != windows.End() ) {
iter->second->EndLevelLoad();
++iter;
}
}
/*
============
sdUserInterfaceLocal::PopGeneralScriptVar
============
*/
void sdUserInterfaceLocal::PopGeneralScriptVar( const char* stackName, idStr& str ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::PopGeneralScriptVar: empty stack name" );
}
stringStack_t& stack = generalStacks[ stackName ];
if( stack.Num() == 0 ) {
gameLocal.Error( "sdUserInterfaceLocal::PopGeneralScriptVar: stack underflow for '%s'", stackName );
}
int index = stack.Num() - 1;
str = stack[ index ];
stack.SetNum( index );
}
/*
============
sdUserInterfaceLocal::PushGeneralScriptVar
============
*/
void sdUserInterfaceLocal::PushGeneralScriptVar( const char* stackName, const char* str ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::PushGeneralScriptVar: empty stack name" );
}
generalStacks[ stackName ].Append( str );
}
/*
============
sdUserInterfaceLocal::GetGeneralScriptVar
============
*/
void sdUserInterfaceLocal::GetGeneralScriptVar( const char* stackName, idStr& str ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::GetGeneralScriptVar: empty stack name" );
}
stringStack_t& stack = generalStacks[ stackName ];
if( stack.Num() == 0 ) {
gameLocal.Error( "sdUserInterfaceLocal::GetGeneralScriptVar: stack underflow for '%s'", stackName );
}
int index = stack.Num() - 1;
str = stack[ index ];
}
/*
============
sdUserInterfaceLocal::ClearGeneralStrings
============
*/
void sdUserInterfaceLocal::ClearGeneralStrings( const char* stackName ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::ClearGeneralStrings: empty stack name" );
}
stringStack_t& stack = generalStacks[ stackName ];
stack.Clear();
}
/*
============
sdUserInterfaceLocal::OnCVarChanged
============
*/
void sdUserInterfaceLocal::OnCVarChanged( idCVar& cvar, int id ) {
bool result = RunEvent( sdUIEventInfo( GE_CVARCHANGED, id ) );
if( result && sdUserInterfaceLocal::g_debugGUIEvents.GetInteger() ) {
gameLocal.Printf( "%s: OnCVarChanged\n", GetName() );
}
}
/*
============
sdUserInterfaceLocal::OnInputInit
============
*/
void sdUserInterfaceLocal::OnInputInit( void ) {
if ( bindContextName.GetValue().IsEmpty() ) {
bindContext = NULL;
} else {
bindContext = keyInputManager->AllocBindContext( bindContextName.GetValue().c_str() );
}
}
/*
============
sdUserInterfaceLocal::OnInputShutdown
============
*/
void sdUserInterfaceLocal::OnInputShutdown( void ) {
bindContext = NULL;
}
/*
============
sdUserInterfaceLocal::OnLanguageInit
============
*/
void sdUserInterfaceLocal::OnLanguageInit( void ) {
if ( desktop != NULL ) {
desktop->OnLanguageInit();
sdUIObject::OnLanguageInit_r( desktop );
}
}
/*
============
sdUserInterfaceLocal::OnLanguageShutdown
============
*/
void sdUserInterfaceLocal::OnLanguageShutdown( void ) {
if ( desktop != NULL ) {
desktop->OnLanguageShutdown();
sdUIObject::OnLanguageShutdown_r( desktop );
}
}
/*
============
sdUserInterfaceLocal::MakeLayoutDirty
============
*/
void sdUserInterfaceLocal::MakeLayoutDirty() {
if ( desktop != NULL ) {
desktop->MakeLayoutDirty();
sdUIObject::MakeLayoutDirty_r( desktop );
}
}
/*
============
sdUserInterfaceLocal::SetCachedMaterial
============
*/
uiMaterialCache_t::Iterator sdUserInterfaceLocal::SetCachedMaterial( const char* alias, const char* newMaterial, int& handle ) {
uiMaterialCache_t::Iterator findResult = FindCachedMaterial( alias, handle );
if( findResult == materialCache.End() ) {
uiMaterialCache_t::InsertResult result = materialCache.Set( alias, materialCacheAllocator.Alloc() );
findResult = result.first;
}
handle = findResult - materialCache.Begin();
uiCachedMaterial_t& cached = *( findResult->second );
idStr material;
bool globalLookup = false;
bool literal = false;
int offset = ParseMaterial( newMaterial, material, globalLookup, literal, cached.drawMode );
if( cached.drawMode != BDM_SINGLE_MATERIAL && cached.drawMode != BDM_USE_ST ) {
InitPartsForBaseMaterial( material, cached );
return findResult;
}
if( globalLookup ) {
material = "::" + material;
}
if( literal ) {
LookupMaterial( va( "literal: %hs", newMaterial + offset ), cached.material );
} else if( ( material.Length() && !globalLookup ) || ( material.Length() > 2 && globalLookup ) ) {
LookupMaterial( material, cached.material );
}
return findResult;
}
/*
============
sdUserInterfaceLocal::FindCachedMaterial
============
*/
uiMaterialCache_t::Iterator sdUserInterfaceLocal::FindCachedMaterial( const char* alias, int& handle ) {
uiMaterialCache_t::Iterator iter = materialCache.Find( alias );
if( iter == materialCache.End() ) {
handle = -1;
} else {
handle = iter - materialCache.Begin();
}
return iter;
}
/*
============
sdUserInterfaceLocal::FindCachedMaterialForHandle
============
*/
uiMaterialCache_t::Iterator sdUserInterfaceLocal::FindCachedMaterialForHandle( int handle ) {
if( handle < 0 || handle >= materialCache.Num() ) {
return materialCache.End();
}
return materialCache.Begin() + handle;
}
/*
============
sdUserInterfaceLocal::LookupPartSizes
============
*/
void sdUserInterfaceLocal::LookupPartSizes( uiDrawPart_t* parts, int num ) {
for ( int i= 0; i < num; i++ ) {
uiDrawPart_t& part = parts[ i ];
if ( part.mi.material == NULL || ( part.width != 0 && part.height != 0 ) ) {
continue;
}
if ( part.mi.material->GetNumStages() == 0 ) {
part.mi.material = NULL;
continue;
}
SetupMaterialInfo( part.mi, &part.width, &part.height );
if ( part.width == 0 || part.height == 0 ) {
assert( 0 );
part.mi.material = NULL;
}
}
}
/*
============
sdUserInterfaceLocal::SetupMaterialInfo
============
*/
void sdUserInterfaceLocal::SetupMaterialInfo( uiMaterialInfo_t& mi, int* baseWidth, int* baseHeight ) {
if( mi.material == NULL ) {
return;
}
if( const idImage* image = mi.material->GetEditorImage() ) {
if( image->sourceWidth == 0 ) { // the image hasn't been loaded yet, so defer texture coordinate calculation
mi.flags.lookupST = true;
return;
}
}
if( !mi.flags.lookupST ) {
return;
}
if( const idImage* image = mi.material->GetEditorImage() ) {
// if they're zeroed assume 0-1 range
if( mi.st0.Compare( vec2_zero, idMath::FLT_EPSILON ) && mi.st1.Compare( vec2_zero, idMath::FLT_EPSILON ) ) {
mi.st0.Set( 0.0f, 0.0f );
mi.st1.Set( 1.0f, 1.0f );
if( baseWidth != NULL ) {
*baseWidth = image->sourceWidth;
}
if( baseHeight != NULL ) {
*baseHeight = image->sourceHeight;
}
} else {
if( baseWidth != NULL ) {
*baseWidth = idMath::Ftoi( mi.st1.x );
}
if( baseHeight != NULL ) {
*baseHeight = idMath::Ftoi( mi.st1.y );
}
mi.st0.x = mi.st0.x / static_cast< float >( image->sourceWidth );
mi.st0.y = mi.st0.y / static_cast< float >( image->sourceHeight );
mi.st1.x = mi.st0.x + ( mi.st1.x / static_cast< float >( image->sourceWidth ) );
mi.st1.y = mi.st0.y + ( mi.st1.y / static_cast< float >( image->sourceHeight ) );
}
}
if( mi.flags.flipX ) {
idSwap( mi.st0.x, mi.st1.x );
}
if( mi.flags.flipY ) {
idSwap( mi.st0.y, mi.st1.y );
}
mi.flags.lookupST = false;
}
/*
============
sdUserInterfaceLocal::ParseMaterial
============
*/
int sdUserInterfaceLocal::ParseMaterial( const char* mat, idStr& outMaterial, bool& globalLookup, bool& literal, uiDrawMode_e& mode ) {
idLexer src( mat, idStr::Length( mat ), "ParseMaterial", LEXFL_ALLOWPATHNAMES );
idToken token;
outMaterial.Empty();
globalLookup = false;
literal = false;
mode = BDM_SINGLE_MATERIAL;
int materialStart = 0;
while( !src.HadError() ) {
materialStart = src.GetFileOffset();
if( !src.ReadToken( &token )) {
break;
}
if( token.Icmp( "literal:" ) == 0 ) {
literal = true;
continue;
}
if( token.Icmp( "_frame" ) == 0 ) {
mode = BDM_FRAME;
continue;
}
if( token.Icmp( "_st" ) == 0 ) {
mode = BDM_USE_ST;
continue;
}
if( token.Icmp( "_3v" ) == 0 ) {
mode = BDM_TRI_PART_V;
continue;
}
if( token.Icmp( "_3h" ) == 0 ) {
mode = BDM_TRI_PART_H;
continue;
}
if( token.Icmp( "_5h" ) == 0 ) {
mode = BDM_FIVE_PART_H;
continue;
}
if( token == "::" ) {
globalLookup = true;
continue;
}
outMaterial = token;
break;
}
return materialStart;
}
/*
============
sdUserInterfaceLocal::InitPartsForBaseMaterial
============
*/
void sdUserInterfaceLocal::InitPartsForBaseMaterial( const char* material, uiCachedMaterial_t& cached ) {
cached.parts.SetNum( FP_MAX );
if( cached.drawMode == BDM_FIVE_PART_H ) {
SetupPart( cached.parts[ FP_TOPLEFT ], partNames[ FP_TOPLEFT ], material );
SetupPart( cached.parts[ FP_LEFT ], partNames[ FP_LEFT ], material ); // stretched
SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material );
SetupPart( cached.parts[ FP_RIGHT ], partNames[ FP_RIGHT ], material ); // stretched
SetupPart( cached.parts[ FP_TOPRIGHT ], partNames[ FP_TOPRIGHT ], material );
return;
}
if( cached.drawMode == BDM_TRI_PART_H ) {
SetupPart( cached.parts[ FP_LEFT ], partNames[ FP_LEFT ], material );
SetupPart( cached.parts[ FP_RIGHT ], partNames[ FP_RIGHT ], material );
SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material );
return;
}
if( cached.drawMode == BDM_TRI_PART_V ) {
SetupPart( cached.parts[ FP_TOP ], partNames[ FP_TOP ], material );
SetupPart( cached.parts[ FP_BOTTOM ], partNames[ FP_BOTTOM ], material );
SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material );
return;
}
for( int i = 0; i < FP_MAX; i++ ) {
SetupPart( cached.parts[ i ], partNames[ i ], material );
}
}
/*
============
sdUserInterfaceLocal::SetupPart
============
*/
void sdUserInterfaceLocal::SetupPart( uiDrawPart_t& part, const char* partName, const char* material ) {
if( idStr::Length( material ) == 0 ) {
part.mi.material = NULL;
part.width = 0;
part.height = 0;
return;
}
LookupMaterial( va( "%s_%s", material, partName ), part.mi, &part.width, &part.height );
if( part.mi.material->GetNumStages() == 0 ) {
part.mi.material = NULL;
part.width = 0;
part.height = 0;
return;
}
}
/*
============
sdUserInterfaceLocal::LookupMaterial
============
*/
void sdUserInterfaceLocal::LookupMaterial( const char* materialName, uiMaterialInfo_t& mi, int* baseWidth, int* baseHeight ) {
mi.Clear();
bool globalLookup = false;
static const char* LITERAL_ID = "literal:";
static const int LITERAL_ID_LENGTH = idStr::Length( LITERAL_ID );
bool literal = !idStr::Icmpn( LITERAL_ID, materialName, LITERAL_ID_LENGTH );
if( !literal ) {
globalLookup = !idStr::Icmpn( "::", materialName, 2 );
if( globalLookup ) {
materialName += 2;
}
}
if( globalLookup ) {
if(idStr::Length( materialName ) == 0 ) {
mi.material = declHolder.FindMaterial( "_default" );
} else {
mi.material = declHolder.FindMaterial( materialName );
}
} else {
const char* materialInfo = materialName;
if( literal ) {
materialInfo += LITERAL_ID_LENGTH;
} else {
materialInfo = GetMaterial( materialName );
}
idToken token;
char buffer[128];
token.SetStaticBuffer( buffer, sizeof(buffer) );
idLexer src( materialInfo, idStr::Length( materialInfo ), "LookupMaterial", LEXFL_ALLOWPATHNAMES );
src.ReadToken( &token ); // material name
if( token.Length() == 0 ) {
mi.material = declHolder.FindMaterial( "_default" );
} else {
mi.material = declHolder.FindMaterial( token );
}
while( src.ReadToken( &token )) {
if( token == "," ) {
continue;
}
if( token.Icmp( "flipX" ) == 0 ) {
mi.flags.flipX = true;
continue;
}
if( token.Icmp( "flipY" ) == 0 ) {
mi.flags.flipY = true;
continue;
}
static idVec4 vec;
if( token.Icmp( "rect" ) == 0 ) {
src.Parse1DMatrix( 4, vec.ToFloatPtr(), true );
mi.st0.x = vec.x;
mi.st0.y = vec.y;
mi.st1.x = vec.z;
mi.st1.y = vec.w;
continue;
}
src.Error( "Unknown token '%s'", token.c_str() );
break;
}
}
if ( mi.material->GetSort() < SS_POST_PROCESS ) {
if ( mi.material->GetSort() != SS_GUI && mi.material->GetSort() != SS_NEAREST ) {
gameLocal.Warning( "LookupMaterial: '%s' material '%s' (alias '%s') used without proper sort", GetName(), mi.material->GetName(), materialName );
}
}
mi.flags.lookupST = true;
SetupMaterialInfo( mi, baseWidth, baseHeight );
}
/*
============
sdUserInterfaceLocal::PushColor
============
*/
void sdUserInterfaceLocal::PushColor( const idVec4& color ) {
currentColor = color;
colorStack.Push( deviceContext->SetColorMultiplier( color ) );
}
/*
============
sdUserInterfaceLocal::PopColor
============
*/
idVec4 sdUserInterfaceLocal::PopColor() {
idVec4 c = colorStack.Top();
deviceContext->SetColorMultiplier( c );
colorStack.Pop();
currentColor = c;
return c;
}
/*
============
sdUserInterfaceLocal::TopColor
============
*/
const idVec4& sdUserInterfaceLocal::TopColor() const{
return currentColor;
}
/*
============
sdUserInterfaceLocal::OnSnapshotHitch
============
*/
void sdUserInterfaceLocal::OnSnapshotHitch( int delta ) {
scriptState.OnSnapshotHitch( delta );
if( timelines.IsValid() ) {
timelines->OnSnapshotHitch( delta );
}
}
/*
============
sdUserInterfaceLocal::OnToolTipEvent
============
*/
void sdUserInterfaceLocal::OnToolTipEvent( const char* arg ) {
sdUIEventInfo event( GE_TOOLTIPEVENT, 0 );
if ( event.eventType.IsValid() ) {
PushScriptVar( arg );
RunEvent( sdUIEventInfo( GE_TOOLTIPEVENT, 0 ) );
ClearScriptStack();
}
}
| 28.907164
| 208
| 0.64534
|
JasonHutton
|
211beb59677d3c88fe37fd2d46ea5ced20f24cd1
| 7,492
|
cpp
|
C++
|
source/Structure/custom_plugins/plugins/HIL_server/server.cpp
|
Guiraffo/ProVANT_Simulator
|
ef2260204b13f39a9f83ad2ab88a9552a0699bff
|
[
"MIT"
] | null | null | null |
source/Structure/custom_plugins/plugins/HIL_server/server.cpp
|
Guiraffo/ProVANT_Simulator
|
ef2260204b13f39a9f83ad2ab88a9552a0699bff
|
[
"MIT"
] | null | null | null |
source/Structure/custom_plugins/plugins/HIL_server/server.cpp
|
Guiraffo/ProVANT_Simulator
|
ef2260204b13f39a9f83ad2ab88a9552a0699bff
|
[
"MIT"
] | null | null | null |
#include "server.h"
#include <time.h>
#include "XMLRead.h"
namespace gazebo
{
HilServer::HilServer()
{
Fr = 0;
Fl = 0;
Tr = 0;
Tl = 0;
}
HilServer::~HilServer()
{
try
{
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
void HilServer::Update()
{
// static int i = 0;
// mutex.lock();
std::lock_guard<std::mutex> lck(mtx);
SetInputVANT20(Fr, Fl, Tr, Tl);
// std::cout << "Fr: " << Fr << std::endl;
// std::cout << "Fl: " << Fl << std::endl;
// std::cout << "Tr: " << Tr << std::endl;
// std::cout << "Tl: " << Tl << std::endl;
// mutex.unlock();
// i++;
// std::cout << "Contador: " << i << std::endl;
}
void HilServer::thread()
{
struct timespec start, stop;
std::chrono::high_resolution_clock::time_point tf;
std::chrono::high_resolution_clock::time_point tf2;
std::chrono::high_resolution_clock::time_point to;
std::chrono::high_resolution_clock::time_point to2;
// clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
to = std::chrono::high_resolution_clock::now();
to2 = to;
while (true)
{
Frame frame;
frame = receive(serial);
if (frame.unbuild())
{
float flag = frame.getFloat();
if (flag == 1) // Envia os estados
{
// std::cout << "1" << std::endl;
// clock_gettime(CLOCK_REALTIME, &stop);
/*double result = (stop.tv_sec - start.tv_sec) * 1e3 + (stop.tv_nsec - start.tv_nsec) / 1e6; // in
microseconds std::cout << result << std::endl; clock_gettime(CLOCK_REALTIME, &start);*/
// depois
tf = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::nano> delta_t = tf - to;
std::chrono::duration<double, std::nano> delta_t2 = tf - to2;
// std::chrono::duration<double,std::ratio<1l,1000000l>> delta_t =
// std::chrono::duration_cast<std::chrono::miliseconds>(tf - to);
std::cout << delta_t.count() / 1000000.0 << "," << delta_t2.count() / 1000000000.0 << ",";
// std::cout << model->GetWorld()->GetRealTime().FormattedString() << ",";
// antes
to = tf;
GetStatesVANT20();
SetSerialData();
}
else
{
if (flag == 0) // se 0
{
// std::cout << "0" << std::endl;
// mutex.lock();
std::lock_guard<std::mutex> lck(mtx);
Fr = frame.getFloat();
Fl = frame.getFloat();
Tr = frame.getFloat();
Tl = frame.getFloat();
std::cout << Fr << ",";
std::cout << Fl << ",";
std::cout << Tr << ",";
std::cout << Tl << std::endl;
// mutex.unlock();
}
else
{
if (flag == 3) // Updates the control inputs
{
std::lock_guard<std::mutex> lck(mtx);
Fr = frame.getFloat();
Fl = frame.getFloat();
Tr = frame.getFloat();
Tl = frame.getFloat();
// Frame frame2;
// frame2.addFloat(3);
// frame2.build();
// serial.send(frame2.buffer(),frame2.buffer_size());
model->GetWorld()->SetPaused(false);
}
else
{
std::cout << "Deu ruim" << std::endl;
}
}
}
}
}
}
void HilServer::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)
{
try
{
model = _model;
// std::cout << "Load" << std::endl;
// conectando comunicação serial
// if (!serial.connect("/tmp/ttyS1",115200)) exit(1);
if (serial.connect("/dev/ttyUSB0", 921600 /*576000*/))
{
// obtendo dados do arquivo de descrição "model.sdf"
NameOfJointR_ = XMLRead::ReadXMLString("NameOfJointR", _sdf);
NameOfJointL_ = XMLRead::ReadXMLString("NameOfJointL", _sdf);
link_name_ = XMLRead::ReadXMLString("bodyName", _sdf);
link_right_ = XMLRead::ReadXMLString("BrushlessR", _sdf);
link_left_ = XMLRead::ReadXMLString("BrushlessL", _sdf);
// apontando ponteiros para acesso a dados do mundo, elo e juntas
world = _model->GetWorld();
link = _model->GetLink(link_name_);
linkR = _model->GetLink(link_right_);
linkL = _model->GetLink(link_left_);
juntaR = _model->GetJoint(NameOfJointR_);
juntaL = _model->GetJoint(NameOfJointL_);
// Iniciando comunicação serial
t = new boost::thread(boost::bind(&gazebo::HilServer::thread, this));
// configurando temporizador para callback
updateConnection = event::Events::ConnectWorldUpdateBegin([this](const common::UpdateInfo& info) {
(void)info; // Supress unused variable warning
this->Update();
});
}
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
void HilServer::Reset()
{
}
// Método para enviar dados para o sistema embarcado
void HilServer::SetSerialData()
{
Frame frame;
frame.addFloat(x);
frame.addFloat(y);
frame.addFloat(z);
frame.addFloat(roll);
frame.addFloat(pitch);
frame.addFloat(yaw);
frame.addFloat(alphar);
frame.addFloat(alphal);
frame.addFloat(vx);
frame.addFloat(vy);
frame.addFloat(vz);
frame.addFloat(wx);
frame.addFloat(wy);
frame.addFloat(wz);
frame.addFloat(dalphar);
frame.addFloat(dalphal);
frame.build();
serial.send(frame.buffer(), frame.buffer_size());
// std::cout << "Dados:" << std::endl;
std::cout << x << ",";
std::cout << y << ",";
std::cout << z << ",";
std::cout << roll << ",";
std::cout << pitch << ",";
std::cout << yaw << ",";
std::cout << alphar << ",";
std::cout << alphal << ",";
std::cout << vx << ",";
std::cout << vy << ",";
std::cout << vz << ",";
std::cout << wx << ",";
std::cout << wy << ",";
std::cout << wz << ",";
std::cout << dalphar << ",";
std::cout << dalphal << ",";
}
// Método para Ler dados de simulação
void HilServer::GetStatesVANT20()
{
// dados da pose inicial
ignition::math::Pose3d pose = link->WorldPose();
x = pose.Pos().X(); // x
y = pose.Pos().Y(); // y
z = pose.Pos().Z(); // z
roll = pose.Rot().Euler().X(); // roll
pitch = pose.Rot().Euler().Y(); // pitch
yaw = pose.Rot().Euler().Z(); // yaw
alphar = juntaR->Position(0); // alphaR
alphal = juntaL->Position(0); // alphaL
ignition::math::Vector3d linear = link->WorldLinearVel();
vx = linear.X(); // vx
vy = linear.Y(); // vy
vz = linear.Z(); // vz
ignition::math::Vector3d angular = link->WorldAngularVel();
wx = angular.X(); // wx
wy = angular.Y(); // wy
wz = angular.Z(); // wz
dalphar = juntaR->GetVelocity(0); // dalphaR
dalphal = juntaL->GetVelocity(0); // dalphaL
}
// Método para escrever dados de simulação
void HilServer::SetInputVANT20(double Fr_, double Fl_, double Tr_, double Tl_)
{
// Força de propulsão do motor direito
ignition::math::Vector3d forceR(0, 0, Fr_);
ignition::math::Vector3d torqueR(0, 0, 0.0178947368 * Fr_);
linkR->AddRelativeForce(forceR);
linkR->AddRelativeTorque(torqueR);
// Força de propulsão do motor esquerdo
ignition::math::Vector3d forceL(0, 0, Fl_);
ignition::math::Vector3d torqueL(0, 0, -0.0178947368 * Fl_);
linkL->AddRelativeForce(forceL);
linkL->AddRelativeTorque(torqueL);
// Torque do servo direito
juntaR->SetForce(0, Tr_);
// Torque do servo esquerdo
juntaL->SetForce(0, Tl_);
}
GZ_REGISTER_MODEL_PLUGIN(HilServer)
} // namespace gazebo
| 28.271698
| 109
| 0.565937
|
Guiraffo
|
21226db6b728ae585642f38bf1fefebb733d5f6f
| 1,109
|
cpp
|
C++
|
Source/FactoryGame/FGTrainStationIdentifier.cpp
|
iam-Legend/Project-Assembly
|
1ff3587704232d5e330515bc0d2aceb64ff09a7f
|
[
"MIT"
] | null | null | null |
Source/FactoryGame/FGTrainStationIdentifier.cpp
|
iam-Legend/Project-Assembly
|
1ff3587704232d5e330515bc0d2aceb64ff09a7f
|
[
"MIT"
] | null | null | null |
Source/FactoryGame/FGTrainStationIdentifier.cpp
|
iam-Legend/Project-Assembly
|
1ff3587704232d5e330515bc0d2aceb64ff09a7f
|
[
"MIT"
] | null | null | null |
// This file has been automatically generated by the Unreal Header Implementation tool
#include "FGTrainStationIdentifier.h"
AFGTrainStationIdentifier::AFGTrainStationIdentifier(){ }
void AFGTrainStationIdentifier::GetLifetimeReplicatedProps( TArray< FLifetimeProperty >& OutLifetimeProps) const{ }
void AFGTrainStationIdentifier::PreSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::PostSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::PreLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::PostLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::GatherDependencies_Implementation( TArray< UObject* >& out_dependentObjects){ }
bool AFGTrainStationIdentifier::NeedTransform_Implementation(){ return bool(); }
bool AFGTrainStationIdentifier::ShouldSave_Implementation() const{ return bool(); }
void AFGTrainStationIdentifier::SetStationName( const FText& text){ }
void AFGTrainStationIdentifier::OnRep_StationName(){ }
| 69.3125
| 115
| 0.844905
|
iam-Legend
|
2124cf8ff359f5a282dceaf7782c4d55b2d40165
| 16,693
|
cpp
|
C++
|
Source/Samples/65_PhysicsTest/ConvexCast.cpp
|
extobias/Urho3D
|
7d08ccac1ff9e9e28076ea879530c6b23974ba42
|
[
"MIT"
] | null | null | null |
Source/Samples/65_PhysicsTest/ConvexCast.cpp
|
extobias/Urho3D
|
7d08ccac1ff9e9e28076ea879530c6b23974ba42
|
[
"MIT"
] | null | null | null |
Source/Samples/65_PhysicsTest/ConvexCast.cpp
|
extobias/Urho3D
|
7d08ccac1ff9e9e28076ea879530c6b23974ba42
|
[
"MIT"
] | null | null | null |
#include "ConvexCast.h"
#include <Urho3D/Core/Profiler.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Physics/RigidBody.h>
#include <Urho3D/Physics/CollisionShape.h>
#include <Urho3D/Physics/PhysicsWorld.h>
#include <Urho3D/Physics/PhysicsUtils.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Math/Ray.h>
#include <Urho3D/Editor/EditorModelDebug.h>
#include <Bullet/BulletDynamics/Dynamics/btRigidBody.h>
#include <Bullet/BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
#include <Bullet/BulletCollision/CollisionDispatch/btCollisionWorld.h>
static const btVector3 WHITE(1.0f, 1.0f, 1.0f);
static const btVector3 GREEN(0.0f, 1.0f, 0.0f);
struct AllConvexResultCallback : public btCollisionWorld::ConvexResultCallback
{
AllConvexResultCallback(const btVector3& convexFromWorld, const btVector3& convexToWorld)
:m_convexFromWorld(convexFromWorld),
m_convexToWorld(convexToWorld),
m_hitCollisionObject(0)
{
// URHO3D_LOGERRORF("AllConvexResultCallback ctor <%i>", m_hitPointWorld.size());
}
btVector3 m_convexFromWorld;//used to calculate hitPointWorld from hitFraction
btVector3 m_convexToWorld;
// btVector3 m_hitNormalWorld;
// btVector3 m_hitPointWorld;
const btCollisionObject* m_hitCollisionObject;
btAlignedObjectArray<const btCollisionObject*> m_collisionObjects;
btAlignedObjectArray<btVector3> m_hitNormalWorld;
btAlignedObjectArray<btVector3> m_hitPointWorld;
btAlignedObjectArray<btVector3> m_hitPointLocal;
btAlignedObjectArray<btScalar> m_hitFractions;
btAlignedObjectArray<int> m_hitShapePart;
btAlignedObjectArray<int> m_hitTriangleIndex;
virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)
{
//caller already does the filter on the m_closestHitFraction
// Assert(convexResult.m_hitFraction <= m_closestHitFraction);
//m_closestHitFraction = convexResult.m_hitFraction;
//m_hitCollisionObject = convexResult.m_hitCollisionObject;
//if (normalInWorldSpace)
//{
// m_hitNormalWorld = convexResult.m_hitNormalLocal;
//}
//else
//{
// ///need to transform normal into worldspace
// m_hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;
//}
//m_hitPointWorld = convexResult.m_hitPointLocal;
//return convexResult.m_hitFraction;
// return m_closestHitFraction;
// URHO3D_LOGERRORF("addSingleResult fraction <%f>", convexResult.m_hitFraction);
m_closestHitFraction = convexResult.m_hitFraction;
m_hitCollisionObject = convexResult.m_hitCollisionObject;
m_collisionObjects.push_back(convexResult.m_hitCollisionObject);
btVector3 hitNormalWorld;
if (normalInWorldSpace)
{
hitNormalWorld = convexResult.m_hitNormalLocal;
}
else
{
///need to transform normal into worldspace
hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal;
}
m_hitNormalWorld.push_back(hitNormalWorld);
btVector3 hitPointWorld;
hitPointWorld.setInterpolate3(m_convexFromWorld, m_convexToWorld, convexResult.m_hitFraction);
m_hitPointWorld.push_back(hitPointWorld);
m_hitFractions.push_back(convexResult.m_hitFraction);
m_hitPointLocal.push_back(convexResult.m_hitPointLocal);
if (convexResult.m_localShapeInfo)
{
m_hitShapePart.push_back(convexResult.m_localShapeInfo->m_shapePart);
m_hitTriangleIndex.push_back(convexResult.m_localShapeInfo->m_triangleIndex);
}
else
{
m_hitShapePart.push_back(-1);
m_hitTriangleIndex.push_back(-1);
}
return convexResult.m_hitFraction;
}
};
ConvexCast::ConvexCast(Context* context)
: Component(context),
hasHit_(false),
radius_(0.40f),
hitPointsSize_(0),
hitBody_(nullptr)
{
}
ConvexCast::~ConvexCast()
{
}
void ConvexCast::RegisterObject(Context* context)
{
context->RegisterFactory<ConvexCast>();
}
void ConvexCast::OnNodeSet(Node* node)
{
if (!node)
return;
ResourceCache* cache = GetSubsystem<ResourceCache>();
// auto* wheelObject = shapeNode_->CreateComponent<StaticModel>();
// wheelObject->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl"));
// auto* wheelBody = wheelNode->CreateComponent<RigidBody>();
shape_ = node->CreateComponent<CollisionShape>();
// shape_->SetCylinder(radius_ * 2, radius_, Vector3::ZERO);
shape_->SetSphere(radius_ * 2);
}
void ConvexCast::SetRadius(float r)
{
radius_ = r;
shape_->SetCylinder(radius_ * 2, radius_, Vector3::ZERO);
}
void ConvexCast::UpdateTransform(WheelInfo& wheel, float steeringTimer)
{
// cylinder rotation
Quaternion rot(90.0f, Vector3::FORWARD);
// steering rotation
rot = rot * Quaternion(45.0f * Urho3D::Sign(wheel.steering_) * 1.0f, Vector3::RIGHT);
shape_->SetRotation(rot);
// va relativo al centro del nodo, sino habria que hacer la transformacion con hardPointCS_
// respecto a la posicion/rotacion del nodo
// Quaternion rot = node_->GetRotation();
// hardPointWS_ = node_->GetPosition() + rot * offset_;
}
float ConvexCast::Update(WheelInfo& wheel, RigidBody* hullBody, float steeringTimer, bool debug, bool interpolateNormal)
{
URHO3D_PROFILE(ConvexCastUpdate);
UpdateTransform(wheel, steeringTimer);
Scene* scene = GetScene();
if (!scene)
return 0.0f;
PhysicsWorld* pw = scene->GetComponent<PhysicsWorld>();
btCollisionWorld* world = pw->GetWorld();
Quaternion worldRotation = node_->GetRotation() * shape_->GetRotation();
Vector3 direction = wheel.raycastInfo_.wheelDirectionWS_.Normalized();
// Ray ray(wheel.raycastInfo_.hardPointWS_, wheel.wheelDirectionCS_);
Ray ray(wheel.raycastInfo_.hardPointWS_, direction);
Vector3 startPos = ray.origin_;
Vector3 endPos = ray.origin_ + wheel.raycastInfo_.suspensionLength_ * 1.0f * ray.direction_;
//Vector3 startPos = Vector3(0.0f, 1.0f, 0.0f);
//Vector3 endPos = Vector3(0.0f, -1.0f, 0.0f);
Quaternion startRot = worldRotation;
Quaternion endRot = worldRotation;
AllConvexResultCallback convexCallback(ToBtVector3(startPos), ToBtVector3(endPos));
convexCallback.m_collisionFilterGroup = (short)0xffff;
convexCallback.m_collisionFilterMask = (short)1 << 0;
btCollisionShape* shape = shape_->GetCollisionShape();
world->convexSweepTest(reinterpret_cast<btConvexShape*>(shape),
btTransform(ToBtQuaternion(startRot), convexCallback.m_convexFromWorld),
btTransform(ToBtQuaternion(endRot), convexCallback.m_convexToWorld),
convexCallback, world->getDispatchInfo().m_allowedCcdPenetration);
hasHit_ = false;
hitPointsSize_ = 0;
hitIndex_ = -1;
hitDistance_.Clear();
hitFraction_.Clear();
hitPointWorld_.Clear();
hitNormalWorld_.Clear();
hitPointLocal_.Clear();
hitShapePart_.Clear();
hitTriangleIndex_.Clear();
float distance = 1000.0f;
hitPointsSize_ = convexCallback.m_hitPointWorld.size();
for (int i = 0; i < hitPointsSize_; i++)
{
hitPoint_ = ToVector3(convexCallback.m_hitPointWorld.at(i));
hitPointWorld_.Push(hitPoint_);
hitPointLocal_.Push(ToVector3(convexCallback.m_hitPointLocal.at(i)));
hitNormal_ = ToVector3(convexCallback.m_hitNormalWorld.at(i));
hitNormalWorld_.Push(hitNormal_);
hitFraction_.Push((float)convexCallback.m_hitFractions.at(i));
if (i < convexCallback.m_hitShapePart.size())
{
hitShapePart_.Push(convexCallback.m_hitShapePart.at(i));
hitTriangleIndex_.Push(convexCallback.m_hitTriangleIndex.at(i));
}
// use most closest to startPos point as index
float d = (hitPoint_ - startPos).Length();
hitDistance_.Push(d);
if (distance > d)
{
distance = d;
hitIndex_ = i;
}
}
float angNormal = 0.0f;
if (convexCallback.hasHit() && hitIndex_ != -1)
{
hasHit_ = true;
hitBody_ = static_cast<RigidBody*>(convexCallback.m_collisionObjects.at(hitIndex_)->getUserPointer());
wheel.raycastInfo_.isInContact_ = true;
wheel.raycastInfo_.distance_ = Max(hitDistance_.At(hitIndex_), wheel.raycastInfo_.suspensionMinRest_);
if (hitDistance_.At(hitIndex_) < wheel.raycastInfo_.suspensionMinRest_)
{
// wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.wheelDirectionCS_ * wheel.raycastInfo_.suspensionMinRest_;
wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + direction * wheel.raycastInfo_.suspensionMinRest_;
}
// else if (hitDistance_.At(hitIndex_) > wheel.raycastInfo_.suspensionMaxRest_)
// {
// wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.wheelDirectionCS_ * wheel.raycastInfo_.suspensionMaxRest_;
// }
else
{
wheel.raycastInfo_.contactPoint_ = hitPointWorld_.At(hitIndex_);
}
wheel.raycastInfo_.contactPointLocal_ = hitPointLocal_.At(hitIndex_);
//
angNormal = hitNormalWorld_.At(hitIndex_).DotProduct(wheel.raycastInfo_.contactNormal_);
// if((acos(angNormal) * M_RADTODEG) > 30.0f)
// {
// wheel.raycastInfo_.contactNormal_ = -wheel.wheelDirectionCS_;
// }
// else
{
if (interpolateNormal)
{
const btRigidBody* hitBody = btRigidBody::upcast(convexCallback.m_collisionObjects.at(hitIndex_));
btCollisionShape* hitShape = (btCollisionShape*)hitBody->getCollisionShape();
if (hitShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
btVector3 in = pw->InterpolateMeshNormal(hitBody->getWorldTransform(), hitShape, hitShapePart_.At(hitIndex_), hitTriangleIndex_.At(hitIndex_),
ToBtVector3(hitPointWorld_.At(hitIndex_)), GetComponent<DebugRenderer>());
wheel.raycastInfo_.contactNormal_ = ToVector3(in);
}
else
{
// result.normal_ = ToVector3(rayCallback.m_hitNormalWorld);
wheel.raycastInfo_.contactNormal_ = hitNormalWorld_.At(hitIndex_);
}
}
else
{
wheel.raycastInfo_.contactNormal_ = hitNormalWorld_.At(hitIndex_);
}
}
// Node* node = hitBody_->GetNode();
// btVector3 scale = ToBtVector3(node->GetScale());
// IntVector3 vc;
// if (hitIndex_ < hitShapePart_.Size())
// {
// bool collisionOk = PhysicsWorld::GetCollisionMask(convexCallback.m_collisionObjects[hitIndex_],
// ToBtVector3(hitPointWorld_.At(hitIndex_)), hitShapePart_.At(hitIndex_),
// hitTriangleIndex_.At(hitIndex_), scale, vc);
// if (collisionOk)
// {
// const VertexCollisionMaskFlags& c0 = (const VertexCollisionMaskFlags)(vc.x_);
// const VertexCollisionMaskFlags& c1 = (const VertexCollisionMaskFlags)(vc.y_);
// const VertexCollisionMaskFlags& c2 = (const VertexCollisionMaskFlags)(vc.z_);
// // color = GetFaceColor(c0);
// if((c0 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY))
// && (c1 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY))
// && (c2 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY))
// && c0 == c1 && c0 == c2 && c1 == c2)
// {
// wheel.raycastInfo_.contactMaterial_ = c0.AsInteger();
// }
// else
// {
// wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD;
// }
// }
// else
// {
// wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD;
// }
// }
// else
// {
// wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD;
// }
float project = wheel.raycastInfo_.contactNormal_.DotProduct(wheel.raycastInfo_.wheelDirectionWS_);
angNormal = project;
Vector3 relPos = wheel.raycastInfo_.contactPoint_ - hullBody->GetPosition();
Vector3 contactVel = hullBody->GetVelocityAtPoint(relPos);
float projVel = wheel.raycastInfo_.contactNormal_.DotProduct(contactVel);
if (project >= -0.1f)
{
wheel.raycastInfo_.suspensionRelativeVelocity_ = 0.0f;
}
else
{
float inv = btScalar(-1.) / project;
wheel.raycastInfo_.suspensionRelativeVelocity_ = projVel * inv;
}
}
else
{
hitBody_ = nullptr;
wheel.raycastInfo_.isInContact_ = false;
wheel.raycastInfo_.distance_ = 0.0f;
wheel.raycastInfo_.contactNormal_ = -wheel.raycastInfo_.wheelDirectionWS_;
wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.raycastInfo_.wheelDirectionWS_;
// wheel.raycastInfo_.suspensionRelativeVelocity_ = 0.0f;
}
return wheel.raycastInfo_.suspensionRelativeVelocity_;
}
void ConvexCast::DebugDraw(const WheelInfo& wheel, Vector3 centerOfMass, bool first, float speed, Vector3 angularVel)
{
DebugRenderer* debug = GetScene()->GetComponent<DebugRenderer>();
PhysicsWorld* pw = GetScene()->GetComponent<PhysicsWorld>();
btCollisionWorld* world = pw->GetWorld();
Ray ray(wheel.raycastInfo_.hardPointWS_, wheel.raycastInfo_.wheelDirectionWS_);
Vector3 startPos = ray.origin_;
Vector3 endPos = ray.origin_ + wheel.raycastInfo_.suspensionLength_ * 1.0f * ray.direction_;
Sphere startSphere(startPos, 0.1f);
debug->AddSphere(startSphere, Color::GREEN, false);
Sphere endSphere(endPos, 0.15f);
debug->AddSphere(endSphere, Color::RED, false);
Vector<Color> colors;
colors.Push(Color::WHITE);
colors.Push(Color::GRAY);
colors.Push(Color::BLACK);
colors.Push(Color::RED);
colors.Push(Color::GREEN);
colors.Push(Color::BLUE);
colors.Push(Color::CYAN);
colors.Push(Color::MAGENTA);
colors.Push(Color::YELLOW);
// Vector3 local(hitPointLocal_.At(i));
Vector3 local(wheel.raycastInfo_.contactPointLocal_);
// Color color = colors.At(i % 9);
Sphere sphere(local, 0.01f);
debug->AddSphere(sphere, Color::YELLOW, false);
// Vector3 hit(wheel.raycastInfo_.contactPoint_ - centerOfMass);
Vector3 hit(wheel.raycastInfo_.contactPoint_);
Sphere sphereHit(hit, 0.005f);
debug->AddSphere(sphereHit, wheel.raycastInfo_.isInContact_ ? Color::GREEN : Color::BLUE, false);
// normal
Vector3 normal(wheel.raycastInfo_.contactNormal_);
debug->AddLine(hit, hit + normal.Normalized(), Color::YELLOW, false);
// debug->AddCylinder(hit, radius_, radius_, Color::BLUE, false);
pw->SetDebugRenderer(debug);
pw->SetDebugDepthTest(true);
Matrix3x4 worldTransform = node_->GetTransform();
Quaternion rotation = shape_->GetRotation();
Quaternion torqueRot(speed, Vector3::UP);
Quaternion worldRotation(worldTransform.Rotation() * rotation * torqueRot);
Vector3 worldPosition(hit);
world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)),
shape_->GetCollisionShape(), btVector3(0.0f, first ? 1.0 : 0.0f, !first ? 1.0f : 0.0f));
pw->SetDebugRenderer(nullptr);
// cylinder
// Vector3 shapePosition(hitPoint_);
// Quaternion shapeRotation(worldTransform.Rotation() * shape_->GetRotation());
// bool bodyActive = false;
// pw->SetDebugRenderer(debug);
// pw->SetDebugDepthTest(false);
// world->debugDrawObject(btTransform(ToBtQuaternion(shapeRotation), ToBtVector3(shapePosition)), shape_->GetCollisionShape(), bodyActive ? WHITE : GREEN);
// pw->SetDebugRenderer(nullptr);
}
| 38.641204
| 162
| 0.669322
|
extobias
|
2133fea2d2f423786a1f5dff1923a21c5d135256
| 1,218
|
hpp
|
C++
|
src/clustering/generic/registration_metadata.hpp
|
sauter-hq/rethinkdb
|
f34541d501bcf109c2825a7a1b67cf8fd39b9133
|
[
"Apache-2.0"
] | null | null | null |
src/clustering/generic/registration_metadata.hpp
|
sauter-hq/rethinkdb
|
f34541d501bcf109c2825a7a1b67cf8fd39b9133
|
[
"Apache-2.0"
] | null | null | null |
src/clustering/generic/registration_metadata.hpp
|
sauter-hq/rethinkdb
|
f34541d501bcf109c2825a7a1b67cf8fd39b9133
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_
#define CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_
#include "containers/uuid.hpp"
#include "rpc/mailbox/typed.hpp"
#include "rpc/semilattice/joins/macros.hpp"
template<class business_card_t>
class registrar_business_card_t {
public:
typedef uuid_u registration_id_t;
typedef mailbox_t<void(registration_id_t, peer_id_t, business_card_t)> create_mailbox_t;
typename create_mailbox_t::address_t create_mailbox;
typedef mailbox_t<void(registration_id_t)> delete_mailbox_t;
typename delete_mailbox_t::address_t delete_mailbox;
registrar_business_card_t() { }
registrar_business_card_t(
const typename create_mailbox_t::address_t &cm,
const typename delete_mailbox_t::address_t &dm) :
create_mailbox(cm), delete_mailbox(dm)
{ }
RDB_MAKE_ME_SERIALIZABLE_2(registrar_business_card_t,
create_mailbox, delete_mailbox);
};
template <class business_card_t>
RDB_MAKE_EQUALITY_COMPARABLE_2(registrar_business_card_t<business_card_t>,
create_mailbox, delete_mailbox);
#endif /* CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_ */
| 32.918919
| 92
| 0.791461
|
sauter-hq
|
2138950715d1c7f2b8c86bd9a09b4d6ba5a296dc
| 1,247
|
cpp
|
C++
|
gk/spritesheet.cpp
|
rpav/GameKernel
|
1f3eb863b58243f5f14aa76283b60a259d881522
|
[
"MIT"
] | 11
|
2016-04-28T15:09:19.000Z
|
2019-07-15T15:58:59.000Z
|
gk/spritesheet.cpp
|
rpav/GameKernel
|
1f3eb863b58243f5f14aa76283b60a259d881522
|
[
"MIT"
] | null | null | null |
gk/spritesheet.cpp
|
rpav/GameKernel
|
1f3eb863b58243f5f14aa76283b60a259d881522
|
[
"MIT"
] | null | null | null |
#include <rpav/log.hpp>
#include <stdlib.h>
#include "gk/gk.hpp"
#include "gk/gl.hpp"
#include "gk/spritesheet.hpp"
using namespace rpav;
void gk_process_spritesheet_create(gk_context* gk, gk_cmd_spritesheet_create* cmd)
{
auto sheet = (gk_spritesheet*)malloc(sizeof(gk_spritesheet));
switch(cmd->format) {
case GK_SSF_TEXTUREPACKER_JSON:
gk_load_ssf_texturepacker_json(gk, cmd, sheet);
break;
default:
say("Unknown sprite sheet format ", cmd->format);
gk_seterror(gk, GK_ERROR_SSF_UNKNOWN);
break;
}
// If there is an error, the loader should free everything it
// allocates
if(gk_haserror(gk)) goto error;
cmd->sheet = sheet;
return;
error:
free(sheet);
}
void gk_free_one_sheet(gk_spritesheet* sheet)
{
GL_CHECK(glDeleteTextures(1, (GLuint*)&sheet->tex));
gl_error:
free(sheet->sprites);
for(size_t i = 0; i < sheet->nsprites; ++i) free(sheet->names[i]);
free(sheet->names);
free(sheet);
}
void gk_process_spritesheet_destroy(gk_context*, gk_cmd_spritesheet_destroy* cmd)
{
for(size_t i = 0; i < cmd->nsheets; ++i) {
auto sheet = cmd->sheets[i];
gk_free_one_sheet(sheet);
}
}
| 22.672727
| 82
| 0.648757
|
rpav
|
213abf05b084f9f7df27ceb2c4505f6b15f9c57d
| 797
|
cpp
|
C++
|
Example/datetime_21/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/datetime_21/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/datetime_21/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
#include <boost/date_time/gregorian/gregorian.hpp>
#include <string>
#include <vector>
#include <locale>
#include <iostream>
using namespace boost::gregorian;
int main()
{
std::locale::global(std::locale{"German"});
std::string months[12]{"Januar", "Februar", "M\xe4rz", "April",
"Mai", "Juni", "Juli", "August", "September", "Oktober",
"November", "Dezember"};
std::string weekdays[7]{"Sonntag", "Montag", "Dienstag",
"Mittwoch", "Donnerstag", "Freitag", "Samstag"};
date d{2014, 5, 12};
date_facet *df = new date_facet{"%A, %d. %B %Y"};
df->long_month_names(std::vector<std::string>{months, months + 12});
df->long_weekday_names(std::vector<std::string>{weekdays,
weekdays + 7});
std::cout.imbue(std::locale{std::cout.getloc(), df});
std::cout << d << '\n';
}
| 33.208333
| 70
| 0.643664
|
KwangjoJeong
|
213ae5345d9ad68812860bb69e049e602d81045e
| 683
|
cpp
|
C++
|
FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp
|
agerith/FPS_Multiplayer_UE4
|
61e2d330c06740de1f19219833ff177c444fdb5c
|
[
"MIT"
] | 1
|
2022-03-22T07:27:29.000Z
|
2022-03-22T07:27:29.000Z
|
FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp
|
agerith/FPS_Multiplayer_UE4
|
61e2d330c06740de1f19219833ff177c444fdb5c
|
[
"MIT"
] | null | null | null |
FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp
|
agerith/FPS_Multiplayer_UE4
|
61e2d330c06740de1f19219833ff177c444fdb5c
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "ConsumableActor.h"
#include "TestRyseUp.h"
#include "ConsumableActor.h"
#include "TestRyseUpCharacter.h"
AConsumableActor::AConsumableActor(const class FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
/* A default to tweak per food variation in Blueprint */
Nutrition = 40;
bAllowRespawn = true;
RespawnDelay = 60.0f;
RespawnDelayRange = 20.0f;
}
void AConsumableActor::OnUsed(APawn* InstigatorPawn)
{
ATestRyseUpCharacter* Pawn = Cast<ATestRyseUpCharacter>(InstigatorPawn);
if (Pawn)
{
Pawn->RestoreLife(Nutrition);
}
Super::OnUsed(InstigatorPawn);
}
| 20.088235
| 85
| 0.764275
|
agerith
|
213bbd49b3a68fc5ca0914014d611b44f3cc9037
| 1,348
|
cpp
|
C++
|
array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp
|
zm66260/Data_Structure_and_Algorithms
|
f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e
|
[
"MIT"
] | null | null | null |
array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp
|
zm66260/Data_Structure_and_Algorithms
|
f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e
|
[
"MIT"
] | null | null | null |
array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp
|
zm66260/Data_Structure_and_Algorithms
|
f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e
|
[
"MIT"
] | null | null | null |
// 378 kth smallest element in a sorted matrix
// Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
// Note that it is the kth smallest element in the sorted order, not the kth distinct element.
// Example:
// matrix = [
// [ 1, 5, 9],
// [10, 11, 13],
// [12, 13, 15]
// ],
// k = 8,
// return 13.
// Note:
// You may assume k is always valid, 1 ≤ k ≤ n2.
#include<vector>
using namespace std;
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int left = matrix[0][0];
int right = matrix[matrix.size()-1][matrix.size()-1];
while(left < right){
int mid = (left + right) / 2;
int count = searchMatrix(matrix, mid);
if(count < k){
left = mid+1;
}
else{right = mid;}
}
return left;
}
int searchMatrix(vector<vector<int>>& matrix, int midvalue){
int r = matrix.size()-1;
int c = 0;
int count = 0;
while(r >= 0 && c < matrix[0].size()){
if(matrix[r][c] <= midvalue){
c++;
count += r + 1;
}
else{r--;}
}
return count;
}
};
| 24.962963
| 135
| 0.488131
|
zm66260
|
214b8ca98d0ead4be58052703f42634928e0f03d
| 876
|
cpp
|
C++
|
android-31/javax/crypto/spec/GCMParameterSpec.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/javax/crypto/spec/GCMParameterSpec.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/javax/crypto/spec/GCMParameterSpec.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../../JByteArray.hpp"
#include "./GCMParameterSpec.hpp"
namespace javax::crypto::spec
{
// Fields
// QJniObject forward
GCMParameterSpec::GCMParameterSpec(QJniObject obj) : JObject(obj) {}
// Constructors
GCMParameterSpec::GCMParameterSpec(jint arg0, JByteArray arg1)
: JObject(
"javax.crypto.spec.GCMParameterSpec",
"(I[B)V",
arg0,
arg1.object<jbyteArray>()
) {}
GCMParameterSpec::GCMParameterSpec(jint arg0, JByteArray arg1, jint arg2, jint arg3)
: JObject(
"javax.crypto.spec.GCMParameterSpec",
"(I[BII)V",
arg0,
arg1.object<jbyteArray>(),
arg2,
arg3
) {}
// Methods
JByteArray GCMParameterSpec::getIV() const
{
return callObjectMethod(
"getIV",
"()[B"
);
}
jint GCMParameterSpec::getTLen() const
{
return callMethod<jint>(
"getTLen",
"()I"
);
}
} // namespace javax::crypto::spec
| 19.043478
| 85
| 0.660959
|
YJBeetle
|
214e9f5ce6327bebe9d5b15be003ba8b0ab70867
| 565
|
cpp
|
C++
|
2019-06/5 - Range generators.cpp
|
st-louis-cpp-meetup/Presentations
|
2e3a31a6285aabf295a9bf494bf7470844196857
|
[
"CC-BY-4.0"
] | 2
|
2019-06-20T13:22:30.000Z
|
2020-03-05T01:19:19.000Z
|
2019-06/5 - Range generators.cpp
|
st-louis-cpp-meetup/Presentations
|
2e3a31a6285aabf295a9bf494bf7470844196857
|
[
"CC-BY-4.0"
] | null | null | null |
2019-06/5 - Range generators.cpp
|
st-louis-cpp-meetup/Presentations
|
2e3a31a6285aabf295a9bf494bf7470844196857
|
[
"CC-BY-4.0"
] | null | null | null |
//-std=c++2a -I/opt/compiler-explorer/libs/cmcstl2/include -fconcepts
#include <iostream>
#include <experimental/ranges/ranges> // from cmcstl2
namespace ranges = std::experimental::ranges;
namespace view = std::experimental::ranges::view;
//range generators (range adaptors)
int main() {
auto count_to_10 = view::iota(1, 11);
auto one_int = view::single(37);
auto no_ints = view::empty<int>;
auto infinite_count = view::iota(1);
auto only1234 = view::counted(infinite_count.begin(), 4);
for (int x: count_to_10) {
std::cout << x << " ";
}
}
| 28.25
| 69
| 0.684956
|
st-louis-cpp-meetup
|
2152b04ecd089a71683f2dc143d9592c6998b5ec
| 24,300
|
cpp
|
C++
|
plugins/protein/src/ToonRendererDeferred.cpp
|
reinago/megamol
|
0438e26e5134a0050a00c6d8d747175a08f85fd9
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/protein/src/ToonRendererDeferred.cpp
|
reinago/megamol
|
0438e26e5134a0050a00c6d8d747175a08f85fd9
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/protein/src/ToonRendererDeferred.cpp
|
reinago/megamol
|
0438e26e5134a0050a00c6d8d747175a08f85fd9
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* ToonRendererDeferred.cpp
*
* Copyright (C) 2011 by Universitaet Stuttgart (VISUS).
* All rights reserved.
*/
#include "stdafx.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/IntParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/view/CallRender3D.h"
#include "mmcore/view/CallRenderDeferred3D.h"
#include "mmcore/CoreInstance.h"
#include "vislib/graphics/gl/ShaderSource.h"
#include "mmcore/utility/log/Log.h"
#include "ToonRendererDeferred.h"
#include "vislib/graphics/gl/IncludeAllGL.h"
using namespace megamol::protein;
/*
* ToonRendererDeferred::ToonRendererDeferred
*/
ToonRendererDeferred::ToonRendererDeferred(void)
: megamol::core::view::AbstractRendererDeferred3D(),
threshFineLinesParam("linesFine", "Threshold for fine silhouette."),
threshCoarseLinesParam("linesCoarse", "Threshold for coarse silhouette."),
ssaoParam("toggleSSAO", "Toggle Screen Space Ambient Occlusion."),
ssaoRadiusParam("ssaoRadius", "Radius for SSAO samples."),
illuminationParam("illumination", "Change local lighting."),
colorParam("toggleColor", "Toggle coloring."),
widthFBO(-1), heightFBO(-1) {
// Threshold for fine lines
this->threshFineLinesParam << new megamol::core::param::FloatParam(9.5f, 0.0f, 9.95f);
this->MakeSlotAvailable(&this->threshFineLinesParam);
// Threshold for coarse lines
this->threshCoarseLinesParam << new megamol::core::param::FloatParam(7.9f, 0.0f, 9.95f);
this->MakeSlotAvailable(&this->threshCoarseLinesParam);
// Toggle SSAO
this->ssaoParam << new megamol::core::param::BoolParam(false);
this->MakeSlotAvailable(&this->ssaoParam);
// Toggle local lighting
megamol::core::param::EnumParam *illuParam =
new megamol::core::param::EnumParam(0);
illuParam->SetTypePair(0, "None");
illuParam->SetTypePair(1, "Phong-Shading");
illuParam->SetTypePair(2, "Toon-Shading");
this->illuminationParam << illuParam;
this->MakeSlotAvailable(&illuminationParam);
// Toggle coloring
this->colorParam << new megamol::core::param::BoolParam(false);
this->MakeSlotAvailable(&this->colorParam);
// SSAO radius param
this->ssaoRadiusParam << new megamol::core::param::FloatParam(1.0, 0.0);
this->MakeSlotAvailable(&this->ssaoRadiusParam);
}
/*
* ToonRendererDeferred::create
*/
bool ToonRendererDeferred::create(void) {
vislib::graphics::gl::ShaderSource vertSrc;
vislib::graphics::gl::ShaderSource fragSrc;
// Init random number generator
srand((unsigned)time(0));
// Create 4x4-texture with random rotation vectors
if(!this->createRandomRotSampler()) {
return false;
}
// Create sampling kernel
if(!this->createRandomKernel(16)) {
return false;
}
megamol::core::CoreInstance *ci = this->GetCoreInstance();
if(!ci) {
return false;
}
if(!areExtsAvailable("GL_EXT_framebuffer_object GL_ARB_draw_buffers")) {
return false;
}
if(!vislib::graphics::gl::GLSLShader::InitialiseExtensions()) {
return false;
}
if(!isExtAvailable("GL_ARB_texture_non_power_of_two")) return false;
// Try to load the gradient shader
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::sobel::vertex", vertSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient vertex shader source", this->ClassName() );
return false;
}
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::sobel::fragment", fragSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient fragment shader source", this->ClassName() );
return false;
}
try {
if(!this->sobelShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count()))
throw vislib::Exception("Generic creation failure", __FILE__, __LINE__);
}
catch(vislib::Exception &e){
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA());
return false;
}
// Try to load the ssao shader
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::ssao::vertex", vertSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient vertex shader source", this->ClassName() );
return false;
}
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::ssao::fragment", fragSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient fragment shader source", this->ClassName() );
return false;
}
try {
if(!this->ssaoShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count()))
throw vislib::Exception("Generic creation failure", __FILE__, __LINE__);
}
catch(vislib::Exception &e){
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA());
return false;
}
// Try to load the toon shader
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::toon::vertex", vertSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load toon vertex shader source", this->ClassName() );
return false;
}
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::toon::fragment", fragSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load toon fragment shader source", this->ClassName() );
return false;
}
try {
if(!this->toonShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count()))
throw vislib::Exception("Generic creation failure", __FILE__, __LINE__);
}
catch(vislib::Exception &e){
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA());
return false;
}
return true;
}
/*
* ToonRendererDeferred::release
*/
void ToonRendererDeferred::release(void) {
this->toonShader.Release();
this->sobelShader.Release();
this->ssaoShader.Release();
glDeleteTextures(1, &this->colorBuffer);
glDeleteTextures(1, &this->normalBuffer);
glDeleteTextures(1, &this->gradientBuffer);
glDeleteTextures(1, &this->depthBuffer);
glDeleteTextures(1, &this->ssaoBuffer);
glDeleteTextures(1, &this->randomKernel);
glDeleteTextures(1, &this->rotationSampler);
glDeleteFramebuffers(1, &this->fbo);
}
/*
* ToonRendererDeferred::~ToonRendererDeferred
*/
ToonRendererDeferred::~ToonRendererDeferred(void) {
this->Release();
}
/*
* ToonRendererDeferred::GetExtents
*/
bool ToonRendererDeferred::GetExtents(megamol::core::Call& call) {
megamol::core::view::CallRender3D *crIn =
dynamic_cast< megamol::core::view::CallRender3D*>(&call);
if(crIn == NULL) return false;
megamol::core::view:: CallRenderDeferred3D *crOut =
this->rendererSlot.CallAs< megamol::core::view::CallRenderDeferred3D>();
if(crOut == NULL) return false;
// Call for getExtends
if(!(*crOut)(core::view::AbstractCallRender::FnGetExtents)) return false;
// Set extends of for incoming render call
crIn->AccessBoundingBoxes() = crOut->GetBoundingBoxes();
crIn->SetLastFrameTime(crOut->LastFrameTime());
crIn->SetTimeFramesCount(crOut->TimeFramesCount());
return true;
}
/*
* ToonRendererDeferred::Render
*/
bool ToonRendererDeferred::Render(megamol::core::Call& call) {
if(!updateParams()) return false;
megamol::core::view::CallRender3D *crIn =
dynamic_cast< megamol::core::view::CallRender3D*>(&call);
if(crIn == NULL) return false;
megamol::core::view::CallRenderDeferred3D *crOut =
this->rendererSlot.CallAs< megamol::core::view::CallRenderDeferred3D>();
if(crOut == NULL) return false;
crOut->SetCameraParameters(crIn->GetCameraParameters());
// Set call time
crOut->SetTime(crIn->Time());
float curVP[4];
glGetFloatv(GL_VIEWPORT, curVP);
vislib::math::Vector<float, 3> ray(0, 0,-1);
vislib::math::Vector<float, 3> up(0, 1, 0);
vislib::math::Vector<float, 3> right(1, 0, 0);
up *= sinf(crIn->GetCameraParameters()->HalfApertureAngle());
right *= sinf(crIn->GetCameraParameters()->HalfApertureAngle())
* curVP[2] / curVP[3];
// Recreate FBO if necessary
if((curVP[2] != this->widthFBO) || (curVP[3] != this->heightFBO)) {
if(!this->createFBO(static_cast<UINT>(curVP[2]), static_cast<UINT>(curVP[3]))) {
return false;
}
this->widthFBO = (int)curVP[2];
this->heightFBO = (int)curVP[3];
}
/// 1. Offscreen rendering ///
// Enable rendering to FBO
glBindFramebufferEXT(GL_FRAMEBUFFER, this->fbo);
// Enable rendering to color attachents 0 and 1
GLenum mrt[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, mrt);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->colorBuffer, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, this->normalBuffer, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, this->depthBuffer, 0);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Call for render
(*crOut)(core::view::AbstractCallRender::FnRender);
// Detach texture that are not needed anymore
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
// Prepare rendering screen quad
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
/// 2. Calculate gradient using the sobel operator ///
GLenum mrt2[] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, mrt2);
glDepthMask(GL_FALSE); // Disable writing to depth buffer
// Attach gradient texture
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->gradientBuffer, 0);
this->sobelShader.Enable();
glUniform1i(this->sobelShader.ParameterLocation("depthBuffer"), 0);
// Bind depth texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer); // Depth buffer
// Draw
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f);
glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f);
glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f);
glEnd();
this->sobelShader.Disable();
glBindTexture(GL_TEXTURE_2D, 0);
/// 3. Calculate ssao value if needed ///
if(this->ssaoParam.Param<core::param::BoolParam>()->Value()) {
// Attach ssao buffer
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->ssaoBuffer, 0);
this->ssaoShader.Enable();
glUniform4f(this->ssaoShader.ParameterLocation("clip"),
crIn->GetCameraParameters()->NearClip(), // Near
crIn->GetCameraParameters()->FarClip(), // Far
tan(crIn->GetCameraParameters()->HalfApertureAngle()) * crIn->GetCameraParameters()->NearClip(), // Top
tan(crIn->GetCameraParameters()->HalfApertureAngle()) * crIn->GetCameraParameters()->NearClip() * curVP[2] / curVP[3]); // Right
glUniform2f(this->ssaoShader.ParameterLocation("winSize"), curVP[2], curVP[3]);
glUniform1i(this->ssaoShader.ParameterLocation("depthBuff"), 0);
glUniform1i(this->ssaoShader.ParameterLocation("rotSampler"), 1);
glUniform1i(this->ssaoShader.ParameterLocation("normalBuff"), 2);
glUniform1f(this->ssaoShader.ParameterLocation("ssaoRadius"),
this->ssaoRadiusParam.Param<core::param::FloatParam>()->Value());
// Bind depth texture
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, this->rotationSampler);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, this->normalBuffer);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer);
// Draw
glBegin(GL_QUADS);
glNormal3fv((ray - right - up).PeekComponents());
glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f);
glNormal3fv((ray + right - up).PeekComponents());
glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f);
glNormal3fv((ray + right + up).PeekComponents());
glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f);
glNormal3fv((ray - right + up).PeekComponents());
glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f);
glEnd();
this->ssaoShader.Disable();
glBindTexture(GL_TEXTURE_2D, 0);
}
// Disable rendering to framebuffer
glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
/// 4. Deferred shading ///
glDepthMask(GL_TRUE); // Enable writing to depth buffer
// Preserve the current framebuffer content (e.g. back of the bounding box)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
this->toonShader.Enable();
glUniform2f(this->toonShader.ParameterLocation("clip"),
crIn->GetCameraParameters()->NearClip(),
crIn->GetCameraParameters()->FarClip());
glUniform2f(this->toonShader.ParameterLocation("winSize"),
curVP[2], curVP[3]);
glUniform1i(this->toonShader.ParameterLocation("depthBuffer"), 0);
glUniform1i(this->toonShader.ParameterLocation("colorBuffer"), 1);
glUniform1i(this->toonShader.ParameterLocation("normalBuffer"), 2);
glUniform1i(this->toonShader.ParameterLocation("gradientBuffer"), 3);
glUniform1i(this->toonShader.ParameterLocation("ssaoBuffer"), 4);
glUniform1f(this->toonShader.ParameterLocation("threshFine"),
(10.0f - this->threshFineLinesParam.Param<core::param::FloatParam>()->Value())*0.1f);
glUniform1f(this->toonShader.ParameterLocation("threshCoarse"),
(10.0f - this->threshCoarseLinesParam.Param<core::param::FloatParam>()->Value())*0.1f);
glUniform1i(this->toonShader.ParameterLocation("ssao"),
this->ssaoParam.Param<core::param::BoolParam>()->Value());
glUniform1i(this->toonShader.ParameterLocation("lighting"),
this->illuminationParam.Param<core::param::EnumParam>()->Value());
glUniform1i(this->toonShader.ParameterLocation("withColor"),
this->colorParam.Param<core::param::BoolParam>()->Value());
// Bind textures
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, this->colorBuffer); // Color buffer
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, this->normalBuffer); // Normal buffer
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, this->gradientBuffer); // Gradient buffer
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, this->ssaoBuffer); // SSAO buffer
glGenerateMipmapEXT(GL_TEXTURE_2D); // Generate mip map levels for ssao texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer); // Depth buffer
// Draw quad
glBegin(GL_QUADS);
glNormal3fv((ray - right - up).PeekComponents());
glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f);
glNormal3fv((ray + right - up).PeekComponents());
glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f);
glNormal3fv((ray + right + up).PeekComponents());
glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f);
glNormal3fv((ray - right + up).PeekComponents());
glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f);
glEnd();
this->toonShader.Disable();
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
return true;
}
/*
* ToonRendererDeferred::createFBO
*/
bool ToonRendererDeferred::createFBO(UINT width, UINT height) {
// Delete textures + fbo if necessary
if(glIsFramebufferEXT(this->fbo)) {
glDeleteTextures(1, &this->colorBuffer);
glDeleteTextures(1, &this->normalBuffer);
glDeleteTextures(1, &this->gradientBuffer);
glDeleteTextures(1, &this->depthBuffer);
glDeleteTextures(1, &this->ssaoBuffer);
glDeleteFramebuffersEXT(1, &this->fbo);
}
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &this->colorBuffer);
glBindTexture(GL_TEXTURE_2D, this->colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Normal buffer
glGenTextures(1, &this->normalBuffer);
glBindTexture(GL_TEXTURE_2D, this->normalBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Gradient buffer
// TODO Texture format
glGenTextures(1, &this->gradientBuffer);
glBindTexture(GL_TEXTURE_2D, this->gradientBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// SSAO buffer
// TODO Texture format
glGenTextures(1, &this->ssaoBuffer);
glBindTexture(GL_TEXTURE_2D, this->ssaoBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Depth buffer
glGenTextures(1, &this->depthBuffer);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Generate framebuffer
glGenFramebuffersEXT(1, &this->fbo);
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
if(status != GL_FRAMEBUFFER_COMPLETE) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "Could not create FBO");
return false;
}
// Detach all textures
glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
return true;
}
/*
* ToonRendererDeferred::updateParams
*/
bool ToonRendererDeferred::updateParams() {
return true;
}
/*
* ToonRendererDeferred::createRandomRotSampler
*/
bool ToonRendererDeferred::createRandomRotSampler() {
float data [4][4][3];
for(unsigned int s = 0; s < 4; s++) {
for(unsigned int t = 0; t < 4; t++) {
data[s][t][0] = getRandomFloat(-1.0, 1.0, 3);
data[s][t][1] = getRandomFloat(-1.0, 1.0, 3);
data[s][t][2] = 0.0;
// Compute magnitude
float mag = sqrt(data[s][t][0]*data[s][t][0] +
data[s][t][1]*data[s][t][1] +
data[s][t][2]*data[s][t][2]);
// Normalize
data[s][t][0] /= mag;
data[s][t][1] /= mag;
data[s][t][2] /= mag;
// Map to range 0 ... 1
data[s][t][0] += 1.0; data[s][t][0] /= 2.0;
data[s][t][1] += 1.0; data[s][t][1] /= 2.0;
data[s][t][2] += 1.0; data[s][t][2] /= 2.0;
}
}
glGenTextures(1, &this->rotationSampler);
glBindTexture(GL_TEXTURE_2D, this->rotationSampler);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 4, 4, 0, GL_RGB, GL_FLOAT, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindTexture(GL_TEXTURE_2D, 0);
if(glGetError() != GL_NO_ERROR)
return false;
return true;
}
/*
* ToonRendererDeferred::getRandomFloat
*/
float ToonRendererDeferred::getRandomFloat(float min, float max, unsigned int prec) {
// Note: RAND_MAX is only guaranteed to be at least 32767, so prec should not be more than 4
float base = 10.0;
float precision = pow(base, (int)prec);
int range = (int)(max*precision - min*precision + 1);
return static_cast<float>(rand()%range + min*precision) / precision;
}
/*
* ToonRendererDeferred::::createRandomKernel
*/
// TODO enforce lower boundary to prevent numerical problems leading to artifacts
bool ToonRendererDeferred::createRandomKernel(UINT size) {
float *kernel;
kernel = new float[size*3];
for(unsigned int s = 0; s < size; s++) {
float scale = float(s) / float(size);
scale *= scale;
scale = 0.1f*(1.0f - scale) + scale; // Interpolate between 0.1 ... 1.0
kernel[s*3 + 0] = getRandomFloat(-1.0, 1.0, 3);
kernel[s*3 + 1] = getRandomFloat(-1.0, 1.0, 3);
kernel[s*3 + 2] = getRandomFloat( 0.0, 1.0, 3);
// Compute magnitude
float mag = sqrt(kernel[s*3 + 0]*kernel[s*3 + 0] +
kernel[s*3 + 1]*kernel[s*3 + 1] +
kernel[s*3 + 2]*kernel[s*3 + 2]);
// Normalize
kernel[s*3 + 0] /= mag;
kernel[s*3 + 1] /= mag;
kernel[s*3 + 2] /= mag;
// Scale values
kernel[s*3 + 0] *= scale;
kernel[s*3 + 1] *= scale;
kernel[s*3 + 2] *= scale;
// Map values to range 0 ... 1
kernel[s*3 + 0] += 1.0; kernel[s*3 + 0] /= 2.0;
kernel[s*3 + 1] += 1.0; kernel[s*3 + 1] /= 2.0;
kernel[s*3 + 2] += 1.0; kernel[s*3 + 2] /= 2.0;
}
glGenTextures(1, &this->randomKernel);
glBindTexture(GL_TEXTURE_2D, this->randomKernel);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, size, 1, 0, GL_RGB, GL_FLOAT, kernel);
glBindTexture(GL_TEXTURE_2D, 0);
delete[] kernel;
if(glGetError() != GL_NO_ERROR)
return false;
return true;
}
| 37.732919
| 144
| 0.672675
|
reinago
|
215435cad45bb8acd7b8cd20bc77538694699099
| 1,134
|
cpp
|
C++
|
luogu/p1067.cpp
|
ajidow/Answers_of_OJ
|
70e0c02d9367c3a154b83a277edbf158f32484a3
|
[
"MIT"
] | null | null | null |
luogu/p1067.cpp
|
ajidow/Answers_of_OJ
|
70e0c02d9367c3a154b83a277edbf158f32484a3
|
[
"MIT"
] | null | null | null |
luogu/p1067.cpp
|
ajidow/Answers_of_OJ
|
70e0c02d9367c3a154b83a277edbf158f32484a3
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int power;
cin >> power;
int num[power+1];
//
int i;
for (i = 0; i < power+1; ++i)
{
cin >> num[i];
}
//
int sub = power;
if (num[0] == 1){
cout << "x" << "^" << sub;
}else if (num[0] == -1)
{
cout << "-x^" << sub;
}else{
cout << num[0] << "x" << "^" << sub;
}
sub--;
for (i = 1; i < power-1; ++i)
{
if ( num[i] != 1 && num[i] != -1 ){
if (num[i] > 0)
{
cout << "+" << num[i] << "x" << "^" << sub;
}else if (num[i] < 0)
{
cout << num[i] << "x" << "^" << sub;
}
}else if (num[i] == 1)
{
cout << "+" << "x" << "^" << sub;
}else if (num[i] == -1)
{
cout << "-" << "x" << "^" << sub;
}
sub--;
}
if (num[power-1] != 1 && num[power-1] != -1)\
{
if (num[power-1] < 0)
{
cout << num[power-1] << "x";
}else if (num[power-1] > 0)
{
cout << "+" << num[power-1] << "x";
}
}else if (num[power-1] == 1)
{
cout << "+x";
}else{
cout << "-x";
}
if (num[power] > 0)
{
cout << "+" << num[power];
}else if (num[power] < 0)
{
cout << num[power];
}
return 0;
}
| 15.324324
| 47
| 0.395062
|
ajidow
|
21552ab246534cf24cf1ad5f67ad7ee779c09346
| 20,590
|
hpp
|
C++
|
libs/boost_1_72_0/boost/locale/message.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/locale/message.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/locale/message.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
//
// Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_LOCALE_MESSAGE_HPP_INCLUDED
#define BOOST_LOCALE_MESSAGE_HPP_INCLUDED
#include <boost/locale/config.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4275 4251 4231 4660)
#endif
#include <boost/locale/formatting.hpp>
#include <locale>
#include <memory>
#include <set>
#include <string>
#include <vector>
// glibc < 2.3.4 declares those as macros if compiled with optimization turned
// on
#ifdef gettext
#undef gettext
#undef ngettext
#undef dgettext
#undef dngettext
#endif
namespace boost {
namespace locale {
///
/// \defgroup message Message Formatting (translation)
///
/// This module provides message translation functionality, i.e. allow your
/// application to speak native language
///
/// @{
///
/// \cond INTERNAL
template <typename CharType>
struct base_message_format : public std::locale::facet {};
/// \endcond
///
/// \brief This facet provides message formatting abilities
///
template <typename CharType>
class message_format : public base_message_format<CharType> {
public:
///
/// Character type
///
typedef CharType char_type;
///
/// String type
///
typedef std::basic_string<CharType> string_type;
///
/// Default constructor
///
message_format(size_t refs = 0) : base_message_format<CharType>(refs) {}
///
/// This function returns a pointer to the string for a message defined by a
/// \a context and identification string \a id. Both create a single key for
/// message lookup in a domain defined by \a domain_id.
///
/// If \a context is NULL it is not considered to be a part of the key
///
/// If a translated string is found, it is returned, otherwise NULL is
/// returned
///
///
virtual char_type const *get(int domain_id, char_type const *context,
char_type const *id) const = 0;
///
/// This function returns a pointer to the string for a plural message defined
/// by a \a context and identification string \a single_id.
///
/// If \a context is NULL it is not considered to be a part of the key
///
/// Both create a single key for message lookup in
/// a domain defined \a domain_id. \a n is used to pick the correct
/// translation string for a specific number.
///
/// If a translated string is found, it is returned, otherwise NULL is
/// returned
///
///
virtual char_type const *get(int domain_id, char_type const *context,
char_type const *single_id, int n) const = 0;
///
/// Convert a string that defines \a domain to the integer id used by \a get
/// functions
///
virtual int domain(std::string const &domain) const = 0;
///
/// Convert the string \a msg to target locale's encoding. If \a msg is
/// already in target encoding it would be returned otherwise the converted
/// string is stored in temporary \a buffer and buffer.c_str() is returned.
///
/// Note: for char_type that is char16_t, char32_t and wchar_t it is no-op,
/// returns msg
///
virtual char_type const *convert(char_type const *msg,
string_type &buffer) const = 0;
#if defined(__SUNPRO_CC) && defined(_RWSTD_VER)
std::locale::id &__get_id(void) const { return id; }
#endif
protected:
virtual ~message_format() {}
};
/// \cond INTERNAL
namespace details {
inline bool is_us_ascii_char(char c) {
// works for null terminated strings regardless char "signness"
return 0 < c && c < 0x7F;
}
inline bool is_us_ascii_string(char const *msg) {
while (*msg) {
if (!is_us_ascii_char(*msg++))
return false;
}
return true;
}
template <typename CharType> struct string_cast_traits {
static CharType const *cast(CharType const *msg,
std::basic_string<CharType> & /*unused*/) {
return msg;
}
};
template <> struct string_cast_traits<char> {
static char const *cast(char const *msg, std::string &buffer) {
if (is_us_ascii_string(msg))
return msg;
buffer.reserve(strlen(msg));
char c;
while ((c = *msg++) != 0) {
if (is_us_ascii_char(c))
buffer += c;
}
return buffer.c_str();
}
};
} // namespace details
/// \endcond
///
/// \brief This class represents a message that can be converted to a specific
/// locale message
///
/// It holds the original ASCII string that is queried in the dictionary when
/// converting to the output string. The created string may be UTF-8, UTF-16,
/// UTF-32 or other 8-bit encoded string according to the target character type
/// and locale encoding.
///
template <typename CharType> class basic_message {
public:
typedef CharType
char_type; ///< The character this message object is used with
typedef std::basic_string<char_type>
string_type; ///< The string type this object can be used with
typedef message_format<char_type>
facet_type; ///< The type of the facet the messages are fetched with
///
/// Create default empty message
///
basic_message() : n_(0), c_id_(0), c_context_(0), c_plural_(0) {}
///
/// Create a simple message from 0 terminated string. The string should exist
/// until the message is destroyed. Generally useful with static constant
/// strings
///
explicit basic_message(char_type const *id)
: n_(0), c_id_(id), c_context_(0), c_plural_(0) {}
///
/// Create a simple plural form message from 0 terminated strings. The strings
/// should exist until the message is destroyed. Generally useful with static
/// constant strings.
///
/// \a n is the number, \a single and \a plural are singular and plural forms
/// of the message
///
explicit basic_message(char_type const *single, char_type const *plural,
int n)
: n_(n), c_id_(single), c_context_(0), c_plural_(plural) {}
///
/// Create a simple message from 0 terminated strings, with context
/// information. The string should exist
/// until the message is destroyed. Generally useful with static constant
/// strings
///
explicit basic_message(char_type const *context, char_type const *id)
: n_(0), c_id_(id), c_context_(context), c_plural_(0) {}
///
/// Create a simple plural form message from 0 terminated strings, with
/// context. The strings should exist until the message is destroyed.
/// Generally useful with static constant strings.
///
/// \a n is the number, \a single and \a plural are singular and plural forms
/// of the message
///
explicit basic_message(char_type const *context, char_type const *single,
char_type const *plural, int n)
: n_(n), c_id_(single), c_context_(context), c_plural_(plural) {}
///
/// Create a simple message from a string.
///
explicit basic_message(string_type const &id)
: n_(0), c_id_(0), c_context_(0), c_plural_(0), id_(id) {}
///
/// Create a simple plural form message from strings.
///
/// \a n is the number, \a single and \a plural are single and plural forms of
/// the message
///
explicit basic_message(string_type const &single, string_type const &plural,
int number)
: n_(number), c_id_(0), c_context_(0), c_plural_(0), id_(single),
plural_(plural) {}
///
/// Create a simple message from a string with context.
///
explicit basic_message(string_type const &context, string_type const &id)
: n_(0), c_id_(0), c_context_(0), c_plural_(0), id_(id),
context_(context) {}
///
/// Create a simple plural form message from strings.
///
/// \a n is the number, \a single and \a plural are single and plural forms of
/// the message
///
explicit basic_message(string_type const &context, string_type const &single,
string_type const &plural, int number)
: n_(number), c_id_(0), c_context_(0), c_plural_(0), id_(single),
context_(context), plural_(plural) {}
///
/// Copy an object
///
basic_message(basic_message const &other)
: n_(other.n_), c_id_(other.c_id_), c_context_(other.c_context_),
c_plural_(other.c_plural_), id_(other.id_), context_(other.context_),
plural_(other.plural_) {}
///
/// Assign other message object to this one
///
basic_message const &operator=(basic_message const &other) {
if (this == &other) {
return *this;
}
basic_message tmp(other);
swap(tmp);
return *this;
}
///
/// Swap two message objects
///
void swap(basic_message &other) {
std::swap(n_, other.n_);
std::swap(c_id_, other.c_id_);
std::swap(c_context_, other.c_context_);
std::swap(c_plural_, other.c_plural_);
id_.swap(other.id_);
context_.swap(other.context_);
plural_.swap(other.plural_);
}
///
/// Message class can be explicitly converted to string class
///
operator string_type() const { return str(); }
///
/// Translate message to a string in the default global locale, using default
/// domain
///
string_type str() const {
std::locale loc;
return str(loc, 0);
}
///
/// Translate message to a string in the locale \a locale, using default
/// domain
///
string_type str(std::locale const &locale) const { return str(locale, 0); }
///
/// Translate message to a string using locale \a locale and message domain \a
/// domain_id
///
string_type str(std::locale const &locale,
std::string const &domain_id) const {
int id = 0;
if (std::has_facet<facet_type>(locale))
id = std::use_facet<facet_type>(locale).domain(domain_id);
return str(locale, id);
}
///
/// Translate message to a string using the default locale and message domain
/// \a domain_id
///
string_type str(std::string const &domain_id) const {
int id = 0;
std::locale loc;
if (std::has_facet<facet_type>(loc))
id = std::use_facet<facet_type>(loc).domain(domain_id);
return str(loc, id);
}
///
/// Translate message to a string using locale \a loc and message domain index
/// \a id
///
string_type str(std::locale const &loc, int id) const {
string_type buffer;
char_type const *ptr = write(loc, id, buffer);
if (ptr == buffer.c_str())
return buffer;
else
buffer = ptr;
return buffer;
}
///
/// Translate message and write to stream \a out, using imbued locale and
/// domain set to the stream
///
void write(std::basic_ostream<char_type> &out) const {
std::locale const &loc = out.getloc();
int id = ios_info::get(out).domain_id();
string_type buffer;
out << write(loc, id, buffer);
}
private:
char_type const *plural() const {
if (c_plural_)
return c_plural_;
if (plural_.empty())
return 0;
return plural_.c_str();
}
char_type const *context() const {
if (c_context_)
return c_context_;
if (context_.empty())
return 0;
return context_.c_str();
}
char_type const *id() const { return c_id_ ? c_id_ : id_.c_str(); }
char_type const *write(std::locale const &loc, int domain_id,
string_type &buffer) const {
char_type const *translated = 0;
static const char_type empty_string[1] = {0};
char_type const *id = this->id();
char_type const *context = this->context();
char_type const *plural = this->plural();
if (*id == 0)
return empty_string;
facet_type const *facet = 0;
if (std::has_facet<facet_type>(loc))
facet = &std::use_facet<facet_type>(loc);
if (facet) {
if (!plural) {
translated = facet->get(domain_id, context, id);
} else {
translated = facet->get(domain_id, context, id, n_);
}
}
if (!translated) {
char_type const *msg = plural ? (n_ == 1 ? id : plural) : id;
if (facet) {
translated = facet->convert(msg, buffer);
} else {
translated = details::string_cast_traits<char_type>::cast(msg, buffer);
}
}
return translated;
}
/// members
int n_;
char_type const *c_id_;
char_type const *c_context_;
char_type const *c_plural_;
string_type id_;
string_type context_;
string_type plural_;
};
///
/// Convenience typedef for char
///
typedef basic_message<char> message;
///
/// Convenience typedef for wchar_t
///
typedef basic_message<wchar_t> wmessage;
#ifdef BOOST_LOCALE_ENABLE_CHAR16_T
///
/// Convenience typedef for char16_t
///
typedef basic_message<char16_t> u16message;
#endif
#ifdef BOOST_LOCALE_ENABLE_CHAR32_T
///
/// Convenience typedef for char32_t
///
typedef basic_message<char32_t> u32message;
#endif
///
/// Translate message \a msg and write it to stream
///
template <typename CharType>
std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out,
basic_message<CharType> const &msg) {
msg.write(out);
return out;
}
///
/// \anchor boost_locale_translate_family \name Indirect message translation
/// function family
/// @{
///
/// \brief Translate a message, \a msg is not copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *msg) {
return basic_message<CharType>(msg);
}
///
/// \brief Translate a message in context, \a msg and \a context are not copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *context,
CharType const *msg) {
return basic_message<CharType>(context, msg);
}
///
/// \brief Translate a plural message form, \a single and \a plural are not
/// copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *single,
CharType const *plural, int n) {
return basic_message<CharType>(single, plural, n);
}
///
/// \brief Translate a plural message from in constext, \a context, \a single
/// and \a plural are not copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *context,
CharType const *single,
CharType const *plural, int n) {
return basic_message<CharType>(context, single, plural, n);
}
///
/// \brief Translate a message, \a msg is copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &msg) {
return basic_message<CharType>(msg);
}
///
/// \brief Translate a message in context,\a context and \a msg is copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &context,
std::basic_string<CharType> const &msg) {
return basic_message<CharType>(context, msg);
}
///
/// \brief Translate a plural message form in constext, \a context, \a single
/// and \a plural are copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &context,
std::basic_string<CharType> const &single,
std::basic_string<CharType> const &plural, int n) {
return basic_message<CharType>(context, single, plural, n);
}
///
/// \brief Translate a plural message form, \a single and \a plural are copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &single,
std::basic_string<CharType> const &plural, int n) {
return basic_message<CharType>(single, plural, n);
}
/// @}
///
/// \anchor boost_locale_gettext_family \name Direct message translation
/// functions family
///
///
/// Translate message \a id according to locale \a loc
///
template <typename CharType>
std::basic_string<CharType> gettext(CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(id).str(loc);
}
///
/// Translate plural form according to locale \a loc
///
template <typename CharType>
std::basic_string<CharType> ngettext(CharType const *s, CharType const *p,
int n,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(s, p, n).str(loc);
}
///
/// Translate message \a id according to locale \a loc in domain \a domain
///
template <typename CharType>
std::basic_string<CharType> dgettext(char const *domain, CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(id).str(loc, domain);
}
///
/// Translate plural form according to locale \a loc in domain \a domain
///
template <typename CharType>
std::basic_string<CharType> dngettext(char const *domain, CharType const *s,
CharType const *p, int n,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(s, p, n).str(loc, domain);
}
///
/// Translate message \a id according to locale \a loc in context \a context
///
template <typename CharType>
std::basic_string<CharType> pgettext(CharType const *context,
CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, id).str(loc);
}
///
/// Translate plural form according to locale \a loc in context \a context
///
template <typename CharType>
std::basic_string<CharType>
npgettext(CharType const *context, CharType const *s, CharType const *p, int n,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, s, p, n).str(loc);
}
///
/// Translate message \a id according to locale \a loc in domain \a domain in
/// context \a context
///
template <typename CharType>
std::basic_string<CharType>
dpgettext(char const *domain, CharType const *context, CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, id).str(loc, domain);
}
///
/// Translate plural form according to locale \a loc in domain \a domain in
/// context \a context
///
template <typename CharType>
std::basic_string<CharType>
dnpgettext(char const *domain, CharType const *context, CharType const *s,
CharType const *p, int n, std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, s, p, n).str(loc, domain);
}
///
/// \cond INTERNAL
///
template <>
struct BOOST_LOCALE_DECL base_message_format<char> : public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
template <>
struct BOOST_LOCALE_DECL base_message_format<wchar_t>
: public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
#ifdef BOOST_LOCALE_ENABLE_CHAR16_T
template <>
struct BOOST_LOCALE_DECL base_message_format<char16_t>
: public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
#endif
#ifdef BOOST_LOCALE_ENABLE_CHAR32_T
template <>
struct BOOST_LOCALE_DECL base_message_format<char32_t>
: public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
#endif
/// \endcond
///
/// @}
///
namespace as {
/// \cond INTERNAL
namespace details {
struct set_domain {
std::string domain_id;
};
template <typename CharType>
std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out,
set_domain const &dom) {
int id = std::use_facet<message_format<CharType>>(out.getloc())
.domain(dom.domain_id);
ios_info::get(out).domain_id(id);
return out;
}
} // namespace details
/// \endcond
///
/// \addtogroup manipulators
///
/// @{
///
/// Manipulator for switching message domain in ostream,
///
/// \note The returned object throws std::bad_cast if the I/O stream does not
/// have \ref message_format facet installed
///
inline
#ifdef BOOST_LOCALE_DOXYGEN
unspecified_type
#else
details::set_domain
#endif
domain(std::string const &id) {
details::set_domain tmp = {id};
return tmp;
}
/// @}
} // namespace as
} // namespace locale
} // namespace boost
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#endif
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| 28.636996
| 80
| 0.657067
|
henrywarhurst
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.