hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e9d6e50343051d7a46cd39ba8de15e3b50100248 | 2,369 | cpp | C++ | Source/OpenTournament/UR_Ammo.cpp | NATOcm/OpenTournament | d279034fdad80bdbacb4d0dc687c334545364688 | [
"OML"
] | null | null | null | Source/OpenTournament/UR_Ammo.cpp | NATOcm/OpenTournament | d279034fdad80bdbacb4d0dc687c334545364688 | [
"OML"
] | null | null | null | Source/OpenTournament/UR_Ammo.cpp | NATOcm/OpenTournament | d279034fdad80bdbacb4d0dc687c334545364688 | [
"OML"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "UR_Ammo.h"
#include "UR_Weapon.h"
#include "UR_InventoryComponent.h"
#include "Engine.h"
#include "OpenTournament.h"
#include "UR_Character.h"
// Sets default values
AUR_Ammo::AUR_Ammo(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
Tbox = CreateDefaultSubobject<UBoxComponent>(TEXT("Box"));
Tbox->SetGenerateOverlapEvents(true);
Tbox->OnComponentBeginOverlap.AddDynamic(this, &AUR_Ammo::OnTriggerEnter);
Tbox->OnComponentEndOverlap.AddDynamic(this, &AUR_Ammo::OnTriggerExit);
RootComponent = Tbox;
SM_TBox = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Box Mesh"));
SM_TBox->SetupAttachment(RootComponent);
AmmoMesh = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("AmmoMesh1"));
AmmoMesh->SetupAttachment(RootComponent);
Sound = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Sound"));
Sound->SetupAttachment(RootComponent);
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AUR_Ammo::BeginPlay()
{
Super::BeginPlay();
Sound->SetActive(false);
}
// Called every frame
void AUR_Ammo::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (PlayerController != NULL)
{
if (bItemIsWithinRange)
{
Pickup();
}
}
}
void AUR_Ammo::Pickup()
{
Sound->SetActive(true);
Sound = UGameplayStatics::SpawnSoundAtLocation(this, Sound->Sound, this->GetActorLocation(), FRotator::ZeroRotator, 1.0f, 1.0f, 0.0f, nullptr, nullptr, true);
PlayerController->InventoryComponent->Add(this);
Destroy();
}
void AUR_Ammo::GetPlayer(AActor* Player)
{
PlayerController = Cast<AUR_Character>(Player);
}
void AUR_Ammo::OnTriggerEnter(UPrimitiveComponent* HitComp, AActor* Other, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
bItemIsWithinRange = true;
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("HI this is ammo")));
GetPlayer(Other);
}
void AUR_Ammo::OnTriggerExit(UPrimitiveComponent* HitComp, AActor* Other, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("BYE this is ammo")));
}
| 29.987342 | 177 | 0.743774 | NATOcm |
e9d828303c4ff6fb18b1755be725f7294977499b | 629 | cpp | C++ | _posts/KickStart/2021_Round_B/Increasing Substring.cpp | Yukun4119/Yukun4119.github.io | 152f87e46295bcb09f485bce2dd27ae2b9316d6a | [
"MIT"
] | null | null | null | _posts/KickStart/2021_Round_B/Increasing Substring.cpp | Yukun4119/Yukun4119.github.io | 152f87e46295bcb09f485bce2dd27ae2b9316d6a | [
"MIT"
] | null | null | null | _posts/KickStart/2021_Round_B/Increasing Substring.cpp | Yukun4119/Yukun4119.github.io | 152f87e46295bcb09f485bce2dd27ae2b9316d6a | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ar array
void solve(int len, string str){
int curSum = 1;
cout << 1 << " ";
for(int i = 1; i < len; i++){
if(str[i] > str[i - 1])
{
curSum++;
}
else{
curSum = 1;
}
cout << curSum << " ";
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
int i = 1;
while(t--){
int len;
string str;
cin >> len >> str;
cout << "Case #" << i++ << ": ";
solve(len, str);
cout << endl;
}
} | 17 | 40 | 0.406995 | Yukun4119 |
e9d9069c98c942b3368527f19576d82262a8b4da | 1,763 | cpp | C++ | src/module/Pid.cpp | Oiwane/etrobocon2019 | 065bbd58f721b479a4862c3344a8fb744fd18df6 | [
"WTFPL"
] | 3 | 2020-02-29T16:32:00.000Z | 2021-05-10T18:30:12.000Z | src/module/Pid.cpp | Oiwane/etrobocon2019 | 065bbd58f721b479a4862c3344a8fb744fd18df6 | [
"WTFPL"
] | 310 | 2019-05-21T06:56:11.000Z | 2019-11-18T19:12:32.000Z | src/module/Pid.cpp | Oiwane/etrobocon2019 | 065bbd58f721b479a4862c3344a8fb744fd18df6 | [
"WTFPL"
] | 12 | 2019-05-21T06:19:59.000Z | 2021-05-17T15:19:48.000Z | /**
* @file Pid.cpp
* @brief PID制御クラス
* @author T.Miyaji
*/
#include "Pid.h"
PidGain::PidGain(double Kp_, double Ki_, double Kd_)
: ConstPidGain(Kp_, Ki_, Kd_)//, Kp(Kp_), Ki(Ki_), Kd(Kd_)
{
}
Pid::Pid(double target_, double Kp_, double Ki_, double Kd_)
: target(target_), gain(Kp_, Ki_, Kd_), integral(0.0f), preError(0.0f)
{
}
void PidGain::setPidGain(double Kp_, double Ki_, double Kd_)
{
Kp = Kp_;
Ki = Ki_;
Kd = Kd_;
}
/**
* [Pid::control]
* @param value [現在値]
* @param delta [タスク周期]
* @return [PID制御後の操作量]
*/
double Pid::control(double value, double delta)
{
// 目標値と現在値との偏差を求める
double error = target - value;
// 偏差の積分処理
integral += error * delta;
// 偏差の微分処理
double diff = (error - preError) / delta;
// 前回偏差の更新
preError = error;
// P制御の計算(Pゲイン * 偏差)
double p = gain.Kp * error;
// I制御の計算(Iゲイン * 偏差の積分値)
double i = gain.Ki * integral;
// D制御の計算(Dゲイン * 偏差の微分値)
double d = gain.Kd * diff;
return limit(p + i + d);
}
/**
* @brief 目標値とPIDゲインの設定をする関数
* @param target_ [設定する目標値]
* @param Kp_ [Pゲイン]
* @param Ki_ [Iゲイン]
* @param Kd_ [Dゲイン]
* @param 設定した目標値
*/
const double Pid::setParameter(double target_, double Kp_, double Ki_, double Kd_)
{
target = target_;
setPidGain(Kp_, Ki_, Kd_);
return target;
}
/**
* @brief PIDゲインの設定をする関数
* @param Kp_ [Pゲイン]
* @param Ki_ [Iゲイン]
* @param Kd_ [Dゲイン]
* @param PidGain構造体の参照
*/
const PidGain& Pid::setPidGain(double Kp_, double Ki_, double Kd_)
{
gain.setPidGain(Kp_, Ki_, Kd_);
return gain;
}
/**
* [Pid::limit 操作量を[-100, 100]の間に設定する]
* @param value [操作量]
* @return [制限をかけた後の操作量]
*/
double Pid::limit(double value)
{
if(value > 100.0) return 100.0;
if(value < -100.0) return -100.0;
return value;
}
| 18.755319 | 82 | 0.6211 | Oiwane |
e9da2f8a629a8c55e28158299f6c63c553f29559 | 13,581 | cpp | C++ | spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/tests/performance-tests/Classes/tests/controller.cpp | BowenCoder/spine-cocos2dx | cfac5100b78782b2d4ce84b472a435f46aff4da9 | [
"MIT"
] | null | null | null | spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/tests/performance-tests/Classes/tests/controller.cpp | BowenCoder/spine-cocos2dx | cfac5100b78782b2d4ce84b472a435f46aff4da9 | [
"MIT"
] | null | null | null | spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/tests/performance-tests/Classes/tests/controller.cpp | BowenCoder/spine-cocos2dx | cfac5100b78782b2d4ce84b472a435f46aff4da9 | [
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "controller.h"
#include <functional>
#include <chrono>
#include "BaseTest.h"
#include "tests.h"
#include "Profile.h"
USING_NS_CC;
#define TEST_TIME_OUT 6000
#define CREATE_TIME_OUT 25
#define LOG_INDENTATION " "
#define LOG_TAG "[TestController]"
static void initCrashCatch();
static void disableCrashCatch();
class RootTests : public TestList
{
public:
RootTests()
{
addTest("Alloc Tests", []() { return new PerformceAllocTests(); });
addTest("Node Children Tests", []() { return new PerformceNodeChildrenTests(); });
addTest("Particle Tests", []() { return new PerformceParticleTests(); });
addTest("Particle3D Tests", []() { return new PerformceParticle3DTests(); });
addTest("Sprite Tests", []() { return new PerformceSpriteTests(); });
addTest("Texture Tests", []() { return new PerformceTextureTests(); });
addTest("Label Tests", []() { return new PerformceLabelTests(); });
addTest("EventDispatcher Tests", []() { return new PerformceEventDispatcherTests(); });
addTest("Scenario Tests", []() { return new PerformceScenarioTests(); });
addTest("Callback Tests", []() { return new PerformceCallbackTests(); });
addTest("Math Tests", []() { return new PerformceMathTests(); });
addTest("Container Tests", []() { return new PerformceContainerTests(); });
}
};
TestController::TestController()
: _stopAutoTest(true)
, _isRunInBackground(false)
, _testSuite(nullptr)
{
_director = Director::getInstance();
_rootTestList = new (std::nothrow) RootTests;
_rootTestList->runThisTest();
}
TestController::~TestController()
{
_rootTestList->release();
_rootTestList = nullptr;
}
void TestController::startAutoTest()
{
if (!_autoTestThread.joinable())
{
_stopAutoTest = false;
_logIndentation = "";
_autoTestThread = std::thread(&TestController::traverseThreadFunc, this);
_autoTestThread.detach();
}
}
void TestController::stopAutoTest()
{
_stopAutoTest = true;
if (_autoTestThread.joinable()) {
_sleepCondition.notify_all();
_autoTestThread.join();
}
}
void TestController::traverseThreadFunc()
{
std::mutex sleepMutex;
auto lock = std::unique_lock<std::mutex>(sleepMutex);
_sleepUniqueLock = &lock;
traverseTestList(_rootTestList);
_sleepUniqueLock = nullptr;
// write the test data into file.
Profile::getInstance()->flush();
Profile::destroyInstance();
}
void TestController::traverseTestList(TestList* testList)
{
if (testList == _rootTestList)
{
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500));
}
else
{
_logIndentation += LOG_INDENTATION;
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500));
}
logEx("%s%sBegin traverse TestList:%s", LOG_TAG, _logIndentation.c_str(), testList->getTestName().c_str());
auto scheduler = _director->getScheduler();
int testIndex = 0;
for (auto& callback : testList->_testCallbacks)
{
if (_stopAutoTest) break;
while (_isRunInBackground)
{
logEx("_director is paused");
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500));
}
if (callback)
{
auto test = callback();
test->setTestParent(testList);
test->setTestName(testList->_childTestNames[testIndex++]);
if (test->isTestList())
{
scheduler->performFunctionInCocosThread([&](){
test->runThisTest();
});
traverseTestList((TestList*)test);
}
else
{
traverseTestSuite((TestSuite*)test);
}
}
}
if (testList == _rootTestList)
{
_stopAutoTest = true;
}
else
{
if (!_stopAutoTest)
{
//Backs up one level and release TestList object.
scheduler->performFunctionInCocosThread([&](){
testList->_parentTest->runThisTest();
});
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500));
testList->release();
}
_logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION));
}
}
void TestController::traverseTestSuite(TestSuite* testSuite)
{
auto scheduler = _director->getScheduler();
int testIndex = 0;
float testCaseDuration = 0.0f;
_logIndentation += LOG_INDENTATION;
logEx("%s%sBegin traverse TestSuite:%s", LOG_TAG, _logIndentation.c_str(), testSuite->getTestName().c_str());
_logIndentation += LOG_INDENTATION;
testSuite->_currTestIndex = -1;
auto logIndentation = _logIndentation;
for (auto& callback : testSuite->_testCallbacks)
{
auto testName = testSuite->_childTestNames[testIndex++];
Scene* testScene = nullptr;
TestCase* testCase = nullptr;
TransitionScene* transitionScene = nullptr;
if (_stopAutoTest) break;
while (_isRunInBackground)
{
logEx("_director is paused");
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500));
}
//Run test case in the cocos[GL] thread.
scheduler->performFunctionInCocosThread([&, logIndentation, testName](){
if (_stopAutoTest) return;
logEx("%s%sRun test:%s.", LOG_TAG, logIndentation.c_str(), testName.c_str());
auto scene = callback();
if (_stopAutoTest) return;
if (scene)
{
transitionScene = dynamic_cast<TransitionScene*>(scene);
if (transitionScene)
{
testCase = (TestCase*)transitionScene->getInScene();
testCaseDuration = transitionScene->getDuration() + 0.5f;
}
else
{
testCase = (TestCase*)scene;
testCaseDuration = testCase->getDuration();
}
testSuite->_currTestIndex++;
testCase->setTestSuite(testSuite);
testCase->setTestCaseName(testName);
testCase->setAutoTesting(true);
_director->replaceScene(scene);
testScene = scene;
}
});
if (_stopAutoTest) break;
//Wait for the test case be created.
float waitTime = 0.0f;
while (!testScene && !_stopAutoTest)
{
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(50));
if (!_isRunInBackground)
{
waitTime += 0.05f;
}
if (waitTime > CREATE_TIME_OUT)
{
logEx("%sCreate test %s time out", LOG_TAG, testName.c_str());
_stopAutoTest = true;
break;
}
}
if (_stopAutoTest) break;
//Wait for test completed.
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(int(1000 * testCaseDuration)));
if (transitionScene == nullptr)
{
waitTime = 0.0f;
while (!_stopAutoTest && testCase->isAutoTesting())
{
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(50));
if (!_isRunInBackground)
{
waitTime += 0.05f;
}
if (waitTime > TEST_TIME_OUT)
{
logEx("%sRun test %s time out", LOG_TAG, testName.c_str());
_stopAutoTest = true;
break;
}
}
if (!_stopAutoTest)
{
//Check the result of test.
checkTest(testCase);
}
}
}
if (!_stopAutoTest)
{
//Backs up one level and release TestSuite object.
auto parentTest = testSuite->_parentTest;
scheduler->performFunctionInCocosThread([parentTest](){
parentTest->runThisTest();
});
_sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(1000));
testSuite->release();
}
_logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION));
_logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION));
}
bool TestController::checkTest(TestCase* testCase)
{
if (testCase)
{
switch (testCase->getTestType())
{
case TestCase::Type::UNIT:
{
if (testCase && testCase->getExpectedOutput() != testCase->getActualOutput())
{
logEx("%s %s test fail", LOG_TAG, testCase->getTestCaseName().c_str());
}
else
{
logEx("%s %s test pass", LOG_TAG, testCase->getTestCaseName().c_str());
}
break;
}
case TestCase::Type::ROBUSTNESS:
{
break;
}
case TestCase::Type::MANUAL:
{
break;
}
default:
break;
}
}
return true;
}
void TestController::handleCrash()
{
disableCrashCatch();
logEx("%sCatch an crash event", LOG_TAG);
if (!_stopAutoTest)
{
stopAutoTest();
}
}
void TestController::onEnterBackground()
{
_isRunInBackground = true;
}
void TestController::onEnterForeground()
{
_isRunInBackground = false;
}
void TestController::logEx(const char * format, ...)
{
char buff[1024];
va_list args;
va_start(args, format);
vsnprintf(buff, 1020, format, args);
strcat(buff, "\n");
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buff);
#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
WCHAR wszBuf[1024] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, buff, -1, wszBuf, sizeof(wszBuf));
OutputDebugStringW(wszBuf);
#else
// Linux, Mac, iOS, etc
fprintf(stdout, "%s", buff);
fflush(stdout);
#endif
va_end(args);
}
static TestController* s_testController = nullptr;
TestController* TestController::getInstance()
{
if (s_testController == nullptr)
{
s_testController = new (std::nothrow) TestController;
initCrashCatch();
}
return s_testController;
}
void TestController::destroyInstance()
{
if (s_testController)
{
s_testController->stopAutoTest();
delete s_testController;
s_testController = nullptr;
}
disableCrashCatch();
}
bool TestController::blockTouchBegan(Touch* touch, Event* event)
{
return !_stopAutoTest;
}
//==================================================================================================
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#include <windows.h>
static long __stdcall windowExceptionFilter(_EXCEPTION_POINTERS* excp)
{
if (s_testController)
{
s_testController->handleCrash();
}
return EXCEPTION_EXECUTE_HANDLER;
}
static void initCrashCatch()
{
SetUnhandledExceptionFilter(windowExceptionFilter);
}
static void disableCrashCatch()
{
SetUnhandledExceptionFilter(UnhandledExceptionFilter);
}
#elif CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
static int s_fatal_signals[] = {
SIGILL,
SIGABRT,
SIGBUS,
SIGFPE,
SIGSEGV,
SIGSTKFLT,
SIGPIPE,
};
#else
static int s_fatal_signals[] = {
SIGABRT,
SIGBUS,
SIGFPE,
SIGILL,
SIGSEGV,
SIGTRAP,
SIGTERM,
SIGKILL
};
#endif
static void signalHandler(int sig)
{
if (s_testController)
{
s_testController->handleCrash();
}
}
static void initCrashCatch()
{
for (auto sig : s_fatal_signals)
{
signal(sig, signalHandler);
}
}
static void disableCrashCatch()
{
for (auto sig : s_fatal_signals)
{
signal(sig, SIG_DFL);
}
}
#else
static void initCrashCatch()
{
}
static void disableCrashCatch()
{
}
#endif
| 27.381048 | 129 | 0.600545 | BowenCoder |
e9dba42178d9d92f71535b72fa3fb4a4ab1115f5 | 6,214 | cc | C++ | src/quicksilver/PopulationControl.cc | cpc/hipcl-samples | 59ce99784b5e3158a9e23a9790a277586ada70e5 | [
"MIT"
] | 1 | 2020-12-29T21:44:16.000Z | 2020-12-29T21:44:16.000Z | src/quicksilver/PopulationControl.cc | cpc/hipcl-samples | 59ce99784b5e3158a9e23a9790a277586ada70e5 | [
"MIT"
] | null | null | null | src/quicksilver/PopulationControl.cc | cpc/hipcl-samples | 59ce99784b5e3158a9e23a9790a277586ada70e5 | [
"MIT"
] | 1 | 2020-04-09T22:04:18.000Z | 2020-04-09T22:04:18.000Z | #include "PopulationControl.hh"
#include "Globals.hh"
#include "MC_Particle.hh"
#include "MC_Processor_Info.hh"
#include "MonteCarlo.hh"
#include "NVTX_Range.hh"
#include "ParticleVault.hh"
#include "ParticleVaultContainer.hh"
#include "utilsMpi.hh"
#include <vector>
namespace {
void PopulationControlGuts(const double splitRRFactor,
uint64_t currentNumParticles,
ParticleVaultContainer *my_particle_vault,
Balance &taskBalance);
}
void PopulationControl(MonteCarlo *monteCarlo, bool loadBalance) {
NVTX_Range range("PopulationControl");
uint64_t targetNumParticles = monteCarlo->_params.simulationParams.nParticles;
uint64_t globalNumParticles = 0;
uint64_t localNumParticles =
monteCarlo->_particleVaultContainer->sizeProcessing();
if (loadBalance) {
// If we are parallel, we will have one domain per mpi processs. The
// targetNumParticles is across all MPI processes, so we need to divide by
// the number or ranks to get the per-mpi-process number targetNumParticles
targetNumParticles = ceil((double)targetNumParticles /
(double)mcco->processor_info->num_processors);
// NO LONGER SPLITING VAULTS BY THREADS
// // If we are threaded, targetNumParticles should be divided by the
// number of threads (tasks) to balance
// // the particles across the thread level vaults.
// targetNumParticles = ceil((double)targetNumParticles /
// (double)mcco->processor_info->num_tasks);
} else {
mpiAllreduce(&localNumParticles, &globalNumParticles, 1, MPI_UINT64_T,
MPI_SUM, MPI_COMM_WORLD);
}
Balance &taskBalance = monteCarlo->_tallies->_balanceTask[0];
double splitRRFactor = 1.0;
if (loadBalance) {
int currentNumParticles = localNumParticles;
if (currentNumParticles != 0)
splitRRFactor = (double)targetNumParticles / (double)currentNumParticles;
else
splitRRFactor = 1.0;
} else {
splitRRFactor = (double)targetNumParticles / (double)globalNumParticles;
}
if (splitRRFactor !=
1.0) // no need to split if population is already correct.
PopulationControlGuts(splitRRFactor, localNumParticles,
monteCarlo->_particleVaultContainer, taskBalance);
monteCarlo->_particleVaultContainer->collapseProcessing();
return;
}
namespace {
void PopulationControlGuts(const double splitRRFactor,
uint64_t currentNumParticles,
ParticleVaultContainer *my_particle_vault,
Balance &taskBalance) {
uint64_t vault_size = my_particle_vault->getVaultSize();
uint64_t fill_vault_index = currentNumParticles / vault_size;
// March backwards through the vault so killed particles doesn't mess up the
// indexing
for (int particleIndex = currentNumParticles - 1; particleIndex >= 0;
particleIndex--) {
uint64_t vault_index = particleIndex / vault_size;
ParticleVault &taskProcessingVault =
*(my_particle_vault->getTaskProcessingVault(vault_index));
uint64_t taskParticleIndex = particleIndex % vault_size;
MC_Base_Particle ¤tParticle = taskProcessingVault[taskParticleIndex];
double randomNumber = rngSample(¤tParticle.random_number_seed);
if (splitRRFactor < 1) {
if (randomNumber > splitRRFactor) {
// Kill
taskProcessingVault.eraseSwapParticle(taskParticleIndex);
taskBalance._rr++;
} else {
currentParticle.weight /= splitRRFactor;
}
} else if (splitRRFactor > 1) {
// Split
int splitFactor = (int)floor(splitRRFactor);
if (randomNumber > (splitRRFactor - splitFactor)) {
splitFactor--;
}
currentParticle.weight /= splitRRFactor;
MC_Base_Particle splitParticle = currentParticle;
for (int splitFactorIndex = 0; splitFactorIndex < splitFactor;
splitFactorIndex++) {
taskBalance._split++;
splitParticle.random_number_seed =
rngSpawn_Random_Number_Seed(¤tParticle.random_number_seed);
splitParticle.identifier = splitParticle.random_number_seed;
my_particle_vault->addProcessingParticle(splitParticle,
fill_vault_index);
}
}
}
}
} // anonymous namespace
// Roulette low-weight particles relative to the source particle weight.
void RouletteLowWeightParticles(MonteCarlo *monteCarlo) {
NVTX_Range range("RouletteLowWeightParticles");
const double lowWeightCutoff =
monteCarlo->_params.simulationParams.lowWeightCutoff;
if (lowWeightCutoff > 0.0) {
uint64_t currentNumParticles =
monteCarlo->_particleVaultContainer->sizeProcessing();
uint64_t vault_size = monteCarlo->_particleVaultContainer->getVaultSize();
Balance &taskBalance = monteCarlo->_tallies->_balanceTask[0];
// March backwards through the vault so killed particles don't mess up the
// indexing
const double source_particle_weight = monteCarlo->source_particle_weight;
const double weightCutoff = lowWeightCutoff * source_particle_weight;
for (int64_t particleIndex = currentNumParticles - 1; particleIndex >= 0;
particleIndex--) {
uint64_t vault_index = particleIndex / vault_size;
ParticleVault &taskProcessingVault =
*(monteCarlo->_particleVaultContainer->getTaskProcessingVault(
vault_index));
uint64_t taskParticleIndex = particleIndex % vault_size;
MC_Base_Particle ¤tParticle =
taskProcessingVault[taskParticleIndex];
if (currentParticle.weight <= weightCutoff) {
double randomNumber = rngSample(¤tParticle.random_number_seed);
if (randomNumber <= lowWeightCutoff) {
// The particle history continues with an increased weight.
currentParticle.weight /= lowWeightCutoff;
} else {
// Kill
taskProcessingVault.eraseSwapParticle(taskParticleIndex);
taskBalance._rr++;
}
}
}
monteCarlo->_particleVaultContainer->collapseProcessing();
}
}
| 36.769231 | 80 | 0.691664 | cpc |
e9dbbf1d6b858347e18074452de13632c686f057 | 926 | cpp | C++ | Lib/Filters/PowerFilter.cpp | vfdev-5/GeoImageViewer | 31e8d6c9340a742c0ffad4c159338da2c15564d7 | [
"Apache-2.0"
] | 3 | 2016-08-27T10:46:43.000Z | 2022-03-11T11:39:37.000Z | Lib/Filters/PowerFilter.cpp | vfdev-5/GeoImageViewer | 31e8d6c9340a742c0ffad4c159338da2c15564d7 | [
"Apache-2.0"
] | null | null | null | Lib/Filters/PowerFilter.cpp | vfdev-5/GeoImageViewer | 31e8d6c9340a742c0ffad4c159338da2c15564d7 | [
"Apache-2.0"
] | 2 | 2016-08-27T10:46:45.000Z | 2018-06-06T01:50:54.000Z |
// Opencv
#include <opencv2/imgproc/imgproc.hpp>
// Project
#include "PowerFilter.h"
namespace Filters
{
//******************************************************************************
/*!
\class PowerFilter
\brief applies power operation on input image
*/
//******************************************************************************
PowerFilter::PowerFilter(QObject *parent) :
AbstractFilter(parent),
_power(2.0)
{
_name = tr("Power filter");
_description = tr("Apply power to image pixels");
}
//******************************************************************************
cv::Mat PowerFilter::filter(const cv::Mat &src) const
{
cv::Mat out;
SD_TRACE(QString("Power filter : power = %1").arg(_power));
cv::pow(src, _power, out);
return out;
}
//******************************************************************************
}
| 21.534884 | 81 | 0.395248 | vfdev-5 |
e9de17cbc602dcd1f34870fed745273110b33f8d | 14,949 | cxx | C++ | ds/adsi/winnt/ccache.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/adsi/winnt/ccache.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/adsi/winnt/ccache.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1995.
//
// File: ccache.cxx
//
// Contents: Class Cache functionality for the NT Provider
//
//
//----------------------------------------------------------------------------
#include "winnt.hxx"
HRESULT
SetOctetPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
BYTE *pByte,
DWORD dwLength,
BOOL fExplicit
)
{
HRESULT hr;
OctetString octString;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
octString.pByte = pByte;
octString.dwSize = dwLength;
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)&octString,
1,
NT_SYNTAX_ID_OCTETSTRING,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
SetLPTSTRPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
LPTSTR pszValue,
BOOL fExplicit
)
{
HRESULT hr;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)pszValue,
1,
NT_SYNTAX_ID_LPTSTR,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
SetDWORDPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
DWORD dwValue,
BOOL fExplicit
)
{
HRESULT hr;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)&dwValue,
1,
NT_SYNTAX_ID_DWORD,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
SetDATE70PropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
DWORD dwValue,
BOOL fExplicit
)
{
HRESULT hr;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)&dwValue,
1,
NT_SYNTAX_ID_DATE_1970,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
SetDATEPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
DWORD dwValue,
BOOL fExplicit
)
{
HRESULT hr;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)&dwValue,
1,
NT_SYNTAX_ID_DATE,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
SetBOOLPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
BOOL fValue,
BOOL fExplicit
)
{
HRESULT hr;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)&fValue,
1,
NT_SYNTAX_ID_BOOL,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
SetSYSTEMTIMEPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
SYSTEMTIME stValue,
BOOL fExplicit
)
{
HRESULT hr;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)&stValue,
1,
NT_SYNTAX_ID_SYSTEMTIME,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
SetDelimitedStringPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
LPTSTR pszValue,
BOOL fExplicit
)
{
HRESULT hr;
DWORD dwNumValues = 0;
LPWSTR pszString = AllocADsStr(pszValue);
if(!pszString){
hr = E_OUTOFMEMORY;
goto error;
}
if(!pPropertyCache){
BAIL_ON_FAILURE(hr = E_POINTER);
}
//
// Find the size of the delimited String
//
if((dwNumValues = DelimitedStrSize(pszString, TEXT(',')))== 0){
hr = E_FAIL;
goto error;
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)pszString,
dwNumValues,
NT_SYNTAX_ID_DelimitedString,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
if(pszString){
FreeADsStr(pszString);
}
RRETURN(hr);
}
HRESULT
SetNulledStringPropertyInCache(
CPropertyCache *pPropertyCache,
LPTSTR pszProperty,
LPTSTR pszValue,
BOOL fExplicit
)
{
HRESULT hr;
DWORD dwNumValues = 0;
if(!pPropertyCache){
RRETURN(E_POINTER);
}
//
// Find the size of the nulled String
//
if((dwNumValues = NulledStrSize(pszValue))== 0){
hr = E_FAIL;
goto error;
}
hr = pPropertyCache->unmarshallproperty(
pszProperty,
(LPBYTE)pszValue,
dwNumValues,
NT_SYNTAX_ID_NulledString,
fExplicit
);
BAIL_ON_FAILURE(hr);
error:
RRETURN(hr);
}
HRESULT
GetOctetPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
OctetString *pOctet)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == pOctet)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)pOctet
);
BAIL_ON_FAILURE(hr);
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetLPTSTRPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
LPTSTR * ppszValue
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == ppszValue)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)ppszValue
);
BAIL_ON_FAILURE(hr);
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetDelimitedStringPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
LPTSTR * ppszValue
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == ppszValue)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
if(SUCCEEDED(hr)){
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)ppszValue
);
}
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetNulledStringPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
LPTSTR * ppszValue
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == ppszValue)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
if(SUCCEEDED(hr)){
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)ppszValue
);
}
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetBOOLPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
PBOOL pBool
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == pBool)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
if(SUCCEEDED(hr)){
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)pBool
);
}
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetDWORDPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
LPDWORD pdwDWORD
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == pdwDWORD)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
if(SUCCEEDED(hr)){
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)pdwDWORD
);
}
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetDATE70PropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
LPDWORD pdwDWORD
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == pdwDWORD)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
if(SUCCEEDED(hr)){
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)pdwDWORD
);
}
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetDATEPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
PDWORD pdwDate
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == pdwDate)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
if(SUCCEEDED(hr)){
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)pdwDate
);
}
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
HRESULT
GetSYSTEMTIMEPropertyFromCache(
CPropertyCache * pPropertyCache,
LPTSTR pszProperty,
SYSTEMTIME * pstTime
)
{
HRESULT hr = S_OK;
DWORD dwSyntaxId = 0;
DWORD dwNumValues = 0;
PNTOBJECT pNTObject = NULL;
if (NULL == pstTime)
BAIL_ON_FAILURE(hr = E_POINTER);
hr = pPropertyCache->marshallgetproperty(
pszProperty,
&dwSyntaxId,
&dwNumValues,
&pNTObject
);
BAIL_ON_FAILURE(hr);
if(SUCCEEDED(hr)){
hr = MarshallNTSynIdToNT(
dwSyntaxId,
pNTObject,
dwNumValues,
(LPBYTE)pstTime
);
}
error:
if (pNTObject) {
NTTypeFreeNTObjects(
pNTObject,
dwNumValues
);
}
RRETURN (hr);
}
| 19.85259 | 79 | 0.45876 | npocmaka |
e9de7686b8409d39b981c1368ed62c5d3aeef028 | 212 | cc | C++ | src/commands/text_processing/TSR.cc | jhhuh/imgui-terminal | 134f9cb6779738ecf00d6aba8315702986f71115 | [
"MIT"
] | 32 | 2017-09-19T07:25:29.000Z | 2022-03-21T08:21:48.000Z | src/commands/text_processing/TSR.cc | jhhuh/imgui-terminal | 134f9cb6779738ecf00d6aba8315702986f71115 | [
"MIT"
] | 1 | 2017-10-24T18:56:36.000Z | 2017-10-24T18:56:36.000Z | src/commands/text_processing/TSR.cc | jhhuh/imgui-terminal | 134f9cb6779738ecf00d6aba8315702986f71115 | [
"MIT"
] | 10 | 2017-10-18T05:08:14.000Z | 2022-03-21T09:29:04.000Z |
#include <terminal/Terminal.hh>
namespace terminal {
// Tabulation Stop Remove
// ECMA-48 8.3.156
bool
Terminal::TSR(uint32_t p)
{
// no default
log("TSR(%u)", p);
//! @todo
return false;
}
}
| 10.095238 | 31 | 0.608491 | jhhuh |
e9e194746202dfce6120c13d255a498a8d780fd5 | 2,848 | cpp | C++ | Deitel/Chapter05/exercises/5.30/Question.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 19 | 2019-09-15T12:23:51.000Z | 2020-06-18T08:31:26.000Z | Deitel/Chapter05/exercises/5.30/Question.cpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 15 | 2021-12-07T06:46:03.000Z | 2022-01-31T07:55:32.000Z | Deitel/Chapter05/exercises/5.30/Question.cpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 13 | 2019-06-29T02:58:27.000Z | 2020-05-07T08:52:22.000Z | /*
* =====================================================================================
*
* Filename:
*
* Description:
*
* Version: 1.0
* Created: Thanks to github you know it
* Revision: none
* Compiler: g++
*
* Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com
*
*
* =====================================================================================
*/
#include <string>
#include "Question.hpp"
// INITIALISATION
// checks if question and answers are set and sets them if not
// creates and randomises an answers vector
void Question::initialise() {
std::string tmp;
if (_q.empty()) {
std::cout << "Enter a question: ";
std::cin >> tmp;
setQuestion(tmp);
}
if (_a.empty()) {
std::cout << "Enter correct answer: ";
std::cin >> tmp;
setA(tmp);
}
if (_b.empty()) {
std::cout << "Enter first incorrect answer: ";
std::cin >> tmp;
setB(tmp);
}
if (_c.empty()) {
std::cout << "Enter second incorrect answer: ";
std::cin >> tmp;
setC(tmp);
}
if (_d.empty()) {
std::cout << "Enter third incorrect answer: ";
std::cin >> tmp;
setD(tmp);
}
// build the answers vector
_answers.push_back(_a);
_answers.push_back(_b);
_answers.push_back(_c);
_answers.push_back(_d);
// randomise answers vector
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle(_answers.begin(), _answers.end(), std::default_random_engine(seed));
}
// SETTERS
void Question::setQuestion(const std::string& Q) { _q = Q; }
void Question::setA(const std::string& A) { _a = A; }
void Question::setB(const std::string& B) { _b = B; }
void Question::setC(const std::string& C) { _c = C; }
void Question::setD(const std::string& D) { _d = D; }
// GETTERS
// prints the question and randomised answers vector
void Question::getQuestion() const {
// question
std::cout << _q << std::endl << std::endl;
// answers
for (unsigned int i = 0; i < _answers.size(); i++) {
std::cout << _answers[i] << std::endl;
}
std::cout << std::endl;
}
// answer the question
// CHAR ANSWER
bool Question::answer(char& ans) {
if (ans == 'a' && _answers[0] == _a) {
_correct = 1;
return true;
}
if (ans == 'b' && _answers[1] == _a) {
_correct = 1;
return true;
}
if (ans == 'c' && _answers[2] == _a) {
_correct = 1;
return true;
}
if (ans == 'd' && _answers[3] == _a) {
_correct = 1;
return true;
}
return false;
}
// INT ANSWER
bool Question::answer(int ans) {
ans--;
if (_answers[ans] == _a) {
_correct = 1;
return true;
}
return false;
}
| 24.982456 | 88 | 0.508076 | SebastianTirado |
e9e19b9fe9823a14ad2f4b9741f0ce517bd24ab5 | 471 | hpp | C++ | Engine/Include/Sapphire/Maths/Space/TrComps.hpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | 2 | 2020-03-18T09:06:21.000Z | 2020-04-09T00:07:56.000Z | Engine/Include/Sapphire/Maths/Space/TrComps.hpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | Engine/Include/Sapphire/Maths/Space/TrComps.hpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | // Copyright 2020 Sapphire development team. All Rights Reserved.
#pragma once
#ifndef SAPPHIRE_MATHS_TR_COMPS_GUARD
#define SAPPHIRE_MATHS_TR_COMPS_GUARD
#include <Core/Types/Int.hpp>
namespace Sa
{
enum class TrComp : uint8
{
None = 0,
Position = 1 << 0,
Rotation = 1 << 1,
Scale = 1 << 2,
// === Groups ===
PR = Position | Rotation,
PS = Position | Scale,
RS = Rotation | Scale,
PRS = Position | Rotation | Scale,
};
}
#endif // GUARD
| 13.852941 | 65 | 0.649682 | SapphireSuite |
e9e2430d410fb5da9fcd33d9f7e3b3ddd6adee8c | 8,588 | hpp | C++ | engine/engine/core/buffers/buffer.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | engine/engine/core/buffers/buffer.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | engine/engine/core/buffers/buffer.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2022-01-28T16:37:51.000Z | 2022-01-28T16:37:51.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include <memory>
#include <type_traits>
#include <utility>
#include "engine/core/allocator/allocators.hpp"
#include "engine/core/buffers/traits.hpp"
#include "engine/core/byte.hpp"
namespace isaac {
// -------------------------------------------------------------------------------------------------
namespace detail {
// A simple pointer which can be tagged. This is used for example to differentiate between a pointer
// to host memory and a pointer to device memory.
template <typename K, typename Tag = byte>
class TaggedPointer {
public:
using value_t = std::remove_cv_t<K>;
using const_pointer_t = TaggedPointer<const value_t, Tag>;
using pointer_t = TaggedPointer<value_t, Tag>;
using tag_t = Tag;
// Standard constructor
TaggedPointer(K* data = nullptr) : data_(data) {}
// Default copy
TaggedPointer(const TaggedPointer& other) = default;
TaggedPointer& operator=(const TaggedPointer& other) = default;
// Move will set source to nullptr
TaggedPointer(TaggedPointer&& other) { *this = std::move(other); }
TaggedPointer& operator=(TaggedPointer&& other) {
data_ = other.data_;
other.data_ = nullptr;
return *this;
}
// Sets the actual pointer
TaggedPointer& operator=(K* other) {
data_ = other;
return *this;
}
// Gets the actual pointer
K* get() const { return data_; }
operator K*() const { return data_; }
private:
K* data_;
};
} // namespace detail
// -------------------------------------------------------------------------------------------------
namespace detail {
// Base class for Buffer and BufferView which provides storage for the memory pointer
// and corresponding dimensions.
template <typename Pointer>
class BufferBase {
public:
using pointer_t = Pointer;
BufferBase() : pointer_(nullptr), size_(0) {}
BufferBase(Pointer pointer, size_t size)
: pointer_(std::move(pointer)), size_(size) {}
// pointer to the first row
const Pointer& pointer() const { return pointer_; }
// The total size of the buffer in bytes
size_t size() const { return size_; }
// A pointer to the first byte of the buffer.
auto begin() const { return pointer_.get(); }
// A pointer behind the last byte of the buffer.
auto end() const { return begin() + size(); }
protected:
Pointer pointer_;
size_t size_;
};
} // namespace detail
// -------------------------------------------------------------------------------------------------
// A buffer which owns its memory
template <typename Pointer, typename Allocator>
class Buffer : public detail::BufferBase<Pointer> {
public:
using mutable_view_t = detail::BufferBase<typename Pointer::pointer_t>;
using const_view_t = detail::BufferBase<typename Pointer::const_pointer_t>;
Buffer() : handle_(nullptr, Deleter{0}) {}
// Allocates memory for `size` bytes.
Buffer(size_t size)
: detail::BufferBase<Pointer>(nullptr, size),
handle_(Allocator::Allocate(size), Deleter{size}) {
// 1) Initialize the base class with a nullptr, the number of rows, and the desired stride.
// 2) Allocate memory and store it in the unique pointer used as handle. This will also change
// the stride stored in the base class to the actual stride chosen by the allocator.
// 3) Get a pointer to the allocated memory and store it in the base class so that calls to
// pointer() actually work.
this->pointer_ = handle_.get();
}
Buffer(Buffer&& buffer)
: detail::BufferBase<Pointer>(nullptr, buffer.size_),
handle_(std::move(buffer.handle_)) {
this->pointer_ = handle_.get();
buffer.pointer_ = nullptr;
buffer.size_ = 0;
}
Buffer& operator=(Buffer&& buffer) {
this->handle_ = std::move(buffer.handle_);
this->pointer_ = this->handle_.get();
this->size_ = buffer.size_;
buffer.pointer_ = nullptr;
buffer.size_ = 0;
return *this;
}
void resize(size_t desired_size) {
if (desired_size == this->size()) return;
*this = Buffer<Pointer, Allocator>(desired_size);
}
// Disowns the pointer from the buffer. The user is now responsible for deallocation.
// WARNING: This is dangerous as the wrong allocator might be called.
byte* release() {
byte* pointer = handle_.release();
this->pointer_ = nullptr;
return pointer;
}
// Creates a view which provides read and write access from this buffer object.
mutable_view_t view() { return mutable_view_t(this->pointer_, this->size_, this->stride_); }
const_view_t view() const {
return const_view_t(typename Pointer::const_pointer_t(this->pointer_.get()), this->size_);
}
// Creates a view which only provides read access from this buffer object.
const_view_t const_view() const {
return const_view_t(typename Pointer::const_pointer_t(this->pointer_.get()), this->size_);
}
private:
// A deleter object for the unique pointer to free allocated memory
struct Deleter {
size_t size;
void operator()(byte* pointer) {
if (size == 0) return;
Allocator::Deallocate(pointer, size);
}
};
// A unique pointer is used to handle the allocator and to make this object non-copyable.
using handle_t = std::unique_ptr<byte, Deleter>;
// Memory handle used to automatically deallocate memory and to disallow copy semantics.
handle_t handle_;
};
// -------------------------------------------------------------------------------------------------
// A pointer to host memory
template <typename K>
using HostPointer =
detail::TaggedPointer<K, std::integral_constant<BufferStorageMode, BufferStorageMode::Host>>;
// A host buffer with stride which owns its memory
using CpuBuffer = Buffer<HostPointer<byte>, CpuAllocator>;
// A host buffer with stride which does not own its memory
using CpuBufferView = detail::BufferBase<HostPointer<byte>>;
// A host buffer with stride which does not own its memory and provides only read access
using CpuBufferConstView = detail::BufferBase<HostPointer<const byte>>;
template <>
struct BufferTraits<Buffer<HostPointer<byte>, CpuAllocator>> {
static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Host;
static constexpr bool kIsMutable = true;
static constexpr bool kIsOwning = true;
using buffer_view_t = CpuBufferView;
using buffer_const_view_t = CpuBufferConstView;
};
template <typename K>
struct BufferTraits<detail::BufferBase<HostPointer<K>>> {
static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Host;
static constexpr bool kIsMutable = !std::is_const<K>::value;
static constexpr bool kIsOwning = false;
using buffer_view_t = CpuBufferView;
using buffer_const_view_t = CpuBufferConstView;
};
// -------------------------------------------------------------------------------------------------
// A pointer to CUDA memory
template <typename K>
using CudaPointer =
detail::TaggedPointer<K, std::integral_constant<BufferStorageMode, BufferStorageMode::Cuda>>;
// A CUDA buffer with stride which owns its memory
using CudaBuffer = Buffer<CudaPointer<byte>, CudaAllocator>;
// A CUDA buffer with stride which does not own its memory
using CudaBufferView = detail::BufferBase<CudaPointer<byte>>;
// A CUDA buffer with stride which does not own its memory and provides only read access
using CudaBufferConstView = detail::BufferBase<CudaPointer<const byte>>;
template <>
struct BufferTraits<Buffer<CudaPointer<byte>, CudaAllocator>> {
static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Cuda;
static constexpr bool kIsMutable = true;
static constexpr bool kIsOwning = true;
using buffer_view_t = CudaBufferView;
using buffer_const_view_t = CudaBufferConstView;
};
template <typename K>
struct BufferTraits<detail::BufferBase<CudaPointer<K>>> {
static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Cuda;
static constexpr bool kIsMutable = !std::is_const<K>::value;
static constexpr bool kIsOwning = false;
using buffer_view_t = CudaBufferView;
using buffer_const_view_t = CudaBufferConstView;
};
// -------------------------------------------------------------------------------------------------
} // namespace isaac
| 34.079365 | 100 | 0.680135 | ddr95070 |
e9e773d1fcbe1bbdfaadbcbae3b45b1baf2afd37 | 803 | ipp | C++ | include/network/protocol/http/client/connection_manager.ipp | iBeacons/cpp-netlib | 9d03a037e465df96a98c1db5f3e50a865f501b64 | [
"BSL-1.0"
] | 1 | 2017-04-11T17:27:38.000Z | 2017-04-11T17:27:38.000Z | include/network/protocol/http/client/connection_manager.ipp | iBeacons/cpp-netlib | 9d03a037e465df96a98c1db5f3e50a865f501b64 | [
"BSL-1.0"
] | null | null | null | include/network/protocol/http/client/connection_manager.ipp | iBeacons/cpp-netlib | 9d03a037e465df96a98c1db5f3e50a865f501b64 | [
"BSL-1.0"
] | null | null | null | // Copyright 2011 Dean Michael Berris <dberris@google.com>.
// Copyright 2011 Google, Inc.
// 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 NETWORK_PROTOCOL_HTTP_CLIENT_CONNECTION_MANAGER_IPP_20111103
#define NETWORK_PROTOCOL_HTTP_CLIENT_CONNECTION_MANAGER_IPP_20111103
#include <network/protocol/http/client/connection_manager.hpp>
#include <network/detail/debug.hpp>
namespace network { namespace http {
connection_manager::~connection_manager() {
NETWORK_MESSAGE("connection_manager::~connection_manager()");
// default implementation, for linkage only.
}
} // namespace http
} // namespace network
#endif /* NETWORK_PROTOCOL_HTTP_CLIENT_CONNECTION_MANAGER_IPP_20111103 */
| 33.458333 | 73 | 0.801993 | iBeacons |
e9eb978e3086fe8baa1e6cfdeb16ca3be755e92b | 7,980 | cpp | C++ | plugins/newarc.ex/Newarc/Source/processname.cpp | MKadaner/FarManager | c99a14c12e3481dd25ce71451ecd264656f631bb | [
"BSD-3-Clause"
] | 1,256 | 2015-07-07T12:19:17.000Z | 2022-03-31T18:41:41.000Z | plugins/newarc.ex/Newarc/Source/processname.cpp | MKadaner/FarManager | c99a14c12e3481dd25ce71451ecd264656f631bb | [
"BSD-3-Clause"
] | 305 | 2017-11-01T18:58:50.000Z | 2022-03-22T11:07:23.000Z | plugins/newarc.ex/Newarc/Source/processname.cpp | MKadaner/FarManager | c99a14c12e3481dd25ce71451ecd264656f631bb | [
"BSD-3-Clause"
] | 183 | 2017-10-28T11:31:14.000Z | 2022-03-30T16:46:24.000Z | #define PF_FLAG_QUOTE_SPACES 1 //Q
#define PF_FLAG_QUOTE_ALL 2 //q
#define PF_FLAG_USE_BACKSLASH 4 //S
#define PF_FLAG_DIR_NAME_AS_MASK 8 //M
#define PF_FLAG_DIR_NAME_AS_NAME 16 //N
#define PF_FLAG_NAME_ONLY 32 //W
#define PF_FLAG_PATH_ONLY 64 //P
#define PF_FLAG_ANSI_CHARSET 128 //A
#define PF_FLAG_UTF8_CHARSET 256 //8
#define PF_FLAG_UTF16_CHARSET 512 //U
#define QUERY_AND_SET_PARAM_FLAG(c, flag) \
case c: \
dwFlags |= flag; \
break;
const TCHAR *GetFlags(const TCHAR *p, DWORD &dwFlags)
{
dwFlags = 0;
while ( *p && (*p != _T(' ')) && (*p != _T('}')) )
{
switch ( *p )
{
QUERY_AND_SET_PARAM_FLAG (_T('Q'), PF_FLAG_QUOTE_SPACES);
QUERY_AND_SET_PARAM_FLAG (_T('q'), PF_FLAG_QUOTE_ALL);
QUERY_AND_SET_PARAM_FLAG (_T('S'), PF_FLAG_USE_BACKSLASH);
QUERY_AND_SET_PARAM_FLAG (_T('M'), PF_FLAG_DIR_NAME_AS_MASK);
QUERY_AND_SET_PARAM_FLAG (_T('N'), PF_FLAG_DIR_NAME_AS_NAME);
QUERY_AND_SET_PARAM_FLAG (_T('W'), PF_FLAG_NAME_ONLY);
QUERY_AND_SET_PARAM_FLAG (_T('P'), PF_FLAG_PATH_ONLY);
QUERY_AND_SET_PARAM_FLAG (_T('A'), PF_FLAG_ANSI_CHARSET);
QUERY_AND_SET_PARAM_FLAG (_T('8'), PF_FLAG_UTF8_CHARSET);
QUERY_AND_SET_PARAM_FLAG (_T('U'), PF_FLAG_UTF16_CHARSET);
}
p++;
}
return p;
}
#define QUERY_AND_SET_PARAM(str) \
p++; \
p = GetFlags (p, dwFlags); \
if ( str && *str ) \
{\
_tcscat (lpResult, str); \
n += StrLength(str); \
bEmpty = false; \
};\
break;
struct ParamStruct {
string strArchiveName;
string strShortArchiveName;
string strPassword;
string strAdditionalCommandLine;
string strTempPath;
string strPathInArchive;
string strListFileName;
};
void ProcessName (
const TCHAR *lpFileName,
string& strResult,
int dwFlags,
bool bForList
)
{
strResult = lpFileName;
if ( OptionIsOn(dwFlags, PF_FLAG_PATH_ONLY) )
CutToSlash(strResult);
if ( bForList )
{
if ( OptionIsOn(dwFlags, PF_FLAG_NAME_ONLY) )
if ( !OptionIsOn(dwFlags, PF_FLAG_PATH_ONLY) )
strResult = FSF.PointToName(lpFileName);
if ( OptionIsOn(dwFlags, PF_FLAG_USE_BACKSLASH) )
{
TCHAR* pBuffer = strResult.GetBuffer();
for (unsigned int i = 0; i < strResult.GetLength(); i++)
{
if ( pBuffer[i] == _T('\\') )
pBuffer[i] = _T('/');
}
strResult.ReleaseBuffer();
}
if ( OptionIsOn(dwFlags, PF_FLAG_QUOTE_SPACES) )
farQuoteSpaceOnly(strResult);
if ( OptionIsOn(dwFlags, PF_FLAG_QUOTE_ALL) )
Quote(strResult); //NOT TESTED!
}
}
void WriteLine(HANDLE hFile, const TCHAR* lpLine, DWORD dwFlags)
{
DWORD dwWritten;
string strProcessed;
ProcessName(
lpLine,
strProcessed,
dwFlags,
true
);
//надо еще UTF-8 добавить и конвертацию OEM/ANSI
if ( OptionIsOn(dwFlags, PF_FLAG_UTF16_CHARSET) )
{
const wchar_t* lpwszCRLF = L"\r\n";
#ifdef UNICODE
const wchar_t* lpBuffer = strProcessed.GetString();
#else
wchar_t* lpBuffer = AnsiToUnicode(strProcessed);
#endif
WriteFile (hFile, lpBuffer, wcslen(lpBuffer)*sizeof(wchar_t), &dwWritten, NULL);
WriteFile (hFile, lpwszCRLF, 2*sizeof(wchar_t), &dwWritten, NULL);
#ifndef UNICODE
free(lpBuffer);
#endif
}
else
{
char* lpBuffer = nullptr;
const char* lpCRLF = "\r\n";
if ( OptionIsOn(dwFlags, PF_FLAG_UTF8_CHARSET) )
{
#ifdef UNICODE
lpBuffer = UnicodeToUTF8(strProcessed);
#else
lpBuffer = AnsiToUnicode(strProcessed);
#endif
}
else
{
#ifdef UNICODE
lpBuffer = UnicodeToAnsi(strProcessed);
#else
lpBuffer = StrDuplicate(strProcessed);
#endif
if ( OptionIsOn(dwFlags, PF_FLAG_ANSI_CHARSET) )
OemToCharA(lpBuffer, lpBuffer);
}
WriteFile (hFile, lpBuffer, strlen(lpBuffer), &dwWritten, NULL);
WriteFile (hFile, lpCRLF, 2, &dwWritten, NULL);
free(lpBuffer);
}
}
void CreateListFile(
const ArchiveItemArray& items,
const TCHAR *lpListFileName,
int dwFlags
)
{
//FarPanelInfo info;
HANDLE hListFile = CreateFile (
lpListFileName,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
CREATE_ALWAYS,
0,
NULL
);
if ( hListFile != INVALID_HANDLE_VALUE )
{
WORD wSignature = 0xFEFF;
DWORD dwWritten;
if ( OptionIsOn(dwFlags, PF_FLAG_UTF16_CHARSET) )
WriteFile(hListFile, &wSignature, 2, &dwWritten, NULL);
for (unsigned int i = 0; i < items.count(); i++)
{
const ArchiveItem *item = &items[i];
if ( (item->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
{
if ( (dwFlags & PF_FLAG_DIR_NAME_AS_MASK) == PF_FLAG_DIR_NAME_AS_MASK )
{
string strFileName = item->lpFileName;
AddEndSlash(strFileName);
strFileName += _T("*.*");
WriteLine(hListFile, strFileName, dwFlags);
}
}
WriteLine(hListFile, item->lpFileName, dwFlags);
}
CloseHandle (hListFile);
}
}
#define PE_SUCCESS 0
#define PE_MORE_FILES 1
int ParseString(
const ArchiveItemArray& items,
const TCHAR *lpString,
string &strResult,
ParamStruct *pParam,
int &pStartItemNumber
)
{
const TCHAR *p = (TCHAR*)lpString;
int bOnlyIfExists = 0;
DWORD dwFlags;
bool bHaveList = false;
bool bHaveAdditionalOptions = false;
bool bEmpty = false;
int n = 0;
int nSavedPos = 0;
TCHAR* lpResult = strResult.GetBuffer(512); //BUGBUG
string strProcessedName;
int nResult = PE_SUCCESS;
while ( *p )
{
switch ( *p )
{
case _T('{'):
bOnlyIfExists++;
p++;
bEmpty = true;
nSavedPos = n-1;
break;
case _T('}'):
bOnlyIfExists--;
p++;
if ( bEmpty )
{
lpResult[nSavedPos] = _T('\0');
n = nSavedPos;
}
break;
case _T('%'):
if ( *(p+1) && (*(p+1) == _T('%')) )
{
p += 2;
switch ( *p )
{
case _T('A'):
p++;
p = GetFlags (p, dwFlags);
if ( !pParam->strArchiveName.IsEmpty() )
{
ProcessName (
pParam->strArchiveName,
strProcessedName,
dwFlags,
false
);
_tcscat (lpResult, strProcessedName);
n += strProcessedName.GetLength();
bEmpty = false;
};
break;
case _T('a'):
p++;
p = GetFlags(p, dwFlags);
if ( !pParam->strShortArchiveName.IsEmpty() )
{
ProcessName (
pParam->strShortArchiveName,
strProcessedName,
dwFlags,
false
);
_tcscat (lpResult, strProcessedName);
n += strProcessedName.GetLength();
bEmpty = false;
};
break;
case _T('W'):
QUERY_AND_SET_PARAM(pParam->strTempPath);
case _T('P'):
QUERY_AND_SET_PARAM(pParam->strPassword);
case _T('R'):
QUERY_AND_SET_PARAM(pParam->strPathInArchive);
case _T('S'):
bHaveAdditionalOptions = true;
QUERY_AND_SET_PARAM(pParam->strAdditionalCommandLine);
case _T('L'):
case _T('l'):
p++;
p = GetFlags (p, dwFlags);
if ( !bHaveList && !pParam->strListFileName.IsEmpty() )
{
bHaveList = true;
CreateListFile (items, pParam->strListFileName, dwFlags);
_tcscat (lpResult, pParam->strListFileName);
n += StrLength (pParam->strListFileName);
bEmpty = false;
};
break;
case _T('f'):
p++;
p = GetFlags (p, dwFlags);
if ( items[pStartItemNumber].lpFileName )
{
ProcessName (
items[pStartItemNumber].lpFileName,
strProcessedName,
dwFlags,
true
);
_tcscat (lpResult, strProcessedName);
n += strProcessedName.GetLength();
bEmpty = false;
pStartItemNumber++;
if ( pStartItemNumber != items.count() )
nResult = PE_MORE_FILES;
};
break;
default:
p++;
break;
}
}
else
{
lpResult[n] = *p;
lpResult[n+1] = _T('\0');
n++;
p++;
}
break;
default:
lpResult[n] = *p;
lpResult[n+1] = _T('\0');
n++;
p++;
}
}
if ( !pParam->strAdditionalCommandLine.IsEmpty() &&
!bHaveAdditionalOptions )
{
_tcscat (lpResult, _T(" "));
_tcscat (lpResult, pParam->strAdditionalCommandLine);
}
strResult.ReleaseBuffer();
return nResult;
}
| 19 | 89 | 0.637719 | MKadaner |
e9ee1d5b06d1784ea7b044621adae46fbb1b4c7f | 459 | hpp | C++ | module/ngx_http_java_module/ngx_http_java_module.hpp | webcpp/hinginx | b380df41df5cd4763fba2a01a0fa0738bf6e5d4d | [
"BSD-2-Clause"
] | null | null | null | module/ngx_http_java_module/ngx_http_java_module.hpp | webcpp/hinginx | b380df41df5cd4763fba2a01a0fa0738bf6e5d4d | [
"BSD-2-Clause"
] | null | null | null | module/ngx_http_java_module/ngx_http_java_module.hpp | webcpp/hinginx | b380df41df5cd4763fba2a01a0fa0738bf6e5d4d | [
"BSD-2-Clause"
] | null | null | null | #pragma once
extern "C"
{
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
}
#include <regex>
#include <memory>
#include "java.hpp"
static std::shared_ptr<std::regex> java_uri_re = nullptr;
static std::shared_ptr<hi::java> java_engine = nullptr;
typedef struct
{
ngx_str_t class_path;
ngx_str_t options;
ngx_str_t servlet;
ngx_str_t uri_pattern;
ngx_int_t expires;
ngx_int_t version;
} ngx_http_java_loc_conf_t; | 17.653846 | 57 | 0.727669 | webcpp |
e9f183f51a30ccbc179e0378846d734e1b3e1fe5 | 235 | cpp | C++ | pytorch/pcdet/ops/nms/src/iou3d_nms_api.cpp | chasingw/pointpillars_pytorch_trt | 941075a23d86991393ea71ddbeb916ca80b73400 | [
"Apache-2.0"
] | 45 | 2021-04-30T04:52:39.000Z | 2022-03-30T07:09:59.000Z | pytorch/pcdet/ops/nms/src/iou3d_nms_api.cpp | chasingw/pointpillars_pytorch_trt | 941075a23d86991393ea71ddbeb916ca80b73400 | [
"Apache-2.0"
] | 17 | 2021-05-27T10:15:32.000Z | 2022-01-15T08:45:53.000Z | pytorch/pcdet/ops/nms/src/iou3d_nms_api.cpp | chasingw/pointpillars_pytorch_trt | 941075a23d86991393ea71ddbeb916ca80b73400 | [
"Apache-2.0"
] | 15 | 2021-05-24T05:43:17.000Z | 2022-03-02T02:53:56.000Z | #include <torch/serialize/tensor.h>
#include <torch/extension.h>
#include <vector>
#include <cuda.h>
#include <cuda_runtime_api.h>
#include "iou3d_nms.h"
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("nms", &nms, "nms func");
}
| 18.076923 | 42 | 0.719149 | chasingw |
e9f4462d7dcf69b6cdb7b0f0cd6fffc36658416c | 3,755 | hpp | C++ | src/tools/log.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | 8 | 2016-04-24T21:02:59.000Z | 2021-11-14T20:37:17.000Z | src/tools/log.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | null | null | null | src/tools/log.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | 1 | 2018-06-09T19:51:38.000Z | 2018-06-09T19:51:38.000Z | /* Created by Darren Otgaar on 2016/03/05. http://www.github.com/otgaard/zap */
#ifndef ZAP_LOG_HPP
#define ZAP_LOG_HPP
#include <mutex>
#include <memory>
#include <sstream>
#include <iostream>
#include <functional>
#include <core/core.hpp>
#if !defined(_WIN32)
const char* const LOG_RESET = "\033[0m";
const char* const LOG_BLACK = "\033[30m";
const char* const LOG_RED = "\033[31m";
const char* const LOG_GREEN = "\033[32m";
const char* const LOG_YELLOW = "\033[33m";
const char* const LOG_BLUE = "\033[34m";
const char* const LOG_MAGENTA = "\033[35m";
const char* const LOG_CYAN = "\033[36m";
const char* const LOG_WHITE = "\033[37m";
const char* const LOG_BOLDBLACK = "\033[1m\033[30m";
const char* const LOG_BOLDRED = "\033[1m\033[31m";
const char* const LOG_BOLDGREEN = "\033[1m\033[32m";
const char* const LOG_BOLDYELLOW = "\033[1m\033[33m";
const char* const LOG_BOLDBLUE = "\033[1m\033[34m";
const char* const LOG_BOLDMAGENTA = "\033[1m\033[35m";
const char* const LOG_BOLDCYAN = "\033[1m\033[36m";
const char* const LOG_BOLDWHITE = "\033[1m\033[37m";
#else
const char* const LOG_RESET = "";
const char* const LOG_BLACK = "";
const char* const LOG_RED = "";
const char* const LOG_GREEN = "";
const char* const LOG_YELLOW = "";
const char* const LOG_BLUE = "";
const char* const LOG_MAGENTA = "";
const char* const LOG_CYAN = "";
const char* const LOG_WHITE = "";
const char* const LOG_BOLDBLACK = "";
const char* const LOG_BOLDRED = "";
const char* const LOG_BOLDGREEN = "";
const char* const LOG_BOLDYELLOW = "";
const char* const LOG_BOLDBLUE = "";
const char* const LOG_BOLDMAGENTA = "";
const char* const LOG_BOLDCYAN = "";
const char* const LOG_BOLDWHITE = "";
#endif
namespace zap { namespace tools {
enum class log_level : uint8_t {
LL_DEBUG,
LL_WARNING,
LL_ERROR
};
inline void def_cleanup_fnc(std::ostream* stream) { UNUSED(stream); }
class logger {
public:
using cleanup_fnc = std::function<void(std::ostream*)>;
logger(std::ostream* ostream_ptr, cleanup_fnc fnc=def_cleanup_fnc) : fnc_(fnc), ostream_(ostream_ptr),
sstream_("") { }
virtual ~logger() { if(fnc_) fnc_(ostream_); }
template<log_level level, typename... Args> void print(Args... args) {
std::unique_lock<std::mutex> lock(lock_);
switch(level) {
case log_level::LL_DEBUG:
sstream_ << "<DEBUG>:";
break;
case log_level::LL_ERROR:
sstream_ << "<ERROR>:" << LOG_BOLDRED;
break;
case log_level::LL_WARNING:
sstream_ << "<WARNING>:" << LOG_BOLDYELLOW;
break;
}
print_i(args...);
}
private:
void print_i() { (*ostream_) << sstream_.rdbuf() << LOG_RESET << std::endl; }
template<typename T, typename... Args> void print_i(T first, Args... rest) {
sstream_ << first << " ";
print_i(rest...);
}
cleanup_fnc fnc_;
std::ostream* ostream_;
std::stringstream sstream_;
std::mutex lock_;
};
}}
static zap::tools::logger default_log(&std::cout);
#if defined(LOGGING_ENABLED)
#define LOG default_log.print<zap::tools::log_level::LL_DEBUG>
#define LOG_ERR default_log.print<zap::tools::log_level::LL_ERROR>
#define LOG_WARN default_log.print<zap::tools::log_level::LL_WARNING>
#else //!LOGGING_ENABLED
#define LOG(...) do {} while (0)
//#define LOG_ERR(...)
#define LOG_ERR default_log.print<zap::tools::log_level::LL_ERROR>
#define LOG_WARN(...) do {} while (0)
#endif //!LOGGING_ENABLED
#endif //ZAP_LOG_HPP
| 33.230088 | 110 | 0.621039 | otgaard |
e9f4fba01c203388e3ddbf7bf0a6640937acbfc0 | 1,754 | cpp | C++ | comps/example/src/ExampleComp.cpp | caochunxi/llbc_comps | 5985c5ac020e21a73cb221f56ae7660ead2cfa3b | [
"MIT"
] | 6 | 2021-01-04T01:21:10.000Z | 2021-12-17T02:25:54.000Z | comps/example/src/ExampleComp.cpp | caochunxi/llbc_comps | 5985c5ac020e21a73cb221f56ae7660ead2cfa3b | [
"MIT"
] | null | null | null | comps/example/src/ExampleComp.cpp | caochunxi/llbc_comps | 5985c5ac020e21a73cb221f56ae7660ead2cfa3b | [
"MIT"
] | 1 | 2020-12-30T12:21:13.000Z | 2020-12-30T12:21:13.000Z | // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "comp_com/Export.h"
#include "ExampleComp.h"
bool ExampleComp::OnInitialize()
{
AddMethod("Foo", &ExampleComp::Call_Foo);
return true;
}
void ExampleComp::Foo(const LLBC_String &arg)
{
std::cout <<"ExampleComp::Foo(const LLBC_String &) called, arg: " <<arg <<std::endl;
}
int ExampleComp::Call_Foo(const LLBC_Variant &arg, LLBC_Variant &ret)
{
Foo(arg);
ret = arg;
return 0;
}
LLBC_IComponent *ExampleCompFactory::Create() const
{
return LLBC_New(ExampleComp);
}
void *llbc_create_comp_ExampleComp()
{
return ExampleCompFactory().Create();
}
| 33.730769 | 88 | 0.736032 | caochunxi |
e9fa2fc6ec5ef65f2e41f93cbf725c68a4894e10 | 1,441 | cpp | C++ | lib/obsolete/ExpertSystem/CLIPSModuleBuilder.cpp | DrItanium/durandal | dd45114bbe30819a69dec5c1162e6fad162119ed | [
"BSD-3-Clause"
] | 1 | 2018-05-25T05:20:09.000Z | 2018-05-25T05:20:09.000Z | lib/obsolete/ExpertSystem/CLIPSModuleBuilder.cpp | DrItanium/durandal | dd45114bbe30819a69dec5c1162e6fad162119ed | [
"BSD-3-Clause"
] | 2 | 2015-11-23T05:22:47.000Z | 2015-11-23T05:24:03.000Z | lib/obsolete/ExpertSystem/CLIPSModuleBuilder.cpp | DrItanium/durandal | dd45114bbe30819a69dec5c1162e6fad162119ed | [
"BSD-3-Clause"
] | null | null | null | #include "ExpertSystem/CLIPSModuleBuilder.h"
#include "llvm/Module.h"
using namespace llvm;
CLIPSModuleBuilder::CLIPSModuleBuilder(std::string nm, std::string ty) : CLIPSObjectBuilder(nm, ty) { }
void CLIPSModuleBuilder::build(Module* mod, KnowledgeConstructor* kc) {
open();
addField("pointer", (PointerAddress)mod);
addFields(mod, kc);
close();
std::string str = getCompletedString();
kc->addToKnowledgeBase((PointerAddress)mod, str);
}
void CLIPSModuleBuilder::addFields(Module* mod, KnowledgeConstructor* kc) {
std::string triple(mod->getTargetTriple());
std::string dataLayout(mod->getDataLayout());
std::string modIdent(mod->getModuleIdentifier());
addField("triple", triple);
addField("data-layout", dataLayout);
addField("module-identifier", modIdent);
Module::Endianness endian = mod->getEndianness();
Module::PointerSize psize = mod->getPointerSize();
if(endian == Module::LittleEndian) {
addField("endianness", "little");
} else if (endian == llvm::Module::BigEndian) {
addField("endianness", "big");
} else {
addField("endianness", "any");
}
if(psize == Module::Pointer32) {
addField("pointer-size", "pointer32");
} else if (psize == Module::Pointer64) {
addField("pointer-size", "pointer64");
} else {
addField("pointer-size", "any");
}
addField("inline-asm", mod->getModuleInlineAsm());
}
| 34.309524 | 103 | 0.664816 | DrItanium |
e9fe3077182502bf34438e939cc5ae6c5883e15d | 1,774 | cpp | C++ | test/api/api_misuse.cpp | SylvainHocq/mapbox-gl-native | bca9d091805dc01a4456ab3f24e9de87f9b4aa48 | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2021-04-26T05:41:57.000Z | 2021-04-26T05:41:57.000Z | test/api/api_misuse.cpp | SylvainHocq/mapbox-gl-native | bca9d091805dc01a4456ab3f24e9de87f9b4aa48 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | test/api/api_misuse.cpp | SylvainHocq/mapbox-gl-native | bca9d091805dc01a4456ab3f24e9de87f9b4aa48 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #include <mbgl/test/util.hpp>
#include <mbgl/test/stub_file_source.hpp>
#include <mbgl/test/fixture_log_observer.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/platform/default/headless_display.hpp>
#include <mbgl/storage/online_file_source.hpp>
#include <mbgl/util/exception.hpp>
#include <mbgl/util/run_loop.hpp>
#include <future>
using namespace mbgl;
TEST(API, RenderWithoutCallback) {
auto log = new FixtureLogObserver();
Log::setObserver(std::unique_ptr<Log::Observer>(log));
util::RunLoop loop;
auto display = std::make_shared<mbgl::HeadlessDisplay>();
HeadlessView view(display, 1);
view.resize(128, 512);
StubFileSource fileSource;
std::unique_ptr<Map> map = std::make_unique<Map>(view, fileSource, MapMode::Still);
map->renderStill(nullptr);
// Force Map thread to join.
map.reset();
const FixtureLogObserver::LogMessage logMessage {
EventSeverity::Error,
Event::General,
int64_t(-1),
"StillImageCallback not set",
};
EXPECT_EQ(log->count(logMessage), 1u);
}
TEST(API, RenderWithoutStyle) {
util::RunLoop loop;
auto display = std::make_shared<mbgl::HeadlessDisplay>();
HeadlessView view(display, 1);
view.resize(128, 512);
StubFileSource fileSource;
Map map(view, fileSource, MapMode::Still);
std::exception_ptr error;
map.renderStill([&](std::exception_ptr error_, PremultipliedImage&&) {
error = error_;
loop.stop();
});
loop.run();
try {
std::rethrow_exception(error);
} catch (const util::MisuseException& ex) {
EXPECT_EQ(std::string(ex.what()), "Map doesn't have a style");
} catch (const std::exception&) {
EXPECT_TRUE(false) << "Unhandled exception.";
}
}
| 26.088235 | 87 | 0.668546 | SylvainHocq |
1800a88c6a34573069996679dd42487ce4aac0a4 | 2,520 | hpp | C++ | modules/scene_manager/include/nav_msgs/srv/set_map__response__rosidl_typesupport_opensplice_cpp.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/scene_manager/include/nav_msgs/srv/set_map__response__rosidl_typesupport_opensplice_cpp.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 3 | 2019-11-14T12:20:06.000Z | 2020-08-07T13:51:10.000Z | modules/scene_manager/include/nav_msgs/srv/set_map__response__rosidl_typesupport_opensplice_cpp.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | // generated from
// rosidl_typesupport_opensplice_cpp/resource/msg__rosidl_typesupport_opensplice_cpp.hpp.em
// generated code does not contain a copyright notice
#ifndef NAV_MSGS__SRV__SET_MAP__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_
#define NAV_MSGS__SRV__SET_MAP__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_
#include "nav_msgs/srv/set_map__response__struct.hpp"
#include "nav_msgs/srv/dds_opensplice/ccpp_SetMap_Response_.h"
#include "rosidl_generator_c/message_type_support_struct.h"
#include "rosidl_typesupport_interface/macros.h"
#include "nav_msgs/msg/rosidl_typesupport_opensplice_cpp__visibility_control.h"
namespace DDS
{
class DomainParticipant;
class DataReader;
class DataWriter;
} // namespace DDS
namespace nav_msgs
{
namespace srv
{
namespace typesupport_opensplice_cpp
{
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs
extern void register_type__SetMap_Response(
DDS::DomainParticipant * participant,
const char * type_name);
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs
extern void convert_ros_message_to_dds(
const nav_msgs::srv::SetMap_Response & ros_message,
nav_msgs::srv::dds_::SetMap_Response_ & dds_message);
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs
extern void publish__SetMap_Response(
DDS::DataWriter * topic_writer,
const void * untyped_ros_message);
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs
extern void convert_dds_message_to_ros(
const nav_msgs::srv::dds_::SetMap_Response_ & dds_message,
nav_msgs::srv::SetMap_Response & ros_message);
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs
extern bool take__SetMap_Response(
DDS::DataReader * topic_reader,
bool ignore_local_publications,
void * untyped_ros_message,
bool * taken);
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_EXPORT_nav_msgs
const char *
serialize__SetMap_Response(
const void * untyped_ros_message,
void * serialized_data);
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_EXPORT_nav_msgs
const char *
deserialize__SetMap_Response(
const uint8_t * buffer,
unsigned length,
void * untyped_ros_message);
} // namespace typesupport_opensplice_cpp
} // namespace srv
} // namespace nav_msgs
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_opensplice_cpp, nav_msgs, srv, SetMap_Response)();
#ifdef __cplusplus
}
#endif
#endif // NAV_MSGS__SRV__SET_MAP__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_
| 27.096774 | 121 | 0.846825 | Omnirobotic |
18013dd6c8dc8cf0aa00540f743c54b5c61b9a94 | 901 | cpp | C++ | src/main/cpp/Autonomous/Steps/TimedDrive.cpp | FRCTeam16/TMW2021OMB | 5ac92a1ac2030d2913c18ba7a55450a4b46abbc7 | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/Autonomous/Steps/TimedDrive.cpp | FRCTeam16/TMW2021OMB | 5ac92a1ac2030d2913c18ba7a55450a4b46abbc7 | [
"BSD-3-Clause"
] | 9 | 2022-01-24T17:02:09.000Z | 2022-01-24T17:02:11.000Z | src/main/cpp/Autonomous/Steps/TimedDrive.cpp | FRCTeam16/TMW2021OMB | 5ac92a1ac2030d2913c18ba7a55450a4b46abbc7 | [
"BSD-3-Clause"
] | 1 | 2022-02-20T02:09:17.000Z | 2022-02-20T02:09:17.000Z | #include "Autonomous/Steps/TimedDrive.h"
#include "Robot.h"
#include "Util/RampUtil.h"
bool TimedDrive::Run(std::shared_ptr<World> world) {
const double currentTime = world->GetClock();
if (startTime < 0) {
startTime = currentTime;
Robot::driveBase->UseOpenLoopDrive();
Robot::driveBase->SetTargetAngle(angle);
std::cout << "TimedDrive("
<< angle << ", "
<< ySpeed << ", "
<< xSpeed << ", "
<< timeToDrive << ", "
<< useGyro << ")\n";
}
const double elapsed = currentTime - startTime;
if (elapsed > timeToDrive) {
return true;
} else {
// const double twist = (useTwist) ? Robot::driveBase->GetTwistControlOutput() : 0.0;
double y = ySpeed;
if (rampUpTime > 0) {
y = RampUtil::RampUp(ySpeed, elapsed, rampUpTime);
}
crab->Update(
(float) Robot::driveBase->GetTwistControlOutput(),
(float) y,
(float) xSpeed,
useGyro);
return false;
}
}
| 25.742857 | 87 | 0.63374 | FRCTeam16 |
18037e0167f3a34a25ee74d5e4da2b275d5d72bd | 506 | inl | C++ | Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/ClassTemplate.inl | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 143 | 2020-04-07T21:38:21.000Z | 2022-03-30T01:06:33.000Z | Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/ClassTemplate.inl | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 7 | 2021-03-30T07:26:21.000Z | 2022-03-28T16:31:02.000Z | Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/ClassTemplate.inl | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 11 | 2020-06-06T09:45:12.000Z | 2022-01-25T17:17:55.000Z | /**
* Copyright (c) 2021 Julien SOYSOUVANH - All Rights Reserved
*
* This file is part of the Refureku library project which is released under the MIT License.
* See the README.md file for full license details.
*/
template <std::size_t ArgsCount>
ClassTemplateInstantiation const* ClassTemplate::getTemplateInstantiation(TemplateArgument const* (&args)[ArgsCount]) const noexcept
{
if constexpr (ArgsCount > 0)
{
return getTemplateInstantiation(&args[0], ArgsCount);
}
else
{
return nullptr;
}
} | 26.631579 | 132 | 0.756917 | jsoysouvanh |
180539f6b3db70c6f377097c4726053ab9b2f786 | 1,109 | cpp | C++ | test/pqxx_test.cpp | ankane/pgvector-cpp | d84bd0cc70eeb5371c7a92efa88163de9ea927ba | [
"MIT"
] | null | null | null | test/pqxx_test.cpp | ankane/pgvector-cpp | d84bd0cc70eeb5371c7a92efa88163de9ea927ba | [
"MIT"
] | null | null | null | test/pqxx_test.cpp | ankane/pgvector-cpp | d84bd0cc70eeb5371c7a92efa88163de9ea927ba | [
"MIT"
] | null | null | null | #include "../include/pqxx.hpp"
#include <cassert>
#include <optional>
#include <pqxx/pqxx>
void setup(pqxx::connection &conn) {
pqxx::work txn{conn};
txn.exec0("CREATE EXTENSION IF NOT EXISTS vector");
txn.exec0("DROP TABLE IF EXISTS items");
txn.exec0("CREATE TABLE items (id serial primary key, factors vector(3))");
txn.commit();
}
void test_works(pqxx::connection &conn) {
pqxx::work txn{conn};
auto factors = pgvector::Vector({1, 2, 3});
float arr[] = {4, 5, 6};
auto factors2 = pgvector::Vector(arr, 3);
txn.exec_params("INSERT INTO items (factors) VALUES ($1), ($2), ($3)",
factors, factors2, std::nullopt);
pqxx::result res{txn.exec_params(
"SELECT factors FROM items ORDER BY factors <-> $1", factors2)};
assert(res.size() == 3);
assert(res[0][0].as<pgvector::Vector>() == factors2);
assert(res[1][0].as<pgvector::Vector>() == factors);
assert(!res[2][0].as<std::optional<pgvector::Vector>>().has_value());
txn.commit();
}
int main() {
pqxx::connection conn("dbname=pgvector_cpp_test");
setup(conn);
test_works(conn);
return 0;
}
| 28.435897 | 77 | 0.646528 | ankane |
1805dd093a477beba6418965c96f7860355a4e63 | 2,944 | cpp | C++ | libraries/chain/wast_to_wasm.cpp | yinchengtsinghua/EOSIOChineseCPP | dceabf6315ab8c9a064c76e943b2b44037165a85 | [
"MIT"
] | 21 | 2019-01-23T04:17:48.000Z | 2021-11-15T10:50:33.000Z | libraries/chain/wast_to_wasm.cpp | jiege1994/EOSIOChineseCPP | dceabf6315ab8c9a064c76e943b2b44037165a85 | [
"MIT"
] | 1 | 2019-08-06T07:53:54.000Z | 2019-08-13T06:51:29.000Z | libraries/chain/wast_to_wasm.cpp | jiege1994/EOSIOChineseCPP | dceabf6315ab8c9a064c76e943b2b44037165a85 | [
"MIT"
] | 11 | 2019-01-24T07:47:43.000Z | 2020-10-29T02:18:20.000Z |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
/*
*@文件
*@eos/license中定义的版权
**/
#include <eosio/chain/wast_to_wasm.hpp>
#include <Inline/BasicTypes.h>
#include <IR/Module.h>
#include <IR/Validate.h>
#include <WAST/WAST.h>
#include <WASM/WASM.h>
#include <Runtime/Runtime.h>
#include <sstream>
#include <iomanip>
#include <fc/exception/exception.hpp>
#include <eosio/chain/exceptions.hpp>
namespace eosio { namespace chain {
std::vector<uint8_t> wast_to_wasm( const std::string& wast )
{
std::stringstream ss;
try {
IR::Module module;
std::vector<WAST::Error> parse_errors;
WAST::parseModule(wast.c_str(),wast.size(),module,parse_errors);
if(parse_errors.size())
{
//打印任何分析错误;
ss << "Error parsing WebAssembly text file:" << std::endl;
for(auto& error : parse_errors)
{
ss << ":" << error.locus.describe() << ": " << error.message.c_str() << std::endl;
ss << error.locus.sourceLine << std::endl;
ss << std::setw(error.locus.column(8)) << "^" << std::endl;
}
EOS_ASSERT( false, wasm_exception, "error parsing wast: ${msg}", ("msg",ss.str()) );
}
for(auto sectionIt = module.userSections.begin();sectionIt != module.userSections.end();++sectionIt)
{
if(sectionIt->name == "name") { module.userSections.erase(sectionIt); break; }
}
try
{
//序列化WebAssembly模块。
Serialization::ArrayOutputStream stream;
WASM::serialize(stream,module);
return stream.getBytes();
}
catch(const Serialization::FatalSerializationException& exception)
{
ss << "Error serializing WebAssembly binary file:" << std::endl;
ss << exception.message << std::endl;
EOS_ASSERT( false, wasm_exception, "error converting to wasm: ${msg}", ("msg",ss.get()) );
} catch(const IR::ValidationException& e) {
ss << "Error validating WebAssembly binary file:" << std::endl;
ss << e.message << std::endl;
EOS_ASSERT( false, wasm_exception, "error converting to wasm: ${msg}", ("msg",ss.get()) );
}
} FC_CAPTURE_AND_RETHROW( (wast) ) } ///WestytotoWASM
std::string wasm_to_wast( const std::vector<uint8_t>& wasm, bool strip_names ) {
return wasm_to_wast( wasm.data(), wasm.size(), strip_names );
} //WasmithtoWaster
std::string wasm_to_wast( const uint8_t* data, uint64_t size, bool strip_names )
{ try {
IR::Module module;
Serialization::MemoryInputStream stream((const U8*)data,size);
WASM::serialize(stream,module);
if(strip_names)
module.userSections.clear();
//将模块打印到WAST。
return WAST::print(module);
} FC_CAPTURE_AND_RETHROW() } //WasmithtoWaster
} } //EOSIO:链
| 32.351648 | 106 | 0.631114 | yinchengtsinghua |
18063fac4a0ba2877f21f81984a018571c325802 | 5,899 | cpp | C++ | src/DecisionEngine/Core/Components/UnitTests/Index_UnitTest.cpp | davidbrownell/DavidBrownell_DecisionEngine | f331b57f7b5ab4a5de84595f79df191fc0c13fba | [
"BSL-1.0"
] | null | null | null | src/DecisionEngine/Core/Components/UnitTests/Index_UnitTest.cpp | davidbrownell/DavidBrownell_DecisionEngine | f331b57f7b5ab4a5de84595f79df191fc0c13fba | [
"BSL-1.0"
] | null | null | null | src/DecisionEngine/Core/Components/UnitTests/Index_UnitTest.cpp | davidbrownell/DavidBrownell_DecisionEngine | f331b57f7b5ab4a5de84595f79df191fc0c13fba | [
"BSL-1.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////
///
/// \file Index_UnitTest.cpp
/// \brief Unit test for Index.h
///
/// \author David Brownell <db@DavidBrownell.com>
/// \date 2020-05-23 10:53:31
///
/// \note
///
/// \bug
///
/////////////////////////////////////////////////////////////////////////
///
/// \attention
/// Copyright David Brownell 2020-21
/// 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.
///
/////////////////////////////////////////////////////////////////////////
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#define CATCH_CONFIG_CONSOLE_WIDTH 200
#include "../Index.h"
#include <catch.hpp>
#include <CommonHelpers/TestHelpers.h>
#include <BoostHelpers/TestHelpers.h>
namespace NS = DecisionEngine::Core::Components;
TEST_CASE("Default Ctor") {
NS::Index const index;
CHECK(index.HasSuffix() == false);
CHECK(index.AtRoot());
CHECK(index.Depth() == 0);
}
TEST_CASE("Index Ctor") {
NS::Index const index(10);
CHECK(index.HasSuffix());
CHECK(index.AtRoot() == false);
CHECK(index.Depth() == 1);
}
TEST_CASE("Indexes Ctor") {
CHECK_THROWS_MATCHES(NS::Index(NS::Index(10), 20), std::invalid_argument, Catch::Matchers::Exception::ExceptionMessageMatcher("index"));
NS::Index const index(
NS::Index(10).Commit(),
20
);
CHECK(index.HasSuffix());
CHECK(index.AtRoot() == false);
CHECK(index.Depth() == 2);
}
NS::Index CreateIndex(NS::Index index, std::vector<NS::Index::value_type> values) {
for(auto const & value: values) {
index = NS::Index(index, value).Commit();
}
return index;
}
TEST_CASE("ToString") {
CHECK(NS::Index().ToString() == "Index()");
CHECK(NS::Index(10).ToString() == "Index((10))");
CHECK(NS::Index(CreateIndex(NS::Index(), {1})).ToString() == "Index(1)");
CHECK(NS::Index(CreateIndex(NS::Index(), {1}), 2).ToString() == "Index(1,(2))");
CHECK(NS::Index(CreateIndex(NS::Index(), {1, 2, 3}), 4).ToString() == "Index(1,2,3,(4))");
}
TEST_CASE("Compare") {
// Equal
CHECK(CommonHelpers::TestHelpers::CompareTest(NS::Index(), NS::Index(), true) == 0);
CHECK(CommonHelpers::TestHelpers::CompareTest(NS::Index(1), NS::Index(1), true) == 0);
CHECK(CommonHelpers::TestHelpers::CompareTest(CreateIndex(NS::Index(), {1}), NS::Index(1), true) == 0);
CHECK(CommonHelpers::TestHelpers::CompareTest(CreateIndex(NS::Index(), {1, 2, 3}), CreateIndex(NS::Index(), {1, 2, 3}), true) == 0);
}
TEST_CASE("Compare Not Equal") {
CHECK(
CommonHelpers::TestHelpers::CompareTest(
CreateIndex(NS::Index(), {1}),
CreateIndex(NS::Index(), {0})
) == 0
);
CHECK(
CommonHelpers::TestHelpers::CompareTest(
CreateIndex(NS::Index(), {1, 2, 3}),
CreateIndex(NS::Index(), {1, 2, 3, 4})
) == 0
);
CHECK(
CommonHelpers::TestHelpers::CompareTest(
CreateIndex(NS::Index(), {0, 2}),
CreateIndex(NS::Index(), {0, 1})
) == 0
);
}
TEST_CASE("Enumeration") {
// ----------------------------------------------------------------------
using Indexes = std::vector<NS::Index::value_type>;
// ----------------------------------------------------------------------
Indexes indexes;
size_t maxNumIndexes(std::numeric_limits<size_t>::max());
auto const func(
[&indexes, &maxNumIndexes](NS::Index::value_type const &value) {
indexes.push_back(value);
return indexes.size() < maxNumIndexes;
}
);
SECTION("None") {
CHECK(NS::Index().Enumerate(func));
CHECK(indexes.empty());
}
SECTION("Single Suffix") {
CHECK(NS::Index(1).Enumerate(func));
CHECK(indexes == Indexes{ 1 });
}
SECTION("Multi Indexes") {
CHECK(CreateIndex(NS::Index(), {1, 2}).Enumerate(func));
CHECK(indexes == Indexes{ 1, 2 });
}
SECTION("Multi Indexes with Suffix") {
CHECK(NS::Index(CreateIndex(NS::Index(), {1, 2}), 3).Enumerate(func));
CHECK(indexes == Indexes{1, 2, 3});
}
SECTION("Cancellation") {
maxNumIndexes = 2;
CHECK(NS::Index(CreateIndex(NS::Index(), {1, 2}), 3).Enumerate(func) == false);
CHECK(indexes == Indexes{1, 2});
}
}
TEST_CASE("Commit") {
CHECK_THROWS_MATCHES(NS::Index().Commit(), std::logic_error, Catch::Matchers::Exception::ExceptionMessageMatcher("Invalid operation"));
NS::Index index(1);
CHECK(index.HasSuffix());
CHECK(index.Commit().HasSuffix() == false);
}
TEST_CASE("Copy") {
NS::Index const index(CreateIndex(NS::Index(), {1}));
CHECK(index.HasSuffix() == false);
CHECK(index.Copy().HasSuffix() == false);
CHECK_THROWS_MATCHES(NS::Index(1).Copy(), std::logic_error, Catch::Matchers::Exception::ExceptionMessageMatcher("Invalid operation"));
}
TEST_CASE("Serialization") {
CHECK(
BoostHelpers::TestHelpers::SerializeTest(
NS::Index(
CreateIndex(NS::Index(), {1, 2, 3}),
4
),
[](std::string const &output) {
UNSCOPED_INFO(output);
CHECK(true);
}
) == 0
);
}
| 32.234973 | 141 | 0.502967 | davidbrownell |
180ada3bcb42c87452c123c24a55712b97ab09a5 | 104,591 | hpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_bgp_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_bgp_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_bgp_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _CISCO_IOS_XE_BGP_OPER_
#define _CISCO_IOS_XE_BGP_OPER_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xe {
namespace Cisco_IOS_XE_bgp_oper {
class BgpStateData : public ydk::Entity
{
public:
BgpStateData();
~BgpStateData();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class Neighbors; //type: BgpStateData::Neighbors
class AddressFamilies; //type: BgpStateData::AddressFamilies
class BgpRouteVrfs; //type: BgpStateData::BgpRouteVrfs
class BgpRouteRds; //type: BgpStateData::BgpRouteRds
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors> neighbors;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies> address_families;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs> bgp_route_vrfs;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds> bgp_route_rds;
}; // BgpStateData
class BgpStateData::Neighbors : public ydk::Entity
{
public:
Neighbors();
~Neighbors();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Neighbor; //type: BgpStateData::Neighbors::Neighbor
ydk::YList neighbor;
}; // BgpStateData::Neighbors
class BgpStateData::Neighbors::Neighbor : public ydk::Entity
{
public:
Neighbor();
~Neighbor();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf afi_safi; //type: AfiSafi
ydk::YLeaf vrf_name; //type: string
ydk::YLeaf neighbor_id; //type: string
ydk::YLeaf description; //type: string
ydk::YLeaf bgp_version; //type: uint16
ydk::YLeaf link; //type: BgpLink
ydk::YLeaf up_time; //type: string
ydk::YLeaf last_write; //type: string
ydk::YLeaf last_read; //type: string
ydk::YLeaf installed_prefixes; //type: uint32
ydk::YLeaf session_state; //type: BgpFsmState
ydk::YLeaf as; //type: uint32
ydk::YLeafList negotiated_cap; //type: list of string
class NegotiatedKeepaliveTimers; //type: BgpStateData::Neighbors::Neighbor::NegotiatedKeepaliveTimers
class BgpNeighborCounters; //type: BgpStateData::Neighbors::Neighbor::BgpNeighborCounters
class Connection; //type: BgpStateData::Neighbors::Neighbor::Connection
class Transport; //type: BgpStateData::Neighbors::Neighbor::Transport
class PrefixActivity; //type: BgpStateData::Neighbors::Neighbor::PrefixActivity
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::NegotiatedKeepaliveTimers> negotiated_keepalive_timers;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::BgpNeighborCounters> bgp_neighbor_counters;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::Connection> connection;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::Transport> transport;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::PrefixActivity> prefix_activity;
}; // BgpStateData::Neighbors::Neighbor
class BgpStateData::Neighbors::Neighbor::NegotiatedKeepaliveTimers : public ydk::Entity
{
public:
NegotiatedKeepaliveTimers();
~NegotiatedKeepaliveTimers();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf hold_time; //type: uint16
ydk::YLeaf keepalive_interval; //type: uint16
}; // BgpStateData::Neighbors::Neighbor::NegotiatedKeepaliveTimers
class BgpStateData::Neighbors::Neighbor::BgpNeighborCounters : public ydk::Entity
{
public:
BgpNeighborCounters();
~BgpNeighborCounters();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf inq_depth; //type: uint32
ydk::YLeaf outq_depth; //type: uint32
class Sent; //type: BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Sent
class Received; //type: BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Received
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Sent> sent;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Received> received;
}; // BgpStateData::Neighbors::Neighbor::BgpNeighborCounters
class BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Sent : public ydk::Entity
{
public:
Sent();
~Sent();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf opens; //type: uint32
ydk::YLeaf updates; //type: uint32
ydk::YLeaf notifications; //type: uint32
ydk::YLeaf keepalives; //type: uint32
ydk::YLeaf route_refreshes; //type: uint32
}; // BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Sent
class BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Received : public ydk::Entity
{
public:
Received();
~Received();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf opens; //type: uint32
ydk::YLeaf updates; //type: uint32
ydk::YLeaf notifications; //type: uint32
ydk::YLeaf keepalives; //type: uint32
ydk::YLeaf route_refreshes; //type: uint32
}; // BgpStateData::Neighbors::Neighbor::BgpNeighborCounters::Received
class BgpStateData::Neighbors::Neighbor::Connection : public ydk::Entity
{
public:
Connection();
~Connection();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf state; //type: TcpFsmState
ydk::YLeaf mode; //type: BgpMode
ydk::YLeaf total_established; //type: uint32
ydk::YLeaf total_dropped; //type: uint32
ydk::YLeaf last_reset; //type: string
ydk::YLeaf reset_reason; //type: string
}; // BgpStateData::Neighbors::Neighbor::Connection
class BgpStateData::Neighbors::Neighbor::Transport : public ydk::Entity
{
public:
Transport();
~Transport();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf path_mtu_discovery; //type: boolean
ydk::YLeaf local_port; //type: uint32
ydk::YLeaf local_host; //type: string
ydk::YLeaf foreign_port; //type: uint32
ydk::YLeaf foreign_host; //type: string
ydk::YLeaf mss; //type: uint32
}; // BgpStateData::Neighbors::Neighbor::Transport
class BgpStateData::Neighbors::Neighbor::PrefixActivity : public ydk::Entity
{
public:
PrefixActivity();
~PrefixActivity();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Sent; //type: BgpStateData::Neighbors::Neighbor::PrefixActivity::Sent
class Received; //type: BgpStateData::Neighbors::Neighbor::PrefixActivity::Received
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::PrefixActivity::Sent> sent;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::Neighbors::Neighbor::PrefixActivity::Received> received;
}; // BgpStateData::Neighbors::Neighbor::PrefixActivity
class BgpStateData::Neighbors::Neighbor::PrefixActivity::Sent : public ydk::Entity
{
public:
Sent();
~Sent();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf current_prefixes; //type: uint64
ydk::YLeaf total_prefixes; //type: uint64
ydk::YLeaf implicit_withdraw; //type: uint64
ydk::YLeaf explicit_withdraw; //type: uint64
ydk::YLeaf bestpaths; //type: uint64
ydk::YLeaf multipaths; //type: uint64
}; // BgpStateData::Neighbors::Neighbor::PrefixActivity::Sent
class BgpStateData::Neighbors::Neighbor::PrefixActivity::Received : public ydk::Entity
{
public:
Received();
~Received();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf current_prefixes; //type: uint64
ydk::YLeaf total_prefixes; //type: uint64
ydk::YLeaf implicit_withdraw; //type: uint64
ydk::YLeaf explicit_withdraw; //type: uint64
ydk::YLeaf bestpaths; //type: uint64
ydk::YLeaf multipaths; //type: uint64
}; // BgpStateData::Neighbors::Neighbor::PrefixActivity::Received
class BgpStateData::AddressFamilies : public ydk::Entity
{
public:
AddressFamilies();
~AddressFamilies();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class AddressFamily; //type: BgpStateData::AddressFamilies::AddressFamily
ydk::YList address_family;
}; // BgpStateData::AddressFamilies
class BgpStateData::AddressFamilies::AddressFamily : public ydk::Entity
{
public:
AddressFamily();
~AddressFamily();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf afi_safi; //type: AfiSafi
ydk::YLeaf vrf_name; //type: string
ydk::YLeaf router_id; //type: string
ydk::YLeaf bgp_table_version; //type: uint64
ydk::YLeaf routing_table_version; //type: uint64
ydk::YLeaf total_memory; //type: uint64
ydk::YLeaf local_as; //type: uint32
class Prefixes; //type: BgpStateData::AddressFamilies::AddressFamily::Prefixes
class Path; //type: BgpStateData::AddressFamilies::AddressFamily::Path
class AsPath; //type: BgpStateData::AddressFamilies::AddressFamily::AsPath
class RouteMap; //type: BgpStateData::AddressFamilies::AddressFamily::RouteMap
class FilterList; //type: BgpStateData::AddressFamilies::AddressFamily::FilterList
class Activities; //type: BgpStateData::AddressFamilies::AddressFamily::Activities
class BgpNeighborSummaries; //type: BgpStateData::AddressFamilies::AddressFamily::BgpNeighborSummaries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies::AddressFamily::Prefixes> prefixes;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies::AddressFamily::Path> path;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies::AddressFamily::AsPath> as_path;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies::AddressFamily::RouteMap> route_map;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies::AddressFamily::FilterList> filter_list;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies::AddressFamily::Activities> activities;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::AddressFamilies::AddressFamily::BgpNeighborSummaries> bgp_neighbor_summaries;
}; // BgpStateData::AddressFamilies::AddressFamily
class BgpStateData::AddressFamilies::AddressFamily::Prefixes : public ydk::Entity
{
public:
Prefixes();
~Prefixes();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf total_entries; //type: uint64
ydk::YLeaf memory_usage; //type: uint64
}; // BgpStateData::AddressFamilies::AddressFamily::Prefixes
class BgpStateData::AddressFamilies::AddressFamily::Path : public ydk::Entity
{
public:
Path();
~Path();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf total_entries; //type: uint64
ydk::YLeaf memory_usage; //type: uint64
}; // BgpStateData::AddressFamilies::AddressFamily::Path
class BgpStateData::AddressFamilies::AddressFamily::AsPath : public ydk::Entity
{
public:
AsPath();
~AsPath();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf total_entries; //type: uint64
ydk::YLeaf memory_usage; //type: uint64
}; // BgpStateData::AddressFamilies::AddressFamily::AsPath
class BgpStateData::AddressFamilies::AddressFamily::RouteMap : public ydk::Entity
{
public:
RouteMap();
~RouteMap();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf total_entries; //type: uint64
ydk::YLeaf memory_usage; //type: uint64
}; // BgpStateData::AddressFamilies::AddressFamily::RouteMap
class BgpStateData::AddressFamilies::AddressFamily::FilterList : public ydk::Entity
{
public:
FilterList();
~FilterList();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf total_entries; //type: uint64
ydk::YLeaf memory_usage; //type: uint64
}; // BgpStateData::AddressFamilies::AddressFamily::FilterList
class BgpStateData::AddressFamilies::AddressFamily::Activities : public ydk::Entity
{
public:
Activities();
~Activities();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefixes; //type: uint64
ydk::YLeaf paths; //type: uint64
ydk::YLeaf scan_interval; //type: string
}; // BgpStateData::AddressFamilies::AddressFamily::Activities
class BgpStateData::AddressFamilies::AddressFamily::BgpNeighborSummaries : public ydk::Entity
{
public:
BgpNeighborSummaries();
~BgpNeighborSummaries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpNeighborSummary; //type: BgpStateData::AddressFamilies::AddressFamily::BgpNeighborSummaries::BgpNeighborSummary
ydk::YList bgp_neighbor_summary;
}; // BgpStateData::AddressFamilies::AddressFamily::BgpNeighborSummaries
class BgpStateData::AddressFamilies::AddressFamily::BgpNeighborSummaries::BgpNeighborSummary : public ydk::Entity
{
public:
BgpNeighborSummary();
~BgpNeighborSummary();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf id; //type: string
ydk::YLeaf bgp_version; //type: uint32
ydk::YLeaf messages_received; //type: uint64
ydk::YLeaf messages_sent; //type: uint64
ydk::YLeaf table_version; //type: uint64
ydk::YLeaf input_queue; //type: uint64
ydk::YLeaf output_queue; //type: uint64
ydk::YLeaf up_time; //type: string
ydk::YLeaf state; //type: BgpFsmState
ydk::YLeaf prefixes_received; //type: uint64
ydk::YLeaf dynamically_configured; //type: boolean
ydk::YLeaf as; //type: uint32
}; // BgpStateData::AddressFamilies::AddressFamily::BgpNeighborSummaries::BgpNeighborSummary
class BgpStateData::BgpRouteVrfs : public ydk::Entity
{
public:
BgpRouteVrfs();
~BgpRouteVrfs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class BgpRouteVrf; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf
ydk::YList bgp_route_vrf;
}; // BgpStateData::BgpRouteVrfs
class BgpStateData::BgpRouteVrfs::BgpRouteVrf : public ydk::Entity
{
public:
BgpRouteVrf();
~BgpRouteVrf();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf vrf; //type: string
class BgpRouteAfs; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs> bgp_route_afs;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs : public ydk::Entity
{
public:
BgpRouteAfs();
~BgpRouteAfs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRouteAf; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf
ydk::YList bgp_route_af;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf : public ydk::Entity
{
public:
BgpRouteAf();
~BgpRouteAf();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_safi; //type: AfiSafi
class BgpRouteFilters; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters
class BgpRouteNeighbors; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors
class BgpPeerGroups; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpPeerGroups
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters> bgp_route_filters;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors> bgp_route_neighbors;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpPeerGroups> bgp_peer_groups;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters : public ydk::Entity
{
public:
BgpRouteFilters();
~BgpRouteFilters();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRouteFilter; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter
ydk::YList bgp_route_filter;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter : public ydk::Entity
{
public:
BgpRouteFilter();
~BgpRouteFilter();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf route_filter; //type: BgpRouteFilters
class BgpRouteEntries; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries> bgp_route_entries;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries : public ydk::Entity
{
public:
BgpRouteEntries();
~BgpRouteEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRouteEntry; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry
ydk::YList bgp_route_entry;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry : public ydk::Entity
{
public:
BgpRouteEntry();
~BgpRouteEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefix; //type: string
ydk::YLeaf version; //type: uint32
ydk::YLeaf available_paths; //type: uint32
ydk::YLeaf advertised_to; //type: string
class BgpPathEntries; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries> bgp_path_entries;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries : public ydk::Entity
{
public:
BgpPathEntries();
~BgpPathEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpPathEntry; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries::BgpPathEntry
ydk::YList bgp_path_entry;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries::BgpPathEntry : public ydk::Entity
{
public:
BgpPathEntry();
~BgpPathEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf nexthop; //type: string
ydk::YLeaf metric; //type: uint32
ydk::YLeaf local_pref; //type: uint32
ydk::YLeaf weight; //type: uint32
ydk::YLeaf as_path; //type: string
ydk::YLeaf origin; //type: BgpOriginCode
ydk::YLeaf rpki_status; //type: BgpRpkiStatus
ydk::YLeaf community; //type: string
ydk::YLeaf mpls_in; //type: string
ydk::YLeaf mpls_out; //type: string
ydk::YLeaf sr_profile_name; //type: string
ydk::YLeaf sr_binding_sid; //type: uint32
ydk::YLeaf sr_label_indx; //type: uint32
ydk::YLeaf as4_path; //type: string
ydk::YLeaf atomic_aggregate; //type: boolean
ydk::YLeaf aggr_as_number; //type: uint32
ydk::YLeaf aggr_as4_number; //type: uint32
ydk::YLeaf aggr_address; //type: string
ydk::YLeaf originator_id; //type: string
ydk::YLeaf cluster_list; //type: string
ydk::YLeaf extended_community; //type: string
ydk::YLeaf ext_aigp_metric; //type: uint64
ydk::YLeaf path_id; //type: uint32
class PathStatus; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries::BgpPathEntry::PathStatus
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries::BgpPathEntry::PathStatus> path_status;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries::BgpPathEntry
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries::BgpPathEntry::PathStatus : public ydk::Entity
{
public:
PathStatus();
~PathStatus();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf suppressed; //type: empty
ydk::YLeaf damped; //type: empty
ydk::YLeaf history; //type: empty
ydk::YLeaf valid; //type: empty
ydk::YLeaf sourced; //type: empty
ydk::YLeaf bestpath; //type: empty
ydk::YLeaf internal; //type: empty
ydk::YLeaf rib_fail; //type: empty
ydk::YLeaf stale; //type: empty
ydk::YLeaf multipath; //type: empty
ydk::YLeaf backup_path; //type: empty
ydk::YLeaf rt_filter; //type: empty
ydk::YLeaf best_external; //type: empty
ydk::YLeaf additional_path; //type: empty
ydk::YLeaf rib_compressed; //type: empty
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteFilters::BgpRouteFilter::BgpRouteEntries::BgpRouteEntry::BgpPathEntries::BgpPathEntry::PathStatus
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors : public ydk::Entity
{
public:
BgpRouteNeighbors();
~BgpRouteNeighbors();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRouteNeighbor; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor
ydk::YList bgp_route_neighbor;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor : public ydk::Entity
{
public:
BgpRouteNeighbor();
~BgpRouteNeighbor();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf nbr_id; //type: string
class BgpNeighborRouteFilters; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters> bgp_neighbor_route_filters;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters : public ydk::Entity
{
public:
BgpNeighborRouteFilters();
~BgpNeighborRouteFilters();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpNeighborRouteFilter; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter
ydk::YList bgp_neighbor_route_filter;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter : public ydk::Entity
{
public:
BgpNeighborRouteFilter();
~BgpNeighborRouteFilter();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf nbr_fltr; //type: BgpNeighborRouteFilters
class BgpNeighborRouteEntries; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries> bgp_neighbor_route_entries;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries : public ydk::Entity
{
public:
BgpNeighborRouteEntries();
~BgpNeighborRouteEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpNeighborRouteEntry; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry
ydk::YList bgp_neighbor_route_entry;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry : public ydk::Entity
{
public:
BgpNeighborRouteEntry();
~BgpNeighborRouteEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefix; //type: string
ydk::YLeaf version; //type: uint32
ydk::YLeaf available_paths; //type: uint32
ydk::YLeaf advertised_to; //type: string
class BgpNeighborPathEntries; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries> bgp_neighbor_path_entries;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries : public ydk::Entity
{
public:
BgpNeighborPathEntries();
~BgpNeighborPathEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpNeighborPathEntry; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries::BgpNeighborPathEntry
ydk::YList bgp_neighbor_path_entry;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries::BgpNeighborPathEntry : public ydk::Entity
{
public:
BgpNeighborPathEntry();
~BgpNeighborPathEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf nexthop; //type: string
ydk::YLeaf metric; //type: uint32
ydk::YLeaf local_pref; //type: uint32
ydk::YLeaf weight; //type: uint32
ydk::YLeaf as_path; //type: string
ydk::YLeaf origin; //type: BgpOriginCode
ydk::YLeaf rpki_status; //type: BgpRpkiStatus
ydk::YLeaf community; //type: string
ydk::YLeaf mpls_in; //type: string
ydk::YLeaf mpls_out; //type: string
ydk::YLeaf sr_profile_name; //type: string
ydk::YLeaf sr_binding_sid; //type: uint32
ydk::YLeaf sr_label_indx; //type: uint32
ydk::YLeaf as4_path; //type: string
ydk::YLeaf atomic_aggregate; //type: boolean
ydk::YLeaf aggr_as_number; //type: uint32
ydk::YLeaf aggr_as4_number; //type: uint32
ydk::YLeaf aggr_address; //type: string
ydk::YLeaf originator_id; //type: string
ydk::YLeaf cluster_list; //type: string
ydk::YLeaf extended_community; //type: string
ydk::YLeaf ext_aigp_metric; //type: uint64
ydk::YLeaf path_id; //type: uint32
class PathStatus; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries::BgpNeighborPathEntry::PathStatus
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries::BgpNeighborPathEntry::PathStatus> path_status;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries::BgpNeighborPathEntry
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries::BgpNeighborPathEntry::PathStatus : public ydk::Entity
{
public:
PathStatus();
~PathStatus();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf suppressed; //type: empty
ydk::YLeaf damped; //type: empty
ydk::YLeaf history; //type: empty
ydk::YLeaf valid; //type: empty
ydk::YLeaf sourced; //type: empty
ydk::YLeaf bestpath; //type: empty
ydk::YLeaf internal; //type: empty
ydk::YLeaf rib_fail; //type: empty
ydk::YLeaf stale; //type: empty
ydk::YLeaf multipath; //type: empty
ydk::YLeaf backup_path; //type: empty
ydk::YLeaf rt_filter; //type: empty
ydk::YLeaf best_external; //type: empty
ydk::YLeaf additional_path; //type: empty
ydk::YLeaf rib_compressed; //type: empty
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpRouteNeighbors::BgpRouteNeighbor::BgpNeighborRouteFilters::BgpNeighborRouteFilter::BgpNeighborRouteEntries::BgpNeighborRouteEntry::BgpNeighborPathEntries::BgpNeighborPathEntry::PathStatus
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpPeerGroups : public ydk::Entity
{
public:
BgpPeerGroups();
~BgpPeerGroups();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpPeerGroup; //type: BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpPeerGroups::BgpPeerGroup
ydk::YList bgp_peer_group;
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpPeerGroups
class BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpPeerGroups::BgpPeerGroup : public ydk::Entity
{
public:
BgpPeerGroup();
~BgpPeerGroup();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf name; //type: string
ydk::YLeaf description; //type: string
ydk::YLeaf remote_as; //type: uint32
ydk::YLeaf bgp_version; //type: uint16
ydk::YLeaf min_time; //type: uint16
ydk::YLeaf num_of_sessions; //type: uint32
ydk::YLeaf num_estab_sessions; //type: uint32
ydk::YLeaf num_sso_sessions; //type: uint32
ydk::YLeaf fmt_grp_ix; //type: uint16
ydk::YLeaf adv_ix; //type: uint16
ydk::YLeaf aspath_in; //type: uint32
ydk::YLeaf aspath_out; //type: uint32
ydk::YLeaf routemap_in; //type: string
ydk::YLeaf routemap_out; //type: string
ydk::YLeaf updated_messages; //type: uint64
ydk::YLeaf rep_count; //type: uint32
ydk::YLeaf slowpeer_detection_value; //type: uint16
ydk::YLeaf weight; //type: uint16
ydk::YLeaf send_community; //type: boolean
ydk::YLeaf extended_community; //type: boolean
ydk::YLeaf remove_private_as; //type: boolean
ydk::YLeafList peer_members; //type: list of string
}; // BgpStateData::BgpRouteVrfs::BgpRouteVrf::BgpRouteAfs::BgpRouteAf::BgpPeerGroups::BgpPeerGroup
class BgpStateData::BgpRouteRds : public ydk::Entity
{
public:
BgpRouteRds();
~BgpRouteRds();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class BgpRouteRd; //type: BgpStateData::BgpRouteRds::BgpRouteRd
ydk::YList bgp_route_rd;
}; // BgpStateData::BgpRouteRds
class BgpStateData::BgpRouteRds::BgpRouteRd : public ydk::Entity
{
public:
BgpRouteRd();
~BgpRouteRd();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf rd_value; //type: string
class BgpRdRouteAfs; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs> bgp_rd_route_afs;
}; // BgpStateData::BgpRouteRds::BgpRouteRd
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs : public ydk::Entity
{
public:
BgpRdRouteAfs();
~BgpRdRouteAfs();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdRouteAf; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf
ydk::YList bgp_rd_route_af;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf : public ydk::Entity
{
public:
BgpRdRouteAf();
~BgpRdRouteAf();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf afi_safi; //type: AfiSafi
class BgpRdRouteFilters; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters
class BgpRdRouteNeighbors; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters> bgp_rd_route_filters;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors> bgp_rd_route_neighbors;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters : public ydk::Entity
{
public:
BgpRdRouteFilters();
~BgpRdRouteFilters();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdRouteFilter; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter
ydk::YList bgp_rd_route_filter;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter : public ydk::Entity
{
public:
BgpRdRouteFilter();
~BgpRdRouteFilter();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf route_filter; //type: BgpRouteFilters
class BgpRdRouteEntries; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries> bgp_rd_route_entries;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries : public ydk::Entity
{
public:
BgpRdRouteEntries();
~BgpRdRouteEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdRouteEntry; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry
ydk::YList bgp_rd_route_entry;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry : public ydk::Entity
{
public:
BgpRdRouteEntry();
~BgpRdRouteEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefix; //type: string
ydk::YLeaf version; //type: uint32
ydk::YLeaf available_paths; //type: uint32
ydk::YLeaf advertised_to; //type: string
class BgpRdPathEntries; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries> bgp_rd_path_entries;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries : public ydk::Entity
{
public:
BgpRdPathEntries();
~BgpRdPathEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdPathEntry; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries::BgpRdPathEntry
ydk::YList bgp_rd_path_entry;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries::BgpRdPathEntry : public ydk::Entity
{
public:
BgpRdPathEntry();
~BgpRdPathEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf nexthop; //type: string
ydk::YLeaf metric; //type: uint32
ydk::YLeaf local_pref; //type: uint32
ydk::YLeaf weight; //type: uint32
ydk::YLeaf as_path; //type: string
ydk::YLeaf origin; //type: BgpOriginCode
ydk::YLeaf rpki_status; //type: BgpRpkiStatus
ydk::YLeaf community; //type: string
ydk::YLeaf mpls_in; //type: string
ydk::YLeaf mpls_out; //type: string
ydk::YLeaf sr_profile_name; //type: string
ydk::YLeaf sr_binding_sid; //type: uint32
ydk::YLeaf sr_label_indx; //type: uint32
ydk::YLeaf as4_path; //type: string
ydk::YLeaf atomic_aggregate; //type: boolean
ydk::YLeaf aggr_as_number; //type: uint32
ydk::YLeaf aggr_as4_number; //type: uint32
ydk::YLeaf aggr_address; //type: string
ydk::YLeaf originator_id; //type: string
ydk::YLeaf cluster_list; //type: string
ydk::YLeaf extended_community; //type: string
ydk::YLeaf ext_aigp_metric; //type: uint64
ydk::YLeaf path_id; //type: uint32
class PathStatus; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries::BgpRdPathEntry::PathStatus
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries::BgpRdPathEntry::PathStatus> path_status;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries::BgpRdPathEntry
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries::BgpRdPathEntry::PathStatus : public ydk::Entity
{
public:
PathStatus();
~PathStatus();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf suppressed; //type: empty
ydk::YLeaf damped; //type: empty
ydk::YLeaf history; //type: empty
ydk::YLeaf valid; //type: empty
ydk::YLeaf sourced; //type: empty
ydk::YLeaf bestpath; //type: empty
ydk::YLeaf internal; //type: empty
ydk::YLeaf rib_fail; //type: empty
ydk::YLeaf stale; //type: empty
ydk::YLeaf multipath; //type: empty
ydk::YLeaf backup_path; //type: empty
ydk::YLeaf rt_filter; //type: empty
ydk::YLeaf best_external; //type: empty
ydk::YLeaf additional_path; //type: empty
ydk::YLeaf rib_compressed; //type: empty
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteFilters::BgpRdRouteFilter::BgpRdRouteEntries::BgpRdRouteEntry::BgpRdPathEntries::BgpRdPathEntry::PathStatus
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors : public ydk::Entity
{
public:
BgpRdRouteNeighbors();
~BgpRdRouteNeighbors();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdRouteNeighbor; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor
ydk::YList bgp_rd_route_neighbor;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor : public ydk::Entity
{
public:
BgpRdRouteNeighbor();
~BgpRdRouteNeighbor();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf neighbor_id; //type: string
class BgpRdNeighborRouteFilters; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters> bgp_rd_neighbor_route_filters;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters : public ydk::Entity
{
public:
BgpRdNeighborRouteFilters();
~BgpRdNeighborRouteFilters();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdNeighborRouteFilter; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter
ydk::YList bgp_rd_neighbor_route_filter;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter : public ydk::Entity
{
public:
BgpRdNeighborRouteFilter();
~BgpRdNeighborRouteFilter();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf neighbor_filter; //type: BgpNeighborRouteFilters
class BgpRdNeighborRouteEntries; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries> bgp_rd_neighbor_route_entries;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries : public ydk::Entity
{
public:
BgpRdNeighborRouteEntries();
~BgpRdNeighborRouteEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdNeighborRouteEntry; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry
ydk::YList bgp_rd_neighbor_route_entry;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry : public ydk::Entity
{
public:
BgpRdNeighborRouteEntry();
~BgpRdNeighborRouteEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf prefix; //type: string
ydk::YLeaf version; //type: uint32
ydk::YLeaf available_paths; //type: uint32
ydk::YLeaf advertised_to; //type: string
class BgpRdNeighborPathEntries; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries> bgp_rd_neighbor_path_entries;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries : public ydk::Entity
{
public:
BgpRdNeighborPathEntries();
~BgpRdNeighborPathEntries();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class BgpRdNeighborPathEntry; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries::BgpRdNeighborPathEntry
ydk::YList bgp_rd_neighbor_path_entry;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries::BgpRdNeighborPathEntry : public ydk::Entity
{
public:
BgpRdNeighborPathEntry();
~BgpRdNeighborPathEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf nexthop; //type: string
ydk::YLeaf metric; //type: uint32
ydk::YLeaf local_pref; //type: uint32
ydk::YLeaf weight; //type: uint32
ydk::YLeaf as_path; //type: string
ydk::YLeaf origin; //type: BgpOriginCode
ydk::YLeaf rpki_status; //type: BgpRpkiStatus
ydk::YLeaf community; //type: string
ydk::YLeaf mpls_in; //type: string
ydk::YLeaf mpls_out; //type: string
ydk::YLeaf sr_profile_name; //type: string
ydk::YLeaf sr_binding_sid; //type: uint32
ydk::YLeaf sr_label_indx; //type: uint32
ydk::YLeaf as4_path; //type: string
ydk::YLeaf atomic_aggregate; //type: boolean
ydk::YLeaf aggr_as_number; //type: uint32
ydk::YLeaf aggr_as4_number; //type: uint32
ydk::YLeaf aggr_address; //type: string
ydk::YLeaf originator_id; //type: string
ydk::YLeaf cluster_list; //type: string
ydk::YLeaf extended_community; //type: string
ydk::YLeaf ext_aigp_metric; //type: uint64
ydk::YLeaf path_id; //type: uint32
class PathStatus; //type: BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries::BgpRdNeighborPathEntry::PathStatus
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_bgp_oper::BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries::BgpRdNeighborPathEntry::PathStatus> path_status;
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries::BgpRdNeighborPathEntry
class BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries::BgpRdNeighborPathEntry::PathStatus : public ydk::Entity
{
public:
PathStatus();
~PathStatus();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf suppressed; //type: empty
ydk::YLeaf damped; //type: empty
ydk::YLeaf history; //type: empty
ydk::YLeaf valid; //type: empty
ydk::YLeaf sourced; //type: empty
ydk::YLeaf bestpath; //type: empty
ydk::YLeaf internal; //type: empty
ydk::YLeaf rib_fail; //type: empty
ydk::YLeaf stale; //type: empty
ydk::YLeaf multipath; //type: empty
ydk::YLeaf backup_path; //type: empty
ydk::YLeaf rt_filter; //type: empty
ydk::YLeaf best_external; //type: empty
ydk::YLeaf additional_path; //type: empty
ydk::YLeaf rib_compressed; //type: empty
}; // BgpStateData::BgpRouteRds::BgpRouteRd::BgpRdRouteAfs::BgpRdRouteAf::BgpRdRouteNeighbors::BgpRdRouteNeighbor::BgpRdNeighborRouteFilters::BgpRdNeighborRouteFilter::BgpRdNeighborRouteEntries::BgpRdNeighborRouteEntry::BgpRdNeighborPathEntries::BgpRdNeighborPathEntry::PathStatus
class BgpFsmState : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf fsm_idle;
static const ydk::Enum::YLeaf fsm_connect;
static const ydk::Enum::YLeaf fsm_active;
static const ydk::Enum::YLeaf fsm_opensent;
static const ydk::Enum::YLeaf fsm_openconfirm;
static const ydk::Enum::YLeaf fsm_established;
static const ydk::Enum::YLeaf fsm_nonnegotiated;
static int get_enum_value(const std::string & name) {
if (name == "fsm-idle") return 0;
if (name == "fsm-connect") return 1;
if (name == "fsm-active") return 2;
if (name == "fsm-opensent") return 3;
if (name == "fsm-openconfirm") return 4;
if (name == "fsm-established") return 5;
if (name == "fsm-nonnegotiated") return 6;
return -1;
}
};
class BgpLink : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf internal;
static const ydk::Enum::YLeaf external;
static int get_enum_value(const std::string & name) {
if (name == "internal") return 0;
if (name == "external") return 1;
return -1;
}
};
class BgpMode : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf mode_active;
static const ydk::Enum::YLeaf mode_passive;
static int get_enum_value(const std::string & name) {
if (name == "mode-active") return 0;
if (name == "mode-passive") return 1;
return -1;
}
};
}
}
#endif /* _CISCO_IOS_XE_BGP_OPER_ */
| 57.625895 | 349 | 0.719746 | CiscoDevNet |
180d3973f99e8ca145b1117d02ee90392b76c118 | 1,696 | cpp | C++ | Laborator8/Project1/Project1/Source.cpp | GeorgeDenis/oop-2022 | 45b026f762a85c4e683f413b5c785b7e8541de04 | [
"MIT"
] | null | null | null | Laborator8/Project1/Project1/Source.cpp | GeorgeDenis/oop-2022 | 45b026f762a85c4e683f413b5c785b7e8541de04 | [
"MIT"
] | null | null | null | Laborator8/Project1/Project1/Source.cpp | GeorgeDenis/oop-2022 | 45b026f762a85c4e683f413b5c785b7e8541de04 | [
"MIT"
] | 1 | 2022-02-23T16:38:17.000Z | 2022-02-23T16:38:17.000Z | #define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <map>
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
bool Comparare(pair<string, int>& stanga, pair<string, int>& dreapta) {
if (stanga.second != dreapta.second)
return stanga.second < dreapta.second;
else {
return stanga.first.compare(dreapta.first) > 0;
}
}
int main() {
FILE* f = fopen("H:\\PROGRAMAREORIENTATEOBIECT\\Fork\\oop-2022\\Laborator8\\Project1\\Project1\\Text.txt", "r");
if (f == nullptr) {
printf("Eroare!!\n");
exit(1);
}
string sir;
char subsir[4096];
while (!feof(f)) {
auto text = fread(subsir, 1, sizeof(subsir), f);
sir.append(subsir, text);
}
fclose(f);
for (int i = 0; i < sir.size(); i++)
sir[i] = tolower(sir[i]);
map<string, int> m;
int poz = 0;
int start = 0;
int pozitie = sir.find_first_of(" ,?!.", poz);
string cuvant;
while (pozitie != string::npos) {
cuvant = sir.substr(start, pozitie - start);
m[cuvant]++;
poz = pozitie + 1;
start = sir.find_first_not_of(" ,?!.", poz);
poz = start;
pozitie = sir.find_first_of(" ,?!.", poz);
}
priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(&Comparare)> queue(Comparare);
map<string, int>::iterator it = m.begin();
while (it != m.end()) {
pair<string, int> p;
p.first = it->first;
p.second = it->second;
queue.push(p);
it++;
}
while (!queue.empty()) {
cout << queue.top().first << " => " << queue.top().second << "\n";
queue.pop();
}
return 0;
} | 27.803279 | 116 | 0.551887 | GeorgeDenis |
180d5d3920f5966139b418540bceb4a9fdcb0a55 | 1,005 | cpp | C++ | evias/core/ro_container.cpp | evias/evias | 5b5d4c16404f855c3234afa05b11c339a3ebb4cb | [
"BSD-3-Clause"
] | 1 | 2015-10-31T03:18:02.000Z | 2015-10-31T03:18:02.000Z | evias/core/ro_container.cpp | evias/evias | 5b5d4c16404f855c3234afa05b11c339a3ebb4cb | [
"BSD-3-Clause"
] | null | null | null | evias/core/ro_container.cpp | evias/evias | 5b5d4c16404f855c3234afa05b11c339a3ebb4cb | [
"BSD-3-Clause"
] | null | null | null | #include "ro_container.cpp"
using namespace evias::core;
evias::core::readOnlyContainer::readOnlyContainer()
: _dataPointer(0),
_dataSize(0)
{
}
evias::core::readOnlyContainer::readOnlyContainer(const Container* copy)
: _dataPointer(copy->getData()),
_dataSize(copy->getSize())
{
}
evias::core::readOnlyContainer::readOnlyContainer(const uint8_t* pointer, uint64_t size)
: _dataPointer(pointer),
_dataSize(size)
{
}
evias::core::readOnlyContainer::readOnlyContainer(const void* pointer, uint64_t size)
: _dataPointer(reinterpret_cast<const uint8_t*> (pointer)),
_dataSize(size)
{
}
evias::core::readOnlyContainer::~readOnlyContainer()
{
}
Container* evias::core::readOnlyContainer::getCopy() const
{
return new readOnlyContainer(this->getData(), this->getSize());
}
const uint8_t* evias::core::readOnlyContainer::getData() const
{
return _dataPointer;
}
uint64_t evias::core::readOnlyContainer::getSize() const
{
return _dataSize;
}
| 20.1 | 88 | 0.715423 | evias |
180ee55b55b026732ba452b197d55f1e6e7f7e22 | 356 | cpp | C++ | lesson01/exampe16.cpp | Youngfellows/LinuxCPP | 6148346ba2c5c0a6d29a4f3a564baf9f06d619fe | [
"Apache-2.0"
] | null | null | null | lesson01/exampe16.cpp | Youngfellows/LinuxCPP | 6148346ba2c5c0a6d29a4f3a564baf9f06d619fe | [
"Apache-2.0"
] | null | null | null | lesson01/exampe16.cpp | Youngfellows/LinuxCPP | 6148346ba2c5c0a6d29a4f3a564baf9f06d619fe | [
"Apache-2.0"
] | null | null | null | #include<iostream>
int main()
{
//类型转换
float temp = 23.3;
std::cout << temp << std::endl;
double volume = 4.57;
long double ld = 6.23E23;
std::cout << volume << std::endl;
std::cout << ld << std::endl;
std::cout << volume * ld << std::endl;
std::cout << temp/volume << std::endl;
return 0;
}
| 17.8 | 43 | 0.5 | Youngfellows |
180f1e49d0102a23cdbcbe6d013dc76e3c430b66 | 2,557 | cpp | C++ | MaterialLib/FractureModels/CreateMohrCoulomb.cpp | HaibingShao/ogs6_ufz | d4acfe7132eaa2010157122da67c7a4579b2ebae | [
"BSD-4-Clause"
] | null | null | null | MaterialLib/FractureModels/CreateMohrCoulomb.cpp | HaibingShao/ogs6_ufz | d4acfe7132eaa2010157122da67c7a4579b2ebae | [
"BSD-4-Clause"
] | null | null | null | MaterialLib/FractureModels/CreateMohrCoulomb.cpp | HaibingShao/ogs6_ufz | d4acfe7132eaa2010157122da67c7a4579b2ebae | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include "CreateMohrCoulomb.h"
#include "ProcessLib/Utils/ProcessUtils.h" // required for findParameter
#include "MohrCoulomb.h"
namespace MaterialLib
{
namespace Fracture
{
template <int DisplacementDim>
std::unique_ptr<FractureModelBase<DisplacementDim>>
createMohrCoulomb(
std::vector<std::unique_ptr<ProcessLib::ParameterBase>> const& parameters,
BaseLib::ConfigTree const& config)
{
//! \ogs_file_param{material__solid__constitutive_relation__type}
config.checkConfigParameter("type", "MohrCoulomb");
DBUG("Create MohrCoulomb material");
auto& Kn = ProcessLib::findParameter<double>(
//! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__normal_stiffness}
config, "normal_stiffness", parameters, 1);
auto& Ks = ProcessLib::findParameter<double>(
//! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__shear_stiffness}
config, "shear_stiffness", parameters, 1);
auto& friction_angle = ProcessLib::findParameter<double>(
//! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__friction_angle}
config, "friction_angle", parameters, 1);
auto& dilatancy_angle = ProcessLib::findParameter<double>(
//! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__dilatancy_angle}
config, "dilatancy_angle", parameters, 1);
auto& cohesion = ProcessLib::findParameter<double>(
//! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__cohesion}
config, "cohesion", parameters, 1);
typename MohrCoulomb<DisplacementDim>::MaterialProperties mp{
Kn, Ks, friction_angle, dilatancy_angle, cohesion};
return std::unique_ptr<MohrCoulomb<DisplacementDim>>{
new MohrCoulomb<DisplacementDim>{mp}};
}
template
std::unique_ptr<FractureModelBase<2>>
createMohrCoulomb(
std::vector<std::unique_ptr<ProcessLib::ParameterBase>> const& parameters,
BaseLib::ConfigTree const& config);
template
std::unique_ptr<FractureModelBase<3>>
createMohrCoulomb(
std::vector<std::unique_ptr<ProcessLib::ParameterBase>> const& parameters,
BaseLib::ConfigTree const& config);
} // namespace Fracture
} // namespace MaterialLib
| 35.027397 | 106 | 0.746187 | HaibingShao |
18134b8fe388d34fa17eb86f057b359995c13d21 | 13,355 | hpp | C++ | include/seqan3/alphabet/detail/alphabet_proxy.hpp | h-2/seqan3 | 2cbc19c6f2cdb76c65ed6ff6ae70fc67334146d7 | [
"CC-BY-4.0",
"CC0-1.0"
] | 4 | 2018-03-09T09:37:51.000Z | 2020-07-28T04:52:01.000Z | include/seqan3/alphabet/detail/alphabet_proxy.hpp | h-2/seqan3 | 2cbc19c6f2cdb76c65ed6ff6ae70fc67334146d7 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | include/seqan3/alphabet/detail/alphabet_proxy.hpp | h-2/seqan3 | 2cbc19c6f2cdb76c65ed6ff6ae70fc67334146d7 | [
"CC-BY-4.0",
"CC0-1.0"
] | 1 | 2018-03-09T09:37:54.000Z | 2018-03-09T09:37:54.000Z | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Hannes Hauswedell <hannes.hauswedell AT fu-berlin.de>
* \brief Free function/type trait wrappers for alphabets with member functions/types.
*
* This shall not need be included manually, just include `alphabet/concept.hpp`.
*/
#pragma once
#include <seqan3/alphabet/alphabet_base.hpp>
#include <seqan3/alphabet/nucleotide/concept.hpp>
#include <seqan3/alphabet/quality/concept.hpp>
#include <seqan3/core/concept/core_language.hpp>
#include <seqan3/core/type_traits/basic.hpp>
#include <seqan3/core/type_traits/template_inspection.hpp>
#include <seqan3/std/concepts>
#if 0 // this is the alphabet_proxy I want, but GCC won't give me:
#include <seqan3/core/type_traits/transformation_trait_or.hpp>
template <typename derived_type, typename alphabet_type>
class alphabet_proxy : public alphabet_type
{
public:
using base_t = alphabet_type;
using base_t::alphabet_size;
using typename base_t::rank_type;
using char_type = detail::transformation_trait_or_t<std::type_identity<alphabet_char_t<<alphabet_type>, void>;
using phred_type = detail::transformation_trait_or_t<alphabet_phred_t<alphabet_type>, void>;
using char_type_virtual = detail::valid_template_spec_or_t<char, alphabet_char_t, alphabet_type>;
using phred_type_virtual = detail::valid_template_spec_or_t<int8_t, alphabet_phred_t, alphabet_type>;
constexpr alphabet_proxy() : base_t{} {}
constexpr alphabet_proxy(alphabet_proxy const &) = default;
constexpr alphabet_proxy(alphabet_proxy &&) = default;
constexpr alphabet_proxy & operator=(alphabet_proxy const &) = default;
constexpr alphabet_proxy & operator=(alphabet_proxy &&) = default;
~alphabet_proxy() = default;
constexpr alphabet_proxy(alphabet_type const a) :
base_t{a}
{}
constexpr alphabet_proxy & operator=(alphabet_type const & c) noexcept
{
base_t::assign_rank(seqan3::to_rank(c));
static_cast<derived_type &>(*this).on_update(); // <- this invokes the actual proxy behaviour!
return *this;
}
template <typename indirect_assignable_type>
requires std::Assignable<alphabet_type &, indirect_assignable_type>
constexpr alphabet_proxy & operator=(indirect_assignable_type const & c) noexcept
{
alphabet_type a{};
a = c;
return operator=(a);
}
constexpr alphabet_proxy & assign_char(char_type_virtual const c) noexcept
requires !std::Same<char_type, void>
{
alphabet_type tmp{};
using seqan3::assign_char_to;
assign_char_to(c, tmp);
return operator=(tmp);
}
constexpr alphabet_proxy & assign_rank(alphabet_rank_t<alphabet_type> const r) noexcept
{
alphabet_type tmp{};
using seqan3::assign_rank_to;
assign_rank_to(r, tmp);
return operator=(tmp);
}
constexpr alphabet_proxy & assign_phred(phred_type_virtual const c) noexcept
requires !std::Same<phred_type, void>
{
alphabet_type tmp{};
assign_phred_to(c, tmp);
return operator=(tmp);
}
};
#endif
#if 1// this is the one that works for most things, but not all
namespace seqan3
{
/*!\brief A CRTP-base that eases the definition of proxy types returned in place of regular alphabets.
* \tparam derived_type The CRTP parameter type.
* \tparam alphabet_type The type of the alphabet that this proxy emulates.
* \ingroup alphabet
*
* \details
*
* \noapi
*
* Certain containers and other data structure hold alphabet values in a non-standard way so they can convert
* to that alphabet when being accessed, but cannot return a reference to the held value. These data structures
* may instead return a *proxy* to the held value which still allows changing it (and updating the underlying data
* structure to reflect this).
*
* This CRTP base facilitates the definition of such proxies. Most users of SeqAn will not need to understand the
* details.
*
* This class ensures that the proxy itself also models seqan3::Semialphabet, seqan3::Alphabet,
* seqan3::QualityAlphabet, seqan3::NucleotideAlphabet and/or seqan3::AminoacidAlphabet if the emulated type models
* these. This makes sure that function templates which accept the original, also accept the proxy. An exception
* are multi-layered composites of alphabets where the proxy currently does not support access via `get`.
*
* ### Implementation notes
*
* The derived type needs to provide an `.on_update()` member function that performs the changes in the underlying
* data structure.
*
* See seqan3::bitcompressed_vector or seqan3::alphabet_tuple_base for examples of how this class is used.
*/
template <typename derived_type, WritableSemialphabet alphabet_type>
class alphabet_proxy : public alphabet_base<derived_type,
alphabet_size<alphabet_type>,
detail::valid_template_spec_or_t<void, alphabet_char_t, alphabet_type>>
{
private:
//!\brief Type of the base class.
using base_t = alphabet_base<derived_type,
alphabet_size<alphabet_type>,
detail::valid_template_spec_or_t<void, alphabet_char_t, alphabet_type>>;
//!\brief Befriend the base type.
friend base_t;
//!\brief The type of the alphabet character.
using char_type = detail::valid_template_spec_or_t<char, alphabet_char_t, alphabet_type>;
//!\brief The type of the phred score.
using phred_type = detail::valid_template_spec_or_t<int8_t, alphabet_phred_t, alphabet_type>;
public:
// Import from base:
using base_t::alphabet_size;
using base_t::to_rank;
/*!\name Member types
* \{
*/
//!\brief The type of the rank representation.
using rank_type = alphabet_rank_t<alphabet_type>;
//!\}
private:
//!\brief Never used, but required for valid definitions.
/*!\name Constructors, destructor and assignment
* \{
*/
constexpr alphabet_proxy() noexcept : base_t{} {} //!< Defaulted.
constexpr alphabet_proxy(alphabet_proxy const &) = default; //!< Defaulted.
constexpr alphabet_proxy(alphabet_proxy &&) = default; //!< Defaulted.
constexpr alphabet_proxy & operator=(alphabet_proxy const &) = default; //!< Defaulted.
constexpr alphabet_proxy & operator=(alphabet_proxy &&) = default; //!< Defaulted.
~alphabet_proxy() = default; //!< Defaulted.
//!\brief Construction from the emulated type.
constexpr alphabet_proxy(alphabet_type const a) noexcept
{
base_t::assign_rank(seqan3::to_rank(a));
}
//!\brief Assigment from the emulated type. This function triggers the specialisation in the derived_type.
constexpr derived_type & operator=(alphabet_type const & c) noexcept
{
base_t::assign_rank(seqan3::to_rank(c));
static_cast<derived_type &>(*this).on_update(); // <- this invokes the actual proxy behaviour!
return static_cast<derived_type &>(*this);
}
//!\brief Assignment from any type that the emulated type is assignable from.
template <typename indirect_assignable_type>
constexpr derived_type & operator=(indirect_assignable_type const & c) noexcept
requires WeaklyAssignable<alphabet_type, indirect_assignable_type>
{
alphabet_type a{};
a = c;
return operator=(a);
}
//!\}
//!\brief Befriend the derived type so it can instantiate.
friend derived_type;
public:
/*!\name Write functions
* \brief All of these call the emulated type's write functions and then delegate to
* the assignment operator which invokes derived behaviour.
* \{
*/
constexpr derived_type & assign_rank(alphabet_rank_t<alphabet_type> const r) noexcept
{
alphabet_type tmp{};
assign_rank_to(r, tmp);
return operator=(tmp);
}
constexpr derived_type & assign_char(char_type const c) noexcept
requires WritableAlphabet<alphabet_type>
{
alphabet_type tmp{};
assign_char_to(c, tmp);
return operator=(tmp);
}
constexpr derived_type & assign_phred(phred_type const c) noexcept
requires WritableQualityAlphabet<alphabet_type>
{
alphabet_type tmp{};
assign_phred_to(c, tmp);
return operator=(tmp);
}
//!\}
/*!\name Read functions
* \brief All of these call the emulated type's read functions.
* \{
*/
//!\brief Implicit conversion to the emulated type.
constexpr operator alphabet_type() const noexcept
{
return assign_rank_to(to_rank(), alphabet_type{});
}
//!\brief Implicit conversion to types that the emulated type is convertible to.
template <typename other_t>
//!\cond
requires std::ConvertibleTo<alphabet_type, other_t>
//!\endcond
constexpr operator other_t() const noexcept
{
return operator alphabet_type();
}
constexpr auto to_char() const noexcept
requires Alphabet<alphabet_type>
{
/* (smehringer) Explicit conversion instead of static_cast:
* See explanation in to_phred().
*/
return seqan3::to_char(operator alphabet_type());
}
constexpr auto to_phred() const noexcept
requires QualityAlphabet<alphabet_type>
{
using seqan3::to_phred;
/* (smehringer) Explicit conversion instead of static_cast:
* The tuple composite qualified returns a component_proxy which inherits from alphabet_proxy_base.
* The qualified alphabet itself inherits from quality_base.
* Now when accessing get<1>(seq_qual_alph) we want to call to_phred at some point because we want the quality,
* therefore the to_phred function from alphabet_proxy is called, but this function did a static_cast to the
* derived type which is calling the constructor from quality_base. Unfortunately now, the generic quality_base
* constructor uses `assign_phred_to(to_phred(other), static_cast<derived_type &>(*this))`; (here) which again
* tries to call to_phred of the alphabet_proxy => infinite loop :boom:
*/
return to_phred(operator alphabet_type());
}
#if 0 // this currently causes GCC ICE in alphabet_tuple_base test
constexpr alphabet_type complement() const noexcept
requires NucleotideAlphabet<alphabet_type>
{
using seqan3::complement;
return complement(static_cast<alphabet_type>(*this));
}
#endif
//!\brief Delegate to the emulated type's validator.
static constexpr bool char_is_valid(char_type const c) noexcept
requires WritableAlphabet<alphabet_type>
{
return char_is_valid_for<alphabet_type>(c);
}
//!\}
/*!\name Comparison operators
* \brief These are only required if the emulated type allows comparison with types it is not convertible to,
* e.g. seqan3::alphabet_variant.
* \{
*/
//!\brief Allow (in-)equality comparison with types that the emulated type is comparable with.
template <typename t>
friend constexpr auto operator==(derived_type const lhs, t const rhs) noexcept
-> std::enable_if_t<!std::Same<derived_type, t> && std::detail::WeaklyEqualityComparableWith<alphabet_type, t>,
bool>
{
return (static_cast<alphabet_type>(lhs) == rhs);
}
//!\brief Allow (in-)equality comparison with types that the emulated type is comparable with.
template <typename t>
friend constexpr auto operator==(t const lhs, derived_type const rhs) noexcept
-> std::enable_if_t<!std::Same<derived_type, t> && std::detail::WeaklyEqualityComparableWith<alphabet_type, t>,
bool>
{
return (rhs == lhs);
}
//!\brief Allow (in-)equality comparison with types that the emulated type is comparable with.
template <typename t>
friend constexpr auto operator!=(derived_type const lhs, t const rhs) noexcept
-> std::enable_if_t<!std::Same<derived_type, t> && std::detail::WeaklyEqualityComparableWith<alphabet_type, t>,
bool>
{
return !(lhs == rhs);
}
//!\brief Allow (in-)equality comparison with types that the emulated type is comparable with.
template <typename t>
friend constexpr auto operator!=(t const lhs, derived_type const rhs) noexcept
-> std::enable_if_t<!std::Same<derived_type, t> && std::detail::WeaklyEqualityComparableWith<alphabet_type, t>,
bool>
{
return (rhs != lhs);
}
//!\}
};
#endif
} // namespace seqan3
| 39.164223 | 119 | 0.673306 | h-2 |
1826e5671918e7fb8faa820ab9cde99cdbf92dbe | 1,255 | cpp | C++ | Source/Life/AI/Perceptions/UtilityAiFindNearestActorPerception.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | 5 | 2022-02-09T21:19:03.000Z | 2022-03-03T01:53:03.000Z | Source/Life/AI/Perceptions/UtilityAiFindNearestActorPerception.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | Source/Life/AI/Perceptions/UtilityAiFindNearestActorPerception.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | #include "Life/AI/Perceptions/UtilityAiFindNearestActorPerception.h"
#include "Systems/Public/Iterator.h"
#include "Life/AI/Reasoner/UtilityAiMemory.h"
struct Meta
{
float DistanceSquared = 0;
AActor* Actor = nullptr;
};
void UUtilityAiFindNearestActorPerception::Perceive(AActor* Actor,
USystemsWorld& Systems,
FUtilityAiMemory& Memory) const
{
const auto Position = Actor->GetActorLocation();
if (auto* ActorsList = Memory.Access(this->SourceMemoryProperty).AsArray())
{
const auto Found = IterStd(*ActorsList)
.FilterMap<Meta>(
[&](auto& Value)
{
auto* OtherActor = Value.CastObject<AActor>();
if (IsValid(OtherActor))
{
const auto OtherPosition =
OtherActor->GetActorLocation();
const auto DistanceSquared =
FVector::DistSquared(Position, OtherPosition);
return TOptional<Meta>({DistanceSquared, OtherActor});
}
return TOptional<Meta>();
})
.ComparedBy([](const auto& A, const auto& B)
{ return A.DistanceSquared < B.DistanceSquared; });
if (Found.IsSet())
{
Memory.Access(this->TargetMemoryProperty) = Found.GetValue().Actor;
}
}
}
| 26.702128 | 76 | 0.631873 | PsichiX |
1826f405a781f2bb0b1730fcdc0cb166cadc0a56 | 3,468 | cpp | C++ | Sourcecode/private/mx/core/YesNoNumber.cpp | Webern/MxOld | 822f5ccc92363ddff118e3aa3a048c63be1e857e | [
"MIT"
] | 45 | 2019-04-16T19:55:08.000Z | 2022-02-14T02:06:32.000Z | Sourcecode/private/mx/core/YesNoNumber.cpp | Webern/MxOld | 822f5ccc92363ddff118e3aa3a048c63be1e857e | [
"MIT"
] | 70 | 2019-04-07T22:45:21.000Z | 2022-03-03T15:35:59.000Z | Sourcecode/private/mx/core/YesNoNumber.cpp | Webern/MxOld | 822f5ccc92363ddff118e3aa3a048c63be1e857e | [
"MIT"
] | 21 | 2019-05-13T13:59:06.000Z | 2022-03-25T02:21:05.000Z | // MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
// self
#include "mx/core/YesNoNumber.h"
// std
#include <sstream>
#include <type_traits>
namespace mx
{
namespace core
{
template<class> inline constexpr bool always_false_v = false;
YesNoNumber::YesNoNumber()
: myValue{ YesNo::yes }
{
}
YesNoNumber::YesNoNumber( YesNo value )
: myValue{ value }
{
}
YesNoNumber::YesNoNumber( Decimal value )
: myValue{ std::move( value ) }
{
}
YesNoNumber::YesNoNumber( const std::string& value )
: YesNoNumber{}
{
parse( value );
}
bool YesNoNumber::getIsYesNo() const
{
return myValue.index() == 0;
}
bool YesNoNumber::getIsDecimal() const
{
return myValue.index() == 1;
}
void YesNoNumber::setYesNo( YesNo value )
{
myValue.emplace<YesNo>( value );
}
void YesNoNumber::setDecimal( Decimal value )
{
myValue.emplace<Decimal>( value );
}
YesNo YesNoNumber::getValueYesNo() const
{
auto result = YesNo::yes;
std::visit([&](auto&& arg)
{
using T = std::decay_t<decltype(arg)>;
if constexpr( std::is_same_v<T, YesNo> )
result = arg;
else if constexpr( std::is_same_v<T, Decimal> )
result = YesNo::yes;
else
static_assert(always_false_v<T>, "non-exhaustive visitor!");
}, myValue);
return result;
}
Decimal YesNoNumber::getValueDecimal() const
{
auto result = Decimal{};
std::visit([&](auto&& arg)
{
using T = std::decay_t<decltype(arg)>;
if constexpr( std::is_same_v<T, YesNo> )
result = Decimal{};
else if constexpr( std::is_same_v<T, Decimal> )
result = arg;
else
static_assert(always_false_v<T>, "non-exhaustive visitor!");
}, myValue);
return result;
}
bool YesNoNumber::parse( const std::string& value )
{
const auto yesNo = tryParseYesNo( value );
if( yesNo )
{
setYesNo( *yesNo );
return true;
}
auto decimal = Decimal{};
if( decimal.parse( value ) )
{
setDecimal( decimal );
return true;
}
return false;
}
std::string toString( const YesNoNumber& value )
{
std::stringstream ss;
toStream( ss, value );
return ss.str();
}
std::ostream& toStream( std::ostream& os, const YesNoNumber& value )
{
if( value.getIsYesNo() )
{
toStream( os, value.getValueYesNo() );
}
if( value.getIsDecimal() )
{
toStream( os, value.getValueDecimal() );
}
return os;
}
std::ostream& operator<<( std::ostream& os, const YesNoNumber& value )
{
return toStream( os, value );
}
}
}
| 25.313869 | 80 | 0.467705 | Webern |
182a280d1798bc89384eb89187c5c31075855e41 | 8,473 | cpp | C++ | src/slib/ui/list_report_view_win32.cpp | emarc99/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 146 | 2017-03-21T07:50:43.000Z | 2022-03-19T03:32:22.000Z | src/slib/ui/list_report_view_win32.cpp | Crasader/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 50 | 2017-03-22T04:08:15.000Z | 2019-10-21T16:55:48.000Z | src/slib/ui/list_report_view_win32.cpp | Crasader/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 55 | 2017-03-21T07:52:58.000Z | 2021-12-27T13:02:08.000Z | /*
* Copyright (c) 2008-2019 SLIBIO <https://github.com/SLIBIO>
*
* 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 "slib/core/definition.h"
#if defined(SLIB_UI_IS_WIN32)
#include "slib/ui/list_report_view.h"
#include "view_win32.h"
#include <commctrl.h>
namespace slib
{
namespace priv
{
namespace list_report_view
{
static int TranslateAlignment(Alignment _align)
{
Alignment align = _align & Alignment::HorizontalMask;
if (align == Alignment::Center) {
return LVCFMT_CENTER;
} else if (align == Alignment::Right) {
return LVCFMT_RIGHT;
}
return LVCFMT_LEFT;
}
class ListReportViewHelper : public ListReportView
{
public:
static sl_uint32 getColumnsCountFromListView(HWND hWnd)
{
HWND hWndHeader = (HWND)(SendMessageW(hWnd, LVM_GETHEADER, 0, 0));
if (hWndHeader) {
return (sl_uint32)(SendMessageW(hWndHeader, HDM_GETITEMCOUNT, 0, 0));
}
return 0;
}
void applyColumnsCount(HWND hWnd)
{
ObjectLocker lock(this);
sl_uint32 nNew = (sl_uint32)(m_columns.getCount());
sl_uint32 nOrig = getColumnsCountFromListView(hWnd);
if (nOrig == nNew) {
return;
}
if (nOrig > nNew) {
for (sl_uint32 i = nOrig; i > nNew; i--) {
SendMessageW(hWnd, LVM_DELETECOLUMN, (WPARAM)(i - 1), 0);
}
} else {
LVCOLUMNW lvc;
Base::zeroMemory(&lvc, sizeof(lvc));
lvc.mask = LVCF_SUBITEM;
for (sl_uint32 i = nOrig; i < nNew; i++) {
lvc.iSubItem = i;
SendMessageW(hWnd, LVM_INSERTCOLUMNW, (WPARAM)i, (LPARAM)&lvc);
}
}
}
void copyColumns(HWND hWnd)
{
applyColumnsCount(hWnd);
LVCOLUMNW lvc;
Base::zeroMemory(&lvc, sizeof(lvc));
lvc.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_FMT;
ListLocker<ListReportViewColumn> columns(m_columns);
for (sl_size i = 0; i < columns.count; i++) {
ListReportViewColumn& column = columns[i];
String16 title = String16::from(column.title);
lvc.pszText = (LPWSTR)(title.getData());
int width = (int)(column.width);
if (width < 0) {
width = 0;
}
lvc.cx = width;
lvc.fmt = TranslateAlignment(column.align);
SendMessageW(hWnd, LVM_SETCOLUMNW, (WPARAM)i, (LPARAM)(&lvc));
}
}
void applyRowsCount(HWND hWnd)
{
sl_uint32 nNew = m_nRows;
SendMessageW(hWnd, LVM_SETITEMCOUNT, (WPARAM)nNew, LVSICF_NOINVALIDATEALL | LVSICF_NOSCROLL);
}
};
class ListReportViewInstance : public Win32_ViewInstance, public IListReportViewInstance
{
SLIB_DECLARE_OBJECT
public:
void refreshColumnsCount(ListReportView* view) override
{
HWND handle = m_handle;
if (handle) {
(static_cast<ListReportViewHelper*>(view))->applyColumnsCount(handle);
}
}
void refreshRowsCount(ListReportView* view) override
{
HWND handle = m_handle;
if (handle) {
(static_cast<ListReportViewHelper*>(view))->applyRowsCount(handle);
InvalidateRect(handle, NULL, TRUE);
}
}
void setHeaderText(ListReportView* view, sl_uint32 iCol, const String& _text) override
{
HWND handle = m_handle;
if (handle) {
LVCOLUMNW lvc;
Base::zeroMemory(&lvc, sizeof(lvc));
lvc.mask = LVCF_TEXT;
String16 text = String16::from(_text);
lvc.pszText = (LPWSTR)(text.getData());
SendMessageW(handle, LVM_SETCOLUMNW, (WPARAM)iCol, (LPARAM)(&lvc));
}
}
void setColumnWidth(ListReportView* view, sl_uint32 iCol, sl_ui_len width) override
{
HWND handle = m_handle;
if (handle) {
if (width < 0) {
width = 0;
}
SendMessageW(handle, LVM_SETCOLUMNWIDTH, (WPARAM)iCol, (LPARAM)(width));
}
}
void setHeaderAlignment(ListReportView* view, sl_uint32 iCol, const Alignment& align) override
{
}
void setColumnAlignment(ListReportView* view, sl_uint32 iCol, const Alignment& align) override
{
HWND handle = m_handle;
if (handle) {
LVCOLUMNW lvc;
Base::zeroMemory(&lvc, sizeof(lvc));
lvc.mask = LVCF_FMT;
lvc.fmt = TranslateAlignment(align);
SendMessageW(handle, LVM_SETCOLUMNW, (WPARAM)iCol, (LPARAM)(&lvc));
}
}
sl_bool getSelectedRow(ListReportView* view, sl_int32& _out) override
{
HWND handle = m_handle;
if (handle) {
_out = (sl_int32)(::SendMessageW(handle, LVM_GETNEXTITEM, (WPARAM)(-1), LVNI_SELECTED));
return sl_true;
}
return sl_false;
}
sl_bool processNotify(NMHDR* nmhdr, LRESULT& result) override
{
Ref<ListReportViewHelper> helper = CastRef<ListReportViewHelper>(getView());
if (helper.isNotNull()) {
NMITEMACTIVATE* nm = (NMITEMACTIVATE*)nmhdr;
UINT code = nmhdr->code;
if (code == LVN_GETDISPINFOW) {
NMLVDISPINFOW* disp = (NMLVDISPINFOW*)nmhdr;
String16 s = String16::from(helper->getItemText(disp->item.iItem, disp->item.iSubItem));
sl_uint32 n = (sl_uint32)(s.getLength());
if (n > 0) {
sl_uint32 m = (sl_uint32)(disp->item.cchTextMax);
if (m > 0) {
if (n >= m) {
n = m - 1;
}
Base::copyMemory(disp->item.pszText, s.getData(), n * 2);
(disp->item.pszText)[n] = 0;
}
}
return sl_true;
} else if (code == LVN_ITEMCHANGED) {
NMLISTVIEW* v = (NMLISTVIEW*)(nm);
if (v->hdr.hwndFrom == getHandle()) {
if (!(v->uOldState & LVIS_SELECTED) && (v->uNewState & LVIS_SELECTED)) {
helper->dispatchSelectRow(v->iItem);
}
}
return sl_true;
} else if (code == NM_CLICK || code == NM_DBLCLK || code == NM_RCLICK) {
LVHITTESTINFO lvhi;
Base::zeroMemory(&lvhi, sizeof(lvhi));
lvhi.pt.x = (LONG)(nm->ptAction.x);
lvhi.pt.y = (LONG)(nm->ptAction.y);
UIPoint pt((sl_ui_pos)(nm->ptAction.x), (sl_ui_pos)(nm->ptAction.y));
sl_int32 n = (sl_int32)(::SendMessageW(getHandle(), LVM_HITTEST, 0, (LPARAM)(&lvhi)));
if (n >= 0) {
if (code == NM_CLICK) {
helper->dispatchClickRow(n, pt);
} else if (code == NM_RCLICK) {
helper->dispatchRightButtonClickRow(n, pt);
} else if (code == NM_DBLCLK) {
helper->dispatchDoubleClickRow(n, pt);
}
}
return sl_true;
}
}
return sl_false;
}
};
SLIB_DEFINE_OBJECT(ListReportViewInstance, Win32_ViewInstance)
}
}
using namespace priv::list_report_view;
Ref<ViewInstance> ListReportView::createNativeWidget(ViewInstance* parent)
{
DWORD style = LVS_REPORT | LVS_SINGLESEL | LVS_OWNERDATA | WS_TABSTOP | WS_BORDER;
Ref<ListReportViewInstance> ret = Win32_ViewInstance::create<ListReportViewInstance>(this, parent, L"SysListView32", sl_null, style, 0);
if (ret.isNotNull()) {
HWND handle = ret->getHandle();
ListReportViewHelper* helper = static_cast<ListReportViewHelper*>(this);
UINT exStyle = LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_ONECLICKACTIVATE | LVS_EX_DOUBLEBUFFER;
::SendMessageW(handle, LVM_SETEXTENDEDLISTVIEWSTYLE, exStyle, exStyle);
helper->copyColumns(handle);
helper->applyRowsCount(handle);
return ret;
}
return sl_null;
}
Ptr<IListReportViewInstance> ListReportView::getListReportViewInstance()
{
return CastRef<ListReportViewInstance>(getViewInstance());
}
}
#endif
| 31.265683 | 138 | 0.646406 | emarc99 |
182b750d61a9fbf8a654b567071e8ad243a5df41 | 9,357 | cpp | C++ | modules/mojo/input/native/keyinfo.cpp | D-a-n-i-l-o/wonkey | 6c9129a12fb622b971468ee5cc7adbedadd372ff | [
"Zlib"
] | 109 | 2021-01-06T20:27:33.000Z | 2022-03-07T19:28:50.000Z | modules/mojo/input/native/keyinfo.cpp | D-a-n-i-l-o/wonkey | 6c9129a12fb622b971468ee5cc7adbedadd372ff | [
"Zlib"
] | 4 | 2021-01-08T20:25:05.000Z | 2021-06-08T05:36:48.000Z | modules/mojo/input/native/keyinfo.cpp | D-a-n-i-l-o/wonkey | 6c9129a12fb622b971468ee5cc7adbedadd372ff | [
"Zlib"
] | 11 | 2021-01-14T17:20:42.000Z | 2021-08-08T18:46:42.000Z |
#include "keyinfo.h"
#include <SDL.h>
wxKeyInfo wxKeyInfos[]={
"0",SDL_SCANCODE_0,SDLK_0,
"1",SDL_SCANCODE_1,SDLK_1,
"2",SDL_SCANCODE_2,SDLK_2,
"3",SDL_SCANCODE_3,SDLK_3,
"4",SDL_SCANCODE_4,SDLK_4,
"5",SDL_SCANCODE_5,SDLK_5,
"6",SDL_SCANCODE_6,SDLK_6,
"7",SDL_SCANCODE_7,SDLK_7,
"8",SDL_SCANCODE_8,SDLK_8,
"9",SDL_SCANCODE_9,SDLK_9,
"A",SDL_SCANCODE_A,SDLK_a,
"AC Back",SDL_SCANCODE_AC_BACK,SDLK_AC_BACK,
"AC Bookmarks",SDL_SCANCODE_AC_BOOKMARKS,SDLK_AC_BOOKMARKS,
"AC Forward",SDL_SCANCODE_AC_FORWARD,SDLK_AC_FORWARD,
"AC Home",SDL_SCANCODE_AC_HOME,SDLK_AC_HOME,
"AC Refresh",SDL_SCANCODE_AC_REFRESH,SDLK_AC_REFRESH,
"AC Search",SDL_SCANCODE_AC_SEARCH,SDLK_AC_SEARCH,
"AC Stop",SDL_SCANCODE_AC_STOP,SDLK_AC_STOP,
"Again",SDL_SCANCODE_AGAIN,SDLK_AGAIN,
"AltErase",SDL_SCANCODE_ALTERASE,SDLK_ALTERASE,
"'",SDL_SCANCODE_APOSTROPHE,SDLK_QUOTE,
"Application",SDL_SCANCODE_APPLICATION,SDLK_APPLICATION,
"AudioMute",SDL_SCANCODE_AUDIOMUTE,SDLK_AUDIOMUTE,
"AudioNext",SDL_SCANCODE_AUDIONEXT,SDLK_AUDIONEXT,
"AudioPlay",SDL_SCANCODE_AUDIOPLAY,SDLK_AUDIOPLAY,
"AudioPrev",SDL_SCANCODE_AUDIOPREV,SDLK_AUDIOPREV,
"AudioStop",SDL_SCANCODE_AUDIOSTOP,SDLK_AUDIOSTOP,
"B",SDL_SCANCODE_B,SDLK_b,
"\\",SDL_SCANCODE_BACKSLASH,SDLK_BACKSLASH,
"Backspace",SDL_SCANCODE_BACKSPACE,SDLK_BACKSPACE,
"BrightnessDown",SDL_SCANCODE_BRIGHTNESSDOWN,SDLK_BRIGHTNESSDOWN,
"BrightnessUp",SDL_SCANCODE_BRIGHTNESSUP,SDLK_BRIGHTNESSUP,
"C",SDL_SCANCODE_C,SDLK_c,
"Calculator",SDL_SCANCODE_CALCULATOR,SDLK_CALCULATOR,
"Cancel",SDL_SCANCODE_CANCEL,SDLK_CANCEL,
"CapsLock",SDL_SCANCODE_CAPSLOCK,SDLK_CAPSLOCK,
"Clear",SDL_SCANCODE_CLEAR,SDLK_CLEAR,
"Clear / Again",SDL_SCANCODE_CLEARAGAIN,SDLK_CLEARAGAIN,
",",SDL_SCANCODE_COMMA,SDLK_COMMA,
"Computer",SDL_SCANCODE_COMPUTER,SDLK_COMPUTER,
"Copy",SDL_SCANCODE_COPY,SDLK_COPY,
"CrSel",SDL_SCANCODE_CRSEL,SDLK_CRSEL,
"CurrencySubUnit",SDL_SCANCODE_CURRENCYSUBUNIT,SDLK_CURRENCYSUBUNIT,
"CurrencyUnit",SDL_SCANCODE_CURRENCYUNIT,SDLK_CURRENCYUNIT,
"Cut",SDL_SCANCODE_CUT,SDLK_CUT,
"D",SDL_SCANCODE_D,SDLK_d,
"DecimalSeparator",SDL_SCANCODE_DECIMALSEPARATOR,SDLK_DECIMALSEPARATOR,
"Delete",SDL_SCANCODE_DELETE,SDLK_DELETE,
"DisplaySwitch",SDL_SCANCODE_DISPLAYSWITCH,SDLK_DISPLAYSWITCH,
"Down",SDL_SCANCODE_DOWN,SDLK_DOWN,
"E",SDL_SCANCODE_E,SDLK_e,
"Eject",SDL_SCANCODE_EJECT,SDLK_EJECT,
"End",SDL_SCANCODE_END,SDLK_END,
"=",SDL_SCANCODE_EQUALS,SDLK_EQUALS,
"Escape",SDL_SCANCODE_ESCAPE,SDLK_ESCAPE,
"Execute",SDL_SCANCODE_EXECUTE,SDLK_EXECUTE,
"ExSel",SDL_SCANCODE_EXSEL,SDLK_EXSEL,
"F",SDL_SCANCODE_F,SDLK_f,
"F1",SDL_SCANCODE_F1,SDLK_F1,
"F10",SDL_SCANCODE_F10,SDLK_F10,
"F11",SDL_SCANCODE_F11,SDLK_F11,
"F12",SDL_SCANCODE_F12,SDLK_F12,
"F13",SDL_SCANCODE_F13,SDLK_F13,
"F14",SDL_SCANCODE_F14,SDLK_F14,
"F15",SDL_SCANCODE_F15,SDLK_F15,
"F16",SDL_SCANCODE_F16,SDLK_F16,
"F17",SDL_SCANCODE_F17,SDLK_F17,
"F18",SDL_SCANCODE_F18,SDLK_F18,
"F19",SDL_SCANCODE_F19,SDLK_F19,
"F2",SDL_SCANCODE_F2,SDLK_F2,
"F20",SDL_SCANCODE_F20,SDLK_F20,
"F21",SDL_SCANCODE_F21,SDLK_F21,
"F22",SDL_SCANCODE_F22,SDLK_F22,
"F23",SDL_SCANCODE_F23,SDLK_F23,
"F24",SDL_SCANCODE_F24,SDLK_F24,
"F3",SDL_SCANCODE_F3,SDLK_F3,
"F4",SDL_SCANCODE_F4,SDLK_F4,
"F5",SDL_SCANCODE_F5,SDLK_F5,
"F6",SDL_SCANCODE_F6,SDLK_F6,
"F7",SDL_SCANCODE_F7,SDLK_F7,
"F8",SDL_SCANCODE_F8,SDLK_F8,
"F9",SDL_SCANCODE_F9,SDLK_F9,
"Find",SDL_SCANCODE_FIND,SDLK_FIND,
"G",SDL_SCANCODE_G,SDLK_g,
"`",SDL_SCANCODE_GRAVE,SDLK_BACKQUOTE,
"H",SDL_SCANCODE_H,SDLK_h,
"Help",SDL_SCANCODE_HELP,SDLK_HELP,
"Home",SDL_SCANCODE_HOME,SDLK_HOME,
"I",SDL_SCANCODE_I,SDLK_i,
"Insert",SDL_SCANCODE_INSERT,SDLK_INSERT,
"J",SDL_SCANCODE_J,SDLK_j,
"K",SDL_SCANCODE_K,SDLK_k,
"KBDIllumDown",SDL_SCANCODE_KBDILLUMDOWN,SDLK_KBDILLUMDOWN,
"KBDIllumToggle",SDL_SCANCODE_KBDILLUMTOGGLE,SDLK_KBDILLUMTOGGLE,
"KBDIllumUp",SDL_SCANCODE_KBDILLUMUP,SDLK_KBDILLUMUP,
"Keypad 0",SDL_SCANCODE_KP_0,SDLK_KP_0,
"Keypad 00",SDL_SCANCODE_KP_00,SDLK_KP_00,
"Keypad 000",SDL_SCANCODE_KP_000,SDLK_KP_000,
"Keypad 1",SDL_SCANCODE_KP_1,SDLK_KP_1,
"Keypad 2",SDL_SCANCODE_KP_2,SDLK_KP_2,
"Keypad 3",SDL_SCANCODE_KP_3,SDLK_KP_3,
"Keypad 4",SDL_SCANCODE_KP_4,SDLK_KP_4,
"Keypad 5",SDL_SCANCODE_KP_5,SDLK_KP_5,
"Keypad 6",SDL_SCANCODE_KP_6,SDLK_KP_6,
"Keypad 7",SDL_SCANCODE_KP_7,SDLK_KP_7,
"Keypad 8",SDL_SCANCODE_KP_8,SDLK_KP_8,
"Keypad 9",SDL_SCANCODE_KP_9,SDLK_KP_9,
"Keypad A",SDL_SCANCODE_KP_A,SDLK_KP_A,
"Keypad &",SDL_SCANCODE_KP_AMPERSAND,SDLK_KP_AMPERSAND,
"Keypad @",SDL_SCANCODE_KP_AT,SDLK_KP_AT,
"Keypad B",SDL_SCANCODE_KP_B,SDLK_KP_B,
"Keypad Backspace",SDL_SCANCODE_KP_BACKSPACE,SDLK_KP_BACKSPACE,
"Keypad Binary",SDL_SCANCODE_KP_BINARY,SDLK_KP_BINARY,
"Keypad C",SDL_SCANCODE_KP_C,SDLK_KP_C,
"Keypad Clear",SDL_SCANCODE_KP_CLEAR,SDLK_KP_CLEAR,
"Keypad ClearEntry",SDL_SCANCODE_KP_CLEARENTRY,SDLK_KP_CLEARENTRY,
"Keypad :",SDL_SCANCODE_KP_COLON,SDLK_KP_COLON,
"Keypad ,",SDL_SCANCODE_KP_COMMA,SDLK_KP_COMMA,
"Keypad D",SDL_SCANCODE_KP_D,SDLK_KP_D,
"Keypad &&",SDL_SCANCODE_KP_DBLAMPERSAND,SDLK_KP_DBLAMPERSAND,
"Keypad ||",SDL_SCANCODE_KP_DBLVERTICALBAR,SDLK_KP_DBLVERTICALBAR,
"Keypad Decimal",SDL_SCANCODE_KP_DECIMAL,SDLK_KP_DECIMAL,
"Keypad /",SDL_SCANCODE_KP_DIVIDE,SDLK_KP_DIVIDE,
"Keypad E",SDL_SCANCODE_KP_E,SDLK_KP_E,
"Keypad Enter",SDL_SCANCODE_KP_ENTER,SDLK_KP_ENTER,
"Keypad =",SDL_SCANCODE_KP_EQUALS,SDLK_KP_EQUALS,
"Keypad = (AS400)",SDL_SCANCODE_KP_EQUALSAS400,SDLK_KP_EQUALSAS400,
"Keypad !",SDL_SCANCODE_KP_EXCLAM,SDLK_KP_EXCLAM,
"Keypad F",SDL_SCANCODE_KP_F,SDLK_KP_F,
"Keypad >",SDL_SCANCODE_KP_GREATER,SDLK_KP_GREATER,
"Keypad #",SDL_SCANCODE_KP_HASH,SDLK_KP_HASH,
"Keypad Hexadecimal",SDL_SCANCODE_KP_HEXADECIMAL,SDLK_KP_HEXADECIMAL,
"Keypad {",SDL_SCANCODE_KP_LEFTBRACE,SDLK_KP_LEFTBRACE,
"Keypad (",SDL_SCANCODE_KP_LEFTPAREN,SDLK_KP_LEFTPAREN,
"Keypad <",SDL_SCANCODE_KP_LESS,SDLK_KP_LESS,
"Keypad MemAdd",SDL_SCANCODE_KP_MEMADD,SDLK_KP_MEMADD,
"Keypad MemClear",SDL_SCANCODE_KP_MEMCLEAR,SDLK_KP_MEMCLEAR,
"Keypad MemDivide",SDL_SCANCODE_KP_MEMDIVIDE,SDLK_KP_MEMDIVIDE,
"Keypad MemMultiply",SDL_SCANCODE_KP_MEMMULTIPLY,SDLK_KP_MEMMULTIPLY,
"Keypad MemRecall",SDL_SCANCODE_KP_MEMRECALL,SDLK_KP_MEMRECALL,
"Keypad MemStore",SDL_SCANCODE_KP_MEMSTORE,SDLK_KP_MEMSTORE,
"Keypad MemSubtract",SDL_SCANCODE_KP_MEMSUBTRACT,SDLK_KP_MEMSUBTRACT,
"Keypad -",SDL_SCANCODE_KP_MINUS,SDLK_KP_MINUS,
"Keypad *",SDL_SCANCODE_KP_MULTIPLY,SDLK_KP_MULTIPLY,
"Keypad Octal",SDL_SCANCODE_KP_OCTAL,SDLK_KP_OCTAL,
"Keypad %",SDL_SCANCODE_KP_PERCENT,SDLK_KP_PERCENT,
"Keypad .",SDL_SCANCODE_KP_PERIOD,SDLK_KP_PERIOD,
"Keypad +",SDL_SCANCODE_KP_PLUS,SDLK_KP_PLUS,
"Keypad +/-",SDL_SCANCODE_KP_PLUSMINUS,SDLK_KP_PLUSMINUS,
"Keypad ^",SDL_SCANCODE_KP_POWER,SDLK_KP_POWER,
"Keypad }",SDL_SCANCODE_KP_RIGHTBRACE,SDLK_KP_RIGHTBRACE,
"Keypad )",SDL_SCANCODE_KP_RIGHTPAREN,SDLK_KP_RIGHTPAREN,
"Keypad Space",SDL_SCANCODE_KP_SPACE,SDLK_KP_SPACE,
"Keypad Tab",SDL_SCANCODE_KP_TAB,SDLK_KP_TAB,
"Keypad |",SDL_SCANCODE_KP_VERTICALBAR,SDLK_KP_VERTICALBAR,
"Keypad XOR",SDL_SCANCODE_KP_XOR,SDLK_KP_XOR,
"L",SDL_SCANCODE_L,SDLK_l,
"Left Alt",SDL_SCANCODE_LALT,SDLK_LALT,
"Left Ctrl",SDL_SCANCODE_LCTRL,SDLK_LCTRL,
"Left",SDL_SCANCODE_LEFT,SDLK_LEFT,
"[",SDL_SCANCODE_LEFTBRACKET,SDLK_LEFTBRACKET,
"Left GUI",SDL_SCANCODE_LGUI,SDLK_LGUI,
"Left Shift",SDL_SCANCODE_LSHIFT,SDLK_LSHIFT,
"M",SDL_SCANCODE_M,SDLK_m,
"Mail",SDL_SCANCODE_MAIL,SDLK_MAIL,
"MediaSelect",SDL_SCANCODE_MEDIASELECT,SDLK_MEDIASELECT,
"Menu",SDL_SCANCODE_MENU,SDLK_MENU,
"-",SDL_SCANCODE_MINUS,SDLK_MINUS,
"ModeSwitch",SDL_SCANCODE_MODE,SDLK_MODE,
"Mute",SDL_SCANCODE_MUTE,SDLK_MUTE,
"N",SDL_SCANCODE_N,SDLK_n,
"Numlock",SDL_SCANCODE_NUMLOCKCLEAR,SDLK_NUMLOCKCLEAR,
"O",SDL_SCANCODE_O,SDLK_o,
"Oper",SDL_SCANCODE_OPER,SDLK_OPER,
"Out",SDL_SCANCODE_OUT,SDLK_OUT,
"P",SDL_SCANCODE_P,SDLK_p,
"PageDown",SDL_SCANCODE_PAGEDOWN,SDLK_PAGEDOWN,
"PageUp",SDL_SCANCODE_PAGEUP,SDLK_PAGEUP,
"Paste",SDL_SCANCODE_PASTE,SDLK_PASTE,
"Pause",SDL_SCANCODE_PAUSE,SDLK_PAUSE,
".",SDL_SCANCODE_PERIOD,SDLK_PERIOD,
"Power",SDL_SCANCODE_POWER,SDLK_POWER,
"PrintScreen",SDL_SCANCODE_PRINTSCREEN,SDLK_PRINTSCREEN,
"Prior",SDL_SCANCODE_PRIOR,SDLK_PRIOR,
"Q",SDL_SCANCODE_Q,SDLK_q,
"R",SDL_SCANCODE_R,SDLK_r,
"Right Alt",SDL_SCANCODE_RALT,SDLK_RALT,
"Right Ctrl",SDL_SCANCODE_RCTRL,SDLK_RCTRL,
"Return",SDL_SCANCODE_RETURN,SDLK_RETURN,
"Return",SDL_SCANCODE_RETURN2,SDLK_RETURN2,
"Right GUI",SDL_SCANCODE_RGUI,SDLK_RGUI,
"Right",SDL_SCANCODE_RIGHT,SDLK_RIGHT,
"]",SDL_SCANCODE_RIGHTBRACKET,SDLK_RIGHTBRACKET,
"Right Shift",SDL_SCANCODE_RSHIFT,SDLK_RSHIFT,
"S",SDL_SCANCODE_S,SDLK_s,
"ScrollLock",SDL_SCANCODE_SCROLLLOCK,SDLK_SCROLLLOCK,
"Select",SDL_SCANCODE_SELECT,SDLK_SELECT,
";",SDL_SCANCODE_SEMICOLON,SDLK_SEMICOLON,
"Separator",SDL_SCANCODE_SEPARATOR,SDLK_SEPARATOR,
"/",SDL_SCANCODE_SLASH,SDLK_SLASH,
"Sleep",SDL_SCANCODE_SLEEP,SDLK_SLEEP,
"Space",SDL_SCANCODE_SPACE,SDLK_SPACE,
"Stop",SDL_SCANCODE_STOP,SDLK_STOP,
"SysReq",SDL_SCANCODE_SYSREQ,SDLK_SYSREQ,
"T",SDL_SCANCODE_T,SDLK_t,
"Tab",SDL_SCANCODE_TAB,SDLK_TAB,
"ThousandsSeparator",SDL_SCANCODE_THOUSANDSSEPARATOR,SDLK_THOUSANDSSEPARATOR,
"U",SDL_SCANCODE_U,SDLK_u,
"Undo",SDL_SCANCODE_UNDO,SDLK_UNDO,
"",SDL_SCANCODE_UNKNOWN,SDLK_UNKNOWN,
"Up",SDL_SCANCODE_UP,SDLK_UP,
"V",SDL_SCANCODE_V,SDLK_v,
"VolumeDown",SDL_SCANCODE_VOLUMEDOWN,SDLK_VOLUMEDOWN,
"VolumeUp",SDL_SCANCODE_VOLUMEUP,SDLK_VOLUMEUP,
"W",SDL_SCANCODE_W,SDLK_w,
"WWW",SDL_SCANCODE_WWW,SDLK_WWW,
"X",SDL_SCANCODE_X,SDLK_x,
"Y",SDL_SCANCODE_Y,SDLK_y,
"Z",SDL_SCANCODE_Z,SDLK_z,
0,0,0
};
| 41.039474 | 77 | 0.84354 | D-a-n-i-l-o |
182baeda498d90c07dd31f944315c68ea155bf34 | 7,217 | cpp | C++ | Src/Reader.cpp | craflin/md2tex | ee813151f5427cea61fa3ea045cea13f594cb58f | [
"Apache-2.0"
] | null | null | null | Src/Reader.cpp | craflin/md2tex | ee813151f5427cea61fa3ea045cea13f594cb58f | [
"Apache-2.0"
] | null | null | null | Src/Reader.cpp | craflin/md2tex | ee813151f5427cea61fa3ea045cea13f594cb58f | [
"Apache-2.0"
] | null | null | null |
#include "Reader.hpp"
#include <nstd/File.hpp>
#include <nstd/Error.hpp>
#include <nstd/Document/Xml.hpp>
#include "InputData.hpp"
bool Reader::read(const String& inputFile, InputData& inputData)
{
inputData.inputFile = inputFile;
if(File::extension(inputFile).compareIgnoreCase("md") == 0)
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = InputData::Component::mdType;
component.filePath = inputFile;
File file;
if(!file.open(component.filePath))
return _errorString = String::fromPrintf("Could not open file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false;
if(!file.readAll(component.value))
return _errorString = String::fromPrintf("Could not read file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false;
return true;
}
Xml::Parser xmlParser;
Xml::Element xmlFile;
if(!xmlParser.load(inputFile, xmlFile))
return _errorLine = xmlParser.getErrorLine(), _errorColumn = xmlParser.getErrorColumn(), _errorString = xmlParser.getErrorString(), false;
if(xmlFile.type != "umdoc")
return _errorLine = xmlParser.getErrorLine(), _errorColumn = xmlParser.getErrorColumn(), _errorString = "Expected element 'umdoc'", false;
inputData.className = *xmlFile.attributes.find("class");
bool documentRead = false;
for(List<Xml::Variant>::Iterator i = xmlFile.content.begin(), end = xmlFile.content.end(); i != end; ++i)
{
const Xml::Variant& variant = *i;
if(!variant.isElement())
continue;
const Xml::Element& element = variant.toElement();
if(documentRead)
return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Unexpected element '%s'", (const char*)element.type), false;
if(element.type == "tex")
{
String filePath = *element.attributes.find("file");
File file;
if(!filePath.isEmpty())
{
String data;
if(!file.open(filePath))
return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not open file '%s': %s", (const char*)filePath, (const char*)Error::getErrorString()), false;
if(!file.readAll(data))
return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not read file '%s': %s", (const char*)filePath, (const char*)Error::getErrorString()), false;
inputData.headerTexFiles.append(data);
}
for(List<Xml::Variant>::Iterator i = element.content.begin(), end = element.content.end(); i != end; ++i)
inputData.headerTexFiles.append(i->toString());
}
else if(element.type == "set")
inputData.variables.append(*element.attributes.find("name"), *element.attributes.find("value"));
else if(element.type == "environment")
{
InputData::Environment& environment = inputData.environments.append(*element.attributes.find("name"), InputData::Environment());
environment.verbatim = element.attributes.find("verbatim")->toBool();
environment.command = *element.attributes.find("command");
}
else if(element.type == "document")
{
for(List<Xml::Variant>::Iterator i = element.content.begin(), end = element.content.end(); i != end; ++i)
{
const Xml::Variant& variant = *i;
if(!variant.isElement())
continue;
const Xml::Element& element = variant.toElement();
if(element.type == "tex" || element.type == "md")
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = element.type == "md" ? InputData::Component::mdType : InputData::Component::texType;
component.filePath = *element.attributes.find("file");
if(!component.filePath.isEmpty())
{
File file;
if(!file.open(component.filePath))
return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not open file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false;
if(!file.readAll(component.value))
return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not read file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false;
}
for(List<Xml::Variant>::Iterator i = element.content.begin(), end = element.content.end(); i != end; ++i)
component.value.append(i->toString());
}
else if(element.type == "toc" || element.type == "tableOfContents")
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = InputData::Component::texTableOfContentsType;
}
else if(element.type == "lof" || element.type == "listOfFigures")
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = InputData::Component::texListOfFiguresType;
}
else if(element.type == "lot" || element.type == "listOfTables")
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = InputData::Component::texListOfTablesType;
}
else if(element.type == "break" || element.type == "newPage" || element.type == "pageBreak")
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = InputData::Component::texNewPageType;
}
else if(element.type == "pdf")
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = InputData::Component::pdfType;
component.filePath = *element.attributes.find("file");
}
else if(element.type == "part")
{
InputData::Component& component = inputData.document.append(InputData::Component());
component.type = InputData::Component::texPartType;
component.value = *element.attributes.find("title");
}
else if(element.type == "environment")
{
InputData::Environment& environment = inputData.environments.append(*element.attributes.find("name"), InputData::Environment());
environment.verbatim = element.attributes.find("verbatim")->toBool();
environment.command = *element.attributes.find("command");
}
else if(element.type == "set")
inputData.variables.append(*element.attributes.find("name"), *element.attributes.find("value"));
else
return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Unexpected element '%s'", (const char*)element.type), false;
}
documentRead = true;
}
else
return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Unexpected element '%s'", (const char*)element.type), false;
}
return true;
}
| 49.431507 | 223 | 0.651656 | craflin |
182c9b2ab3bc7625270be9f9f6686c5b92a9c634 | 984 | cc | C++ | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/nnvm/src/top/vision/yolo/region.cc | mengkai94/training_results_v0.6 | 43dc3e250f8da47b5f8833197d74cb8cf1004fc9 | [
"Apache-2.0"
] | 64 | 2021-05-02T14:42:34.000Z | 2021-05-06T01:35:03.000Z | nnvm/src/top/vision/yolo/region.cc | clhne/tvm | d59320c764bd09474775e1b292f3c05c27743d24 | [
"Apache-2.0"
] | 23 | 2019-07-29T05:21:52.000Z | 2020-08-31T18:51:42.000Z | nnvm/src/top/vision/yolo/region.cc | clhne/tvm | d59320c764bd09474775e1b292f3c05c27743d24 | [
"Apache-2.0"
] | 51 | 2019-07-12T05:10:25.000Z | 2021-07-28T16:19:06.000Z | /*!
* Copyright (c) 2018 by Contributors
* \file region.cc
* \brief Property def of pooling operators.
*/
#include <nnvm/op.h>
#include <nnvm/node.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/top/nn.h>
#include "../../op_common.h"
#include "region.h"
namespace nnvm {
namespace top {
NNVM_REGISTER_OP(yolo_region)
.describe(R"code(Region layer
)code" NNVM_ADD_FILELINE)
.set_num_inputs(1)
.set_num_outputs(1)
.set_support_level(5)
.add_argument("data", "Tensor", "Input data")
.set_attr<FInferType>("FInferType", RegionType<1, 1>)
.set_attr<FInferShape>("FInferShape", RegionShape<1, 1>)
.set_attr<FInplaceOption>(
"FInplaceOption",
[](const NodeAttrs &attrs) {
return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}};
})
.set_attr<FGradient>("FGradient", [](const NodePtr &n,
const std::vector<NodeEntry> &ograds) {
return std::vector<NodeEntry>{ograds[0], ograds[0]};
});
} // namespace top
} // namespace nnvm
| 27.333333 | 76 | 0.66565 | mengkai94 |
183005e1ac1b6fe93255b485f6550f4df62974c4 | 940 | ipp | C++ | freeflow/sdn/request.ipp | flowgrammable/freeflow-legacy | c5cd77495d44fe3a9e48a2e06fbb44f7418d388e | [
"Apache-2.0"
] | 1 | 2017-07-30T04:18:29.000Z | 2017-07-30T04:18:29.000Z | freeflow/sdn/request.ipp | flowgrammable/freeflow-legacy | c5cd77495d44fe3a9e48a2e06fbb44f7418d388e | [
"Apache-2.0"
] | null | null | null | freeflow/sdn/request.ipp | flowgrammable/freeflow-legacy | c5cd77495d44fe3a9e48a2e06fbb44f7418d388e | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2013-2014 Flowgrammable, LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
namespace freeflow {
inline
Request_data::Request_data(const Disconnect_request& x)
: disconnect(x) { }
inline
Request_data::Request_data(const Terminate_request& x)
: terminate(x) { }
template<typename T>
inline
Request::Request(Application* a, const T& x)
: app(a), type(x.Kind), data(x) { }
} // namespace freeflow
| 30.322581 | 70 | 0.729787 | flowgrammable |
183197b782f702659fe52b087e8ba4d16e27559e | 2,484 | cc | C++ | zircon/system/ulib/async/test/irq_tests.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | zircon/system/ulib/async/test/irq_tests.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | zircon/system/ulib/async/test/irq_tests.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2019 The Fuchsia 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 <lib/async-testing/dispatcher_stub.h>
#include <lib/async/cpp/irq.h>
#include <lib/zx/interrupt.h>
#include <unittest/unittest.h>
namespace {
class MockDispatcher : public async::DispatcherStub {
public:
zx_status_t BindIrq(async_irq_t* irq) override {
last_bound_irq = irq;
return ZX_OK;
}
zx_status_t UnbindIrq(async_irq_t* irq) override {
last_unbound_irq = irq;
return ZX_OK;
}
async_irq_t* last_bound_irq = nullptr;
async_irq_t* last_unbound_irq = nullptr;
};
bool bind_irq_test() {
BEGIN_TEST;
MockDispatcher dispatcher;
zx::interrupt irq_object;
ASSERT_EQ(ZX_OK, zx::interrupt::create(zx::resource(0), 0, ZX_INTERRUPT_VIRTUAL, &irq_object));
async::Irq irq;
irq.set_object(irq_object.get());
bool triggered = false;
zx_packet_interrupt_t packet;
irq.set_handler([&](async_dispatcher_t* dispatcher_arg, async::Irq* irq_arg, zx_status_t status,
const zx_packet_interrupt_t* interrupt) {
triggered = true;
EXPECT_EQ(&dispatcher, dispatcher_arg);
EXPECT_EQ(irq_arg, &irq);
EXPECT_EQ(ZX_OK, status);
EXPECT_EQ(&packet, interrupt);
});
EXPECT_EQ(ZX_OK, irq.Begin(&dispatcher));
EXPECT_EQ(ZX_ERR_ALREADY_EXISTS, irq.Begin(&dispatcher));
EXPECT_EQ(irq_object.get(), dispatcher.last_bound_irq->object);
dispatcher.last_bound_irq->handler(&dispatcher, dispatcher.last_bound_irq, ZX_OK, &packet);
EXPECT_TRUE(triggered);
triggered = false;
EXPECT_EQ(ZX_OK, irq.Cancel());
EXPECT_EQ(ZX_ERR_NOT_FOUND, irq.Cancel());
EXPECT_EQ(irq_object.get(), dispatcher.last_unbound_irq->object);
dispatcher.last_unbound_irq->handler(&dispatcher, dispatcher.last_unbound_irq, ZX_OK, &packet);
EXPECT_TRUE(triggered);
END_TEST;
}
bool unsupported_bind_irq_test() {
BEGIN_TEST;
async::DispatcherStub dispatcher;
async_irq_t irq{};
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, async_bind_irq(&dispatcher, &irq), "valid args");
END_TEST;
}
bool unsupported_unbind_irq_test() {
BEGIN_TEST;
async::DispatcherStub dispatcher;
async_irq_t irq{};
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, async_unbind_irq(&dispatcher, &irq), "valid args");
END_TEST;
}
} // namespace
BEGIN_TEST_CASE(irq_tests)
RUN_TEST(unsupported_bind_irq_test)
RUN_TEST(unsupported_unbind_irq_test)
RUN_TEST(bind_irq_test)
END_TEST_CASE(irq_tests)
| 30.666667 | 98 | 0.75 | opensource-assist |
1835de201ce5637e1a52e6fba2c78b2ed804ffc6 | 1,732 | hpp | C++ | src/ivorium_graphics/Animation/Connectors/Cooldown_Connector.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | 3 | 2021-02-26T02:59:09.000Z | 2022-02-08T16:44:21.000Z | src/ivorium_graphics/Animation/Connectors/Cooldown_Connector.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | src/ivorium_graphics/Animation/Connectors/Cooldown_Connector.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Transform_ConnectorI.hpp"
#include "../Animation/AnimNode.hpp"
#include "../../Defs.hpp"
#include <ivorium_core/ivorium_core.hpp>
#include <cmath>
namespace iv
{
/**
This connector changes value of child node at most at given rate.
Slows down changes of target - change will not be applied before specified time passes after previous change.
This consumes changes that are overriden by a following change before the cooldown times out.
This has two cooldowns - which one is selected depends on if the next value his greater or lesser than the current value.
*/
template< class T >
class Cooldown_Connector : public Transform_ConnectorI< T, T >
{
public:
using Transform_ConnectorI< T, T >::instance;
ClientMarker cm;
//----------------------------- Cooldown_Connector -------------------------------------------------------------------
Cooldown_Connector( Instance * inst );
//-------------------------- configuration -----------------------------------------------------
Cooldown_Connector< T > * cooldown_increasing( Anim_float );
Anim_float cooldown_increasing();
Cooldown_Connector< T > * cooldown_decreasing( Anim_float );
Anim_float cooldown_decreasing();
//----------------------------- AnimConnector ------------------------------------------------------
virtual void UpdatePass_Down() override;
virtual void UpdatePass_Up() override;
private:
Anim_float _cooldown_increasing;
Anim_float _cooldown_decreasing;
Anim_float _time;
};
}
#include "Cooldown_Connector.inl"
| 35.346939 | 125 | 0.56582 | ivorne |
183a11e9f6e0c5fd5a67ff0be320e96838534ac3 | 20,992 | cpp | C++ | libakumuli/page.cpp | vladon/Akumuli | c45672a23b929ccb3a5743cc5e9aae980c160eb0 | [
"Apache-2.0"
] | null | null | null | libakumuli/page.cpp | vladon/Akumuli | c45672a23b929ccb3a5743cc5e9aae980c160eb0 | [
"Apache-2.0"
] | null | null | null | libakumuli/page.cpp | vladon/Akumuli | c45672a23b929ccb3a5743cc5e9aae980c160eb0 | [
"Apache-2.0"
] | 1 | 2021-09-22T07:11:13.000Z | 2021-09-22T07:11:13.000Z | /**
* Copyright (c) 2013 Eugene Lazin <4lazin@gmail.com>
*
* 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 <cstring>
#include <cassert>
#include <algorithm>
#include <mutex>
#include <apr_time.h>
#include "timsort.hpp"
#include "page.h"
#include "compression.h"
#include "akumuli_def.h"
#include "search.h"
#include "buffer_cache.h"
#include <random>
#include <iostream>
#include <boost/crc.hpp>
namespace Akumuli {
// Page
// ----
PageHeader::PageHeader(uint32_t count, uint64_t length, uint32_t page_id, uint32_t numpages)
: version(0)
, count(0)
, next_offset(0)
, open_count(0)
, close_count(0)
, page_id(page_id)
, numpages(numpages)
, length(length - sizeof(PageHeader))
{
}
uint32_t PageHeader::get_page_id() const {
return page_id;
}
uint32_t PageHeader::get_numpages() const {
return numpages;
}
uint32_t PageHeader::get_open_count() const {
return open_count;
}
uint32_t PageHeader::get_close_count() const {
return close_count;
}
void PageHeader::set_open_count(uint32_t cnt) {
open_count = cnt;
}
void PageHeader::set_close_count(uint32_t cnt) {
close_count = cnt;
}
void PageHeader::create_checkpoint() {
checkpoint = count;
}
bool PageHeader::restore() {
if (count != checkpoint) {
count = checkpoint;
return true;
}
return false;
}
aku_EntryIndexRecord* PageHeader::page_index(int index) {
char* ptr = payload + length - sizeof(aku_EntryIndexRecord);
aku_EntryIndexRecord* entry = reinterpret_cast<aku_EntryIndexRecord*>(ptr);
entry -= index;
return entry;
}
const aku_EntryIndexRecord* PageHeader::page_index(int index) const {
const char* ptr = payload + length - sizeof(aku_EntryIndexRecord);
const aku_EntryIndexRecord* entry = reinterpret_cast<const aku_EntryIndexRecord*>(ptr);
entry -= index;
return entry;
}
std::pair<aku_EntryIndexRecord, int> PageHeader::index_to_offset(uint32_t index) const {
if (index > count) {
return std::make_pair(aku_EntryIndexRecord(), AKU_EBAD_ARG);
}
return std::make_pair(*page_index(index), AKU_SUCCESS);
}
uint32_t PageHeader::get_entries_count() const {
return count;
}
size_t PageHeader::get_free_space() const {
auto begin = payload + next_offset;
auto end = (payload + length) - count*sizeof(aku_EntryIndexRecord);
assert(end >= payload);
return end - begin;
}
void PageHeader::reuse() {
count = 0;
checkpoint = 0;
count = 0;
open_count++;
next_offset = 0;
}
void PageHeader::close() {
close_count++;
}
aku_Status PageHeader::add_entry( const aku_ParamId param
, const aku_Timestamp timestamp
, const aku_MemRange &range )
{
if (count != 0) {
// Require >= timestamp
if (timestamp < page_index(count - 1)->timestamp) {
return AKU_EBAD_ARG;
}
}
const auto SPACE_REQUIRED = sizeof(aku_Entry) // entry header
+ range.length // data size (in bytes)
+ sizeof(aku_EntryIndexRecord); // offset inside page_index
const auto ENTRY_SIZE = sizeof(aku_Entry) + range.length;
if (!range.length) {
return AKU_EBAD_DATA;
}
if (SPACE_REQUIRED > get_free_space()) {
return AKU_EOVERFLOW;
}
char* free_slot = payload + next_offset;
aku_Entry* entry = reinterpret_cast<aku_Entry*>(free_slot);
entry->param_id = param;
entry->length = range.length;
memcpy((void*)&entry->value, range.address, range.length);
page_index(count)->offset = next_offset;
page_index(count)->timestamp = timestamp;
next_offset += ENTRY_SIZE;
count++;
return AKU_SUCCESS;
}
aku_Status PageHeader::add_chunk(const aku_MemRange range, const uint32_t free_space_required, uint32_t* out_offset) {
const auto
SPACE_REQUIRED = range.length + free_space_required,
SPACE_NEEDED = range.length;
if (get_free_space() < SPACE_REQUIRED) {
return AKU_EOVERFLOW;
}
*out_offset = next_offset;
char* free_slot = payload + next_offset;
memcpy((void*)free_slot, range.address, SPACE_NEEDED);
next_offset += SPACE_NEEDED;
return AKU_SUCCESS;
}
aku_Status PageHeader::complete_chunk(const UncompressedChunk& data) {
CompressedChunkDesc desc;
Rand rand;
aku_Timestamp first_ts;
aku_Timestamp last_ts;
struct Writer : ChunkWriter {
PageHeader *header;
char* begin;
char* end;
Writer(PageHeader *h) : header(h) {}
virtual aku_MemRange allocate() {
size_t bytes_free = header->get_free_space();
char* data = header->payload + header->next_offset;
begin = data;
return {(void*)data, (uint32_t)bytes_free};
}
virtual aku_Status commit(size_t bytes_written) {
if (bytes_written < header->get_free_space()) {
header->next_offset += bytes_written;
end = begin + bytes_written;
return AKU_SUCCESS;
}
return AKU_EOVERFLOW;
}
};
Writer writer(this);
// Write compressed data
aku_Status status = CompressionUtil::encode_chunk(&desc.n_elements, &first_ts, &last_ts, &writer, data);
if (status != AKU_SUCCESS) {
return status;
}
// Calculate checksum of the new compressed data
boost::crc_32_type checksum;
checksum.process_block(writer.begin, writer.end);
desc.checksum = checksum.checksum();
desc.begin_offset = writer.begin - payload;
desc.end_offset = writer.end - payload;
aku_MemRange head = {&desc, sizeof(desc)};
status = add_entry(AKU_CHUNK_BWD_ID, first_ts, head);
if (status != AKU_SUCCESS) {
return status;
}
status = add_entry(AKU_CHUNK_FWD_ID, last_ts, head);
if (status != AKU_SUCCESS) {
return status;
}
return status;
}
const aku_Timestamp PageHeader::read_timestamp_at(uint32_t index) const {
return page_index(index)->timestamp;
}
const aku_Entry *PageHeader::read_entry_at(uint32_t index) const {
if (index < count) {
auto offset = page_index(index)->offset;
return read_entry(offset);
}
return 0;
}
const aku_Entry *PageHeader::read_entry(uint32_t offset) const {
auto ptr = payload + offset;
auto entry_ptr = reinterpret_cast<const aku_Entry*>(ptr);
return entry_ptr;
}
const void* PageHeader::read_entry_data(uint32_t offset) const {
return payload + offset;
}
int PageHeader::get_entry_length_at(int entry_index) const {
auto entry_ptr = read_entry_at(entry_index);
if (entry_ptr) {
return entry_ptr->length;
}
return 0;
}
int PageHeader::get_entry_length(uint32_t offset) const {
auto entry_ptr = read_entry(offset);
if (entry_ptr) {
return entry_ptr->length;
}
return 0;
}
int PageHeader::copy_entry_at(int index, aku_Entry *receiver) const {
auto entry_ptr = read_entry_at(index);
if (entry_ptr) {
size_t size = entry_ptr->length + sizeof(aku_Entry);
if (entry_ptr->length > receiver->length) {
return -1*entry_ptr->length;
}
memcpy((void*)receiver, (void*)entry_ptr, size);
return entry_ptr->length;
}
return 0;
}
int PageHeader::copy_entry(uint32_t offset, aku_Entry *receiver) const {
auto entry_ptr = read_entry(offset);
if (entry_ptr) {
if (entry_ptr->length > receiver->length) {
return -1*entry_ptr->length;
}
memcpy((void*)receiver, (void*)entry_ptr, entry_ptr->length);
return entry_ptr->length;
}
return 0;
}
SearchStats& get_global_search_stats() {
static SearchStats stats;
return stats;
}
namespace {
struct ChunkHeaderSearcher : InterpolationSearch<ChunkHeaderSearcher> {
UncompressedChunk const& header;
ChunkHeaderSearcher(UncompressedChunk const& h) : header(h) {}
// Interpolation search supporting functions
bool read_at(aku_Timestamp* out_timestamp, uint32_t ix) const {
if (ix < header.timestamps.size()) {
*out_timestamp = header.timestamps[ix];
return true;
}
return false;
}
bool is_small(SearchRange range) const {
return false;
}
SearchStats& get_search_stats() {
return get_global_search_stats();
}
};
}
struct SearchAlgorithm : InterpolationSearch<SearchAlgorithm>
{
const PageHeader *page_;
std::shared_ptr<QP::IQueryProcessor> query_;
std::shared_ptr<ChunkCache> cache_;
const uint32_t MAX_INDEX_;
const bool IS_BACKWARD_;
const aku_Timestamp key_;
const aku_Timestamp lowerbound_;
const aku_Timestamp upperbound_;
SearchRange range_;
SearchAlgorithm(PageHeader const* page, std::shared_ptr<QP::IQueryProcessor> query, std::shared_ptr<ChunkCache> cache)
: page_(page)
, query_(query)
, cache_(cache)
, MAX_INDEX_(page->get_entries_count())
, IS_BACKWARD_(query->direction() == AKU_CURSOR_DIR_BACKWARD)
, key_(IS_BACKWARD_ ? query->upperbound() : query->lowerbound())
, lowerbound_(query->lowerbound())
, upperbound_(query->upperbound())
{
if (MAX_INDEX_) {
range_.begin = 0u;
range_.end = MAX_INDEX_ - 1;
} else {
range_.begin = 0u;
range_.end = 0u;
}
}
bool fast_path() {
if (!MAX_INDEX_) {
return true;
}
if (key_ > page_->page_index(range_.end)->timestamp ||
key_ < page_->page_index(range_.begin)->timestamp)
{
// Shortcut for corner cases
if (key_ > page_->page_index(range_.end)->timestamp) {
if (IS_BACKWARD_) {
range_.begin = range_.end;
return false;
} else {
// return empty result
return true;
}
}
else if (key_ < page_->page_index(range_.begin)->timestamp) {
if (!IS_BACKWARD_) {
range_.end = range_.begin;
return false;
} else {
// return empty result
return true;
}
}
}
return false;
}
// Interpolation search supporting functions
bool read_at(aku_Timestamp* out_timestamp, uint32_t ix) const {
if (ix < page_->get_entries_count()) {
*out_timestamp = page_->page_index(ix)->timestamp;
return true;
}
return false;
}
bool is_small(SearchRange range) const {
auto ps = get_page_size();
auto b = align_to_page(reinterpret_cast<void const*>(page_->read_entry_at(range.begin)), ps);
auto e = align_to_page(reinterpret_cast<void const*>(page_->read_entry_at(range.end)), ps);
return b == e;
}
SearchStats& get_search_stats() {
return get_global_search_stats();
}
bool interpolation() {
if (!run(key_, &range_)) {
query_->set_error(AKU_ENOT_FOUND);
return false;
}
return true;
}
void binary_search() {
// TODO: use binary search from stdlib
uint64_t steps = 0ul;
if (range_.begin == range_.end) {
return;
}
uint32_t probe_index = 0u;
while (range_.end >= range_.begin) {
steps++;
probe_index = range_.begin + ((range_.end - range_.begin) / 2u);
if (probe_index >= MAX_INDEX_) {
query_->set_error(AKU_EOVERFLOW);
range_.begin = range_.end = MAX_INDEX_;
return;
}
auto probe = page_->page_index(probe_index)->timestamp;
if (probe == key_) { // found
break;
} else if (probe < key_) {
range_.begin = probe_index + 1u; // change min index to search upper subarray
if (range_.begin >= MAX_INDEX_) { // we hit the upper bound of the array
break;
}
} else {
range_.end = probe_index - 1u; // change max index to search lower subarray
if (range_.end == ~0u) { // we hit the lower bound of the array
break;
}
}
}
range_.begin = probe_index;
range_.end = probe_index;
auto& stats = get_global_search_stats();
std::lock_guard<std::mutex> guard(stats.mutex);
auto& bst = stats.stats.bstats;
bst.n_times += 1;
bst.n_steps += steps;
}
bool scan_compressed_entries(uint32_t current_index, aku_Entry const* probe_entry, bool binary_search=false) {
aku_Status status = AKU_SUCCESS;
std::shared_ptr<UncompressedChunk> chunk_header, header;
auto npages = page_->get_numpages(); // This needed to prevent key collision
auto nopens = page_->get_open_count(); // between old and new page data, when
auto pageid = page_->get_page_id(); // page is reallocated.
auto key = std::make_tuple(npages*nopens + pageid, current_index);
if (cache_ && cache_->contains(key)) {
// Fast path
header = cache_->get(key);
} else {
chunk_header.reset(new UncompressedChunk());
header.reset(new UncompressedChunk());
auto pdesc = reinterpret_cast<CompressedChunkDesc const*>(&probe_entry->value[0]);
auto pbegin = (const unsigned char*)page_->read_entry_data(pdesc->begin_offset);
auto pend = (const unsigned char*)page_->read_entry_data(pdesc->end_offset);
auto probe_length = pdesc->n_elements;
boost::crc_32_type checksum;
checksum.process_block(pbegin, pend);
if (checksum.checksum() != pdesc->checksum) {
AKU_PANIC("File damaged!");
}
status = CompressionUtil::decode_chunk(chunk_header.get(), pbegin, pend, probe_length);
if (status != AKU_SUCCESS) {
AKU_PANIC("Can't decode chunk");
}
// TODO: depending on a query type we can use chunk order or convert back to time-order.
// If we extract evertyhing it is better to convert to time order. If we picking some
// parameter ids it is better to check if this ids present in a chunk and extract values
// in chunk order and only after that - convert results to time-order.
// Convert from chunk order to time order
if (!CompressionUtil::convert_from_chunk_order(*chunk_header, header.get())) {
AKU_PANIC("Bad chunk");
}
if (cache_) {
cache_->put(key, header);
}
}
int start_pos = 0;
if (IS_BACKWARD_) {
start_pos = static_cast<int>(header->timestamps.size() - 1);
}
bool probe_in_time_range = true;
auto queryproc = query_;
auto page = page_;
auto put_entry = [&header, queryproc, page] (uint32_t i) {
aku_PData pdata;
pdata.type = AKU_PAYLOAD_FLOAT;
pdata.float64 = header->values.at(i);
pdata.size = sizeof(aku_Sample);
aku_Sample result = {
header->timestamps.at(i),
header->paramids.at(i),
pdata,
};
return queryproc->put(result);
};
if (IS_BACKWARD_) {
for (int i = static_cast<int>(start_pos); i >= 0; i--) {
probe_in_time_range = lowerbound_ <= header->timestamps[i] &&
upperbound_ >= header->timestamps[i];
if (probe_in_time_range) {
if (!put_entry(i)) {
probe_in_time_range = false;
break;
}
} else {
probe_in_time_range = lowerbound_ <= header->timestamps[i];
if (!probe_in_time_range) {
break;
}
}
}
} else {
auto end_pos = (int)header->timestamps.size();
for (auto i = start_pos; i != end_pos; i++) {
probe_in_time_range = lowerbound_ <= header->timestamps[i] &&
upperbound_ >= header->timestamps[i];
if (probe_in_time_range) {
if (!put_entry(i)) {
probe_in_time_range = false;
break;
}
} else {
probe_in_time_range = upperbound_ >= header->timestamps[i];
if (!probe_in_time_range) {
break;
}
}
}
}
return probe_in_time_range;
}
std::tuple<uint64_t, uint64_t> scan_impl(uint32_t probe_index) {
int index_increment = IS_BACKWARD_ ? -1 : 1;
while (true) {
auto current_index = probe_index;
probe_index += index_increment;
auto probe_offset = page_->page_index(current_index)->offset;
auto probe_time = page_->page_index(current_index)->timestamp;
auto probe_entry = page_->read_entry(probe_offset);
auto probe = probe_entry->param_id;
bool proceed = false;
if (probe == AKU_CHUNK_FWD_ID && IS_BACKWARD_ == false) {
proceed = scan_compressed_entries(current_index, probe_entry, false);
} else if (probe == AKU_CHUNK_BWD_ID && IS_BACKWARD_ == true) {
proceed = scan_compressed_entries(current_index, probe_entry, false);
} else {
proceed = IS_BACKWARD_ ? lowerbound_ <= probe_time
: upperbound_ >= probe_time;
}
if (!proceed || probe_index >= MAX_INDEX_) {
// When scanning forward probe_index will be equal to MAX_INDEX_ at the end of the page
// When scanning backward probe_index will be equal to ~0 (probe_index > MAX_INDEX_)
// at the end of the page
break;
}
}
return std::make_tuple(0ul, 0ul);
}
void scan() {
if (range_.begin != range_.end) {
query_->set_error(AKU_EGENERAL);
return;
}
if (range_.begin >= MAX_INDEX_) {
query_->set_error(AKU_EOVERFLOW);
return;
}
auto sums = scan_impl(range_.begin);
auto& stats = get_global_search_stats();
{
std::lock_guard<std::mutex> guard(stats.mutex);
stats.stats.scan.fwd_bytes += std::get<0>(sums);
stats.stats.scan.bwd_bytes += std::get<1>(sums);
}
}
};
void PageHeader::search(std::shared_ptr<QP::IQueryProcessor> query, std::shared_ptr<ChunkCache> cache) const {
SearchAlgorithm search_alg(this, query, cache);
if (search_alg.fast_path() == false) {
if (search_alg.interpolation()) {
search_alg.binary_search();
search_alg.scan();
}
}
}
void PageHeader::get_stats(aku_StorageStats* rcv_stats) {
uint64_t used_space = 0,
free_space = 0,
n_entries = 0;
auto all = length;
auto free = get_free_space();
used_space = all - free;
free_space = free;
n_entries = count;
rcv_stats->free_space += free_space;
rcv_stats->used_space += used_space;
rcv_stats->n_entries += n_entries;
rcv_stats->n_volumes += 1;
}
void PageHeader::get_search_stats(aku_SearchStats* stats, bool reset) {
auto& gstats = get_global_search_stats();
std::lock_guard<std::mutex> guard(gstats.mutex);
memcpy( reinterpret_cast<void*>(stats)
, reinterpret_cast<void*>(&gstats.stats)
, sizeof(aku_SearchStats));
if (reset) {
memset(reinterpret_cast<void*>(&gstats.stats), 0, sizeof(aku_SearchStats));
}
}
} // namepsace
| 31.614458 | 122 | 0.58608 | vladon |
183c1e2d937ce1c624a715fce3d36848893944f0 | 1,075 | cpp | C++ | src/titanic/model/AlternativeMachine.cpp | LaroyenneG/Fuzzy-Logic | 0d2911c02b5bd4eedcca42925e7e35c5dd450bf8 | [
"Apache-2.0"
] | null | null | null | src/titanic/model/AlternativeMachine.cpp | LaroyenneG/Fuzzy-Logic | 0d2911c02b5bd4eedcca42925e7e35c5dd450bf8 | [
"Apache-2.0"
] | null | null | null | src/titanic/model/AlternativeMachine.cpp | LaroyenneG/Fuzzy-Logic | 0d2911c02b5bd4eedcca42925e7e35c5dd450bf8 | [
"Apache-2.0"
] | null | null | null |
#include "AlternativeMachine.h"
namespace model {
AlternativeMachine::AlternativeMachine()
: Engine(ALTERNATIVE_DEFAULT_PROPELLER_DIAMETER / 2.0, ALTERNATIVE_DEFAULT_PROPELLER_WEIGHT,
ALTERNATIVE_DEFAULT_MAX_POWER, ALTERNATIVE_DEFAULT_MAX_SPEED, ALTERNATIVE_DEFAULT_FRICTION,
ALTERNATIVE_DEFAULT_POWER_STEP, ALTERNATIVE_DEFAULT_BLADE_NUMBER) {
}
std::string AlternativeMachine::getName() const {
return std::string(ALTERNATIVE_DEFAULT_ENGINE_NAME);
}
double
AlternativeMachine::powerStepFunction(double _powerStep, double time, double _power, double _desiredPower) const {
static const int SLEEP_NUMBER = 3;
if (_power < _desiredPower && fabs(_power) < pow(10, -SLEEP_NUMBER)) {
_powerStep /= pow(10, SLEEP_NUMBER);
} else if (_power > _desiredPower && fabs(_power) < pow(10, -SLEEP_NUMBER)) {
_powerStep /= pow(10, SLEEP_NUMBER);
}
return Engine::powerStepFunction(_powerStep, time, _power, _desiredPower);
}
} | 34.677419 | 118 | 0.685581 | LaroyenneG |
183d00a9783887b9081c3b3756936046cbc55051 | 552 | cpp | C++ | Conversion.cpp | dabbertorres/unicode | a886097339711371e178a8e39dbc4bc33370d0c1 | [
"MIT"
] | 1 | 2018-04-24T12:03:34.000Z | 2018-04-24T12:03:34.000Z | Conversion.cpp | dabbertorres/utf8 | a886097339711371e178a8e39dbc4bc33370d0c1 | [
"MIT"
] | 1 | 2016-09-13T01:36:24.000Z | 2016-09-13T01:36:24.000Z | Conversion.cpp | dabbertorres/unicode | a886097339711371e178a8e39dbc4bc33370d0c1 | [
"MIT"
] | null | null | null | #include "Conversion.hpp"
#include <memory>
namespace dbr
{
namespace unicode
{
utf32::ImmutableString toUTF32(const utf8::ImmutableString& str)
{
auto* data = str.data();
auto len = utf8::characterLength(data);
auto out = std::make_unique<utf32::Char[]>(len);
for(auto i = 0u; i < len; ++i)
{
std::size_t seqLen = 0;
out[i] = utf8::decode(data, seqLen);
data += seqLen;
}
return{out.get()};
}
utf8::ImmutableString toUTF8(const utf32::ImmutableString& /*str*/)
{
// TODO
return{};
}
}
}
| 16.235294 | 69 | 0.603261 | dabbertorres |
183d46b469eaad5abd7c23a99133ffd19a75a17b | 118 | cc | C++ | code/snip_overflow_tle.cc | xry111/2019-summer-lecture-debug | ee9800750050cf724bd001c5f511dd0445a82cfe | [
"CC-BY-4.0"
] | 3 | 2019-09-08T11:41:34.000Z | 2020-11-14T12:20:57.000Z | code/snip_overflow_tle.cc | xry111/2019-summer-lecture-debug | ee9800750050cf724bd001c5f511dd0445a82cfe | [
"CC-BY-4.0"
] | 2 | 2021-09-14T09:40:40.000Z | 2021-09-19T13:22:10.000Z | code/snip_overflow_tle.cc | xry111/2019-summer-lecture-debug | ee9800750050cf724bd001c5f511dd0445a82cfe | [
"CC-BY-4.0"
] | null | null | null | int a, b, ans = 0;
scanf("%d%d", &a, &b);
for (int i = a; i <= b; i++)
ans += foo(i);
printf("%d\n", ans);
return 0;
| 16.857143 | 28 | 0.457627 | xry111 |
183e619df94fdd7eb005fd72e5033c9ab8ff2266 | 5,527 | hpp | C++ | 3rdparty/libprocess/src/mpsc_linked_queue.hpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 4,537 | 2015-01-01T03:26:40.000Z | 2022-03-31T03:07:00.000Z | 3rdparty/libprocess/src/mpsc_linked_queue.hpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 227 | 2015-01-29T02:21:39.000Z | 2022-03-29T13:35:50.000Z | 3rdparty/libprocess/src/mpsc_linked_queue.hpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 1,992 | 2015-01-05T12:29:19.000Z | 2022-03-31T03:07:07.000Z | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#ifndef __MPSC_LINKED_QUEUE_HPP__
#define __MPSC_LINKED_QUEUE_HPP__
#include <atomic>
#include <functional>
#include <glog/logging.h>
namespace process {
// This queue is a C++ port of the MpscLinkedQueue of JCTools, but limited to
// the core methods:
// https://github.com/JCTools/JCTools/blob/master/jctools-core/src/main/java/org/jctools/queues/MpscLinkedQueue.java
//
// which is a Java port of the MPSC algorithm as presented in following article:
// http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue
//
// The queue has following properties:
// Producers are wait-free (one atomic exchange per enqueue)
// Consumer is
// - lock-free
// - mostly wait-free, except when consumer reaches the end of the queue
// and producer enqueued a new node, but did not update the next pointer
// on the old node, yet
template <typename T>
class MpscLinkedQueue
{
private:
template <typename E>
struct Node
{
public:
explicit Node(E* element = nullptr) : element(element) {}
E* element;
std::atomic<Node<E>*> next = ATOMIC_VAR_INIT(nullptr);
};
public:
MpscLinkedQueue()
{
tail = new Node<T>();
head.store(tail);
}
~MpscLinkedQueue()
{
while (auto element = dequeue()) {
delete element;
}
delete tail;
}
// Multi producer safe.
void enqueue(T* element)
{
// A `nullptr` is used to denote an empty queue when doing a
// `dequeue()` so producers can't use it as an element.
CHECK_NOTNULL(element);
auto newNode = new Node<T>(element);
// Exchange is guaranteed to only give the old value to one
// producer, so this is safe and wait-free.
auto oldhead = head.exchange(newNode, std::memory_order_acq_rel);
// At this point if this thread context switches out we may block
// the consumer from doing a dequeue (see below). Eventually we'll
// unblock the consumer once we run again and execute the next
// line of code.
oldhead->next.store(newNode, std::memory_order_release);
}
// Single consumer only.
T* dequeue()
{
auto currentTail = tail;
// Check and see if there is an actual element linked from `tail`
// since we use `tail` as a "stub" rather than the actual element.
auto nextTail = currentTail->next.load(std::memory_order_acquire);
// There are three possible cases here:
//
// (1) The queue is empty.
// (2) The queue appears empty but a producer is still enqueuing
// so let's wait for it and then dequeue.
// (3) We have something to dequeue.
//
// Start by checking if the queue is or appears empty.
if (nextTail == nullptr) {
// Now check if the queue is actually empty or just appears
// empty. If it's actually empty then return `nullptr` to denote
// emptiness.
if (head.load(std::memory_order_relaxed) == tail) {
return nullptr;
}
// Another thread already inserted a new node, but did not
// connect it to the tail, yet, so we spin-wait. At this point
// we are not wait-free anymore.
do {
nextTail = currentTail->next.load(std::memory_order_acquire);
} while (nextTail == nullptr);
}
CHECK_NOTNULL(nextTail);
// Set next pointer of current tail to null to disconnect it
// from the queue.
currentTail->next.store(nullptr, std::memory_order_release);
auto element = nextTail->element;
nextTail->element = nullptr;
tail = nextTail;
delete currentTail;
return element;
}
// Single consumer only.
//
// TODO(drexin): Provide C++ style iteration so someone can just use
// the `std::for_each()`.
template <typename F>
void for_each(F&& f)
{
auto end = head.load();
auto node = tail;
for (;;) {
node = node->next.load();
// We are following the linked structure until we reach the end
// node. There is a race with new nodes being added, so we limit
// the traversal to the last node at the time we started.
if (node == nullptr) {
return;
}
f(node->element);
if (node == end) {
return;
}
}
}
// Single consumer only.
bool empty()
{
return tail->next.load(std::memory_order_relaxed) == nullptr &&
head.load(std::memory_order_relaxed) == tail;
}
private:
// TODO(drexin): Programatically get the cache line size.
//
// We align head to 64 bytes (x86 cache line size) to guarantee
// it to be put on a new cache line. This is to prevent false
// sharing with other objects that could otherwise end up on
// the same cache line as this queue. We also align tail to
// avoid false sharing with head and add padding after tail
// to avoid false sharing with other objects.
alignas(64) std::atomic<Node<T>*> head;
alignas(64) Node<T>* tail;
char pad[64 - sizeof(Node<T>*)];
};
} // namespace process {
#endif // __MPSC_LINKED_QUEUE_HPP__
| 29.55615 | 116 | 0.666908 | zagrev |
183ea26e68695c2e3a498e28b78f6f563ed68fa6 | 7,955 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_cfgcreator.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_cfgcreator.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_cfgcreator.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #ifndef INCLUDED_STDDEFX
#include "stddefx.h"
#define INCLUDED_STDDEFX
#endif
#ifndef INCLUDED_CALC_CFGCREATOR
#include "calc_cfgcreator.h"
#define INCLUDED_CALC_CFGCREATOR
#endif
// Library headers.
#ifndef INCLUDED_STACK
#include <stack>
#define INCLUDED_STACK
#endif
// PCRaster library headers.
// Module headers.
#ifndef INCLUDED_CALC_ASTSTAT
#include "calc_aststat.h"
#define INCLUDED_CALC_ASTSTAT
#endif
#ifndef INCLUDED_CALC_POINTCODEBLOCK
#include "calc_pointcodeblock.h"
#define INCLUDED_CALC_POINTCODEBLOCK
#endif
#ifndef INCLUDED_CALC_ASTVISITOR
#include "calc_astvisitor.h"
#define INCLUDED_CALC_ASTVISITOR
#endif
#ifndef INCLUDED_CALC_CFGNODE
#include "calc_cfgnode.h"
#define INCLUDED_CALC_CFGNODE
#endif
#ifndef INCLUDED_CALC_BASEEXPR
#include "calc_baseexpr.h"
#define INCLUDED_CALC_BASEEXPR
#endif
#ifndef INCLUDED_CALC_NONASSEXPR
#include "calc_nonassexpr.h"
#define INCLUDED_CALC_NONASSEXPR
#endif
#ifndef INCLUDED_CALC_ASTNUMBER
#include "calc_astnumber.h"
#define INCLUDED_CALC_ASTNUMBER
#endif
#ifndef INCLUDED_CALC_ASTPAR
#include "calc_astpar.h"
#define INCLUDED_CALC_ASTPAR
#endif
#ifndef INCLUDED_CALC_ASTASS
#include "calc_astass.h"
#define INCLUDED_CALC_ASTASS
#endif
#ifndef INCLUDED_CALC_JUMPNODE
#include "calc_jumpnode.h"
#define INCLUDED_CALC_JUMPNODE
#endif
#ifndef INCLUDED_CALC_BLOCKENTRANCE
#include "calc_blockentrance.h"
#define INCLUDED_CALC_BLOCKENTRANCE
#endif
/*!
\file
This file contains the implementation of the CFGCreator class.
*/
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace calc {
class CFGCreatorPrivate : public ASTVisitor
{
private:
//! Assignment operator. NOT IMPLEMENTED.
CFGCreatorPrivate& operator= (const CFGCreatorPrivate&);
//! Copy constructor. NOT IMPLEMENTED.
CFGCreatorPrivate (const CFGCreatorPrivate&);
CFGNode *d_last;
CFGNode *d_first;
ASTAss *d_currentAss;
std::stack<CFGNode *> d_blockEntrances;
void add(ASTNode *an);
void setBack(CFGNode *an);
void visitPar (ASTPar *p);
void visitNumber (ASTNumber *n);
void visitStat (ASTStat *s);
void visitPointCodeBlock(PointCodeBlock *b);
void visitExpr (BaseExpr *e);
void visitAss (ASTAss *a);
void visitNonAssExpr(NonAssExpr *e);
void visitJumpNode (JumpNode *j);
void visitBlockEntrance(BlockEntrance *e);
public:
//----------------------------------------------------------------------------
// CREATORS
//----------------------------------------------------------------------------
CFGCreatorPrivate ();
/* virtual */ ~CFGCreatorPrivate ();
//----------------------------------------------------------------------------
// MANIPULATORS
//----------------------------------------------------------------------------
CFGNode* releaseFirst() ;
//----------------------------------------------------------------------------
// ACCESSORS
//----------------------------------------------------------------------------
};
} // namespace calc
//------------------------------------------------------------------------------
// DEFINITION OF STATIC CFGCREATOR MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF CFGCREATOR MEMBERS
//------------------------------------------------------------------------------
calc::CFGNode *calc::createCFG(ASTNode *n) {
std::vector<ASTNode *> nodeVector(1,n);
return createCFG(nodeVector);
}
calc::CFGNode *calc::createCFG(const std::vector<ASTNode *>& nodeVector)
{
CFGCreatorPrivate c;
for(size_t i=0; i < nodeVector.size(); ++i)
if (nodeVector[i])
nodeVector[i]->accept(c);
return c.releaseFirst();
}
calc::ScopedCFG::ScopedCFG(CFGNode *n):
cfg(n)
{
}
calc::ScopedCFG::ScopedCFG(ASTNode *n):
cfg(createCFG(n))
{}
calc::ScopedCFG::~ScopedCFG()
{
delete cfg;
cfg=0;
}
//! ctor
calc::CFGCreatorPrivate::CFGCreatorPrivate():
d_last(0),d_first(0),
d_currentAss(0)
{
}
calc::CFGCreatorPrivate::~CFGCreatorPrivate()
{
delete d_first;
}
//! release the start of CFG
calc::CFGNode* calc::CFGCreatorPrivate::releaseFirst() {
CFGNode* first=d_first;
d_first=0;
return first;
}
void calc::CFGCreatorPrivate::add(ASTNode *an)
{
CFGNode *n= new CFGNode(an);
if (d_last) {
d_last->setForward(n);
n->setPred(d_last);
} else {
d_first=n;
}
d_last=n;
}
void calc::CFGCreatorPrivate::setBack(CFGNode *b)
{
PRECOND(d_last); // something to point back to
d_last->setBack(b);
// FTTB pred not set
}
void calc::CFGCreatorPrivate::visitPar(ASTPar *p)
{
add(p);
}
void calc::CFGCreatorPrivate::visitNumber(ASTNumber *n)
{
add(n);
}
void calc::CFGCreatorPrivate::visitPointCodeBlock(PointCodeBlock *b)
{
add(b);
}
void calc::CFGCreatorPrivate::visitStat(ASTStat *s)
{
add(s);
PRECOND(s->stat());
s->stat()->accept(*this);
}
void calc::CFGCreatorPrivate::visitNonAssExpr(NonAssExpr *e)
{
e->expr()->accept(*this);
add(e);
}
void calc::CFGCreatorPrivate::visitExpr(BaseExpr *e)
{
ASTVisitor::visitExpr(e);
add(e);
}
void calc::CFGCreatorPrivate::visitAss (ASTAss *a)
{
// d_currentAss=a;
a->rhs()->accept(*this);
add(a);
}
void calc::CFGCreatorPrivate::visitJumpNode(JumpNode *j)
{
add(j);
setBack(d_blockEntrances.top());
d_blockEntrances.pop();
}
void calc::CFGCreatorPrivate::visitBlockEntrance(BlockEntrance *e)
{
add(e);
d_blockEntrances.push(d_last);
}
//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF STATIC CFGCREATOR MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF CFGCREATOR MEMBERS
//------------------------------------------------------------------------------
// NOT USED
// calc::CFGCreator::CFGCreator()
// {
// d_data=new CFGCreatorPrivate();
// }
//
//
//
// /* NOT IMPLEMENTED
// //! Copy constructor.
// calc::CFGCreator::CFGCreator(CFGCreator const& rhs)
//
// : Base(rhs)
//
// {
// }
// */
//
//
//
// calc::CFGCreator::~CFGCreator()
// {
// delete d_data;
// }
//
//
//
// /* NOT IMPLEMENTED
// //! Assignment operator.
// calc::CFGCreator& calc::CFGCreator::operator=(CFGCreator const& rhs)
// {
// if (this != &rhs) {
// }
// return *this;
// }
// */
//
// //! add AST fragment to CFG in creation
// void calc::CFGCreator::add(ASTNode *fragment)
// {
// fragment->accept(*d_data);
// }
//
//
// //! create the CFG with the add()'ed fragments
// /*!
// * This always the last call to this object, since
// * it is destructive.
// */
// calc::CFGNode* calc::CFGCreator::create()
// {
// return d_data->releaseFirst();
// }
//
//
//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------
| 22.158774 | 80 | 0.508737 | quanpands |
183f69fee2cdc3929bd87a080dbf16710817c42c | 4,857 | cpp | C++ | packages/monte_carlo/core/test/tstAdjointKleinNishinaSamplingTypeHelpers.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/monte_carlo/core/test/tstAdjointKleinNishinaSamplingTypeHelpers.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/monte_carlo/core/test/tstAdjointKleinNishinaSamplingTypeHelpers.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_AdjointKleinNishinaSamplingType.hpp
//! \author Alex Robinson
//! \brief Adjoint Klein-Nishina sampling type helper function unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <sstream>
// FRENSIE Includes
#include "MonteCarlo_AdjointKleinNishinaSamplingType.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
#include "ArchiveTestHelpers.hpp"
//---------------------------------------------------------------------------//
// Testing Types
//---------------------------------------------------------------------------//
typedef TestArchiveHelper::TestArchives TestArchives;
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that a sampling type can be converted to a string
FRENSIE_UNIT_TEST( AdjointKleinNishinaSamplingType, toString )
{
std::string sampling_name =
Utility::toString( MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING );
FRENSIE_CHECK_EQUAL( sampling_name, "Two Branch Rejection Adjoint Klein-Nishina Sampling" );
sampling_name = Utility::toString( MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING );
FRENSIE_CHECK_EQUAL( sampling_name, "Three Branch Lin Mixed Adjoint Klein-Nishina Sampling" );
sampling_name = Utility::toString( MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING );
FRENSIE_CHECK_EQUAL( sampling_name, "Three Branch Log Mixed Adjoint Klein-Nishina Sampling" );
}
//---------------------------------------------------------------------------//
// Check that a sampling type can be placed in a stream
FRENSIE_UNIT_TEST( AdjointKleinNishinaSamplingType, ostream_operator )
{
std::ostringstream oss;
oss << MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING;
FRENSIE_CHECK_EQUAL( oss.str(), "Two Branch Rejection Adjoint Klein-Nishina Sampling" );
oss.str( "" );
oss.clear();
oss << MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING;
FRENSIE_CHECK_EQUAL( oss.str(), "Three Branch Lin Mixed Adjoint Klein-Nishina Sampling" );
oss.str( "" );
oss.clear();
oss << MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING;
FRENSIE_CHECK_EQUAL( oss.str(), "Three Branch Log Mixed Adjoint Klein-Nishina Sampling" );
}
//---------------------------------------------------------------------------//
// Check that a sampling type can be archived
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( AdjointKleinNishinaSamplingType,
archive,
TestArchives )
{
FETCH_TEMPLATE_PARAM( 0, RawOArchive );
FETCH_TEMPLATE_PARAM( 1, RawIArchive );
typedef typename std::remove_pointer<RawOArchive>::type OArchive;
typedef typename std::remove_pointer<RawIArchive>::type IArchive;
std::string archive_base_name( "test_adjoint_kn_sampling_type" );
std::ostringstream archive_ostream;
{
std::unique_ptr<OArchive> oarchive;
createOArchive( archive_base_name, archive_ostream, oarchive );
MonteCarlo::AdjointKleinNishinaSamplingType type_1 =
MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING;
MonteCarlo::AdjointKleinNishinaSamplingType type_2 =
MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING;
MonteCarlo::AdjointKleinNishinaSamplingType type_3 =
MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING;
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_1 ) );
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_2 ) );
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_3 ) );
}
// Copy the archive ostream to an istream
std::istringstream archive_istream( archive_ostream.str() );
// Load the archived distributions
std::unique_ptr<IArchive> iarchive;
createIArchive( archive_istream, iarchive );
MonteCarlo::AdjointKleinNishinaSamplingType type_1, type_2, type_3;
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_1 ) );
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_2 ) );
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_3 ) );
iarchive.reset();
FRENSIE_CHECK_EQUAL( type_1, MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING );
FRENSIE_CHECK_EQUAL( type_2, MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING );
FRENSIE_CHECK_EQUAL( type_3, MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING );
}
//---------------------------------------------------------------------------//
// end MonteCarlo_AdjointKleinNishinaSamplingType.hpp
//---------------------------------------------------------------------------//
| 38.244094 | 98 | 0.646695 | bam241 |
1841dc01afabd4ea7b689d52988926927bed8374 | 4,199 | cpp | C++ | Main alarm box/MainAlarm/TimerMode.cpp | nicholas-p1/LightAlarm | 3528a196edcba485cefac7a57adffb4e6434b97c | [
"MIT"
] | null | null | null | Main alarm box/MainAlarm/TimerMode.cpp | nicholas-p1/LightAlarm | 3528a196edcba485cefac7a57adffb4e6434b97c | [
"MIT"
] | null | null | null | Main alarm box/MainAlarm/TimerMode.cpp | nicholas-p1/LightAlarm | 3528a196edcba485cefac7a57adffb4e6434b97c | [
"MIT"
] | null | null | null | #include "Arduino.h"
#include "TimerMode.h"
#include "IMode.h"
#include "ILogger.h"
#include "UserIO.h"
TimerMode::TimerMode(ILogger *_logger, UserIO *_io)
: logger{_logger}, io(_io), isEnabled{false}, isPaused{false}, IMode("Timer mode") {}
void TimerMode::resetAll()
{
timeAtStartMS = 0;
timerDurationMS = 0;
isEnabled = false;
isPaused = false;
}
byte TimerMode::getNumberOfOptions() const
{
return numberOfOptions;
}
void TimerMode::displayTimeLeft() const
{
io->setCursor(0, 0);
if (isEnabled)
{
const unsigned long timeLeftMS = isPaused ? (timeAtStartMS + timerDurationMS - timeAtPauseStartMS) : (timeAtStartMS + timerDurationMS - millis());
int secondsLeft = (int)((timeLeftMS / 1000UL) % 60UL);
int minutesLeft = (int)((timeLeftMS / (1000UL * 60UL)) % 60UL);
int hoursLeft = (int)(timeLeftMS / (1000UL * 60UL * 60UL));
io->print(F("Time left: "));
io->printDigits(hoursLeft, true);
io->printDigits(minutesLeft);
io->printDigits(secondsLeft);
}
else
{
io->print(F("No timer set"));
}
}
void TimerMode::displayOptions()
{
const unsigned long displayOptionsIntervalMS PROGMEM = 2000;
//display different timer mode options
unsigned long currentTimerMillis = millis();
if ((unsigned long)(currentTimerMillis - previousTimerMillis) >= displayOptionsIntervalMS)
{
//don't want to clear first row as used to display time left
io->clearRow(1);
io->clearRow(2);
io->clearRow(3);
io->setCursor(0, 1);
io->print("Select one (#=Quit):");
for (int i{2}; i < 4 && currentDisplayedOption < numberOfOptions; i++)
{
String optionName = optionNames[currentDisplayedOption];
io->setCursor(0, i);
io->print(optionName);
currentDisplayedOption++;
}
//check if need to rollover to first option
if (currentDisplayedOption >= numberOfOptions)
{
currentDisplayedOption = 0;
}
previousTimerMillis = currentTimerMillis; //restart display option interval
}
}
byte TimerMode::selectOption()
{
byte option = io->selectOption(numberOfOptions);
if (option)
{
currentDisplayedOption = 0; //make sure to start with displaying first option when displayOptions() is entered again
}
return option;
}
void TimerMode::executeOption(int selectedOption)
{
switch (selectedOption)
{
case 1: //set new timer
//blocking operation
setNewTimer();
break;
case 2: //disable timer
disableTimer();
break;
case 3: //pause timer
pauseTimer();
break;
case 4: //resume timer
resumeTimer();
break;
case 5: //restart timer
restartTimer();
break;
default:
logger->logError(F("Tried to execute non-existing timer option"), F("TimerMode, executeOption"));
break;
}
previousTimerMillis = 0; //eliminate any possible delay
}
void TimerMode::setNewTimer()
{
io->clearScreen();
io->setCursor(0, 0);
io->print(F("Entering timer time"));
int *durations = io->getHoursMinutesSeconds();
if (!durations)
{
return;
}
int hours{durations[0]}, minutes{durations[1]}, seconds{durations[2]};
delete[] durations;
isEnabled = true;
timeAtStartMS = millis();
timerDurationMS = (hours * 60UL * 60UL * 1000UL + minutes * 60UL * 1000UL + seconds * 1000UL);
}
void TimerMode::disableTimer()
{
resetAll();
}
void TimerMode::pauseTimer()
{
if (!isEnabled || isPaused)
{
logger->logError(F("Tried to pause already paused or disabled timer"), F("TimerMode, pauseTimer"));
return;
}
isPaused = true;
timeAtPauseStartMS = millis();
}
void TimerMode::resumeTimer()
{
if (!isEnabled || !isPaused)
{
logger->logError(F("Tried to resume non-paused timer"), F("TimerMode, resumeTimer"));
return;
}
timerDurationMS += millis() - timeAtPauseStartMS; //icnrease duration by pause time
isPaused = false;
}
void TimerMode::restartTimer()
{
timeAtStartMS = millis();
}
bool TimerMode::hasTimerFinished() const
{
//also considers rare case of millis() overflow
if (isEnabled && !isPaused && (unsigned long)(millis() - timeAtStartMS) >= timerDurationMS)
{
return true;
}
else
{
return false;
}
}
| 23.723164 | 150 | 0.663253 | nicholas-p1 |
1842316ff2cf1820289cd7b10b7efa8223b2cb5b | 3,566 | cpp | C++ | Source/10.0.18362.0/ucrt/stdlib/bsearch.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 2 | 2021-01-27T10:19:30.000Z | 2021-02-09T06:24:30.000Z | Source/10.0.18362.0/ucrt/stdlib/bsearch.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | null | null | null | Source/10.0.18362.0/ucrt/stdlib/bsearch.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 1 | 2021-01-27T10:19:36.000Z | 2021-01-27T10:19:36.000Z | //
// bsearch.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Defines bsearch(), which performs a binary search over an array.
//
#include <corecrt_internal.h>
#include <search.h>
#ifdef _M_CEE
#define __fileDECL __clrcall
#else
#define __fileDECL __cdecl
#endif
/***
*char *bsearch() - do a binary search on an array
*
*Purpose:
* Does a binary search of a sorted array for a key.
*
*Entry:
* const char *key - key to search for
* const char *base - base of sorted array to search
* unsigned int num - number of elements in array
* unsigned int width - number of bytes per element
* int (*compare)() - pointer to function that compares two array
* elements, returning neg when #1 < #2, pos when #1 > #2, and
* 0 when they are equal. Function is passed pointers to two
* array elements.
*
*Exit:
* if key is found:
* returns pointer to occurrence of key in array
* if key is not found:
* returns nullptr
*
*Exceptions:
* Input parameters are validated. Refer to the validation section of the function.
*
*******************************************************************************/
#ifdef __USE_CONTEXT
#define __COMPARE(context, p1, p2) (*compare)(context, p1, p2)
#else
#define __COMPARE(context, p1, p2) (*compare)(p1, p2)
#endif
#ifndef _M_CEE
extern "C"
#endif
_CRT_SECURITYSAFECRITICAL_ATTRIBUTE
#ifdef __USE_CONTEXT
void* __fileDECL bsearch_s(
void const* const key,
void const* const base,
size_t num,
size_t const width,
int (__fileDECL* const compare)(void*, void const*, void const*),
void* const context
)
#else // __USE_CONTEXT
void* __fileDECL bsearch(
void const* const key,
void const* const base,
size_t num,
size_t const width,
int (__fileDECL* const compare)(void const*, void const*)
)
#endif // __USE_CONTEXT
{
_VALIDATE_RETURN(base != nullptr || num == 0, EINVAL, nullptr);
_VALIDATE_RETURN(width > 0, EINVAL, nullptr);
_VALIDATE_RETURN(compare != nullptr, EINVAL, nullptr);
char const* lo = reinterpret_cast<char const*>(base);
char const* hi = reinterpret_cast<char const*>(base) + (num - 1) * width;
// Reentrancy diligence: Save (and unset) global-state mode to the stack before making callout to 'compare'
__crt_state_management::scoped_global_state_reset saved_state;
// We allow a nullptr key here because it breaks some older code and because
// we do not dereference this ourselves so we can't be sure that it's a
// problem for the comparison function
while (lo <= hi)
{
size_t const half = num / 2;
if (half != 0)
{
char const* const mid = lo + (num & 1 ? half : (half - 1)) * width;
int const result = __COMPARE(context, key, mid);
if (result == 0)
{
return const_cast<void*>(static_cast<void const*>(mid));
}
else if (result < 0)
{
hi = mid - width;
num = num & 1 ? half : half - 1;
}
else
{
lo = mid + width;
num = half;
}
}
else if (num != 0)
{
return __COMPARE(context, key, lo)
? nullptr
: const_cast<void*>(static_cast<void const*>(lo));
}
else
{
break;
}
}
return nullptr;
}
#undef __COMPARE
| 28.07874 | 111 | 0.579361 | 825126369 |
18476dc64a5ae27c1cf6c1ce7d5783cc31d8910d | 7,492 | cpp | C++ | vespalib/src/vespa/vespalib/datastore/fixed_size_hash_map.cpp | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | vespalib/src/vespa/vespalib/datastore/fixed_size_hash_map.cpp | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | vespalib/src/vespa/vespalib/datastore/fixed_size_hash_map.cpp | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "fixed_size_hash_map.h"
#include "entry_comparator.h"
#include <vespa/vespalib/util/array.hpp>
#include <vespa/vespalib/util/memoryusage.h>
#include <cassert>
#include <stdexcept>
namespace vespalib::datastore {
FixedSizeHashMap::Node::Node(Node&&)
{
throw std::runtime_error("vespalib::datastore::FixedSizeHashMap::Node move constructor should never be called");
}
void
FixedSizeHashMap::Node::on_free()
{
_kv = std::make_pair(AtomicEntryRef(), AtomicEntryRef());
}
FixedSizeHashMap::FixedSizeHashMap(uint32_t modulo, uint32_t capacity, uint32_t num_shards)
: _chain_heads(modulo),
_nodes(),
_modulo(modulo),
_count(0u),
_free_head(no_node_idx),
_free_count(0u),
_hold_count(0u),
_hold_1_list(),
_hold_2_list(),
_num_shards(num_shards)
{
_nodes.reserve(capacity);
}
FixedSizeHashMap::FixedSizeHashMap(uint32_t modulo, uint32_t capacity, uint32_t num_shards, const FixedSizeHashMap &orig, const EntryComparator& comp)
: FixedSizeHashMap(modulo, capacity, num_shards)
{
for (const auto &chain_head : orig._chain_heads) {
for (uint32_t node_idx = chain_head.load_relaxed(); node_idx != no_node_idx;) {
auto& node = orig._nodes[node_idx];
force_add(comp, node.get_kv());
node_idx = node.get_next_node_idx().load(std::memory_order_relaxed);
}
}
}
FixedSizeHashMap::~FixedSizeHashMap() = default;
void
FixedSizeHashMap::force_add(const EntryComparator& comp, const KvType& kv)
{
ShardedHashComparator shardedComp(comp, kv.first.load_relaxed(), _num_shards);
uint32_t hash_idx = shardedComp.hash_idx() % _modulo;
auto& chain_head = _chain_heads[hash_idx];
assert(_nodes.size() < _nodes.capacity());
uint32_t node_idx = _nodes.size();
new (_nodes.push_back_fast()) Node(kv, chain_head.load_relaxed());
chain_head.set(node_idx);
++_count;
}
FixedSizeHashMap::KvType&
FixedSizeHashMap::add(const ShardedHashComparator & comp, std::function<EntryRef(void)>& insert_entry)
{
uint32_t hash_idx = comp.hash_idx() % _modulo;
auto& chain_head = _chain_heads[hash_idx];
uint32_t node_idx = chain_head.load_relaxed();
while (node_idx != no_node_idx) {
auto& node = _nodes[node_idx];
if (comp.equal(node.get_kv().first.load_relaxed())) {
return node.get_kv();
}
node_idx = node.get_next_node_idx().load(std::memory_order_relaxed);
}
if (_free_head != no_node_idx) {
node_idx = _free_head;
auto& node = _nodes[node_idx];
_free_head = node.get_next_node_idx().load(std::memory_order_relaxed);
--_free_count;
node.get_kv().first.store_release(insert_entry());
node.get_next_node_idx().store(chain_head.load_relaxed());
chain_head.set(node_idx);
++_count;
return node.get_kv();
}
assert(_nodes.size() < _nodes.capacity());
node_idx = _nodes.size();
new (_nodes.push_back_fast()) Node(std::make_pair(AtomicEntryRef(insert_entry()), AtomicEntryRef()), chain_head.load_relaxed());
chain_head.set(node_idx);
++_count;
return _nodes[node_idx].get_kv();
}
void
FixedSizeHashMap::transfer_hold_lists_slow(generation_t generation)
{
auto &hold_2_list = _hold_2_list;
for (uint32_t node_idx : _hold_1_list) {
hold_2_list.push_back(std::make_pair(generation, node_idx));
}
_hold_1_list.clear();
}
void
FixedSizeHashMap::trim_hold_lists_slow(generation_t first_used)
{
while (!_hold_2_list.empty()) {
auto& first = _hold_2_list.front();
if (static_cast<sgeneration_t>(first.first - first_used) >= 0) {
break;
}
uint32_t node_idx = first.second;
auto& node = _nodes[node_idx];
node.get_next_node_idx().store(_free_head, std::memory_order_relaxed);
_free_head = node_idx;
++_free_count;
--_hold_count;
node.on_free();
_hold_2_list.erase(_hold_2_list.begin());
}
}
FixedSizeHashMap::KvType*
FixedSizeHashMap::remove(const ShardedHashComparator & comp)
{
uint32_t hash_idx = comp.hash_idx() % _modulo;
auto& chain_head = _chain_heads[hash_idx];
uint32_t node_idx = chain_head.load_relaxed();
uint32_t prev_node_idx = no_node_idx;
while (node_idx != no_node_idx) {
auto &node = _nodes[node_idx];
uint32_t next_node_idx = node.get_next_node_idx().load(std::memory_order_relaxed);
if (comp.equal(node.get_kv().first.load_relaxed())) {
if (prev_node_idx != no_node_idx) {
_nodes[prev_node_idx].get_next_node_idx().store(next_node_idx, std::memory_order_release);
} else {
chain_head.set(next_node_idx);
}
--_count;
++_hold_count;
_hold_1_list.push_back(node_idx);
return &_nodes[node_idx].get_kv();
}
prev_node_idx = node_idx;
node_idx = next_node_idx;
}
return nullptr;
}
MemoryUsage
FixedSizeHashMap::get_memory_usage() const
{
size_t fixed_size = sizeof(FixedSizeHashMap);
size_t chain_heads_size = sizeof(ChainHead) * _chain_heads.size();
size_t nodes_used_size = sizeof(Node) * _nodes.size();
size_t nodes_alloc_size = sizeof(Node) * _nodes.capacity();
size_t nodes_dead_size = sizeof(Node) * _free_count;
size_t nodes_hold_size = sizeof(Node) * _hold_count;
return MemoryUsage(fixed_size + chain_heads_size + nodes_alloc_size,
fixed_size + chain_heads_size + nodes_used_size,
nodes_dead_size,
nodes_hold_size);
}
void
FixedSizeHashMap::foreach_key(const std::function<void(EntryRef)>& callback) const
{
for (auto& chain_head : _chain_heads) {
uint32_t node_idx = chain_head.load_relaxed();
while (node_idx != no_node_idx) {
auto& node = _nodes[node_idx];
callback(node.get_kv().first.load_relaxed());
node_idx = node.get_next_node_idx().load(std::memory_order_relaxed);
}
}
}
void
FixedSizeHashMap::move_keys(const std::function<EntryRef(EntryRef)>& callback)
{
for (auto& chain_head : _chain_heads) {
uint32_t node_idx = chain_head.load_relaxed();
while (node_idx != no_node_idx) {
auto& node = _nodes[node_idx];
EntryRef old_ref = node.get_kv().first.load_relaxed();
EntryRef new_ref = callback(old_ref);
if (new_ref != old_ref) {
node.get_kv().first.store_release(new_ref);
}
node_idx = node.get_next_node_idx().load(std::memory_order_relaxed);
}
}
}
bool
FixedSizeHashMap::normalize_values(const std::function<EntryRef(EntryRef)>& normalize)
{
bool changed = false;
for (auto& chain_head : _chain_heads) {
uint32_t node_idx = chain_head.load_relaxed();
while (node_idx != no_node_idx) {
auto& node = _nodes[node_idx];
EntryRef old_ref = node.get_kv().second.load_relaxed();
EntryRef new_ref = normalize(old_ref);
if (new_ref != old_ref) {
node.get_kv().second.store_release(new_ref);
changed = true;
}
node_idx = node.get_next_node_idx().load(std::memory_order_relaxed);
}
}
return changed;
}
}
| 33.900452 | 150 | 0.65977 | kashiish |
18485249c4aeacdef37195d8192a339a60b0b808 | 24,156 | hh | C++ | tests/Titon/Route/RouterTest.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 206 | 2015-01-02T20:01:12.000Z | 2021-04-15T09:49:56.000Z | tests/Titon/Route/RouterTest.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 44 | 2015-01-02T06:03:43.000Z | 2017-11-20T18:29:06.000Z | tests/Titon/Route/RouterTest.hh | titon/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 27 | 2015-01-03T05:51:29.000Z | 2022-02-21T13:50:40.000Z | <?hh
namespace Titon\Route;
use Titon\Cache\Storage\MemoryStorage;
use Titon\Test\Stub\Route\FilterStub;
use Titon\Test\Stub\Route\TestRouteStub;
use Titon\Test\TestCase;
use Titon\Utility\State\Get;
use Titon\Utility\State\Server;
use Titon\Context\Depository;
/**
* @property \Titon\Route\Router $object
*/
class RouterTest extends TestCase {
protected function setUp(): void {
parent::setUp();
$container = Depository::getInstance();
$container->singleton('Titon\Route\Router');
$this->object = $router = Depository::getInstance()->make('Titon\Route\Router');
invariant($router instanceof Router, 'Must be a Router.');
$container->register('Titon\Route\UrlBuilder')->with($router);
$this->object->map('action.ext', new TestRouteStub('/{module}/{controller}/{action}.{ext}', 'Module\Controller@action'));
$this->object->map('action', new TestRouteStub('/{module}/{controller}/{action}', 'Module\Controller@action'));
$this->object->map('controller', new TestRouteStub('/{module}/{controller}', 'Module\Controller@action'));
$this->object->map('module', new TestRouteStub('/{module}', 'Module\Controller@action'));
$this->object->map('root', new TestRouteStub('/', 'Module\Controller@action'));
}
protected function tearDown(): void {
Depository::getInstance()
->remove('Titon\Route\Router')
->remove('Titon\Route\UrlBuilder');
}
public function testBuildAction(): void {
$this->assertEquals('Controller@action', Router::buildAction(shape('class' => 'Controller', 'action' => 'action')));
}
public function testCaching(): void {
$storage = new MemoryStorage();
$route1 = new Route('/{module}', 'Module\Controller@action');
$route2 = new Route('/', 'Module\Controller@action');
$router1 = new Router();
$router1->setStorage($storage);
$router1->map('module', $route1);
$router1->map('root', $route2);
$this->assertFalse($storage->has('routes'));
$router1->match('/');
$this->assertTrue($storage->has('routes'));
// Now load another instance
$router2 = new Router();
$router2->setStorage($storage);
$this->assertEquals(Map {}, $router2->getRoutes());
$router2->map('root', new Route('/foobar', 'Module\Controller@action'));
$router2->match('/');
$this->assertEquals(Map {'module' => $route1, 'root' => $route2}, $router2->getRoutes());
// The previous routes should be overwritten
$this->assertEquals('/', $router2->getRoute('root')->getPath());
}
public function testFilters(): void {
$stub = new FilterStub();
$this->object->filter('test', $stub);
$this->object->filterCallback('test2', () ==> {});
$this->assertEquals(inst_meth($stub, 'filter'), $this->object->getFilter('test'));
$this->assertEquals(Vector {'test', 'test2'}, $this->object->getFilters()->keys());
// Filtering is passed to routes
$this->object->map('f1', (new Route('/f1', 'Controller@action'))->addFilter('test2'));
$this->object->group(($router, $group) ==> {
$group->setFilters(Vector {'test'});
$router->map('f2', new Route('/f2', 'Controller@action'));
});
$this->object->map('f3', new Route('/f3', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals(Vector {'test2'}, $routes['f1']->getFilters());
$this->assertEquals(Vector {'test'}, $routes['f2']->getFilters());
$this->assertEquals(Vector {}, $routes['f3']->getFilters());
}
/**
* @expectedException \Titon\Route\Exception\MissingFilterException
*/
public function testFilterMissingKey(): void {
$this->object->getFilter('fakeKey');
}
public function testFilterIsTriggered(): void {
$router = new Router();
$count = 0;
$router->filterCallback('test', function($router, $route) use (&$count) {
$count++;
});
$router->map('f1', (new Route('/f1', 'Controller@action'))->addFilter('test'));
$router->group(($router, $group) ==> {
$group->setFilters(Vector {'test'});
$router->map('f2', new Route('/f2', 'Controller@action'));
});
$router->map('f3', new Route('/f3', 'Controller@action'));
$router->match('/f1');
$this->assertEquals(1, $count);
$router->match('/f2');
$this->assertEquals(2, $count);
$router->match('/f3');
$this->assertEquals(2, $count);
}
/**
* @expectedException \Exception
*/
public function testFilterCanThrowException(): void {
$this->object->filterCallback('test', () ==> {
throw new \Exception('Filter error!');
});
$this->object->map('root', (new Route('/', 'Controller@action'))->addFilter('test'));
$this->object->match('/');
}
public function testGroupPrefixing(): void {
$this->object->group(($router, $group) ==> {
$group->setPrefix('/pre/');
$router->map('group1', new Route('/group-1', 'Controller@action'));
$router->map('group2', new Route('/group-2', 'Controller@action'));
});
$this->object->map('solo', new Route('/solo', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals('/', $routes['root']->getPath());
$this->assertEquals('/pre/group-1', $routes['group1']->getPath());
$this->assertEquals('/pre/group-2', $routes['group2']->getPath());
$this->assertEquals('/solo', $routes['solo']->getPath());
}
public function testGroupSuffixing(): void {
$this->object->group(($router, $group) ==> {
$group->setSuffix('/post/');
$router->map('group1', new Route('/group-1', 'Controller@action'));
$router->map('group2', new Route('/group-2', 'Controller@action'));
});
$this->object->map('solo', new Route('/solo', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals('/', $routes['root']->getPath());
$this->assertEquals('/group-1/post', $routes['group1']->getPath());
$this->assertEquals('/group-2/post', $routes['group2']->getPath());
$this->assertEquals('/solo', $routes['solo']->getPath());
}
public function testGroupSecure(): void {
$this->object->group(($router, $group) ==> {
$group->setSecure(true);
$router->map('group1', new Route('/group-1', 'Controller@action'));
$router->map('group2', new Route('/group-2', 'Controller@action'));
});
$this->object->map('solo', new Route('/solo', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals(false, $routes['root']->getSecure());
$this->assertEquals(true, $routes['group1']->getSecure());
$this->assertEquals(true, $routes['group2']->getSecure());
$this->assertEquals(false, $routes['solo']->getSecure());
}
public function testGroupPatterns(): void {
$this->object->group(($router, $group) ==> {
$group->setPrefix('<token>');
$group->addPattern('token', '([abcd]+)');
$router->map('group1', new Route('/group-1', 'Controller@action'));
$router->map('group2', (new Route('/group-2', 'Controller@action'))->addPattern('foo', '(bar|baz)'));
});
$this->object->map('solo', new Route('/solo', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals('/', $routes['root']->getPath());
$this->assertEquals('/<token>/group-1', $routes['group1']->getPath());
$this->assertEquals('/<token>/group-2', $routes['group2']->getPath());
$this->assertEquals('/solo', $routes['solo']->getPath());
$this->assertEquals(Map {}, $routes['root']->getPatterns());
$this->assertEquals(Map {'token' => '([abcd]+)'}, $routes['group1']->getPatterns());
$this->assertEquals(Map {'foo' => '(bar|baz)', 'token' => '([abcd]+)'}, $routes['group2']->getPatterns());
$this->assertEquals(Map {}, $routes['solo']->getPatterns());
}
public function testGroupConditions(): void {
$cond1 = () ==> {};
$cond2 = () ==> {};
$this->object->group(($router, $group) ==> {
$group->setConditions(Vector {$cond1, $cond2});
$router->map('group1', new Route('/group-1', 'Controller@action'));
$router->map('group2', new Route('/group-2', 'Controller@action'));
});
$this->object->map('solo', new Route('/solo', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals(Vector {}, $routes['root']->getConditions());
$this->assertEquals(Vector {$cond1, $cond2}, $routes['group1']->getConditions());
$this->assertEquals(Vector {$cond1, $cond2}, $routes['group2']->getConditions());
$this->assertEquals(Vector {}, $routes['solo']->getConditions());
}
public function testGroupNesting(): void {
$this->object->group(($router, $group1) ==> {
$group1->setPrefix('/pre/');
$router->map('group1', new Route('/group-1', 'Controller@action'));
$router->group(($router, $group2) ==> {
$group2->setSuffix('/post');
$router->map('group2', new Route('/group-2', 'Controller@action'));
});
});
$this->object->map('solo', new Route('/solo', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals('/', $routes['root']->getPath());
$this->assertEquals('/pre/group-1', $routes['group1']->getPath());
$this->assertEquals('/pre/group-2/post', $routes['group2']->getPath());
$this->assertEquals('/solo', $routes['solo']->getPath());
}
public function testGroupNestingInherits(): void {
$this->object->group(($router, $group1) ==> {
$group1->setFilters(Vector {'foo'})->setMethods(Vector {'get'});
$router->map('group1', new Route('/group-1', 'Controller@action'));
$router->group(($router, $group2) ==> {
$group2->setFilters(Vector {'bar'});
$router->map('group2', new Route('/group-2', 'Controller@action'));
$router->group(($router, $group3) ==> {
$group3->setMethods(Vector {'post'});
$router->map('group3', new Route('/group-3', 'Controller@action'));
});
});
});
$routes = $this->object->getRoutes();
$this->assertEquals(Vector {'foo'}, $routes['group1']->getFilters());
$this->assertEquals(Vector {'foo', 'bar'}, $routes['group2']->getFilters());
$this->assertEquals(Vector {'foo', 'bar'}, $routes['group3']->getFilters());
$this->assertEquals(Vector {'get'}, $routes['group1']->getMethods());
$this->assertEquals(Vector {'get'}, $routes['group2']->getMethods());
$this->assertEquals(Vector {'get', 'post'}, $routes['group3']->getMethods());
}
public function testHttpMapping(): void {
$this->object->map('url1', new Route('/url', 'Controller@action'));
$this->object->get('url2', new Route('/url', 'Controller@action'));
$this->object->post('url3', new Route('/url', 'Controller@action'));
$this->object->put('url4', new Route('/url', 'Controller@action'));
$this->object->delete('url5', new Route('/url', 'Controller@action'));
$this->object->head('url6', new Route('/url', 'Controller@action'));
$this->object->options('url7', new Route('/url', 'Controller@action'));
$this->object->http('url8', Vector {'get', 'post'}, new Route('/url', 'Controller@action'));
$routes = $this->object->getRoutes();
$this->assertEquals(Vector {}, $routes['url1']->getMethods());
$this->assertEquals(Vector {'get'}, $routes['url2']->getMethods());
$this->assertEquals(Vector {'post'}, $routes['url3']->getMethods());
$this->assertEquals(Vector {'put'}, $routes['url4']->getMethods());
$this->assertEquals(Vector {'delete'}, $routes['url5']->getMethods());
$this->assertEquals(Vector {'head'}, $routes['url6']->getMethods());
$this->assertEquals(Vector {'options'}, $routes['url7']->getMethods());
$this->assertEquals(Vector {'get', 'post'}, $routes['url8']->getMethods());
}
public function testLoopMatch(): void {
$route = $this->object->match('/');
$this->assertEquals('/', $route->getPath());
$this->assertEquals($route, $this->object->current());
$route = $this->object->match('/users');
$this->assertEquals('/{module}', $route->getPath());
$route = $this->object->match('/users/profile');
$this->assertEquals('/{module}/{controller}', $route->getPath());
$route = $this->object->match('/users/profile/view');
$this->assertEquals('/{module}/{controller}/{action}', $route->getPath());
$route = $this->object->match('/users/profile/view.json');
$this->assertEquals('/{module}/{controller}/{action}.{ext}', $route->getPath());
}
/**
* @expectedException \Titon\Route\Exception\NoMatchException
*/
public function testLoopMatchNoMatch(): void {
$this->object->match('/path~tilde');
}
public function testParseAction(): void {
$this->assertEquals(shape(
'class' => 'Controller',
'action' => 'action'
), Router::parseAction('Controller@action'));
$this->assertEquals(shape(
'class' => 'Controller',
'action' => 'foo'
), Router::parseAction('Controller@foo'));
$this->assertEquals(shape(
'class' => 'Module\Controller',
'action' => 'index'
), Router::parseAction('Module\Controller@index'));
$this->assertEquals(shape(
'class' => 'Module\Controller_With_Underscores',
'action' => 'index'
), Router::parseAction('Module\Controller_With_Underscores@index'));
$this->assertEquals(shape(
'class' => 'Module\Controller_With_Numbers123',
'action' => 'index'
), Router::parseAction('Module\Controller_With_Numbers123@index'));
$this->assertEquals(shape(
'class' => 'Module\Controller',
'action' => 'action'
), Router::parseAction('Module\Controller@action'));
$this->assertEquals(shape(
'class' => 'Module\Controller',
'action' => 'multiWordAction'
), Router::parseAction('Module\Controller@multiWordAction'));
$this->assertEquals(shape(
'class' => 'Module\Controller',
'action' => 'action_with_underscores'
), Router::parseAction('Module\Controller@action_with_underscores'));
}
/**
* @expectedException \Titon\Route\Exception\InvalidRouteActionException
*/
public function testParseActionInvalidRoute(): void {
Router::parseAction('Broken+Route');
}
public function testPrgMapping(): void {
$this->object->prg('prg', (new Route('/foo', 'Controller@action'))->addFilter('auth'));
$routes = $this->object->getRoutes();
// Keys
$this->assertFalse(isset($routes['prg']));
$this->assertTrue(isset($routes['prg.get']));
$this->assertTrue(isset($routes['prg.post']));
// Paths
$this->assertEquals('/foo', $routes['prg.get']->getPath());
$this->assertEquals('/foo', $routes['prg.post']->getPath());
// Action
$this->assertEquals(shape('class' => 'Controller', 'action' => 'getAction'), $routes['prg.get']->getAction());
$this->assertEquals(shape('class' => 'Controller', 'action' => 'postAction'), $routes['prg.post']->getAction());
// Method
$this->assertEquals(Vector {'get'}, $routes['prg.get']->getMethods());
$this->assertEquals(Vector {'post'}, $routes['prg.post']->getMethods());
// Filters should be cloned also
$this->assertEquals(Vector {'auth'}, $routes['prg.get']->getFilters());
$this->assertEquals(Vector {'auth'}, $routes['prg.post']->getFilters());
}
public function testResourceMap(): void {
$this->assertEquals(Map {
'list' => 'index',
'create' => 'create',
'read' => 'read',
'update' => 'update',
'delete' => 'delete'
}, $this->object->getResourceMap());
$this->object->setResourceMap(Map {
'create' => 'add',
'read' => 'view',
'update' => 'edit',
'delete' => 'remove'
});
$this->assertEquals(Map {
'list' => 'index',
'create' => 'add',
'read' => 'view',
'update' => 'edit',
'delete' => 'remove'
}, $this->object->getResourceMap());
}
public function testResourceMapping(): void {
$this->object->resource('rest', new Route('/rest', 'Api\Rest@action'));
$routes = $this->object->getRoutes();
// Keys
$this->assertFalse(isset($routes['rest']));
$this->assertTrue(isset($routes['rest.list']));
$this->assertTrue(isset($routes['rest.create']));
$this->assertTrue(isset($routes['rest.read']));
$this->assertTrue(isset($routes['rest.update']));
$this->assertTrue(isset($routes['rest.delete']));
// Paths
$this->assertEquals('/rest', $routes['rest.list']->getPath());
$this->assertEquals('/rest', $routes['rest.create']->getPath());
$this->assertEquals('/rest/{id}', $routes['rest.read']->getPath());
$this->assertEquals('/rest/{id}', $routes['rest.update']->getPath());
$this->assertEquals('/rest/{id}', $routes['rest.delete']->getPath());
// Action
$this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'index'), $routes['rest.list']->getAction());
$this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'create'), $routes['rest.create']->getAction());
$this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'read'), $routes['rest.read']->getAction());
$this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'update'), $routes['rest.update']->getAction());
$this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'delete'), $routes['rest.delete']->getAction());
// Method
$this->assertEquals(Vector {'get'}, $routes['rest.list']->getMethods());
$this->assertEquals(Vector {'post'}, $routes['rest.create']->getMethods());
$this->assertEquals(Vector {'get'}, $routes['rest.read']->getMethods());
$this->assertEquals(Vector {'put', 'post'}, $routes['rest.update']->getMethods());
$this->assertEquals(Vector {'delete', 'post'}, $routes['rest.delete']->getMethods());
}
public function testRouteStubs(): void {
$route = new Route('/', 'Controller@action');
$router = new Router();
$router->map('key', $route);
$this->assertEquals($route, $router->getRoute('key'));
$this->assertEquals(Map {'key' => $route}, $router->getRoutes());
}
/**
* @expectedException \Titon\Route\Exception\MissingRouteException
*/
public function testRouteStubsMissingKey(): void {
$this->object->getRoute('fakeKey');
}
public function testWireClassMapping(): void {
$this->object->wire('Titon\Test\Stub\Route\RouteAnnotatedStub');
$routes = $this->object->getRoutes();
// Keys
$this->assertFalse(isset($routes['parent']));
$this->assertTrue(isset($routes['parent.list']));
$this->assertTrue(isset($routes['parent.create']));
$this->assertTrue(isset($routes['parent.read']));
$this->assertTrue(isset($routes['parent.update']));
$this->assertTrue(isset($routes['parent.delete']));
// Paths
$this->assertEquals('/controller', $routes['parent.list']->getPath());
$this->assertEquals('/controller', $routes['parent.create']->getPath());
$this->assertEquals('/controller/{id}', $routes['parent.read']->getPath());
$this->assertEquals('/controller/{id}', $routes['parent.update']->getPath());
$this->assertEquals('/controller/{id}', $routes['parent.delete']->getPath());
// Action
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'index'), $routes['parent.list']->getAction());
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'create'), $routes['parent.create']->getAction());
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'read'), $routes['parent.read']->getAction());
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'update'), $routes['parent.update']->getAction());
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'delete'), $routes['parent.delete']->getAction());
// Method
$this->assertEquals(Vector {'get'}, $routes['parent.list']->getMethods());
$this->assertEquals(Vector {'post'}, $routes['parent.create']->getMethods());
$this->assertEquals(Vector {'get'}, $routes['parent.read']->getMethods());
$this->assertEquals(Vector {'put', 'post'}, $routes['parent.update']->getMethods());
$this->assertEquals(Vector {'delete', 'post'}, $routes['parent.delete']->getMethods());
}
public function testWireMethodMapping(): void {
$this->object->wire('Titon\Test\Stub\Route\RouteAnnotatedStub');
$routes = $this->object->getRoutes();
// Keys
$this->assertTrue(isset($routes['foo']));
$this->assertTrue(isset($routes['bar']));
$this->assertTrue(isset($routes['baz']));
$this->assertTrue(isset($routes['qux']));
// Paths
$this->assertEquals('/foo', $routes['foo']->getPath());
$this->assertEquals('/bar', $routes['bar']->getPath());
$this->assertEquals('/baz', $routes['baz']->getPath());
$this->assertEquals('/qux', $routes['qux']->getPath());
// Action
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'foo'), $routes['foo']->getAction());
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'bar'), $routes['bar']->getAction());
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'baz'), $routes['baz']->getAction());
$this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'qux'), $routes['qux']->getAction());
// Method
$this->assertEquals(Vector {}, $routes['foo']->getMethods());
$this->assertEquals(Vector {'post'}, $routes['bar']->getMethods());
$this->assertEquals(Vector {'get'}, $routes['baz']->getMethods());
$this->assertEquals(Vector {'put', 'post'}, $routes['qux']->getMethods());
// Filter
$this->assertEquals(Vector {}, $routes['foo']->getFilters());
$this->assertEquals(Vector {}, $routes['bar']->getFilters());
$this->assertEquals(Vector {'auth', 'guest'}, $routes['baz']->getFilters());
$this->assertEquals(Vector {}, $routes['qux']->getFilters());
// Pattern
$this->assertEquals(Map {}, $routes['foo']->getPatterns());
$this->assertEquals(Map {}, $routes['bar']->getPatterns());
$this->assertEquals(Map {}, $routes['baz']->getPatterns());
$this->assertEquals(Map {'id' => '[1-8]+'}, $routes['qux']->getPatterns());
}
}
| 41.864818 | 151 | 0.569382 | ciklon-z |
1849d981ceba91e60cfe1f51ab8e262572a514cf | 2,779 | cc | C++ | Lacewing/src/cxx/filter2.cc | SortaCore/bluewing-cpp-server | 14fa85d7493cde2a62cc84183032f5d240dc3743 | [
"MIT"
] | 2 | 2021-07-17T21:08:47.000Z | 2021-07-25T08:50:27.000Z | Lacewing/src/cxx/filter2.cc | SortaCore/bluewing-cpp-server | 14fa85d7493cde2a62cc84183032f5d240dc3743 | [
"MIT"
] | null | null | null | Lacewing/src/cxx/filter2.cc | SortaCore/bluewing-cpp-server | 14fa85d7493cde2a62cc84183032f5d240dc3743 | [
"MIT"
] | 2 | 2019-09-08T10:00:42.000Z | 2020-11-11T20:49:38.000Z |
/* vim: set et ts=3 sw=3 ft=cpp:
*
* Copyright (C) 2012, 2013 James McLaughlin et al. 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 THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "../common.h"
filter lacewing::filter_new ()
{
return (filter) lw_filter_new ();
}
void lacewing::filter_delete (lacewing::filter filter)
{
lw_filter_delete ((lw_filter) filter);
}
void _filter::local (address addr)
{
lw_filter_set_local ((lw_filter) this, (lw_addr) addr);
}
void _filter::remote (address addr)
{
lw_filter_set_remote ((lw_filter) this, (lw_addr) addr);
}
address _filter::local ()
{
return (address) lw_filter_local ((lw_filter) this);
}
address _filter::remote ()
{
return (address) lw_filter_remote ((lw_filter) this);
}
long _filter::local_port ()
{
return lw_filter_local_port ((lw_filter) this);
}
void _filter::local_port (long port)
{
lw_filter_set_local_port ((lw_filter) this, port);
}
long _filter::remote_port ()
{
return lw_filter_remote_port ((lw_filter) this);
}
void _filter::remote_port (long port)
{
lw_filter_set_remote_port ((lw_filter) this, port);
}
bool _filter::reuse ()
{
return lw_filter_reuse ((lw_filter) this);
}
void _filter::reuse (bool reuse)
{
lw_filter_set_reuse ((lw_filter) this, reuse);
}
bool _filter::ipv6 ()
{
return lw_filter_ipv6 ((lw_filter) this);
}
void _filter::ipv6 (bool ipv6)
{
lw_filter_set_ipv6 ((lw_filter) this, ipv6);
}
void * _filter::tag ()
{
return lw_filter_tag ((lw_filter) this);
}
void _filter::tag (void * tag)
{
lw_filter_set_tag ((lw_filter) this, tag);
}
| 24.8125 | 77 | 0.738035 | SortaCore |
184c55598661b95d8dff818e631ad839701b49fd | 1,677 | hpp | C++ | libs/core/include/core/containers/set_difference.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | 1 | 2019-09-11T09:46:04.000Z | 2019-09-11T09:46:04.000Z | libs/core/include/core/containers/set_difference.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | null | null | null | libs/core/include/core/containers/set_difference.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | 1 | 2019-09-19T12:38:46.000Z | 2019-09-19T12:38:46.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 <algorithm>
#include <iterator>
#include <unordered_map>
#include <unordered_set>
namespace fetch {
template <typename K>
std::unordered_set<K> operator-(std::unordered_set<K> const &lhs, std::unordered_set<K> const &rhs)
{
std::unordered_set<K> result;
std::copy_if(lhs.begin(), lhs.end(), std::inserter(result, result.begin()),
[&rhs](K const &item) { return rhs.find(item) == rhs.end(); });
return result;
}
template <typename K, typename V, typename H>
std::unordered_set<K, H> operator-(std::unordered_set<K, H> const & lhs,
std::unordered_map<K, V, H> const &rhs)
{
std::unordered_set<K> result;
std::copy_if(lhs.begin(), lhs.end(), std::inserter(result, result.begin()),
[&rhs](K const &item) { return rhs.find(item) == rhs.end(); });
return result;
}
} // namespace fetch
| 32.882353 | 99 | 0.601073 | devjsc |
184f32469faf8b91612fcddd71a61b81fd04f66e | 520 | cpp | C++ | Code-Chef/easy/RESQ.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | 1 | 2019-05-20T14:38:05.000Z | 2019-05-20T14:38:05.000Z | Code-Chef/easy/RESQ.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | null | null | null | Code-Chef/easy/RESQ.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main(int argc, char const *argv[])
{
ll t;
cin>>t;
while(t--)
{
ll n,i=1,val,c=INT_MAX;
cin>>n;
while(i*i<=n)
{
if(n%i==0)
{
val=n/i;
if(i!=val) val=abs(val-i);
else val=0;
if(val<c) c=val;
}
if(c==0) break;
i++;
}
cout<<c<<'\n';
}
return 0;
}
| 16.774194 | 42 | 0.361538 | kishorevarma369 |
1850257d868f83544e8335089ad0962fbf99dc43 | 2,640 | cpp | C++ | source/Transcriptome_geneCountsAddAlign.cpp | Gavin-Lijy/STAR | 4571190968fc134aa4bd0d4d7065490253b1a4c5 | [
"MIT"
] | 1,315 | 2015-01-07T02:03:15.000Z | 2022-03-30T09:48:17.000Z | source/Transcriptome_geneCountsAddAlign.cpp | Gavin-Lijy/STAR | 4571190968fc134aa4bd0d4d7065490253b1a4c5 | [
"MIT"
] | 1,429 | 2015-01-08T00:09:17.000Z | 2022-03-31T08:12:14.000Z | source/Transcriptome_geneCountsAddAlign.cpp | Gavin-Lijy/STAR | 4571190968fc134aa4bd0d4d7065490253b1a4c5 | [
"MIT"
] | 495 | 2015-01-23T20:00:45.000Z | 2022-03-31T13:24:50.000Z | #include "Transcriptome.h"
#include "serviceFuns.cpp"
void Transcriptome::geneCountsAddAlign(uint nA, Transcript **aAll, vector<int32> &gene1) {
gene1.assign(quants->geneCounts.nType,-1);
if (nA>1) {
quants->geneCounts.cMulti++;
} else {
Transcript& a=*aAll[0];//one unique alignment only
int64 e1=-1;
for (int ib=a.nExons-1; ib>=0; ib--) {//scan through all blocks of the alignments
uint64 g1=a.exons[ib][EX_G]+a.exons[ib][EX_L]-1;//end of the block
// if ((uint)ib==a.nExons-1)
// {//binary search for the first time: end of the block among the starts of exons
e1=binarySearch1a<uint64>(g1, exG.s, (int32) exG.nEx);
// } else
// {//simple backwards scan
// while (e1>=0 && exG.s[e1]>g1)
// {//stop when exon start is less than block end
// --e1;
// };
// };
while (e1>=0 && exG.eMax[e1]>=a.exons[ib][EX_G]) {//these exons may overlap this block
if (exG.e[e1]>=a.exons[ib][EX_G]) {//this exon overlaps the block
uint str1=(uint)exG.str[e1]-1;
for (int itype=0; itype<quants->geneCounts.nType; itype++) {
//str1<2 (i.e. strand=0) requirement means that genes w/o strand will accept reads from both strands
if ( itype==1 && a.Str!=str1 && str1<2) continue; //same strand
if ( itype==2 && a.Str==str1 && str1<2) continue; //reverse strand
if (gene1.at(itype)==-1) {//first gene overlapping this read
gene1[itype]=exG.g[e1];
} else if (gene1.at(itype)==-2) {
continue;//this align was already found to be ambig for this strand
} else if (gene1.at(itype)!=(int32)exG.g[e1]) {//another gene overlaps this read
gene1[itype]=-2;//mark ambiguous
};//otherwise it's the same gene
};
};
--e1;// go to the previous exon
};
};
for (int itype=0; itype<quants->geneCounts.nType; itype++) {
if (gene1.at(itype)==-1) {
quants->geneCounts.cNone[itype]++;
} else if (gene1.at(itype)==-2) {
quants->geneCounts.cAmbig[itype]++;
} else {
quants->geneCounts.gCount[itype][gene1.at(itype)]++;
};
};
};
};
| 41.25 | 125 | 0.481061 | Gavin-Lijy |
185136c00cc13479752b2120e562a951fd07c971 | 1,542 | cpp | C++ | src/repeater_firing_result.cpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 4 | 2016-07-05T07:42:07.000Z | 2020-07-15T15:27:22.000Z | src/repeater_firing_result.cpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 1 | 2020-05-07T20:58:21.000Z | 2020-05-07T20:58:21.000Z | src/repeater_firing_result.cpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014 Matthew Harvey
*
* 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 "repeater_firing_result.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <sqloxx/id.hpp>
using sqloxx::Id;
namespace gregorian = boost::gregorian;
namespace dcm
{
RepeaterFiringResult::RepeaterFiringResult
( Id p_draft_journal_id,
gregorian::date const& p_firing_date,
bool p_successful
):
m_draft_journal_id(p_draft_journal_id),
m_firing_date(p_firing_date),
m_successful(p_successful)
{
}
Id
RepeaterFiringResult::draft_journal_id() const
{
return m_draft_journal_id;
}
gregorian::date
RepeaterFiringResult::firing_date() const
{
return m_firing_date;
}
bool
RepeaterFiringResult::successful() const
{
return m_successful;
}
void
RepeaterFiringResult::mark_as_successful()
{
m_successful = true;
return;
}
bool
operator<(RepeaterFiringResult const& lhs, RepeaterFiringResult const& rhs)
{
return lhs.firing_date() < rhs.firing_date();
}
} // namespace dcm
| 21.71831 | 75 | 0.748379 | skybaboon |
4c75092335ad9deed6540605874af80c92dc45d4 | 7,375 | cpp | C++ | Game/Client/WXCore/Core/TerrainTileOptimized.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/Client/WXCore/Core/TerrainTileOptimized.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/Client/WXCore/Core/TerrainTileOptimized.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | #include "TerrainTileOptimized.h"
#include "Terrain.h"
#include "TerrainTileRenderable.h"
#include <OgreSceneManager.h>
#include <OgreSceneNode.h>
namespace WX {
class TerrainTileOptimizedRenderable : public TerrainTileRenderable
{
public:
TerrainTileOptimizedRenderable(TerrainTile *parent)
: TerrainTileRenderable(parent)
{
}
~TerrainTileOptimizedRenderable()
{
// Only vertex data need to delete
delete mRenderOp.vertexData;
}
};
//-----------------------------------------------------------------------
TerrainTileOptimized::TerrainTileOptimized(Ogre::SceneNode* parent, Terrain *owner,
int xbase, int zbase, int xsize, int zsize)
: TerrainTile(parent, owner, xbase, zbase, xsize, zsize)
, mRenderables()
, mGeometryOutOfDate(true)
{
}
TerrainTileOptimized::~TerrainTileOptimized()
{
destoryGeometry();
}
//-----------------------------------------------------------------------
const String&
TerrainTileOptimized::getMovableType(void) const
{
static const String type = "TerrainTileOptimized";
return type;
}
void
TerrainTileOptimized::_updateRenderQueue(Ogre::RenderQueue* queue)
{
if (mGeometryOutOfDate)
{
createGeometry(mOwner->getData(), mXBase, mZBase, mXSize, mZSize);
}
queueRenderables(queue, mRenderables);
}
//-----------------------------------------------------------------------
void
TerrainTileOptimized::destoryGeometry(void)
{
destroyRenderables(mRenderables);
mGeometryOutOfDate = true;
}
void
TerrainTileOptimized::createGeometry(TerrainData* data, int xbase, int zbase, int xsize, int zsize)
{
destoryGeometry();
// build the material backet map
MaterialBucketMap materialBucketMap;
buildMaterialBucketMap(materialBucketMap);
// statistic number grids for each layer
size_t numGridsOfLayer[2] = { 0 };
for (MaterialBucketMap::const_iterator im = materialBucketMap.begin(); im != materialBucketMap.end(); ++im)
{
numGridsOfLayer[im->second.layerIndex] += im->second.grids.size();
}
bool includeLightmap = mOwner->_isLightmapUsed();
// create vertex buffer and lock it
Ogre::VertexData vertexDatas[2];
Ogre::HardwareVertexBufferSharedPtr buffers[2];
float* pBuffers[2] = { NULL };
for (size_t layerIndex = 0; layerIndex < 2; ++layerIndex)
{
if (!numGridsOfLayer[layerIndex])
continue;
enum
{
MAIN_BINDING,
};
Ogre::VertexDeclaration* decl = vertexDatas[layerIndex].vertexDeclaration;
Ogre::VertexBufferBinding* bind = vertexDatas[layerIndex].vertexBufferBinding;
vertexDatas[layerIndex].vertexStart = 0;
vertexDatas[layerIndex].vertexCount = numGridsOfLayer[layerIndex] * 4;
size_t offset = 0;
size_t texCoordSet = 0;
// positions
decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
offset += 3 * sizeof(float);
// normals
decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL);
offset += 3 * sizeof(float);
// texture layer 0
decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, texCoordSet++);
offset += 2 * sizeof(float);
// texture layer 1
if (layerIndex == 1)
{
decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, texCoordSet++);
offset += 2 * sizeof(float);
}
// light-map layer
if (includeLightmap)
{
decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, texCoordSet++);
offset += 2 * sizeof(float);
}
buffers[layerIndex] =
Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING),
vertexDatas[layerIndex].vertexCount,
Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
bind->setBinding(MAIN_BINDING, buffers[layerIndex]);
pBuffers[layerIndex] = static_cast<float*>(buffers[layerIndex]->lock(Ogre::HardwareBuffer::HBL_DISCARD));
}
Real xscale = 1.0 / xsize;
Real zscale = 1.0 / zsize;
// build renderables, group by material
size_t vertexStarts[2] = { 0 };
for (MaterialBucketMap::const_iterator im = materialBucketMap.begin(); im != materialBucketMap.end(); ++im)
{
TerrainTileOptimizedRenderable* renderable = new TerrainTileOptimizedRenderable(this);
mRenderables.push_back(renderable);
const MaterialBucket* mb = &im->second;
size_t layerIndex = mb->layerIndex;
size_t numQuads = mb->grids.size();
size_t vertexCount = numQuads * 4;
renderable->mMaterial = mb->material;
// Clone vertex data but shared vertex buffers
Ogre::VertexData* vertexData = vertexDatas[layerIndex].clone(false);
vertexData->vertexStart = vertexStarts[layerIndex];
vertexData->vertexCount = vertexCount;
renderable->mRenderOp.vertexData = vertexData;
renderable->mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
renderable->mRenderOp.useIndexes = true;
renderable->mRenderOp.indexData = mOwner->_getIndexData(numQuads);
float* pFloat = pBuffers[layerIndex];
for (GridIdList::const_iterator igrid = mb->grids.begin(); igrid != mb->grids.end(); ++igrid)
{
size_t grid = *igrid;
const TerrainData::GridInfo& gridInfo = data->mGridInfos[grid];
const TerrainData::Corner* corners = gridInfo.getCorners();
int x = grid % data->mXSize;
int z = grid / data->mXSize;
// NB: Store the quad vertices in clockwise order, index data will
// take care with this.
for (size_t i = 0; i < 4; ++i)
{
Ogre::Vector3 v;
std::pair<Real, Real> t;
TerrainData::Corner corner = corners[i];
// position
v = data->_getPosition((x+(corner&1)), (z+(corner>>1)));
*pFloat++ = v.x; *pFloat++ = v.y; *pFloat++ = v.z;
// normal
v = data->_getNormal((x+(corner&1)), (z+(corner>>1)));
*pFloat++ = v.x; *pFloat++ = v.y; *pFloat++ = v.z;
// layer 0
t = mOwner->_getPixmapCorner(gridInfo.layers[0], corner, gridInfo.flags);
*pFloat++ = t.first; *pFloat++ = t.second;
// layer 1
if (gridInfo.layers[1].pixmapId)
{
t = mOwner->_getPixmapCorner(gridInfo.layers[1], corner, gridInfo.flags);
*pFloat++ = t.first; *pFloat++ = t.second;
}
// light-map
if (includeLightmap)
{
*pFloat++ = xscale * (x - xbase + (corner&1));
*pFloat++ = zscale * (z - zbase + (corner>>1));
}
}
}
pBuffers[layerIndex] = pFloat;
vertexStarts[layerIndex] += vertexCount;
}
// unlock vertex buffer
for (size_t layerIndex = 0; layerIndex < 2; ++layerIndex)
{
if (!buffers[layerIndex].isNull())
buffers[layerIndex]->unlock();
}
mGeometryOutOfDate = false;
}
}
| 33.220721 | 115 | 0.599729 | hackerlank |
4c77b4642b45cbc045a61b46666e3907b1ab53c3 | 762 | cpp | C++ | 3rdparty/eigen3/test/signTest.cpp | OpenMA/openma | 6f3b55292fd0a862b3444f11d71d0562cfe81ac1 | [
"Unlicense"
] | 41 | 2016-06-28T13:51:39.000Z | 2022-01-20T16:33:00.000Z | 3rdparty/eigen3/test/signTest.cpp | bmswgnp/openma | 6f3b55292fd0a862b3444f11d71d0562cfe81ac1 | [
"Unlicense"
] | 82 | 2016-04-09T15:19:31.000Z | 2018-11-15T18:56:12.000Z | 3rdparty/eigen3/test/signTest.cpp | bmswgnp/openma | 6f3b55292fd0a862b3444f11d71d0562cfe81ac1 | [
"Unlicense"
] | 9 | 2016-03-29T14:28:31.000Z | 2020-07-29T07:39:19.000Z | #include <cxxtest/TestDrive.h>
#include <Eigen_openma/Utils/sign.h>
CXXTEST_SUITE(SignTest)
{
CXXTEST_TEST(positive)
{
TS_ASSERT_EQUALS(sign(1292) > 0, true);
TS_ASSERT_EQUALS(sign(9999) > 0, true);
TS_ASSERT_EQUALS(sign(1) > 0, true);
};
CXXTEST_TEST(negative)
{
TS_ASSERT_EQUALS(sign(-11) < 0, true);
TS_ASSERT_EQUALS(sign(-5000) < 0, true);
TS_ASSERT_EQUALS(sign(-1) < 0, true);
};
CXXTEST_TEST(null)
{
TS_ASSERT_EQUALS(sign(+0) == 0, true);
TS_ASSERT_EQUALS(sign(-0) == 0, true);
TS_ASSERT_EQUALS(sign(0) == 0, true);
};
};
CXXTEST_SUITE_REGISTRATION(SignTest)
CXXTEST_TEST_REGISTRATION(SignTest, positive)
CXXTEST_TEST_REGISTRATION(SignTest, negative)
CXXTEST_TEST_REGISTRATION(SignTest, null)
| 23.090909 | 45 | 0.691601 | OpenMA |
4c7949b64ead14c6e43e448268b857d014f3665b | 3,321 | hpp | C++ | external/swak/libraries/simpleSearchableSurfaces/Transformations/rotateSearchableSurface.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/simpleSearchableSurfaces/Transformations/rotateSearchableSurface.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/simpleSearchableSurfaces/Transformations/rotateSearchableSurface.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright: ICE Stroemungsfoschungs GmbH
Copyright held by original author
-------------------------------------------------------------------------------
License
This file is based on CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::rotateSearchableSurface
Description
Searching on rotated surface
SourceFiles
rotateSearchableSurface.cpp
Contributors/Copyright:
2009, 2013-2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at>
\*---------------------------------------------------------------------------*/
#ifndef rotateSearchableSurface_H
#define rotateSearchableSurface_H
#include "transformationSearchableSurface.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
// Forward declaration of classes
/*---------------------------------------------------------------------------*\
Class rotateSearchableSurface Declaration
\*---------------------------------------------------------------------------*/
class rotateSearchableSurface
:
public transformationSearchableSurface
{
private:
// Private Member Data
tensor rotation_;
tensor backRotation_;
//- Disallow default bitwise copy construct
rotateSearchableSurface(const rotateSearchableSurface&);
//- Disallow default bitwise assignment
void operator=(const rotateSearchableSurface&);
protected:
// Do the transformation for a point
virtual point transform(const point &) const;
// Do the inverse transformation for a point
virtual point inverseTransform(const point &) const;
public:
//- Runtime type information
TypeName("rotate");
// Constructors
//- Construct from components
rotateSearchableSurface(const IOobject& io, const treeBoundBox& bb);
//- Construct from dictionary (used by transformationSearchableSurface)
rotateSearchableSurface
(
const IOobject& io,
const dictionary& dict
);
// Destructor
virtual ~rotateSearchableSurface();
//- From a set of points and indices get the normal
virtual void getNormal
(
const List<pointIndexHit>&,
vectorField& normal
) const;
virtual void boundingSpheres
(
pointField& centres,
scalarField& radiusSqr
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 27 | 79 | 0.551039 | MrAwesomeRocks |
4c7c38d24cae81840f1295d3a38f43b657403330 | 531 | cpp | C++ | code/tst/utility/array.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 3 | 2020-04-29T14:55:58.000Z | 2020-08-20T08:43:24.000Z | code/tst/utility/array.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 1 | 2022-03-12T11:37:46.000Z | 2022-03-12T20:17:38.000Z | code/tst/utility/array.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | null | null | null | #include "utility/array.hpp"
#include <catch2/catch.hpp>
#include <array>
TEST_CASE( "array_span", "[utility]" )
{
auto myarray = std::array<int, 7>{{1, 2, 3, 4, 5, 6, 7}};
auto myarrayspan = utility::make_array_span(myarray);
(void)myarrayspan; // fix warning about not being used
// auto myhalfspan = make_array_span<3>(myarrayspan.begin() + 2);
// iterator_traits:
// * access the underlaying type?
//auto kjhs = utility::array_span<int, 3>{myarray.begin() + 2};
//(void)kjhs; // fix warning about not being used
}
| 26.55 | 66 | 0.677966 | shossjer |
4c826bd4ebdbef1d135ec2ba108d48d69bbe8ecd | 1,839 | cpp | C++ | core/graphics/geom/Area.cpp | yangxlei/F2Native | 69a27994ccb0be65ce6f905ed258f5dc286cbb70 | [
"MIT"
] | 178 | 2020-11-16T06:35:02.000Z | 2022-03-28T07:41:47.000Z | core/graphics/geom/Area.cpp | yangxlei/F2Native | 69a27994ccb0be65ce6f905ed258f5dc286cbb70 | [
"MIT"
] | 9 | 2020-11-21T03:56:02.000Z | 2022-03-07T11:12:03.000Z | core/graphics/geom/Area.cpp | yangxlei/F2Native | 69a27994ccb0be65ce6f905ed258f5dc286cbb70 | [
"MIT"
] | 16 | 2020-11-20T15:54:19.000Z | 2022-03-21T10:12:30.000Z | #include "Area.h"
#include "graphics/XChart.h"
using namespace xg;
nlohmann::json geom::Area::CreateShapePointsCfg(XChart &chart, nlohmann::json &data) {
auto &xScale = chart.GetScale(GetXScaleField());
auto &yScale = chart.GetScale(GetYScaleField());
nlohmann::json &xVal = data[GetXScaleField()];
nlohmann::json &yVal = data[GetYScaleField()];
nlohmann::json rst;
rst["x"] = xScale.Scale(xVal);
if(yVal.is_array()) {
nlohmann::json yRst;
for(std::size_t index = 0; index < yVal.size(); ++index) {
yRst.push_back(yScale.Scale(yVal[index]));
}
rst["y"] = yRst;
} else {
rst["y"] = yScale.Scale(yVal);
}
rst["y0"] = yScale.Scale(this->GetYMinValue(chart));
return rst;
}
nlohmann::json geom::Area::GetAreaPoints(XChart &chart, nlohmann::json &data, nlohmann::json &cfg) {
auto &x = cfg["x"];
auto &y = cfg["y"];
auto &y0 = cfg["y0"];
if(!y.is_array()) {
y = {y0, y};
}
return {{{"x", x}, {"y", y[0]}}, {{"x", x}, {"y", y[1]}}};
}
void geom::Area::BeforeMapping(XChart &chart, nlohmann::json &dataArray) {
auto &xScale = chart.GetScale(GetXScaleField());
for(std::size_t i = 0; i < dataArray.size(); ++i) {
nlohmann::json &groupData = dataArray[i];
std::size_t start = 0, end = groupData.size() - 1;
if(scale::IsCategory(xScale.GetType())) {
start = fmax(start, xScale.min);
end = fmin(end, xScale.max);
}
for(std::size_t index = start; index <= end; ++index) {
nlohmann::json &data = groupData[index];
nlohmann::json cfg = CreateShapePointsCfg(chart, data);
nlohmann::json points = GetAreaPoints(chart, data, cfg);
data["_points"] = points;
}
// nextPoints.
}
}
| 30.65 | 100 | 0.566069 | yangxlei |
4c8450c141f087fb9a3b5f30a9063fdb6203b5e9 | 492 | cpp | C++ | REDSI_1160929_1161573/boost_1_67_0/libs/log/config/visibility/visibility.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 1 | 2018-12-15T19:57:24.000Z | 2018-12-15T19:57:24.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/log/config/visibility/visibility.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | null | null | null | REDSI_1160929_1161573/boost_1_67_0/libs/log/config/visibility/visibility.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 1 | 2019-03-08T11:06:22.000Z | 2019-03-08T11:06:22.000Z | /*
* Copyright Andrey Semashev 2007 - 2015.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
// Guess what, MSVC doesn't ever fail on unknown options, even with /WX. Hence this additional check.
#if !defined(__GNUC__)
#error Visibility option is only supported by gcc and compatible compilers
#endif
int main(int, char*[])
{
return 0;
}
| 28.941176 | 102 | 0.674797 | Wultyc |
4c856d5befa26187a9e2e0b1d896e28c95e005a8 | 98,864 | cxx | C++ | ds/ds/src/ldap/client/open.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/ds/src/ldap/client/open.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/ds/src/ldap/client/open.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
open.cxx open a connection to an LDAP server
Abstract:
This module implements the LDAP ldap_open API.
Author:
Andy Herron (andyhe) 08-May-1996
Anoop Anantha (AnoopA) 24-Jun-1998
Revision History:
--*/
#include "precomp.h"
#pragma hdrstop
#include "ldapp2.hxx"
#include <dststlog.h>
#define LDAP_CONNECT_TIMEOUT 45 // seconds
#define MAX_PARALLEL_CONNECTS 20 // Limited to 64 because select can't handle more
#define CONNECT_INTERVAL 100 // milliseconds
#define MAX_SOCK_ADDRS 100 // max number of records we will retrieve
#define SAMESITE_CONNECT_TIMEOUT 10 // seconds for intra site connections
#define LDAP_QUICK_TIMEOUT 2 // in seconds to accomodate high latency links.
DEFINE_DSLOG;
LDAP *LdapConnectionOpen (
PWCHAR HostName,
ULONG PortNumber,
BOOLEAN Udp
);
INT
OpenLdapServer (
PLDAP_CONN Connection,
struct l_timeval *timeout
);
ULONG
LdapWinsockConnect (
PLDAP_CONN Connection,
USHORT PortNumber,
PWCHAR HostName,
struct l_timeval *timeout,
BOOLEAN samesite
);
BOOLEAN
LdapIsAddressNumeric (
PWCHAR HostName
);
struct hostent *
GetHostByNameW(
PWCHAR hostName
);
ULONG
Inet_addrW(
PWCHAR IpAddressW
);
ULONG
GetCurrentMachineParams(
PWCHAR* Address,
PWCHAR* DnsHostName
);
ULONG
GetPrimaryDomainName(
PWCHAR* pDomainName
);
//
// This routine is one of the main entry points for clients calling into the
// ldap API. The Hostname is a list of 0 to n hosts, separated by spaces.
// The host name can be either a name or a TCP address of the form
// nnn.nnn.nnn.nnn.
//
LDAP * __cdecl ldap_openW (
PWCHAR HostName,
ULONG PortNumber
)
{
return LdapConnectionOpen( HostName, PortNumber, FALSE );
}
//
// This routine is one of the main entry points for clients calling into the
// ldap API. The Hostname is a list of 0 to n hosts, separated by spaces.
// The host name can be either a name or a TCP address of the form
// nnn.nnn.nnn.nnn.
//
LDAP * __cdecl ldap_open (
PCHAR HostName,
ULONG PortNumber
)
{
LDAP* ExternalHandle = NULL;
ULONG err;
PWCHAR wHostName = NULL;
err = ToUnicodeWithAlloc( HostName,
-1,
&wHostName,
LDAP_UNICODE_SIGNATURE,
LANG_ACP );
if (err == LDAP_SUCCESS) {
ExternalHandle = LdapConnectionOpen( wHostName, PortNumber, FALSE );
}
ldapFree(wHostName, LDAP_UNICODE_SIGNATURE);
return ExternalHandle;
}
LDAP * __cdecl cldap_open (
PCHAR HostName,
ULONG PortNumber
)
{
LDAP* ExternalHandle = NULL;
ULONG err;
PWCHAR wHostName = NULL;
err = ToUnicodeWithAlloc( HostName,
-1,
&wHostName,
LDAP_UNICODE_SIGNATURE,
LANG_ACP );
if (err == LDAP_SUCCESS) {
ExternalHandle = LdapConnectionOpen( wHostName, PortNumber, TRUE );
}
ldapFree(wHostName, LDAP_UNICODE_SIGNATURE);
return ExternalHandle;
}
LDAP * __cdecl cldap_openW (
PWCHAR HostName,
ULONG PortNumber
)
{
return LdapConnectionOpen( HostName, PortNumber, TRUE );
}
LDAP * __cdecl ldap_sslinit (
PCHAR HostName,
ULONG PortNumber,
int Secure
)
{
LDAP* connection = NULL;
ULONG err;
PWCHAR wHostName = NULL;
err = ToUnicodeWithAlloc( HostName,
-1,
&wHostName,
LDAP_UNICODE_SIGNATURE,
LANG_ACP );
if (err == LDAP_SUCCESS) {
connection = ldap_sslinitW( wHostName, PortNumber,(ULONG) Secure );
}
ldapFree(wHostName, LDAP_UNICODE_SIGNATURE);
return connection;
}
LDAP * __cdecl ldap_init (
PCHAR HostName,
ULONG PortNumber
)
{
return ldap_sslinit( HostName, PortNumber, 0 );
}
LDAP * __cdecl ldap_initW (
PWCHAR HostName,
ULONG PortNumber
)
{
return ldap_sslinitW( HostName, PortNumber, 0 );
}
LDAP * __cdecl ldap_sslinitW (
PWCHAR HostName,
ULONG PortNumber,
int Secure
)
{
PLDAP_CONN connection;
connection = LdapAllocateConnection( HostName, PortNumber, (ULONG) Secure, FALSE );
if (connection == NULL) {
return NULL;
}
//
// No locks needed - not yet added to connection list
//
connection->HandlesGivenToCaller++;
//
// Add it to global list of connections
//
ACQUIRE_LOCK( &ConnectionListLock );
InsertTailList( &GlobalListActiveConnections, &connection->ConnectionListEntry );
RELEASE_LOCK( &ConnectionListLock );
DereferenceLdapConnection( connection );
return connection->ExternalInfo;
}
LDAP_CONN * LdapAllocateConnection (
PWCHAR HostName,
ULONG PortNumber,
ULONG Secure,
BOOLEAN Udp
)
//
// This routine creates a data block containing instance data for a connection.
//
// Must return a Win32 error code.
//
{
PLDAP_CONN connection = NULL;
ULONG err;
HANDLE hConnectEvent = NULL;
DWORD dwCritSectInitStage = 0;
if (LdapInitializeWinsock() == FALSE) {
IF_DEBUG(ERRORS) {
LdapPrint1( "LdapAllocateConnection could not initialize winsock, 0x%x.\n", GetLastError());
}
SetLastError( ERROR_NETWORK_UNREACHABLE );
SetConnectionError(NULL, LDAP_CONNECT_ERROR, NULL);
return NULL;
}
(VOID) LdapInitSecurity();
hConnectEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
if (hConnectEvent == NULL) {
IF_DEBUG(ERRORS) {
LdapPrint1( "LdapAllocateConnection could not alloc event, 0x%x.\n", GetLastError());
}
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
SetConnectionError(NULL, LDAP_NO_MEMORY, NULL);
return NULL;
}
//
// allocate the connection block and setup all the initial values
//
connection = (PLDAP_CONN) ldapMalloc( sizeof( LDAP_CONN ), LDAP_CONN_SIGNATURE );
if (connection == NULL) {
IF_DEBUG(OUTMEMORY) {
LdapPrint1( "ldap_open could not allocate 0x%x bytes.\n", sizeof( LDAP_CONN ) );
}
CloseHandle( hConnectEvent );
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
SetConnectionError(NULL, LDAP_NO_MEMORY, NULL);
return NULL;
}
if (HostName != NULL) {
connection->ListOfHosts = ldap_dup_stringW( HostName, 0, LDAP_HOST_NAME_SIGNATURE );
if (connection->ListOfHosts == NULL) {
IF_DEBUG(OUTMEMORY) {
LdapPrint1( "ldap_open could not allocate mem for %s\n", HostName );
}
ldapFree( connection, LDAP_CONN_SIGNATURE );
CloseHandle( hConnectEvent );
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
SetConnectionError(NULL, LDAP_NO_MEMORY, NULL);
return NULL;
}
}
InterlockedIncrement( &GlobalConnectionCount );
//
// keep in mind the memory is already zero initialized
//
connection->ReferenceCount = 2;
connection->ConnectEvent = hConnectEvent;
connection->ConnObjectState = ConnObjectActive;
connection->publicLdapStruct.ld_options = LDAP_OPT_DNS |
LDAP_OPT_CHASE_REFERRALS |
LDAP_CHASE_SUBORDINATE_REFERRALS |
LDAP_CHASE_EXTERNAL_REFERRALS;
connection->PortNumber = LOWORD( PortNumber );
connection->AREC_Exclusive = FALSE;
connection->ExternalInfo = &connection->publicLdapStruct;
connection->publicLdapStruct.ld_version = ( Udp ? LDAP_VERSION3 : LDAP_VERSION2 );
connection->HighestSupportedLdapVersion = LDAP_VERSION2;
connection->TcpHandle = INVALID_SOCKET;
connection->UdpHandle = INVALID_SOCKET;
connection->MaxReceivePacket = INITIAL_MAX_RECEIVE_BUFFER;
connection->NegotiateFlags = DEFAULT_NEGOTIATE_FLAGS;
connection->SendDrainTimeSeconds = (ULONG) -1;
// setup fields for keep alive processing
connection->TimeOfLastReceive = LdapGetTickCount();
connection->PingLimit = LOWORD( GlobalLdapPingLimit );
connection->KeepAliveSecondCount = GlobalWaitSecondsForSelect;
connection->PingWaitTimeInMilliseconds = GlobalPingWaitTime;
connection->HostConnectState = HostConnectStateUnconnected;
InitializeListHead( &connection->CompletedReceiveList );
InitializeListHead( &connection->PendingCryptoList );
SetNullCredentials( connection );
connection->ConnectionListEntry.Flink = NULL;
__try {
INITIALIZE_LOCK( &(connection->ReconnectLock) );
dwCritSectInitStage = 1;
INITIALIZE_LOCK( &(connection->StateLock) );
dwCritSectInitStage = 2;
INITIALIZE_LOCK( &(connection->SocketLock) );
dwCritSectInitStage = 3;
INITIALIZE_LOCK( &(connection->ScramblingLock) );
dwCritSectInitStage = 4;
}
__except (EXCEPTION_EXECUTE_HANDLER) {
//
// Something went wrong
//
IF_DEBUG(ERRORS) {
LdapPrint0( "LdapAllocateConnection could not initialize critical sections.\n");
}
switch (dwCritSectInitStage) {
// fall-through is deliberate
case 4:
DELETE_LOCK(&(connection->ScramblingLock));
case 3:
DELETE_LOCK(&(connection->SocketLock));
case 2:
DELETE_LOCK(&(connection->StateLock));
case 1:
DELETE_LOCK(&(connection->ReconnectLock));
case 0:
default:
break;
}
InterlockedDecrement( &GlobalConnectionCount );
ldapFree( connection->ListOfHosts, LDAP_HOST_NAME_SIGNATURE );
ldapFree( connection, LDAP_CONN_SIGNATURE );
CloseHandle( hConnectEvent );
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
SetConnectionError(NULL, LDAP_NO_MEMORY, NULL);
return NULL;
}
connection->publicLdapStruct.ld_deref = LDAP_DEREF_NEVER;
connection->publicLdapStruct.ld_timelimit = LDAP_TIME_LIMIT_DEFAULT;
connection->publicLdapStruct.ld_errno = LDAP_SUCCESS;
connection->publicLdapStruct.ld_cldaptries = CLDAP_DEFAULT_RETRY_COUNT;
connection->publicLdapStruct.ld_cldaptimeout = CLDAP_DEFAULT_TIMEOUT_COUNT;
connection->publicLdapStruct.ld_refhoplimit = LDAP_REF_DEFAULT_HOP_LIMIT;
connection->publicLdapStruct.ld_lberoptions = LBER_USE_DER;
connection->PromptForCredentials = TRUE;
connection->AutoReconnect = TRUE;
connection->UserAutoRecChoice = TRUE;
connection->ClientCertRoutine = NULL;
connection->ServerCertRoutine = NULL;
connection->SentPacket = FALSE;
connection->ProcessedListOfHosts = FALSE;
connection->ForceHostBasedSPN = FALSE;
connection->DefaultServer = FALSE;
if (Udp) {
connection->UdpHandle = (*psocket)(PF_INET, SOCK_DGRAM, 0);
err = ( connection->UdpHandle == INVALID_SOCKET ) ? ERROR_BAD_NET_NAME : 0;
} else {
connection->TcpHandle = (*psocket)(PF_INET, SOCK_STREAM, 0);
err = ( connection->TcpHandle == INVALID_SOCKET ) ? ERROR_BAD_NET_NAME : 0;
}
if ((err == 0) && psetsockopt) {
// prevent socket hijacking
BOOL t = TRUE;
(*psetsockopt)( Udp ? connection->UdpHandle : connection->TcpHandle,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
reinterpret_cast<char*>(&t),
sizeof(t) );
}
if (err != 0) {
IF_DEBUG(NETWORK_ERRORS) {
LdapPrint1( "ldap_create failed to open socket, err = 0x%x.\n", (*pWSAGetLastError)());
}
exitWithError:
CloseLdapConnection( connection );
DereferenceLdapConnection( connection );
SetLastError(err);
SetConnectionError(NULL, (err == ERROR_SUCCESS ? LDAP_SUCCESS : LDAP_OPERATIONS_ERROR), NULL);
return NULL;
}
ULONG secure = PtrToUlong(((Secure == 0) ? LDAP_OPT_OFF : LDAP_OPT_ON ));
err = LdapSetConnectionOption( connection, LDAP_OPT_SSL, &secure, FALSE );
if (err != LDAP_SUCCESS) {
err = ERROR_OPEN_FAILED;
goto exitWithError;
}
return connection;
}
//
// After all of the above plethora of ways to get to this routine, we
// have some code that actually allocates a connection block and sets it up.
//
LDAP *LdapConnectionOpen (
PWCHAR HostName,
ULONG PortNumber,
BOOLEAN Udp
)
{
PLDAP_CONN connection = NULL;
ULONG err;
connection = LdapAllocateConnection( HostName, PortNumber, 0, Udp );
if (connection == NULL) {
IF_DEBUG(CONNECTION) {
LdapPrint1( "ldap_open failed to create connection, err = 0x%x.\n", GetLastError());
}
return NULL;
}
//
// open a connection to any of the servers specified
//
err = LdapConnect( connection, NULL, FALSE );
if (err != 0) {
CloseLdapConnection( connection );
DereferenceLdapConnection( connection );
connection = NULL;
SetConnectionError(NULL, err, NULL);
SetLastError( LdapMapErrorToWin32( err ));
IF_DEBUG(CONNECTION) {
LdapPrint1( "ldap_open failed to open connection, err = 0x%x.\n", err);
}
return NULL;
}
//
// We haven't given the connection to anyone - so object must be active
//
ASSERT(connection->ConnObjectState == ConnObjectActive);
connection->HandlesGivenToCaller++;
//
// Add it to global list of connections
//
ACQUIRE_LOCK( &ConnectionListLock );
InsertTailList( &GlobalListActiveConnections, &connection->ConnectionListEntry );
RELEASE_LOCK( &ConnectionListLock );
//
// Wake up select so that it picks up the new connection handle.
//
LdapWakeupSelect();
DereferenceLdapConnection( connection );
return connection->ExternalInfo;
}
INT
OpenLdapServer (
PLDAP_CONN Connection,
struct l_timeval *timeout
)
//
// The Connection->ListOfHosts parameter is a list of hosts of the form :
// hostname
// hostaddr
// hostname:port
// hostaddr:port
//
// We should, for each one, do the following :
//
// If name, call DsGetDcOpen to get DCs
// If name and DsGetDcOpen fails, call gethostbyname, get list of addrs
// for every addr we have, try connect()
//
// Each of them is null terminated, the number is specified by
// Connection->NumberOfHosts
//
// This returns a Win32 error code.
{
USHORT PortNumber;
USHORT hostsTried;
PWCHAR hostName;
INT rc = ERROR_HOST_UNREACHABLE;
INT wsErr;
USHORT port;
PWCHAR endOfHost;
PWCHAR hostPtr;
BOOLEAN haveTriedExplicitHost = FALSE;
BOOLEAN tryingExplicitHost = FALSE;
BOOLEAN samesite = FALSE;
ULONGLONG startTime;
BOOLEAN fIsValidDnsSuppliedName = FALSE;
DWORD DCFlags = 0;
#if DBG
startTime = LdapGetTickCount();
#endif
if ((Connection->ProcessedListOfHosts) && (Connection->DefaultServer == TRUE)) {
//
// If we're reconnecting, and the user originally asked us to find the default
// server (by passing in NULL), we reset the internal state and go through the
// DsGetDcName process again to retrieve a fresh DC. This way, we have all the
// data we need in order to generate a valid DNS-based SPN for Kerberos.
//
//
// We need to free ListOfHosts. ExplicitHostName and HostNameW may be aliased
// to ListOfHosts. So if they are, we need to take appropriate action. We'll
// just reset HostNameW later, so we free it if it didn't point to the same
// memory as ListOfHosts, and reset it to NULL. This prevents a leak.
// For ExplicitHostName, we want to preserve it, so we copy it off if it is
// currently an alias for ListOfHosts (in practice, I don't think this will
// ever happen)
//
if (Connection->ExplicitHostName == Connection->ListOfHosts) {
// Copy this off before freeing ListOfHosts if it's an alias to
// ListOfHosts (see unbind.cxx)
Connection->ExplicitHostName = ldap_dup_stringW(Connection->ExplicitHostName,
0,
LDAP_HOST_NAME_SIGNATURE);
if ((Connection->ExplicitHostName) == NULL) {
return LDAP_NO_MEMORY;
}
}
if (( Connection->HostNameW != Connection->ExplicitHostName ) &&
( Connection->HostNameW != Connection->ListOfHosts )) {
// Reset HostNameW --- this may point to a allocated block of memory,
// or it may be a alias for ListOfHosts, hence the check above
// (see unbind.cxx)
ldapFree( Connection->HostNameW, LDAP_HOST_NAME_SIGNATURE );
}
Connection->HostNameW = NULL;
// Free everything we'll set in the code to find a DC below
ldapFree( Connection->ListOfHosts, LDAP_HOST_NAME_SIGNATURE );
Connection->ListOfHosts = NULL;
ldapFree( Connection->DnsSuppliedName, LDAP_HOST_NAME_SIGNATURE );
Connection->DnsSuppliedName = NULL;
ldapFree( Connection->DomainName, LDAP_HOST_NAME_SIGNATURE);
Connection->DomainName = NULL;
DCFlags = DS_FORCE_REDISCOVERY; // since our old DC may have gone down
Connection->ProcessedListOfHosts = FALSE; // we're resetting ListOfHosts
}
if (Connection->ListOfHosts == NULL) {
PWCHAR Address, DnsName, DomainName;
DWORD numAddrs = 1;
ULONG strLen0, strLen1;
BOOLEAN fGC = FALSE;
Address = DnsName = DomainName = NULL;
if ((!GlobalWin9x) &&
((Connection->PortNumber == LDAP_PORT) ||
(Connection->PortNumber == LDAP_SSL_PORT))) {
rc = GetCurrentMachineParams( &Address, &DnsName );
}
if (( Connection->PortNumber == LDAP_GC_PORT ) ||
( Connection->PortNumber == LDAP_SSL_GC_PORT )) {
fGC = TRUE;
}
if (rc != LDAP_SUCCESS) {
//
// Either the current machine is not a DC or we failed trying to
// find out.Get the domain name for the currently logged in user.
// alas, for now we just get the server name of a NTDS DC in the domain.
//
rc = GetDefaultLdapServer( NULL,
&Address,
&DnsName,
(fGC ? &DomainName : NULL),
&numAddrs,
Connection->GetDCFlags | DCFlags,
&samesite,
Connection->PortNumber,
&Connection->ResolvedGetDCFlags
);
if ((rc == NO_ERROR) && !fGC) {
rc = GetPrimaryDomainName(&DomainName);
}
}
if (rc != NO_ERROR) {
return rc;
}
strLen0 = (Address == NULL) ? 0 : (strlenW( Address ) + 1);
strLen1 = (DomainName == NULL) ? 0 : (strlenW( DomainName ) + 1);
if (strLen0 > 1) {
Connection->ListOfHosts = ldap_dup_stringW( Address,
strLen1, // Allocate extra for the domain name
LDAP_HOST_NAME_SIGNATURE );
if (Connection->ListOfHosts && (strLen1 > 1)) {
PWCHAR nextHost = Connection->ListOfHosts + strLen0;
// make this a space separated list of names
if (strLen0 > 0) {
*(nextHost-1) = L' ';
}
ldap_MoveMemory( (PCHAR) nextHost, (PCHAR) DomainName, sizeof(WCHAR)*strLen1 );
}
ldapFree( Address, LDAP_HOST_NAME_SIGNATURE );
Address = NULL;
Connection->DnsSuppliedName = DnsName;
fIsValidDnsSuppliedName = TRUE;
Connection->DomainName = DomainName;
}
if (Connection->ListOfHosts == NULL) {
ldapFree( Address, LDAP_HOST_NAME_SIGNATURE );
SetLastError( ERROR_INCORRECT_ADDRESS );
return ERROR_INCORRECT_ADDRESS;
}
Connection->DefaultServer = TRUE;
}
//
// if we haven't already processed the list of hosts (i.e., this isn't
// a autoreconnect), go through the list of hosts and replace all spaces
// with nulls and count up number of hosts
//
// If this is a autoreconnect, the NULLs were already inserted during the
// initial connect, and trying to do it a second time will cause us to
// lost all but the first host on the list (since we'll stop at the first
// NULL)
//
if (!Connection->ProcessedListOfHosts)
{
Connection->NumberOfHosts = 1;
hostPtr = Connection->ListOfHosts;
while (*hostPtr != L'\0') {
if (*hostPtr == L' ') {
Connection->NumberOfHosts++;
*hostPtr = L'\0';
hostPtr++;
while (*hostPtr == L' ') {
hostPtr++;
}
} else {
hostPtr++;
}
}
Connection->ProcessedListOfHosts = TRUE;
}
//
// Try to connect to the server(s) specified by hostName
//
RetryWithoutExplicitHost:
PortNumber = Connection->PortNumber;
hostsTried = 0;
hostName = Connection->ListOfHosts;
//
// if the app suggested a server to try by calling ldap_set_option with
// LDAP_OPT_HOSTNAME before we got in here, then we try that name first
//
if ((haveTriedExplicitHost == FALSE) &&
(Connection->ExplicitHostName != NULL)) {
hostName = Connection->ExplicitHostName;
haveTriedExplicitHost = TRUE;
tryingExplicitHost = TRUE;
}
Connection->SocketAddress.sin_family = AF_INET;
if (PortNumber == 0) {
PortNumber = LDAP_SERVER_PORT;
}
Connection->SocketAddress.sin_port = (*phtons)( LOWORD( PortNumber ));
rc = ERROR_HOST_UNREACHABLE;
while (( hostsTried < Connection->NumberOfHosts ) &&
( rc != 0 )) {
port = LOWORD( PortNumber );
IF_DEBUG(CONNECTION) {
LdapPrint2( "LDAP conn 0x%x trying host %S\n", Connection, hostName );
}
//
// pick up :nnn for port number
//
endOfHost = hostName;
while ((*endOfHost != L':') &&
(*endOfHost != L'\0')) {
endOfHost++;
}
if (*endOfHost != L'\0') {
PWCHAR portPtr = endOfHost + 1;
//
// pick up port number
//
port = 0;
while (*portPtr != L'\0') {
if (*portPtr < L'0' ||
*portPtr > L'9') {
IF_DEBUG(CONNECTION) {
LdapPrint2( "LDAP conn 0x%x invalid port number for %S\n", Connection, hostName );
}
rc = ERROR_INVALID_NETNAME;
goto tryNextServer;
}
port = (port * 10) + (*portPtr++ - L'0');
}
if (port == 0) {
port = LOWORD( PortNumber );
}
*endOfHost = L'\0';
} else {
endOfHost = NULL;
}
Connection->SocketAddress.sin_port = (*phtons)( port );
if ( LdapIsAddressNumeric(hostName) ) {
Connection->SocketAddress.sin_addr.s_addr = Inet_addrW( hostName );
if (Connection->SocketAddress.sin_addr.s_addr != INADDR_NONE) {
rc = LdapWinsockConnect( Connection, port, hostName, timeout, samesite );
if (!fIsValidDnsSuppliedName) {
if (Connection->DnsSuppliedName) {
ldapFree( Connection->DnsSuppliedName, LDAP_HOST_NAME_SIGNATURE );
Connection->DnsSuppliedName = NULL;
}
}
//
// If the user explicitly connects via a numeric IP address, we want to
// make sure that the resulting SPN contains that IP address, not a
// retrieved DNS name corresponding to that IP address, for security
// reasons (DNS can be spoofed).
//
// If we're here, the user must have explicitly passed in a IP address,
// unless we just retrieved the IP address from the locator because the
// user passed in NULL (fIsValidDnsSuppliedName).
//
if (!fIsValidDnsSuppliedName)
{
Connection->ForceHostBasedSPN = TRUE;
}
} else {
IF_DEBUG(CONNECTION) {
LdapPrint1( "LDAP inet_addr failed to get address from %S\n", hostName );
}
}
} else {
struct hostent *hostEntry = NULL;
BOOLEAN connected = FALSE;
ULONG dnsSrvRecordCount = 0;
BOOLEAN LoopBack = FALSE;
if (ldapWStringsIdentical(
Connection->ListOfHosts,
-1,
L"localhost",
-1)) {
LoopBack = TRUE;
}
if ( (Connection->AREC_Exclusive == FALSE) &&
(tryingExplicitHost == FALSE) &&
(LoopBack == FALSE)) {
rc = ConnectToSRVrecs( Connection,
hostName,
tryingExplicitHost,
port,
timeout );
if (rc == LDAP_SUCCESS) {
connected = TRUE;
}
}
if (connected == FALSE) {
PWCHAR HostAddress = NULL;
PWCHAR DnsName = NULL;
PWCHAR DomainName = NULL;
PWCHAR hostNameUsedByGetHostByName = hostName;
//
// The hostname is of the form HOSTNAME. Do a gethostbyname
// and try to connect to it.
//
hostEntry = GetHostByNameW( hostName );
if ((hostEntry == NULL) &&
(Connection->AREC_Exclusive == FALSE) &&
(tryingExplicitHost == FALSE) &&
(LoopBack == FALSE)) {
wsErr = (*pWSAGetLastError)();
IF_DEBUG(CONNECTION) {
LdapPrint2( "LDAP gethostbyname failed for %S, 0x%x\n", hostName, wsErr );
}
rc = ERROR_INCORRECT_ADDRESS;
// now we try to connect to the name as if it were a
// domain name. We've already checked SRV records, so
// try to make it work simply for a flat name like "ntdev".
if ((dnsSrvRecordCount == 0) &&
(tryingExplicitHost == FALSE)) {
DWORD numAddrs = 1;
samesite= FALSE;
rc = GetDefaultLdapServer( hostName,
&HostAddress,
&DnsName,
&DomainName,
&numAddrs,
Connection->GetDCFlags | DS_IS_FLAT_NAME,
&samesite,
port,
&Connection->ResolvedGetDCFlags
);
if ((rc == 0) && (HostAddress != NULL)) {
if ( LdapIsAddressNumeric(HostAddress) ) {
Connection->SocketAddress.sin_addr.s_addr = Inet_addrW( HostAddress );
if (Connection->SocketAddress.sin_addr.s_addr != INADDR_NONE) {
rc = LdapWinsockConnect( Connection, port, HostAddress, timeout, samesite );
//
// if we succeeded here, we have to
// move the HostName pointer in the
// connection record to point to the
// domain name since the server name
// may go away
//
// Also, store the real machine name in
// the DnsSuppliedName field to be
// used later for making up the SPN
// during bind.
//
if (rc == 0) {
Connection->HostNameW = hostName;
Connection->DnsSuppliedName = DnsName;
Connection->DomainName = DomainName;
}
} else {
IF_DEBUG(CONNECTION) {
LdapPrint1( "LDAP inet_addr failed to get address from %S\n", hostName );
}
rc = ERROR_INCORRECT_ADDRESS;
}
} else {
hostEntry = GetHostByNameW( HostAddress );
hostNameUsedByGetHostByName = HostAddress;
rc = ERROR_INCORRECT_ADDRESS;
}
} else {
rc = ERROR_INCORRECT_ADDRESS;
}
}
}
if (hostEntry != NULL) {
//
// gethostbyname has returned us a list of addresses which we
// can use to do a parallel connect.
//
rc = ConnectToArecs( Connection,
hostEntry,
tryingExplicitHost,
port,
timeout );
if (rc == LDAP_SUCCESS) {
connected = TRUE;
#if LDAPDBG
if ( (Connection->AREC_Exclusive == FALSE) && (tryingExplicitHost == FALSE) ) {
char tempBuff[1000];
DWORD tempErr = GetModuleFileName( NULL, tempBuff, 1000);
if (tempErr == 0) {
LdapPrint1("Process 0x%x is calling LDAP without setting the LDAP_OPT_AREC_EXCLUSIVE flag\n", GetCurrentProcessId());
LdapPrint0("Using this flag when passing in a fully-qualified server DNS name can\n");
LdapPrint0("improve the performance of this application when connecting.\n");
LdapPrint0("You can use tlist.exe to get the process name of the application.\n");
} else {
LdapPrint2("%s [PID 0x%x] is calling LDAP without setting the LDAP_OPT_AREC_EXCLUSIVE flag\n", tempBuff, GetCurrentProcessId());
LdapPrint0("Using this flag when passing in a fully-qualified server DNS name can\n");
LdapPrint0("improve the performance of this application when connecting.\n");
}
}
#endif
}
}
if (HostAddress != NULL) {
if (rc == 0) {
ldapFree( Connection->ExplicitHostName, LDAP_HOST_NAME_SIGNATURE );
Connection->ExplicitHostName = HostAddress;
} else {
ldapFree( HostAddress, LDAP_HOST_NAME_SIGNATURE );
}
}
}
//
// Free the hostent structure if we have allocated it
//
if (hostEntry &&
pWSALookupServiceBeginW &&
pWSALookupServiceNextW &&
pWSALookupServiceEnd) {
PCHAR* temp = hostEntry->h_addr_list;
int i=0;
while (temp[i]) {
ldapFree(temp[i], LDAP_ANSI_SIGNATURE);
i++;
}
ldapFree(temp, LDAP_ANSI_SIGNATURE);
ldapFree(hostEntry->h_name, LDAP_HOST_NAME_SIGNATURE);
ldapFree(hostEntry->h_aliases, LDAP_HOST_NAME_SIGNATURE);
ldapFree(hostEntry, LDAP_ANSI_SIGNATURE);
}
}
if (endOfHost != NULL) {
*endOfHost = L':';
}
tryNextServer:
if (rc != 0) {
hostsTried++;
//
// go to next host
//
while (*hostName != L'\0') {
hostName++;
}
hostName++;
}
}
if ((rc != 0) && (tryingExplicitHost == TRUE)) {
tryingExplicitHost = FALSE;
goto RetryWithoutExplicitHost;
}
if ((rc == 0) && (tryingExplicitHost == TRUE)) {
//
// if we succeeded here, we have to move the HostName pointer in the
// connection record to point to the domain name since the server name
// may go away.
//
if ((Connection->HostNameW != NULL) &&
(Connection->HostNameW != Connection->ListOfHosts) &&
(Connection->HostNameW != Connection->ExplicitHostName)) {
ldapFree( Connection->HostNameW, LDAP_HOST_NAME_SIGNATURE );
}
Connection->HostNameW = Connection->ListOfHosts;
}
if ((rc==0) && (hostsTried)) {
//
// The Hostname ptr will be pointing somewhere inbetween the ListOfHost
// we have to reset it.
//
Connection->HostNameW = Connection->ListOfHosts;
}
//
// We finally need an ANSI version of the hostname on the connection
// block to be compliant with the UMICH implementation.
//
ldapFree( Connection->publicLdapStruct.ld_host, LDAP_HOST_NAME_SIGNATURE );
FromUnicodeWithAlloc( Connection->HostNameW,
&Connection->publicLdapStruct.ld_host,
LDAP_HOST_NAME_SIGNATURE,
LANG_ACP
);
if ( ( rc == 0 ) && ( Connection->SslPort ) ) {
rc = LdapSetupSslSession( Connection );
}
START_LOGGING;
DSLOG((DSLOG_FLAG_TAG_CNPN,"[+][ID=0]"));
DSLOG((0,"[OP=ldap_open][SV=%s][ST=%I64d][ET=%I64d][ER=%d][-]\n",
Connection->publicLdapStruct.ld_host, startTime, LdapGetTickCount(), rc));
END_LOGGING;
return rc;
}
ULONG
LdapWinsockConnect (
PLDAP_CONN Connection,
USHORT PortNumber,
PWCHAR HostName,
struct l_timeval *timeout,
BOOLEAN samesite
)
{
ULONG wsErr;
BOOLEAN isAsync = FALSE;
ULONG nonblockingMode;
BOOLEAN tcpSocket = (Connection->TcpHandle != INVALID_SOCKET) ? TRUE : FALSE;
//
// we call connect both for UDP and TCP. With UDP, it just
// associates the address with the socket.
// With TCP, we leave the socket in nonblocking mode.
//
if (tcpSocket && pioctlsocket) {
nonblockingMode = 1;
isAsync = TRUE;
//
// We set the socket to nonblocking, do the connect, call select
// with the timeout value, and fail the whole thing if it doesn't
// work.
//
wsErr = (*pioctlsocket)( Connection->TcpHandle,
FIONBIO,
&nonblockingMode
);
if (wsErr != 0) {
//
// if it fails, we just do a synchronous connect... we tried.
//
wsErr = (*pWSAGetLastError)();
IF_DEBUG(NETWORK_ERRORS) {
LdapPrint2( "LDAP conn %u ioclsocket returned 0x%x\n", Connection, wsErr );
}
isAsync = FALSE;
}
}
if (tcpSocket && psetsockopt && Connection->UseTCPKeepAlives) {
// turn on TCP keep-alives if requested
int t = TRUE;
wsErr = (*psetsockopt)( Connection->TcpHandle,
SOL_SOCKET,
SO_KEEPALIVE,
reinterpret_cast<char*>(&t),
sizeof(t)
);
if (wsErr != 0) {
// we'll treat failure to turn on keep-alives as non-fatal
wsErr = (*pWSAGetLastError)();
IF_DEBUG(NETWORK_ERRORS) {
LdapPrint2( "LDAP conn %u setsockopt for keepalive returned 0x%x\n", Connection, wsErr );
}
}
}
TryConnectAgain:
wsErr = (*pconnect)(get_socket( Connection ),
(struct sockaddr *)&Connection->SocketAddress,
sizeof(Connection->SocketAddress) );
if (wsErr != 0) {
wsErr = (*pWSAGetLastError)();
//
// if someone in our process set OVERLAPPED to TRUE for all sockets,
// then the connect will fail here if we've set it to nonblocking
// mode, so we'll pick up this error code and revert to blocking.
//
if (wsErr == WSAEINVAL && isAsync == TRUE) {
IF_DEBUG(CONNECT) {
LdapPrint2( "LDAP connect switching back to sync for host %S, port %u\n",
HostName, PortNumber );
}
SOCKET newSocket = (*psocket)(PF_INET,
tcpSocket ? SOCK_STREAM : SOCK_DGRAM,
0);
if (newSocket != INVALID_SOCKET) {
if (psetsockopt) {
// prevent socket hijacking
BOOL t = TRUE;
(*psetsockopt)( newSocket,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
reinterpret_cast<char*>(&t),
sizeof(t) );
}
BeginSocketProtection( Connection );
int sockerr = (*pclosesocket)( tcpSocket ? Connection->TcpHandle : Connection->UdpHandle);
ASSERT(sockerr == 0);
if (tcpSocket) {
Connection->TcpHandle = newSocket;
} else {
Connection->UdpHandle = newSocket;
}
EndSocketProtection( Connection );
isAsync = FALSE;
goto TryConnectAgain;
}
}
if (wsErr == 0) {
wsErr = WSA_WAIT_TIMEOUT;
}
IF_DEBUG(CONNECTION) {
LdapPrint3( "LDAP connect returned err %u for addr %S, port %u\n",
wsErr, HostName, PortNumber );
}
}
if (isAsync) {
BOOLEAN failedSelect = FALSE;
if (wsErr == WSAEWOULDBLOCK) {
fd_set writeSelectSet;
fd_set excSelectSet;
timeval selectTimeout;
FD_ZERO( &writeSelectSet );
FD_SET( Connection->TcpHandle, &writeSelectSet );
FD_ZERO( &excSelectSet );
FD_SET( Connection->TcpHandle, &excSelectSet );
if (timeout == NULL) {
if (samesite == TRUE) {
//
// We are connecting to servers in the same site. We can afford
// to have a small timeout.
//
selectTimeout.tv_sec = SAMESITE_CONNECT_TIMEOUT;
selectTimeout.tv_usec = 0;
} else {
selectTimeout.tv_sec = LDAP_CONNECT_TIMEOUT;
selectTimeout.tv_usec = 0;
}
} else {
//
// honor the user specified timeout
//
selectTimeout.tv_sec = timeout->tv_sec;
selectTimeout.tv_usec = timeout->tv_usec;
}
wsErr = (*pselect)( 0,
NULL,
&writeSelectSet,
&excSelectSet,
&selectTimeout );
if ((wsErr == SOCKET_ERROR) || (wsErr == 0)) {
failedSelect:
if (wsErr == SOCKET_ERROR) {
wsErr = (*pWSAGetLastError)();
}
if (wsErr == 0) {
wsErr = WSA_WAIT_TIMEOUT;
}
IF_DEBUG(NETWORK_ERRORS) {
LdapPrint2( "LDAP conn 0x%x connect/select returned %u\n", Connection, wsErr );
}
failedSelect = TRUE;
ASSERT( wsErr != 0 );
} else {
if ((*pwsafdisset)(Connection->TcpHandle, &writeSelectSet )) {
wsErr = 0;
} else {
IF_DEBUG(CONNECTION) {
LdapPrint3( "LDAP connect returned err 0x%x for addr %S, port %u\n",
wsErr, HostName, PortNumber );
}
wsErr = (ULONG) SOCKET_ERROR;
goto failedSelect;
}
}
}
}
if (wsErr == 0) {
Connection->PortNumber = PortNumber;
IF_DEBUG(CONNECTION) {
LdapPrint2( "LDAP conn 0x%x connected to addr %S\n", Connection, HostName );
}
if (( PortNumber == LDAP_SERVER_PORT_SSL ) ||
( PortNumber == LDAP_SSL_GC_PORT)) {
Connection->SslPort = TRUE;
}
Connection->HostNameW = HostName;
} else {
IF_DEBUG(CONNECTION) {
LdapPrint4( "LDAP conn 0x%x connecting to addr %S, port %u err = 0x%x\n",
Connection, HostName, PortNumber, wsErr );
}
SOCKET newSocket = (*psocket)(PF_INET,
tcpSocket ? SOCK_STREAM : SOCK_DGRAM,
0);
if (newSocket != INVALID_SOCKET) {
if (psetsockopt) {
// prevent socket hijacking
BOOL t = TRUE;
(*psetsockopt)( newSocket,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
reinterpret_cast<char*>(&t),
sizeof(t) );
}
BeginSocketProtection( Connection );
int sockerr = (*pclosesocket)( tcpSocket ? Connection->TcpHandle : Connection->UdpHandle);
ASSERT(sockerr == 0);
if (tcpSocket) {
Connection->TcpHandle = newSocket;
} else {
Connection->UdpHandle = newSocket;
}
EndSocketProtection( Connection );
}
}
return wsErr;
}
//
// This is the function which takes in an LDAP handle returned
// from ldap_init( ) and connects to the server for you
//
ULONG __cdecl ldap_connect (
LDAP *ExternalHandle,
struct l_timeval *timeout
)
{
PLDAP_CONN connection = NULL;
ULONG err;
connection = GetConnectionPointer(ExternalHandle);
if (connection == NULL) {
return LDAP_PARAM_ERROR;
}
err = LdapConnect( connection, timeout, FALSE );
DereferenceLdapConnection( connection );
return err;
}
ULONG
LdapConnect (
PLDAP_CONN connection,
struct l_timeval *timeout,
BOOLEAN DontWait
)
{
ULONG err;
BOOLEAN haveLock = FALSE;
//
// Check if the connection has already been established
// if yes, simply return. If not, establish it
//
if ( connection->HostConnectState == HostConnectStateConnected ) {
return LDAP_SUCCESS;
}
waitAgain:
if (haveLock == FALSE) {
ACQUIRE_LOCK( &connection->StateLock );
haveLock = TRUE;
}
//
// single thread the call to OpenLdapServer
//
if ( connection->HostConnectState == HostConnectStateConnected ) {
IF_DEBUG(CONNECT) {
LdapPrint1( "ldap_connect reports connection 0x%x already connected\n",
connection );
}
err = LDAP_SUCCESS;
goto connectDone;
}
if (( connection->ServerDown == TRUE) && (connection->AutoReconnect == FALSE) ) {
err = LDAP_SERVER_DOWN;
goto connectDone;
}
if (connection->ConnObjectState != ConnObjectActive) {
IF_DEBUG(CONNECT) {
LdapPrint3( "ldap_connect connection 0x%x is in state 0x%x for thread 0x%x\n",
connection,
connection->ConnObjectState,
GetCurrentThreadId() );
}
err = LDAP_USER_CANCELLED;
goto connectDone;
}
//
// if no thread is currently handling the reconnect, volunteer... but then
// don't go into a wait state waiting for someone else to do it.
//
if (DontWait == FALSE) {
if ((connection->HostConnectState == HostConnectStateError) &&
(connection->AutoReconnect == TRUE)) {
//
// Let go of the StateLock while waiting for the ReconnectLock
//
RELEASE_LOCK( &connection->StateLock );
haveLock = FALSE;
ACQUIRE_LOCK( &connection->ReconnectLock );
//
// Grab the StateLock again before checking the state which
// could have changed while we were waiting for the ReconnectLock
//
ACQUIRE_LOCK( &connection->StateLock );
haveLock = TRUE;
if ((connection->HostConnectState == HostConnectStateError) &&
(connection->AutoReconnect == TRUE)) {
IF_DEBUG(CONNECT) {
LdapPrint2( "ldap_connect connection 0x%x is in error state for thread 0x%x, reconnecting...\n",
connection,
GetCurrentThreadId() );
}
//
// we'll call off to autoreconnect and then recursively come back in
// here. kind of ugly, but auto-reconnect involves a lot of
// processing, so we keep it in one place.
//
connection->HostConnectState = HostConnectStateReconnecting;
RELEASE_LOCK( &connection->StateLock );
haveLock = FALSE;
err = LdapAutoReconnect( connection );
RELEASE_LOCK( &connection->ReconnectLock );
goto connectDone;
}
RELEASE_LOCK( &connection->ReconnectLock );
goto waitAgain;
}
if (haveLock == FALSE) {
ACQUIRE_LOCK( &connection->StateLock );
haveLock = TRUE;
}
//
// if some other thread is doing the reconnect, wait for it to finish
//
if ((( connection->HostConnectState == HostConnectStateConnecting ) ||
( connection->HostConnectState == HostConnectStateReconnecting ))) {
IF_DEBUG(CONNECT) {
LdapPrint2( "ldap_connect thread 0x%x is waiting on connection 0x%x\n",
GetCurrentThreadId(),
connection );
}
RELEASE_LOCK( &connection->StateLock );
haveLock = FALSE;
WaitForSingleObjectEx( connection->ConnectEvent,
INFINITE,
TRUE ); // alertable
goto waitAgain;
}
}
ResetEvent( connection->ConnectEvent );
connection->HostConnectState = HostConnectStateConnecting;
IF_DEBUG(CONNECT) {
LdapPrint2( "ldap_connect thread 0x%x is opening connection 0x%x\n",
GetCurrentThreadId(),
connection );
}
RELEASE_LOCK( &connection->StateLock );
haveLock = FALSE;
//
// open a connection to any of the servers specified
//
err = OpenLdapServer( connection, timeout );
//
// If we couldn't open the LDAP server, then the address that
// DsGetDCName passed us isn't valid (or the value in the
// registry isn't valid). Either way, we mark to force rediscovery
// and then try this whole thing again.
//
ACQUIRE_LOCK( &connection->StateLock );
haveLock = TRUE;
if (err != 0) {
connection->HostConnectState = HostConnectStateError;
if (DontWait == FALSE) {
SetEvent( connection->ConnectEvent );
}
IF_DEBUG(CONNECT) {
LdapPrint2( "LdapConnect failed to open connection 0x%x, err = 0x%x.\n",
connection, err);
}
IF_DEBUG(SERVERDOWN) {
LdapPrint2( "LdapConnect thread 0x%x has connection 0x%x as down.\n",
GetCurrentThreadId(),
connection );
}
err = LDAP_SERVER_DOWN;
goto connectDone;
}
IF_DEBUG(CONNECT) {
LdapPrint2( "ldap_connect thread 0x%x has opened connection 0x%x\n",
GetCurrentThreadId(),
connection );
}
connection->HostConnectState = HostConnectStateConnected;
if (DontWait == FALSE) {
SetEvent( connection->ConnectEvent );
}
if (connection->ConnObjectState != ConnObjectActive) {
IF_DEBUG(CONNECT) {
LdapPrint1( "LdapConnect connection 0x%x is closing.\n", connection);
}
err = LDAP_USER_CANCELLED;
goto connectDone;
}
IF_DEBUG(CONNECTION) {
LdapPrint2( "ldap_connect marking 0x%x as open, host is %S.\n",
connection, connection->HostNameW );
}
LdapWakeupSelect();
connectDone:
IF_DEBUG(CONNECT) {
LdapPrint3( "ldap_connect thread 0x%x is leaving for conn 0x%x with 0x%x\n",
GetCurrentThreadId(),
connection,
err );
}
if (haveLock) {
RELEASE_LOCK( &connection->StateLock );
}
SetConnectionError(connection, err, NULL);
return(err);
}
BOOLEAN
LdapIsAddressNumeric (
PWCHAR HostName
)
{
BOOLEAN rc = FALSE;
//
// to check to see if it's a TCP address, we check for it to only
// contain only numerals and periods.
//
while (((*HostName >= L'0') && (*HostName <= L'9')) ||
(*HostName == L'.')) {
HostName++;
}
//
// if we hit the end of the hostname, then it's an address.
//
if (*HostName == L'\0' || *HostName == L':') {
rc = TRUE;
}
return rc;
}
ULONG
ConnectToSRVrecs(
PLDAP_CONN Connection,
PWCHAR HostName,
BOOLEAN SuggestedHost,
USHORT port,
struct l_timeval *timeout
)
//
// HostName can be of the form "ntdsdc1.ntdev.microsoft.com" or simply
// "ntdev.microsoft.com". If this is a SuggestedHost, we try to connect to
// that host first (1 second preference) before the rest of the address records.
//
//
{
HANDLE enumHandle = NULL;
PWCHAR hostname = NULL;
ULONG hostCount;
LPWSTR site = NULL;
ULONG rc = LDAP_SUCCESS;
BOOLEAN GetDcSucceeded = FALSE;
BOOLEAN StartedEnumeration = FALSE;
ULONG totalCount = 0;
struct l_timeval localtimeout = {0};
PWCHAR Address = NULL;
PWCHAR DnsHostName = NULL;
PWCHAR DomainName = NULL;
PSOCKHOLDER2 sockAddressArr[MAX_SOCK_ADDRS];
//
// Initialize all elements of our SOCKHOLDER2 array.
//
for (int j=0; j<MAX_SOCK_ADDRS; j++ ) {
sockAddressArr[j] = NULL;
}
hostname = ( HostName==NULL ) ? Connection->ListOfHosts : HostName;
//
// If a hostname wasn't suggested, we try DsGetDcName
// because it will return to us a "sticky" address to connect to. This will
// ensure that we always hit the same DC everytime someone comes in with a
// domain name like "ntdev.microsoft.com". This will also ensure that if we
// are on a DC, we connect to the same machine without going on the wire. Note
// that if the "sticky" DC goes down, the user has to repeat the process
// with the ForceVerify flag set.
//
// Note that we assume the hostname is of a DNS style name. This is to prevent
// DsGetDcName from performing a lengthy NetBT broadcast.
//
//
if ( SuggestedHost == FALSE ) {
sockaddr_in *ptemp;
BOOLEAN samesite = FALSE;
DWORD numAddrs = 1;
ULONG tempAddr = 0;
ULONG Flags = 0;
BOOLEAN ForcedRetry = FALSE;
TryAgain:
if (ForcedRetry) {
Flags = DS_FORCE_REDISCOVERY;
}
rc = GetDefaultLdapServer( hostname,
&Address,
&DnsHostName,
&DomainName,
&numAddrs,
Connection->GetDCFlags | Flags | DS_IS_DNS_NAME,
&samesite,
Connection->PortNumber,
&Connection->ResolvedGetDCFlags
);
if ((rc == NO_ERROR) && (Address != NULL)) {
sockAddressArr[totalCount] = (PSOCKHOLDER2)ldapMalloc(sizeof(SOCKHOLDER2), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[totalCount] == NULL) {
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
sockAddressArr[totalCount]->psocketaddr = (LPSOCKET_ADDRESS)ldapMalloc(sizeof(SOCKET_ADDRESS), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[totalCount]->psocketaddr == NULL) {
ldapFree(sockAddressArr[totalCount],LDAP_SOCKADDRL_SIGNATURE );
sockAddressArr[totalCount] = NULL;
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
sockAddressArr[totalCount]->psocketaddr->lpSockaddr = (LPSOCKADDR)ldapMalloc(sizeof(SOCKADDR), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[totalCount]->psocketaddr->lpSockaddr == NULL) {
ldapFree(sockAddressArr[totalCount]->psocketaddr,LDAP_SOCKADDRL_SIGNATURE );
ldapFree(sockAddressArr[totalCount],LDAP_SOCKADDRL_SIGNATURE );
sockAddressArr[totalCount] = NULL;
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
ptemp = (sockaddr_in *) sockAddressArr[totalCount]->psocketaddr->lpSockaddr;
sockAddressArr[totalCount]->psocketaddr->iSockaddrLength = sizeof(sockaddr_in);
tempAddr = Inet_addrW( Address );
if (tempAddr != INADDR_NONE) {
CopyMemory( &(ptemp->sin_addr.s_addr), &tempAddr, sizeof(tempAddr) );
ptemp->sin_family = AF_INET;
ptemp->sin_port = (*phtons)( port );
GetDcSucceeded = TRUE;
} else {
ldapFree(sockAddressArr[totalCount]->psocketaddr->lpSockaddr,LDAP_SOCKADDRL_SIGNATURE );
ldapFree(sockAddressArr[totalCount]->psocketaddr,LDAP_SOCKADDRL_SIGNATURE );
ldapFree(sockAddressArr[totalCount],LDAP_SOCKADDRL_SIGNATURE );
sockAddressArr[totalCount] = NULL;
rc = LDAP_LOCAL_ERROR;
}
}
if ((rc == LDAP_SUCCESS) && (GetDcSucceeded)) {
//
// We give the address returned by DsGetDcName preference. Keep in mind
// that this server may not respond in 1 second in which case we move
// on to enumerate DNS records.
//
sockAddressArr[totalCount]->DnsSuppliedName = DnsHostName;
DnsHostName = NULL;
IF_DEBUG(CONNECTION) {
LdapPrint1("Dns supplied hostname from DsGetDcName is %s\n", sockAddressArr[totalCount]->DnsSuppliedName);
}
totalCount++;
sockAddressArr[totalCount] = NULL; // Null terminate the array.
localtimeout.tv_sec = LDAP_QUICK_TIMEOUT;
if (ForcedRetry) {
//
// This must be a reachable DC we are connecting to. Wait twice
// as long if necessary.
//
localtimeout.tv_sec = localtimeout.tv_sec * 2;
}
localtimeout.tv_usec = 0;
rc = LdapParallelConnect( Connection,
&sockAddressArr[0],
port,
totalCount,
&localtimeout
);
if (rc == LDAP_SUCCESS) {
Connection->HostNameW = ldap_dup_stringW( hostname,
0,
LDAP_HOST_NAME_SIGNATURE );
Connection->DomainName = DomainName;
DomainName = NULL;
goto ExitWithCleanup;
}
//
// We failed to connect to the DC returned from DsGetDcName. Maybe
// it was a cached DC and has gone down since. Let's force the
// locator to find a fresh DC.
//
ldapFree( DomainName, LDAP_HOST_NAME_SIGNATURE );
DomainName = NULL;
ldapFree( Address, LDAP_HOST_NAME_SIGNATURE);
Address = NULL;
if (!ForcedRetry) {
ForcedRetry = TRUE;
goto TryAgain;
}
}
}
//
// This could be a third party SRV record registration. DsGetDcName will
// not find such a name by default.
//
// Note that if this is not a third party SRV record domain but an A record
// instead, it will result in unnecessary delay and traffic. For this reason,
// applications MUST specify the LDAP_OPT_AREC_EXCLUSIVE flag when specifying
// SRV records.
//
rc = InitLdapServerFromDomain( hostname,
Connection->GetDCFlags | DS_ONLY_LDAP_NEEDED,
&enumHandle,
&site
);
if (rc != LDAP_SUCCESS) {
goto ExitWithCleanup;
}
StartedEnumeration = TRUE;
while (totalCount < MAX_SOCK_ADDRS-1) {
LPSOCKET_ADDRESS sockAddresses;
//
// Try to collect all the addresses into the array of addresses
//
hostCount = 0;
rc = NextLdapServerFromDomain( enumHandle,
&sockAddresses,
&DnsHostName,
&hostCount
);
if (rc != NO_ERROR) {
break;
}
ULONG count = 0;
while ((count < hostCount) && (totalCount < MAX_SOCK_ADDRS-1)) {
sockAddressArr[totalCount] = (PSOCKHOLDER2)ldapMalloc(sizeof(SOCKHOLDER2), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[totalCount] == NULL) {
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
sockAddressArr[totalCount]->psocketaddr = (LPSOCKET_ADDRESS)ldapMalloc(sizeof(SOCKET_ADDRESS), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[totalCount]->psocketaddr == NULL) {
ldapFree(sockAddressArr[totalCount],LDAP_SOCKADDRL_SIGNATURE );
sockAddressArr[totalCount] = NULL;
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
sockAddressArr[totalCount]->psocketaddr->lpSockaddr = (LPSOCKADDR)ldapMalloc(max(sizeof(SOCKADDR), (&sockAddresses[count])->iSockaddrLength),
LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[totalCount]->psocketaddr->lpSockaddr == NULL) {
ldapFree(sockAddressArr[totalCount]->psocketaddr,LDAP_SOCKADDRL_SIGNATURE );
ldapFree(sockAddressArr[totalCount],LDAP_SOCKADDRL_SIGNATURE );
sockAddressArr[totalCount] = NULL;
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
sockAddressArr[totalCount]->psocketaddr->iSockaddrLength = (&sockAddresses[count])->iSockaddrLength;
CopyMemory(sockAddressArr[totalCount]->psocketaddr->lpSockaddr,
(&sockAddresses[count])->lpSockaddr,
(&sockAddresses[count])->iSockaddrLength);
sockAddressArr[totalCount]->DnsSuppliedName = ldap_dup_stringW( DnsHostName,
0,
LDAP_HOST_NAME_SIGNATURE
);
IF_DEBUG(CONNECTION) {
LdapPrint3("Dns supplied hostname from DsGetDcNext is %s totalcount %d intermediatecount %d\n", sockAddressArr[totalCount]->DnsSuppliedName, totalCount, count );
}
totalCount++;
count++;
}
ldapFree( DnsHostName, LDAP_HOST_NAME_SIGNATURE );
DnsHostName = NULL;
LocalFree( sockAddresses );
}
sockAddressArr[totalCount] = NULL;
IF_DEBUG(CONNECTION) {
LdapPrint2("Collected a total of %d address records for host %S\n",totalCount, hostname);
}
if (totalCount == 0) {
CloseLdapServerFromDomain( enumHandle, site );
return rc;
}
//
// We can now connect to any address in this null terminated array.
//
if (timeout == NULL) {
if (site != NULL) {
//
// We are connecting to servers in the same site. We can afford
// to have a small timeout.
//
localtimeout.tv_sec = (SuggestedHost) ? LDAP_QUICK_TIMEOUT : SAMESITE_CONNECT_TIMEOUT;
localtimeout.tv_usec = 0;
} else {
localtimeout.tv_sec = (SuggestedHost) ? LDAP_QUICK_TIMEOUT : LDAP_CONNECT_TIMEOUT;
localtimeout.tv_usec = 0;
}
} else {
//
// honor the user specified timeout
//
localtimeout.tv_sec = (SuggestedHost) ? 1:timeout->tv_sec;
localtimeout.tv_usec = timeout->tv_usec;
}
rc = LdapParallelConnect( Connection,
&sockAddressArr[0],
port,
totalCount,
&localtimeout
);
if (rc == LDAP_SUCCESS) {
Connection->HostNameW = ldap_dup_stringW( hostname,
0,
LDAP_HOST_NAME_SIGNATURE );
}
ExitWithCleanup:
//
// Cleanup allocated socket addresses.
//
ULONG i =0;
while (sockAddressArr[i] != NULL) {
ldapFree(sockAddressArr[i]->psocketaddr->lpSockaddr, LDAP_SOCKADDRL_SIGNATURE);
ldapFree(sockAddressArr[i]->psocketaddr, LDAP_SOCKADDRL_SIGNATURE);
ldapFree(sockAddressArr[i]->DnsSuppliedName, LDAP_HOST_NAME_SIGNATURE);
ldapFree(sockAddressArr[i], LDAP_SOCKADDRL_SIGNATURE);
sockAddressArr[i] = NULL;
i++;
}
if ( Address != NULL) {
ldapFree( Address, LDAP_HOST_NAME_SIGNATURE );
}
if ( DnsHostName != NULL ) {
ldapFree( DnsHostName, LDAP_HOST_NAME_SIGNATURE );
}
if ( DomainName != NULL) {
ldapFree( DomainName, LDAP_HOST_NAME_SIGNATURE );
}
if ( StartedEnumeration ) {
CloseLdapServerFromDomain( enumHandle, site );
}
return rc;
}
ULONG
ConnectToArecs(
PLDAP_CONN Connection,
struct hostent *hostEntry,
BOOLEAN SuggestedHost,
USHORT port,
struct l_timeval *timeout
)
{
PSOCKHOLDER2 sockAddressArr[MAX_SOCK_ADDRS];
sockaddr_in *ptemp;
ULONG rc, hostCount = 0;
PCHAR hostAddr = hostEntry->h_addr_list[0];
while ((hostAddr != NULL) && (hostCount < MAX_SOCK_ADDRS-1)) {
//
// Allocate both the SOCKET_ADDRESS & sockaddr structures
//
sockAddressArr[hostCount] = (PSOCKHOLDER2)ldapMalloc(sizeof(SOCKHOLDER2), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[hostCount] == NULL) {
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
sockAddressArr[hostCount]->psocketaddr = (LPSOCKET_ADDRESS)ldapMalloc(sizeof(SOCKET_ADDRESS), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[hostCount]->psocketaddr == NULL) {
rc = LDAP_NO_MEMORY;
goto ExitWithCleanup;
}
sockAddressArr[hostCount]->psocketaddr->lpSockaddr = (LPSOCKADDR)ldapMalloc(sizeof(SOCKADDR), LDAP_SOCKADDRL_SIGNATURE);
if (sockAddressArr[hostCount]->psocketaddr->lpSockaddr == NULL) {
rc = LDAP_LOCAL_ERROR;
goto ExitWithCleanup;
}
ptemp = (sockaddr_in *) sockAddressArr[hostCount]->psocketaddr->lpSockaddr;
sockAddressArr[hostCount]->psocketaddr->iSockaddrLength = sizeof(sockaddr_in);
ASSERT( sizeof(ptemp->sin_addr.s_addr) == hostEntry->h_length );
if (hostEntry->h_length <= sizeof(ptemp->sin_addr.s_addr)) {
CopyMemory( &(ptemp->sin_addr.s_addr), hostAddr, hostEntry->h_length );
}
else {
LdapPrint1("h_length is too big (%d)\n", hostEntry->h_length );
rc = LDAP_LOCAL_ERROR;
goto ExitWithCleanup;
}
ptemp->sin_family = AF_INET;
ptemp->sin_port = (*phtons)( port );
//
// All address records will have the same name. So, we will not bother
// to hook up the DNS supplied hostname. We will do it later if the
// connect is successful.
//
sockAddressArr[hostCount]->DnsSuppliedName = NULL;
hostAddr = hostEntry->h_addr_list[++hostCount];
}
sockAddressArr[hostCount] = NULL;
if (Connection->PortNumber == 0) {
Connection->PortNumber = LDAP_SERVER_PORT;
}
IF_DEBUG(CONNECTION) {
LdapPrint2("gethostbyname collected %d records for %S\n", hostCount, hostEntry->h_name );
}
struct l_timeval localtimeout;
if (timeout == NULL) {
//
// gethostbyname does not give us any site information, so we use a long
// timeout.
//
localtimeout.tv_sec = (SuggestedHost) ? 1:LDAP_CONNECT_TIMEOUT;
localtimeout.tv_usec = 0;
} else {
//
// honor the user specified timeout
//
localtimeout.tv_sec = (SuggestedHost) ? 1:timeout->tv_sec;
localtimeout.tv_usec = timeout->tv_usec;
}
rc = LdapParallelConnect( Connection,
&sockAddressArr[0],
port,
hostCount,
&localtimeout
);
if (rc == LDAP_SUCCESS) {
//
// Convert from ANSI to Unicode before storing off the hostnames internally
// We do this only if we called gethostbyname() in winsock 1.1.
//
if (pWSALookupServiceBeginW &&
pWSALookupServiceNextW &&
pWSALookupServiceEnd) {
Connection->DnsSuppliedName = ldap_dup_stringW( hostEntry->h_aliases ?
(PWCHAR)hostEntry->h_aliases : (PWCHAR) hostEntry->h_name,
0,
LDAP_HOST_NAME_SIGNATURE
);
FromUnicodeWithAlloc( hostEntry->h_aliases ?
(PWCHAR)hostEntry->h_aliases : (PWCHAR) hostEntry->h_name,
&Connection->publicLdapStruct.ld_host,
LDAP_HOST_NAME_SIGNATURE,
LANG_ACP
);
} else {
//
// Probably Win95 without Unicode RNR APIs. We are dealing with a TRUE hostEnt
// structure.
//
ToUnicodeWithAlloc( hostEntry->h_aliases ?
hostEntry->h_aliases[0] : hostEntry->h_name,
-1,
&Connection->DnsSuppliedName,
LDAP_HOST_NAME_SIGNATURE,
LANG_ACP
);
Connection->publicLdapStruct.ld_host = ldap_dup_string( hostEntry->h_aliases ?
hostEntry->h_aliases[0] : hostEntry->h_name,
0,
LDAP_HOST_NAME_SIGNATURE );
}
Connection->HostNameW = ldap_dup_stringW( Connection->DnsSuppliedName,
0,
LDAP_HOST_NAME_SIGNATURE
);
IF_DEBUG(CONNECTION) {
LdapPrint1("Successfully connected to host %S\n", Connection->DnsSuppliedName);
}
}
ExitWithCleanup:
for (ULONG i = 0; i < hostCount; i++) {
if ( sockAddressArr[i]->psocketaddr->lpSockaddr ) {
ldapFree(sockAddressArr[i]->psocketaddr->lpSockaddr, LDAP_SOCKADDRL_SIGNATURE);
if ( sockAddressArr[i]->psocketaddr ) {
ldapFree(sockAddressArr[i]->psocketaddr, LDAP_SOCKADDRL_SIGNATURE);
if ( sockAddressArr[i] ) {
ldapFree(sockAddressArr[i], LDAP_SOCKADDRL_SIGNATURE);
}
}
}
}
return rc;
}
ULONG
LdapParallelConnect(
PLDAP_CONN Connection,
PSOCKHOLDER2 *sockAddressArr,
USHORT port,
UINT totalCount,
struct l_timeval *timeout
)
{
//
// we take in an array of pointers to SOCKET_ADDRESS structures. The goal is to try to issue connect
// to any one of those addresses. To do this, we issues async connects to each address in intervals of
// 1/10 sec (default).
//
SOCKHOLDER sockarray [MAX_PARALLEL_CONNECTS];
ULONG remainingcount = totalCount;
ULONG currentset = 0;
ULONG startingpos = 0;
ULONG index, k;
ULONG sockpos = 0;
ULONG wsErr = 0;
ULONG nonblockingMode = 1;
ULONG hoststried = 0;
ULONG currentsock = 0;
fd_set writeSelectSet;
fd_set excSelectSet;
fd_set retrywriteSelectSet;
fd_set retryexcSelectSet;
timeval selectTimeout;
ULONGLONG starttime;
BOOLEAN connected = FALSE;
BOOLEAN LastTimeout = FALSE;
BOOLEAN StreamSocket = TRUE;
ULONG sockErr = 0;
if ((Connection == NULL)||
(sockAddressArr == NULL)||
(totalCount == 0)||
(timeout == NULL)) {
return LDAP_PARAM_ERROR;
}
port = (port == 0) ? LDAP_SERVER_PORT : port;
if (( port == LDAP_SERVER_PORT_SSL ) ||
( port == LDAP_SSL_GC_PORT ) ) {
Connection->SslPort = TRUE;
}
FD_ZERO( &retrywriteSelectSet );
FD_ZERO( &retryexcSelectSet );
selectTimeout.tv_sec = 0;
selectTimeout.tv_usec = CONNECT_INTERVAL*1000;
starttime = LdapGetTickCount();
while ((connected == FALSE) &&
(remainingcount > 0) &&
((LdapGetTickCount() - starttime)/1000 < (DWORD) timeout->tv_sec)) {
if (remainingcount <= MAX_PARALLEL_CONNECTS) {
currentset = remainingcount;
remainingcount = 0;
} else {
currentset = MAX_PARALLEL_CONNECTS;
remainingcount -= currentset;
}
for (index=startingpos, sockpos=0;
index < (currentset+hoststried);
index++, startingpos++, sockpos++) {
ASSERT (sockAddressArr[index] != NULL);
LastTimeout = FALSE;
//
// Create an appropriate socket and issue a connect
//
if (Connection->TcpHandle != INVALID_SOCKET) {
sockarray[sockpos].sock = (*psocket)(PF_INET, SOCK_STREAM, 0);
StreamSocket = TRUE;
} else {
sockarray[sockpos].sock = (*psocket)(PF_INET, SOCK_DGRAM, 0);
StreamSocket = FALSE;
}
if (sockarray[sockpos].sock == INVALID_SOCKET) {
goto ExitWithCleanup;
}
sockarray[sockpos].psocketaddr = sockAddressArr[index]->psocketaddr;
sockarray[sockpos].DnsSuppliedName = sockAddressArr[index]->DnsSuppliedName;
if (psetsockopt) {
// prevent socket hijacking
BOOL t = TRUE;
(*psetsockopt)( sockarray[sockpos].sock,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
reinterpret_cast<char*>(&t),
sizeof(t) );
}
wsErr = (*pioctlsocket)( sockarray[sockpos].sock,
FIONBIO,
&nonblockingMode
);
if (wsErr != 0) {
LdapPrint1("ioctlsocket failed with 0x%x . .\n", GetLastError());
LdapCleanupSockets( sockpos+1 );
goto ExitWithCleanup;
}
if (StreamSocket && psetsockopt && Connection->UseTCPKeepAlives) {
// turn on TCP keep-alives if requested
int t = TRUE;
wsErr = (*psetsockopt)( sockarray[sockpos].sock,
SOL_SOCKET,
SO_KEEPALIVE,
reinterpret_cast<char*>(&t),
sizeof(t)
);
if (wsErr != 0) {
// we'll treat failure to turn on keep-alives as non-fatal
wsErr = (*pWSAGetLastError)();
IF_DEBUG(NETWORK_ERRORS) {
LdapPrint2( "LDAP conn %u setsockopt for keepalive returned 0x%x\n", Connection, wsErr );
}
}
}
sockaddr_in *inetSocket = (sockaddr_in *) sockAddressArr[index]->psocketaddr->lpSockaddr;
inetSocket->sin_port = (*phtons)( port );
wsErr = (*pconnect)(sockarray[sockpos].sock,
(struct sockaddr *) inetSocket,
sizeof(struct sockaddr_in) );
if ((wsErr != SOCKET_ERROR) ||
(wsErr == SOCKET_ERROR)&&
((*pWSAGetLastError)() == WSAEWOULDBLOCK)) {
FD_SET( sockarray[sockpos].sock, &retrywriteSelectSet );
FD_SET( sockarray[sockpos].sock, &retryexcSelectSet );
writeSelectSet = retrywriteSelectSet;
excSelectSet = retryexcSelectSet;
if (index >= (currentset + hoststried - 1)) {
//
// We will not be issuing any more connects for this set
// So, we should wait for the entire timeout period.
//
// We should actually wait for the remainder of the
// timeout period but this method is accurate to within 1%
//
LastTimeout = TRUE;
selectTimeout.tv_sec = timeout->tv_sec;
selectTimeout.tv_usec = timeout->tv_usec;
}
wsErr = (*pselect)( 0,
NULL,
&writeSelectSet,
&excSelectSet,
&selectTimeout );
if (wsErr == SOCKET_ERROR) {
LdapPrint1("select failed with 0x%x . .\n", GetLastError());
LdapCleanupSockets( sockpos+1 );
goto ExitWithCleanup;
} else if (wsErr == 0) {
//
// We timed out without receiving a response.
// Go ahead and issue another connect.
//
wsErr = WSA_WAIT_TIMEOUT;
connected = FALSE;
IF_DEBUG(CONNECTION) {
LdapPrint0("No response yet. . .\n");
}
} else {
for (k=0; k<=sockpos; k++) {
if ((*pwsafdisset)(sockarray[k].sock, &writeSelectSet )) {
//
// Yes! This connect was successful
//
connected = TRUE;
BeginSocketProtection( Connection );
if (StreamSocket) {
if (Connection->TcpHandle != INVALID_SOCKET) {
sockErr = (*pclosesocket)( Connection->TcpHandle );
ASSERT(sockErr == 0);
}
Connection->TcpHandle = sockarray[k].sock;
} else {
if (Connection->UdpHandle != INVALID_SOCKET) {
sockErr = (*pclosesocket)( Connection->UdpHandle );
ASSERT(sockErr == 0);
}
Connection->UdpHandle = sockarray[k].sock;
}
EndSocketProtection( Connection );
sockarray[k].sock = INVALID_SOCKET;
inetSocket = (sockaddr_in *) sockarray[k].psocketaddr->lpSockaddr;
ASSERT( sizeof(Connection->SocketAddress.sin_addr.s_addr) ==
sizeof( inetSocket->sin_addr.s_addr ) );
CopyMemory( &Connection->SocketAddress.sin_addr.s_addr,
&inetSocket->sin_addr.s_addr,
sizeof(Connection->SocketAddress.sin_addr.s_addr) );
Connection->DnsSuppliedName = ldap_dup_stringW(sockarray[k].DnsSuppliedName,
0,
LDAP_HOST_NAME_SIGNATURE);
Connection->PortNumber = port;
IF_DEBUG(CONNECTION) {
LdapPrint1("Successfully connected to host %S\n", Connection->DnsSuppliedName);
}
LdapCleanupSockets( sockpos+1 );
goto ExitWithCleanup;
} else if ((*pwsafdisset)(sockarray[k].sock, &excSelectSet )) {
//
// If there was an exception, we have no other choice
// Remove the socket from the select sets and close it.
FD_CLR( sockarray[k].sock, &retryexcSelectSet);
FD_CLR( sockarray[k].sock, &retrywriteSelectSet);
sockErr = (*pclosesocket)(sockarray[k].sock);
ASSERT(sockErr == 0);
sockarray[k].sock = INVALID_SOCKET;
}
}
}
//
// If this is the last timeout for the current set, close
// all the sockets we created and clear the fd_sets because
// they can't hold more than 64 sockets.
//
if (LastTimeout == TRUE) {
LdapCleanupSockets( sockpos+1 );
FD_ZERO( &retrywriteSelectSet );
FD_ZERO( &retryexcSelectSet );
}
} else {
wsErr = (*pWSAGetLastError)();
IF_DEBUG(CONNECTION) {
LdapPrint1("Connect failed with 0x%x\n",wsErr );
}
sockErr = (*pclosesocket)( sockarray[sockpos].sock );
ASSERT(sockErr == 0);
goto ExitWithCleanup;
}
}
hoststried += currentset;
}
ExitWithCleanup:
//
// We need to close all the sockets we created
//
LdapCleanupSockets( sockpos );
if ((connected == FALSE) && (wsErr != WSA_WAIT_TIMEOUT)) {
wsErr = (*pWSAGetLastError)();
SetConnectionError( Connection, wsErr, NULL );
IF_DEBUG(NETWORK_ERRORS) {
LdapPrint2( "LDAP conn %u returned 0x%x\n", Connection, wsErr );
}
return LDAP_CONNECT_ERROR;
}
if (connected == TRUE) {
return LDAP_SUCCESS;
} else if (wsErr == 0) {
return LDAP_SERVER_DOWN;
}
return wsErr;
}
struct hostent *
GetHostByNameW(
PWCHAR hostName
)
{
//
// We try to make use of Winsock2 functionality if available. This is
// because gethostbyname in Winsock 1.1 supports only ANSI.
//
if (pWSALookupServiceBeginW &&
pWSALookupServiceNextW &&
pWSALookupServiceEnd) {
//
// We will fabricate a hostent structure of our own. It will look
// like the following. The only fields of interest are h_name, h_aliases[0],
// h_length and h_addr_list. Note that we will fill in a UNICODE
// h_name and h_aliases[0] field instead of the standard ANSI name.
//
//
// struct hostent {
// WCHAR * h_name; /* official name of host */
// WCHAR * h_aliases; /* first alias */
// short h_addrtype; /* host address type */
// short h_length; /* length of address */
// char FAR * FAR * h_addr_list; /* list of addresses */
// };
//
//
#define INITIAL_COUNT 20
WSAQUERYSETW qsQuery;
PWSAQUERYSETW pBuffer = NULL;
HANDLE hRnr = NULL;
ULONG totalCount = 0;
DWORD dwQuerySize = 0;
GUID ServiceGuid = SVCID_INET_HOSTADDRBYNAME;
struct hostent *phostent = NULL;
int retval = 0;
PCHAR *IPArray = NULL;
ULONG arraySize = INITIAL_COUNT;
BOOLEAN bCapturedOfficialName = FALSE;
ULONG dnsFlags = LUP_RETURN_ADDR | LUP_RETURN_NAME | LUP_RETURN_BLOB | LUP_RETURN_ALIASES;
//
// Allocate a hostent structure which the callee will free later
//
phostent = (struct hostent*) ldapMalloc(sizeof(struct hostent), LDAP_ANSI_SIGNATURE );
if (!phostent) {
goto Cleanup;
}
//
// Fill in the size of an IP address.
// This will change when we move to IPv6.
//
phostent->h_length = 4;
//
// Initialize the query structure
//
memset(&qsQuery, 0, sizeof(WSAQUERYSETW));
qsQuery.dwSize = sizeof(WSAQUERYSETW); // the dwSize field has to be initialised like this
qsQuery.dwNameSpace = NS_ALL;
qsQuery.lpServiceClassId = &ServiceGuid; // this is the GUID to perform forward name resolution (name to IP)
qsQuery.lpszServiceInstanceName = hostName;
if( pWSALookupServiceBeginW( &qsQuery,
dnsFlags,
&hRnr ) == SOCKET_ERROR ) {
IF_DEBUG(CONNECTION) {
LdapPrint1( "WSALookupServiceBegin failed %d\n", GetLastError() );
}
goto Cleanup;
}
//
// Determine the size of the buffer required to store the results.
//
retval = pWSALookupServiceNextW( hRnr,
dnsFlags,
&dwQuerySize,
NULL // No buffer supplied
);
if (GetLastError() != WSAEFAULT) {
IF_DEBUG(CONNECTION) {
LdapPrint1( "WSALookupServiceNext failed with %d\n", GetLastError() );
}
goto Cleanup;
}
IF_DEBUG(CONNECTION) {
LdapPrint1( "WSALookupServiceNext requires a buffer of %d\n", dwQuerySize );
}
pBuffer = (PWSAQUERYSETW) ldapMalloc(dwQuerySize, LDAP_BUFFER_SIGNATURE);
if (!pBuffer) {
goto Cleanup;
}
//
// Allocate an initial array capable of holding upto INITIAL_COUNT addresses.
//
IPArray = (PCHAR*) ldapMalloc( (INITIAL_COUNT+1)*sizeof(PCHAR),
LDAP_ANSI_SIGNATURE
);
if (!IPArray) {
goto Cleanup;
}
//
// Marshall the returned data into a hostent structure. Note that
// we use a Unicode hostname instead of the ANSI name.
//
while (( pWSALookupServiceNextW( hRnr,
dnsFlags,
&dwQuerySize,
pBuffer ) == NO_ERROR )) {
if ((bCapturedOfficialName) && (pBuffer->lpszServiceInstanceName)) {
//
// We pick up the first alias -- verified with JamesG.
// Note that we shoe horn a Unicode string instead of a ptr to
// null-terminated array of ANSI strings.
//
phostent->h_aliases = (PCHAR*) ldap_dup_stringW(pBuffer->lpszServiceInstanceName,
0,
LDAP_HOST_NAME_SIGNATURE
);
if (!phostent->h_aliases) {
goto Cleanup;
}
IF_DEBUG(CONNECTION) {
LdapPrint1("First host alias is %S\n", phostent->h_aliases);
}
}
//
// We pick off the official name first; Clarified with JamesG.
//
if ((!phostent->h_name) &&
(pBuffer->dwNumberOfCsAddrs > 0)) {
phostent->h_name = (PCHAR) ldap_dup_stringW(pBuffer->lpszServiceInstanceName,
0,
LDAP_HOST_NAME_SIGNATURE
);
if (!phostent->h_name) {
goto Cleanup;
}
IF_DEBUG(CONNECTION) {
LdapPrint1("Official host %S\n", phostent->h_name);
}
bCapturedOfficialName = TRUE;
}
struct sockaddr_in *ptemp;
ptemp = (sockaddr_in *) pBuffer->lpcsaBuffer->RemoteAddr.lpSockaddr;
ASSERT(sizeof(ptemp->sin_addr) == phostent->h_length);
IF_DEBUG(CONNECTION) {
LdapPrint1("Number of addresses collected 0x%x\n", pBuffer->dwNumberOfCsAddrs );
}
UINT i;
for (i=0 ;( i < pBuffer->dwNumberOfCsAddrs ); i++,totalCount++) {
ptemp = (struct sockaddr_in *) pBuffer->lpcsaBuffer[i].RemoteAddr.lpSockaddr;
if ( totalCount == arraySize ) {
PCHAR *newArray;
int j=0;
//
// It is time to realloc our IPArray since it is too small.
//
arraySize *=2;
newArray = (PCHAR*) ldapMalloc( (arraySize+1)*sizeof(PCHAR),
LDAP_ANSI_SIGNATURE
);
if (!newArray) {
goto Cleanup;
}
//
// Copy all the old entries to the new one.
//
while (IPArray[j]) {
newArray[j] = IPArray[j];
j++;
}
//
// Free the old array.
//
ldapFree( IPArray, LDAP_ANSI_SIGNATURE );
IPArray = newArray;
}
IPArray[totalCount] = (PCHAR) ldapMalloc(phostent->h_length,
LDAP_ANSI_SIGNATURE);
if (IPArray[totalCount] == NULL) {
goto Cleanup;
}
CopyMemory( IPArray[totalCount], &ptemp->sin_addr, phostent->h_length );
IF_DEBUG(CONNECTION) {
if (pinet_ntoa) {
LdapPrint1("Copied address %s\n", pinet_ntoa(ptemp->sin_addr));
}
}
}
//
// We need to determine the required buffer size before each call to
// WSALookupServiceBegin. Keep in mind that the buffer length can change
// for each call.
//
DWORD dwNewQuerySize = 0;
retval = pWSALookupServiceNextW( hRnr,
dnsFlags,
&dwNewQuerySize,
NULL // No buffer supplied on purpose
);
if (GetLastError() != WSAEFAULT) {
IF_DEBUG(CONNECTION) {
LdapPrint1( "WSALookupServiceNext failed with %d\n", GetLastError() );
}
break;
} else {
if (dwNewQuerySize > dwQuerySize) {
IF_DEBUG(CONNECTION) {
LdapPrint1( "WSALookupServiceNext requires a bigger buffer of %d\n", dwNewQuerySize );
}
ldapFree( pBuffer, LDAP_BUFFER_SIGNATURE);
pBuffer = (PWSAQUERYSETW) ldapMalloc(dwNewQuerySize, LDAP_BUFFER_SIGNATURE);
if (!pBuffer) {
break;
}
dwQuerySize = dwNewQuerySize;
}
}
}
phostent->h_addr_list = IPArray;
Cleanup:
ldapFree( pBuffer, LDAP_BUFFER_SIGNATURE );
if ( hRnr ) {
pWSALookupServiceEnd( hRnr );
}
if ( ( totalCount == 0 ) ||
( phostent && (phostent->h_addr_list == NULL) ) ) {
if (phostent) {
ldapFree(phostent->h_name, LDAP_HOST_NAME_SIGNATURE);
ldapFree(phostent->h_aliases, LDAP_HOST_NAME_SIGNATURE);
ldapFree(phostent, LDAP_ANSI_SIGNATURE);
phostent = NULL;
}
int j=0;
if (IPArray) {
while (IPArray[j]) {
ldapFree(IPArray[j], LDAP_ANSI_SIGNATURE);
j++;
}
ldapFree(IPArray, LDAP_ANSI_SIGNATURE);
}
}
return phostent;
} else {
//
// We don't have winsock2 functionality, do our best by calling gethostbyname
//
PCHAR ansiHostname = NULL;
struct hostent * retval = NULL;
ULONG err = 0;
LdapPrint0("No Winsock2 functionality found.\n");
err = FromUnicodeWithAlloc( hostName,
&ansiHostname,
LDAP_HOST_NAME_SIGNATURE,
LANG_ACP);
if (err != LDAP_SUCCESS) {
return NULL;
}
retval = ((*pgethostbyname)( ansiHostname ));
ldapFree( ansiHostname, LDAP_HOST_NAME_SIGNATURE );
return retval;
}
}
ULONG
Inet_addrW(
PWCHAR IpAddressW
)
{
//
// Convert from Unicode to ANSI because inet_addr does not handle
// Unicode.
//
PCHAR IpAddressA = NULL;
ULONG err, retval;
err = FromUnicodeWithAlloc( IpAddressW,
&IpAddressA,
LDAP_BUFFER_SIGNATURE,
LANG_ACP);
if (err != LDAP_SUCCESS) {
return INADDR_NONE;
}
retval = (*pinet_addr)( IpAddressA );
ldapFree( IpAddressA, LDAP_BUFFER_SIGNATURE );
return retval;
}
// open.cxx eof.
| 31.677027 | 178 | 0.4912 | npocmaka |
4c8621d6bb1d223d9f320ca6ca26b110b62eefe1 | 13,059 | cpp | C++ | dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp | Coquinho/dali-adaptor | a8006aea66b316a5eb710e634db30f566acda144 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp | Coquinho/dali-adaptor | a8006aea66b316a5eb710e634db30f566acda144 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-10-19T13:45:40.000Z | 2020-12-10T20:21:03.000Z | dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp | expertisesolutions/dali-adaptor | 810bf4dea833ea7dfbd2a0c82193bc0b3b155011 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/imaging/tizen/native-image-source-impl-tizen.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/integration-api/gl-defines.h>
#include <cstring>
#include <tbm_surface_internal.h>
// INTERNAL INCLUDES
#include <dali/internal/graphics/common/egl-image-extensions.h>
#include <dali/internal/graphics/gles/egl-graphics.h>
#include <dali/internal/adaptor/common/adaptor-impl.h>
#include <dali/integration-api/adaptor-framework/render-surface-interface.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
const char* FRAGMENT_PREFIX = "#extension GL_OES_EGL_image_external:require\n";
const char* SAMPLER_TYPE = "samplerExternalOES";
tbm_format FORMATS_BLENDING_REQUIRED[] = {
TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444,
TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444,
TBM_FORMAT_RGBX5551, TBM_FORMAT_BGRX5551,
TBM_FORMAT_ARGB1555, TBM_FORMAT_ABGR1555,
TBM_FORMAT_RGBA5551, TBM_FORMAT_BGRA5551,
TBM_FORMAT_ARGB8888, TBM_FORMAT_ABGR8888,
TBM_FORMAT_RGBA8888, TBM_FORMAT_BGRA8888,
TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010,
TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102
};
const int NUM_FORMATS_BLENDING_REQUIRED = 18;
}
using Dali::Integration::PixelBuffer;
NativeImageSourceTizen* NativeImageSourceTizen::New( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
{
NativeImageSourceTizen* image = new NativeImageSourceTizen( width, height, depth, nativeImageSource );
DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." );
if( image )
{
image->Initialize();
}
return image;
}
NativeImageSourceTizen::NativeImageSourceTizen( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
: mWidth( width ),
mHeight( height ),
mOwnTbmSurface( false ),
mTbmSurface( NULL ),
mTbmFormat( 0 ),
mBlendingRequired( false ),
mColorDepth( depth ),
mEglImageKHR( NULL ),
mEglGraphics( NULL ),
mEglImageExtensions( NULL ),
mSetSource( false ),
mMutex(),
mIsBufferAcquired( false )
{
DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() );
GraphicsInterface* graphics = &( Adaptor::GetImplementation( Adaptor::Get() ).GetGraphicsInterface() );
mEglGraphics = static_cast<EglGraphics *>(graphics);
mTbmSurface = GetSurfaceFromAny( nativeImageSource );
if( mTbmSurface != NULL )
{
tbm_surface_internal_ref( mTbmSurface );
mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );
mWidth = tbm_surface_get_width( mTbmSurface );
mHeight = tbm_surface_get_height( mTbmSurface );
}
}
void NativeImageSourceTizen::Initialize()
{
if( mTbmSurface != NULL || mWidth == 0 || mHeight == 0 )
{
return;
}
tbm_format format = TBM_FORMAT_RGB888;
int depth = 0;
switch( mColorDepth )
{
case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
{
format = TBM_FORMAT_ARGB8888;
depth = 32;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_8:
{
format = TBM_FORMAT_C8;
depth = 8;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_16:
{
format = TBM_FORMAT_RGB565;
depth = 16;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_24:
{
format = TBM_FORMAT_RGB888;
depth = 24;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_32:
{
format = TBM_FORMAT_ARGB8888;
depth = 32;
break;
}
default:
{
DALI_LOG_WARNING( "Wrong color depth.\n" );
return;
}
}
// set whether blending is required according to pixel format based on the depth
/* default pixel format is RGB888
If depth = 8, Pixel::A8;
If depth = 16, Pixel::RGB565;
If depth = 32, Pixel::RGBA8888 */
mBlendingRequired = ( depth == 32 || depth == 8 );
mTbmSurface = tbm_surface_create( mWidth, mHeight, format );
mOwnTbmSurface = true;
}
tbm_surface_h NativeImageSourceTizen::GetSurfaceFromAny( Any source ) const
{
if( source.Empty() )
{
return NULL;
}
if( source.GetType() == typeid( tbm_surface_h ) )
{
return AnyCast< tbm_surface_h >( source );
}
else
{
return NULL;
}
}
void NativeImageSourceTizen::DestroySurface()
{
if( mTbmSurface )
{
if( mIsBufferAcquired )
{
ReleaseBuffer();
}
if( mOwnTbmSurface )
{
if( tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
{
DALI_LOG_ERROR( "Failed to destroy tbm_surface\n" );
}
}
else
{
tbm_surface_internal_unref( mTbmSurface );
}
}
}
NativeImageSourceTizen::~NativeImageSourceTizen()
{
DestroySurface();
}
Any NativeImageSourceTizen::GetNativeImageSource() const
{
return Any( mTbmSurface );
}
bool NativeImageSourceTizen::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const
{
Dali::Mutex::ScopedLock lock( mMutex );
if( mTbmSurface != NULL )
{
tbm_surface_info_s surface_info;
if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE )
{
DALI_LOG_ERROR( "Fail to map tbm_surface\n" );
width = 0;
height = 0;
return false;
}
tbm_format format = surface_info.format;
uint32_t stride = surface_info.planes[0].stride;
unsigned char* ptr = surface_info.planes[0].ptr;
width = mWidth;
height = mHeight;
size_t lineSize;
size_t offset;
size_t cOffset;
switch( format )
{
case TBM_FORMAT_RGB888:
{
lineSize = width*3;
pixelFormat = Pixel::RGB888;
pixbuf.resize( lineSize*height );
unsigned char* bufptr = &pixbuf[0];
for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )
{
for( unsigned int c = 0; c < width; ++c )
{
cOffset = c*3;
offset = cOffset + r*stride;
*(bufptr+cOffset) = ptr[offset+2];
*(bufptr+cOffset+1) = ptr[offset+1];
*(bufptr+cOffset+2) = ptr[offset];
}
}
break;
}
case TBM_FORMAT_RGBA8888:
{
lineSize = width*4;
pixelFormat = Pixel::RGBA8888;
pixbuf.resize( lineSize*height );
unsigned char* bufptr = &pixbuf[0];
for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )
{
for( unsigned int c = 0; c < width; ++c )
{
cOffset = c*4;
offset = cOffset + r*stride;
*(bufptr+cOffset) = ptr[offset+3];
*(bufptr+cOffset+1) = ptr[offset+2];
*(bufptr+cOffset+2) = ptr[offset+1];
*(bufptr+cOffset+3) = ptr[offset];
}
}
break;
}
case TBM_FORMAT_ARGB8888:
{
lineSize = width*4;
pixelFormat = Pixel::RGBA8888;
pixbuf.resize( lineSize*height );
unsigned char* bufptr = &pixbuf[0];
for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )
{
for( unsigned int c = 0; c < width; ++c )
{
cOffset = c*4;
offset = cOffset + r*stride;
*(bufptr+cOffset) = ptr[offset+2];
*(bufptr+cOffset+1) = ptr[offset+1];
*(bufptr+cOffset+2) = ptr[offset];
*(bufptr+cOffset+3) = ptr[offset+3];
}
}
break;
}
default:
{
DALI_ASSERT_ALWAYS( 0 && "Tbm surface has unsupported pixel format.\n" );
return false;
}
}
if( tbm_surface_unmap( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
{
DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" );
}
return true;
}
DALI_LOG_WARNING( "TBM surface does not exist.\n" );
width = 0;
height = 0;
return false;
}
void NativeImageSourceTizen::SetSource( Any source )
{
Dali::Mutex::ScopedLock lock( mMutex );
DestroySurface();
mOwnTbmSurface = false;
mTbmSurface = GetSurfaceFromAny( source );
if( mTbmSurface != NULL )
{
mSetSource = true;
tbm_surface_internal_ref( mTbmSurface );
mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );
mWidth = tbm_surface_get_width( mTbmSurface );
mHeight = tbm_surface_get_height( mTbmSurface );
}
}
bool NativeImageSourceTizen::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )
{
uint32_t* formats;
uint32_t formatNum;
tbm_format format = TBM_FORMAT_RGB888;
switch( colorDepth )
{
case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
{
format = TBM_FORMAT_ARGB8888;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_8:
{
format = TBM_FORMAT_C8;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_16:
{
format = TBM_FORMAT_RGB565;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_24:
{
format = TBM_FORMAT_RGB888;
break;
}
case Dali::NativeImageSource::COLOR_DEPTH_32:
{
format = TBM_FORMAT_ARGB8888;
break;
}
}
if( tbm_surface_query_formats( &formats, &formatNum ) )
{
for( unsigned int i = 0; i < formatNum; i++ )
{
if( formats[i] == format )
{
free( formats );
return true;
}
}
}
free( formats );
return false;
}
bool NativeImageSourceTizen::CreateResource()
{
// casting from an unsigned int to a void *, which should then be cast back
// to an unsigned int in the driver.
EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer >(mTbmSurface);
if( !eglBuffer || !tbm_surface_internal_is_valid( mTbmSurface ) )
{
return false;
}
mEglImageExtensions = mEglGraphics->GetImageExtensions();
DALI_ASSERT_DEBUG( mEglImageExtensions );
mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer );
return mEglImageKHR != NULL;
}
void NativeImageSourceTizen::DestroyResource()
{
Dali::Mutex::ScopedLock lock( mMutex );
if( mEglImageKHR )
{
mEglImageExtensions->DestroyImageKHR(mEglImageKHR);
mEglImageKHR = NULL;
}
}
uint32_t NativeImageSourceTizen::TargetTexture()
{
mEglImageExtensions->TargetTextureKHR(mEglImageKHR);
return 0;
}
void NativeImageSourceTizen::PrepareTexture()
{
Dali::Mutex::ScopedLock lock( mMutex );
if( mSetSource )
{
void* eglImage = mEglImageKHR;
if( CreateResource() )
{
TargetTexture();
}
mEglImageExtensions->DestroyImageKHR( eglImage );
mSetSource = false;
}
}
const char* NativeImageSourceTizen::GetCustomFragmentPrefix() const
{
return FRAGMENT_PREFIX;
}
const char* NativeImageSourceTizen::GetCustomSamplerTypename() const
{
return SAMPLER_TYPE;
}
int NativeImageSourceTizen::GetTextureTarget() const
{
return GL_TEXTURE_EXTERNAL_OES;
}
Any NativeImageSourceTizen::GetNativeImageHandle() const
{
return GetNativeImageSource();
}
bool NativeImageSourceTizen::SourceChanged() const
{
return false;
}
bool NativeImageSourceTizen::CheckBlending( tbm_format format )
{
if( mTbmFormat != format )
{
for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i)
{
if( format == FORMATS_BLENDING_REQUIRED[i] )
{
mBlendingRequired = true;
break;
}
}
mTbmFormat = format;
}
return mBlendingRequired;
}
uint8_t* NativeImageSourceTizen::AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride )
{
Dali::Mutex::ScopedLock lock( mMutex );
if( mTbmSurface != NULL )
{
tbm_surface_info_s info;
if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &info) != TBM_SURFACE_ERROR_NONE )
{
DALI_LOG_ERROR( "Fail to map tbm_surface\n" );
width = 0;
height = 0;
return NULL;
}
tbm_surface_internal_ref( mTbmSurface );
mIsBufferAcquired = true;
stride = info.planes[0].stride;
width = mWidth;
height = mHeight;
return info.planes[0].ptr;
}
return NULL;
}
bool NativeImageSourceTizen::ReleaseBuffer()
{
Dali::Mutex::ScopedLock lock( mMutex );
bool ret = false;
if( mTbmSurface != NULL )
{
ret = ( tbm_surface_unmap( mTbmSurface ) == TBM_SURFACE_ERROR_NONE );
if( !ret )
{
DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" );
}
tbm_surface_internal_unref( mTbmSurface );
mIsBufferAcquired = false;
}
return ret;
}
} // namespace Adaptor
} // namespace internal
} // namespace Dali
| 23.657609 | 152 | 0.65832 | Coquinho |
4c8b57362fcf4c2b8573a0eea0588030b6d23f26 | 940 | hpp | C++ | include/Module/Decoder/Turbo/Decoder_turbo_std.hpp | FredrikBlomgren/aff3ct | fa616bd923b2dcf03a4cf119cceca51cf810d483 | [
"MIT"
] | 315 | 2016-06-21T13:32:14.000Z | 2022-03-28T09:33:59.000Z | include/Module/Decoder/Turbo/Decoder_turbo_std.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 153 | 2017-01-17T03:51:06.000Z | 2022-03-24T15:39:26.000Z | include/Module/Decoder/Turbo/Decoder_turbo_std.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 119 | 2017-01-04T14:31:58.000Z | 2022-03-21T08:34:16.000Z | /*!
* \file
* \brief Class module::Decoder_turbo_std.
*/
#ifndef DECODER_TURBO_NAIVE_HPP
#define DECODER_TURBO_NAIVE_HPP
#include "Module/Interleaver/Interleaver.hpp"
#include "Module/Decoder/Decoder_SISO.hpp"
#include "Module/Decoder/Turbo/Decoder_turbo.hpp"
namespace aff3ct
{
namespace module
{
template <typename B = int, typename R = float>
class Decoder_turbo_std : public Decoder_turbo<B,R>
{
public:
Decoder_turbo_std(const int& K,
const int& N,
const int& n_ite,
const Decoder_SISO<B,R> &siso_n,
const Decoder_SISO<B,R> &siso_i,
const Interleaver<R> &pi,
const bool buffered_encoding = true);
virtual ~Decoder_turbo_std() = default;
virtual Decoder_turbo_std<B,R>* clone() const;
protected:
virtual int _decode_siho(const R *Y_N, B *V_K, const size_t frame_id);
};
}
}
#endif /* DECODER_TURBO_NAIVE_HPP */
| 25.405405 | 71 | 0.667021 | FredrikBlomgren |
4c8d334444a7d507f32a37789da0a5c4e52b0128 | 17,762 | cpp | C++ | export/windows/cpp/obj/src/openfl/_legacy/utils/ArrayBufferView.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/openfl/_legacy/utils/ArrayBufferView.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/openfl/_legacy/utils/ArrayBufferView.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_ArrayBufferView
#include <openfl/_legacy/utils/ArrayBufferView.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_ByteArray
#include <openfl/_legacy/utils/ByteArray.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_IDataInput
#include <openfl/_legacy/utils/IDataInput.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_IDataOutput
#include <openfl/_legacy/utils/IDataOutput.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_IMemoryRange
#include <openfl/_legacy/utils/IMemoryRange.h>
#endif
namespace openfl{
namespace _legacy{
namespace utils{
void ArrayBufferView_obj::__construct( ::Dynamic lengthOrBuffer,hx::Null< Int > __o_byteOffset, ::Dynamic length){
Int byteOffset = __o_byteOffset.Default(0);
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","new",0xc608e72f,"openfl._legacy.utils.ArrayBufferView.new","openfl/_legacy/utils/ArrayBufferView.hx",24,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(lengthOrBuffer,"lengthOrBuffer")
HX_STACK_ARG(byteOffset,"byteOffset")
HX_STACK_ARG(length,"length")
HXLINE( 26) Bool _hx_tmp = ::Std_obj::is(lengthOrBuffer,hx::ClassOf< ::Int >());
HXDLIN( 26) if (_hx_tmp) {
HXLINE( 28) this->byteLength = ::Std_obj::_hx_int(lengthOrBuffer);
HXLINE( 29) this->byteOffset = (int)0;
HXLINE( 30) Int _hx_tmp1 = ::Std_obj::_hx_int(lengthOrBuffer);
HXDLIN( 30) this->buffer = ::openfl::_legacy::utils::ByteArray_obj::__new(_hx_tmp1);
}
else {
HXLINE( 34) this->buffer = lengthOrBuffer;
HXLINE( 36) Bool _hx_tmp2 = hx::IsNull( this->buffer );
HXDLIN( 36) if (_hx_tmp2) {
HXLINE( 38) HX_STACK_DO_THROW(HX_("Invalid input buffer",3f,39,2d,2c));
}
HXLINE( 42) this->byteOffset = byteOffset;
HXLINE( 44) if ((byteOffset > this->buffer->length)) {
HXLINE( 46) HX_STACK_DO_THROW(HX_("Invalid starting position",80,e7,c8,7a));
}
HXLINE( 50) Bool _hx_tmp3 = hx::IsNull( length );
HXDLIN( 50) if (_hx_tmp3) {
HXLINE( 52) this->byteLength = (this->buffer->length - byteOffset);
}
else {
HXLINE( 56) this->byteLength = length;
HXLINE( 58) if (((this->byteLength + byteOffset) > this->buffer->length)) {
HXLINE( 60) HX_STACK_DO_THROW(HX_("Invalid buffer length",fd,68,79,28));
}
}
}
HXLINE( 68) this->buffer->bigEndian = false;
HXLINE( 71) this->bytes = this->buffer->b;
}
Dynamic ArrayBufferView_obj::__CreateEmpty() { return new ArrayBufferView_obj; }
hx::ObjectPtr< ArrayBufferView_obj > ArrayBufferView_obj::__new( ::Dynamic lengthOrBuffer,hx::Null< Int > __o_byteOffset, ::Dynamic length)
{
hx::ObjectPtr< ArrayBufferView_obj > _hx_result = new ArrayBufferView_obj();
_hx_result->__construct(lengthOrBuffer,__o_byteOffset,length);
return _hx_result;
}
Dynamic ArrayBufferView_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< ArrayBufferView_obj > _hx_result = new ArrayBufferView_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]);
return _hx_result;
}
static ::openfl::_legacy::utils::IMemoryRange_obj _hx_openfl__legacy_utils_ArrayBufferView__hx_openfl__legacy_utils_IMemoryRange= {
( ::openfl::_legacy::utils::ByteArray (hx::Object::*)())&::openfl::_legacy::utils::ArrayBufferView_obj::getByteBuffer,
( Int (hx::Object::*)())&::openfl::_legacy::utils::ArrayBufferView_obj::getStart,
( Int (hx::Object::*)())&::openfl::_legacy::utils::ArrayBufferView_obj::getLength,
};
void *ArrayBufferView_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0x0ecba48c: return &_hx_openfl__legacy_utils_ArrayBufferView__hx_openfl__legacy_utils_IMemoryRange;
}
#ifdef HXCPP_SCRIPTABLE
return super::_hx_getInterface(inHash);
#else
return 0;
#endif
}
::openfl::_legacy::utils::ByteArray ArrayBufferView_obj::getByteBuffer(){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getByteBuffer",0x3010f1ed,"openfl._legacy.utils.ArrayBufferView.getByteBuffer","openfl/_legacy/utils/ArrayBufferView.hx",79,0xb2044664)
HX_STACK_THIS(this)
HXLINE( 79) return this->buffer;
}
HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getByteBuffer,return )
Float ArrayBufferView_obj::getFloat32(Int position){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getFloat32",0x59ee0856,"openfl._legacy.utils.ArrayBufferView.getFloat32","openfl/_legacy/utils/ArrayBufferView.hx",87,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HXLINE( 87) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 87) return ::__hxcpp_memory_get_float(this->bytes,_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getFloat32,return )
Int ArrayBufferView_obj::getInt16(Int position){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getInt16",0x25f27bef,"openfl._legacy.utils.ArrayBufferView.getInt16","openfl/_legacy/utils/ArrayBufferView.hx",99,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HXLINE( 99) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 99) return ::__hxcpp_memory_get_i16(this->bytes,_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getInt16,return )
Int ArrayBufferView_obj::getInt32(Int position){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getInt32",0x25f27da9,"openfl._legacy.utils.ArrayBufferView.getInt32","openfl/_legacy/utils/ArrayBufferView.hx",111,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HXLINE( 111) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 111) return ::__hxcpp_memory_get_i32(this->bytes,_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getInt32,return )
Int ArrayBufferView_obj::getLength(){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getLength",0x0ee2ba2b,"openfl._legacy.utils.ArrayBufferView.getLength","openfl/_legacy/utils/ArrayBufferView.hx",122,0xb2044664)
HX_STACK_THIS(this)
HXLINE( 122) return this->byteLength;
}
HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getLength,return )
::Dynamic ArrayBufferView_obj::getNativePointer(){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getNativePointer",0xd6cecd41,"openfl._legacy.utils.ArrayBufferView.getNativePointer","openfl/_legacy/utils/ArrayBufferView.hx",130,0xb2044664)
HX_STACK_THIS(this)
HXLINE( 130) return this->buffer->getNativePointer();
}
HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getNativePointer,return )
Int ArrayBufferView_obj::getStart(){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getStart",0xebdd5ebd,"openfl._legacy.utils.ArrayBufferView.getStart","openfl/_legacy/utils/ArrayBufferView.hx",140,0xb2044664)
HX_STACK_THIS(this)
HXLINE( 140) return this->byteOffset;
}
HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getStart,return )
Int ArrayBufferView_obj::getUInt8(Int position){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getUInt8",0xf64839d9,"openfl._legacy.utils.ArrayBufferView.getUInt8","openfl/_legacy/utils/ArrayBufferView.hx",148,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HXLINE( 148) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 148) return ::__hxcpp_memory_get_byte(this->bytes,_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getUInt8,return )
void ArrayBufferView_obj::setFloat32(Int position,Float value){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setFloat32",0x5d6ba6ca,"openfl._legacy.utils.ArrayBufferView.setFloat32","openfl/_legacy/utils/ArrayBufferView.hx",160,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HX_STACK_ARG(value,"value")
HXLINE( 160) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 160) ::__hxcpp_memory_set_float(this->bytes,_hx_tmp,value);
}
HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setFloat32,(void))
void ArrayBufferView_obj::setInt16(Int position,Int value){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setInt16",0xd44fd563,"openfl._legacy.utils.ArrayBufferView.setInt16","openfl/_legacy/utils/ArrayBufferView.hx",172,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HX_STACK_ARG(value,"value")
HXLINE( 172) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 172) ::__hxcpp_memory_set_i16(this->bytes,_hx_tmp,value);
}
HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setInt16,(void))
void ArrayBufferView_obj::setInt32(Int position,Int value){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setInt32",0xd44fd71d,"openfl._legacy.utils.ArrayBufferView.setInt32","openfl/_legacy/utils/ArrayBufferView.hx",184,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HX_STACK_ARG(value,"value")
HXLINE( 184) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 184) ::__hxcpp_memory_set_i32(this->bytes,_hx_tmp,value);
}
HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setInt32,(void))
void ArrayBufferView_obj::setUInt8(Int position,Int value){
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setUInt8",0xa4a5934d,"openfl._legacy.utils.ArrayBufferView.setUInt8","openfl/_legacy/utils/ArrayBufferView.hx",196,0xb2044664)
HX_STACK_THIS(this)
HX_STACK_ARG(position,"position")
HX_STACK_ARG(value,"value")
HXLINE( 196) Int _hx_tmp = (position + this->byteOffset);
HXDLIN( 196) ::__hxcpp_memory_set_byte(this->bytes,_hx_tmp,value);
}
HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setUInt8,(void))
::String ArrayBufferView_obj::invalidDataIndex;
ArrayBufferView_obj::ArrayBufferView_obj()
{
}
void ArrayBufferView_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(ArrayBufferView);
HX_MARK_MEMBER_NAME(buffer,"buffer");
HX_MARK_MEMBER_NAME(byteOffset,"byteOffset");
HX_MARK_MEMBER_NAME(byteLength,"byteLength");
HX_MARK_MEMBER_NAME(bytes,"bytes");
HX_MARK_END_CLASS();
}
void ArrayBufferView_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(buffer,"buffer");
HX_VISIT_MEMBER_NAME(byteOffset,"byteOffset");
HX_VISIT_MEMBER_NAME(byteLength,"byteLength");
HX_VISIT_MEMBER_NAME(bytes,"bytes");
}
hx::Val ArrayBufferView_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"bytes") ) { return hx::Val( bytes); }
break;
case 6:
if (HX_FIELD_EQ(inName,"buffer") ) { return hx::Val( buffer); }
break;
case 8:
if (HX_FIELD_EQ(inName,"getInt16") ) { return hx::Val( getInt16_dyn()); }
if (HX_FIELD_EQ(inName,"getInt32") ) { return hx::Val( getInt32_dyn()); }
if (HX_FIELD_EQ(inName,"getStart") ) { return hx::Val( getStart_dyn()); }
if (HX_FIELD_EQ(inName,"getUInt8") ) { return hx::Val( getUInt8_dyn()); }
if (HX_FIELD_EQ(inName,"setInt16") ) { return hx::Val( setInt16_dyn()); }
if (HX_FIELD_EQ(inName,"setInt32") ) { return hx::Val( setInt32_dyn()); }
if (HX_FIELD_EQ(inName,"setUInt8") ) { return hx::Val( setUInt8_dyn()); }
break;
case 9:
if (HX_FIELD_EQ(inName,"getLength") ) { return hx::Val( getLength_dyn()); }
break;
case 10:
if (HX_FIELD_EQ(inName,"byteOffset") ) { return hx::Val( byteOffset); }
if (HX_FIELD_EQ(inName,"byteLength") ) { return hx::Val( byteLength); }
if (HX_FIELD_EQ(inName,"getFloat32") ) { return hx::Val( getFloat32_dyn()); }
if (HX_FIELD_EQ(inName,"setFloat32") ) { return hx::Val( setFloat32_dyn()); }
break;
case 13:
if (HX_FIELD_EQ(inName,"getByteBuffer") ) { return hx::Val( getByteBuffer_dyn()); }
break;
case 16:
if (HX_FIELD_EQ(inName,"getNativePointer") ) { return hx::Val( getNativePointer_dyn()); }
}
return super::__Field(inName,inCallProp);
}
bool ArrayBufferView_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 16:
if (HX_FIELD_EQ(inName,"invalidDataIndex") ) { outValue = invalidDataIndex; return true; }
}
return false;
}
hx::Val ArrayBufferView_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"bytes") ) { bytes=inValue.Cast< ::Array< unsigned char > >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"buffer") ) { buffer=inValue.Cast< ::openfl::_legacy::utils::ByteArray >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"byteOffset") ) { byteOffset=inValue.Cast< Int >(); return inValue; }
if (HX_FIELD_EQ(inName,"byteLength") ) { byteLength=inValue.Cast< Int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
bool ArrayBufferView_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 16:
if (HX_FIELD_EQ(inName,"invalidDataIndex") ) { invalidDataIndex=ioValue.Cast< ::String >(); return true; }
}
return false;
}
void ArrayBufferView_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("buffer","\x00","\xbd","\x94","\xd0"));
outFields->push(HX_HCSTRING("byteOffset","\xbb","\x20","\x44","\x38"));
outFields->push(HX_HCSTRING("byteLength","\x0e","\x1e","\x0c","\x77"));
outFields->push(HX_HCSTRING("bytes","\x6b","\x08","\x98","\xbd"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo ArrayBufferView_obj_sMemberStorageInfo[] = {
{hx::fsObject /*::openfl::_legacy::utils::ByteArray*/ ,(int)offsetof(ArrayBufferView_obj,buffer),HX_HCSTRING("buffer","\x00","\xbd","\x94","\xd0")},
{hx::fsInt,(int)offsetof(ArrayBufferView_obj,byteOffset),HX_HCSTRING("byteOffset","\xbb","\x20","\x44","\x38")},
{hx::fsInt,(int)offsetof(ArrayBufferView_obj,byteLength),HX_HCSTRING("byteLength","\x0e","\x1e","\x0c","\x77")},
{hx::fsObject /*Array< unsigned char >*/ ,(int)offsetof(ArrayBufferView_obj,bytes),HX_HCSTRING("bytes","\x6b","\x08","\x98","\xbd")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo ArrayBufferView_obj_sStaticStorageInfo[] = {
{hx::fsString,(void *) &ArrayBufferView_obj::invalidDataIndex,HX_HCSTRING("invalidDataIndex","\x91","\x8a","\x9d","\x3b")},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String ArrayBufferView_obj_sMemberFields[] = {
HX_HCSTRING("buffer","\x00","\xbd","\x94","\xd0"),
HX_HCSTRING("byteOffset","\xbb","\x20","\x44","\x38"),
HX_HCSTRING("byteLength","\x0e","\x1e","\x0c","\x77"),
HX_HCSTRING("bytes","\x6b","\x08","\x98","\xbd"),
HX_HCSTRING("getByteBuffer","\x5e","\xa2","\x0b","\x05"),
HX_HCSTRING("getFloat32","\x45","\x17","\x6a","\x39"),
HX_HCSTRING("getInt16","\x1e","\xa1","\xf7","\x1d"),
HX_HCSTRING("getInt32","\xd8","\xa2","\xf7","\x1d"),
HX_HCSTRING("getLength","\x1c","\x1e","\x5e","\x1b"),
HX_HCSTRING("getNativePointer","\x70","\x39","\x53","\x7a"),
HX_HCSTRING("getStart","\xec","\x83","\xe2","\xe3"),
HX_HCSTRING("getUInt8","\x08","\x5f","\x4d","\xee"),
HX_HCSTRING("setFloat32","\xb9","\xb5","\xe7","\x3c"),
HX_HCSTRING("setInt16","\x92","\xfa","\x54","\xcc"),
HX_HCSTRING("setInt32","\x4c","\xfc","\x54","\xcc"),
HX_HCSTRING("setUInt8","\x7c","\xb8","\xaa","\x9c"),
::String(null()) };
static void ArrayBufferView_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(ArrayBufferView_obj::__mClass,"__mClass");
HX_MARK_MEMBER_NAME(ArrayBufferView_obj::invalidDataIndex,"invalidDataIndex");
};
#ifdef HXCPP_VISIT_ALLOCS
static void ArrayBufferView_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(ArrayBufferView_obj::__mClass,"__mClass");
HX_VISIT_MEMBER_NAME(ArrayBufferView_obj::invalidDataIndex,"invalidDataIndex");
};
#endif
hx::Class ArrayBufferView_obj::__mClass;
static ::String ArrayBufferView_obj_sStaticFields[] = {
HX_HCSTRING("invalidDataIndex","\x91","\x8a","\x9d","\x3b"),
::String(null())
};
void ArrayBufferView_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl._legacy.utils.ArrayBufferView","\xbd","\x23","\x44","\x5c");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &ArrayBufferView_obj::__GetStatic;
__mClass->mSetStaticField = &ArrayBufferView_obj::__SetStatic;
__mClass->mMarkFunc = ArrayBufferView_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(ArrayBufferView_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(ArrayBufferView_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< ArrayBufferView_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = ArrayBufferView_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ArrayBufferView_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ArrayBufferView_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void ArrayBufferView_obj::__boot()
{
{
HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","boot",0x79da6283,"openfl._legacy.utils.ArrayBufferView.boot","openfl/_legacy/utils/ArrayBufferView.hx",18,0xb2044664)
HXLINE( 18) invalidDataIndex = HX_("Invalid data index",45,2f,02,8f);
}
}
} // end namespace openfl
} // end namespace _legacy
} // end namespace utils
| 41.990544 | 210 | 0.721371 | TinyPlanetStudios |
4c8ec46d7c8e5b75c587e9ef9ed0b6fee0bffd90 | 3,523 | cpp | C++ | c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/src/sys/io/_Process/Stdin.cpp | amenoyoya/old-project | 640ec696af5d18267d86629098f41451857f8103 | [
"MIT"
] | null | null | null | c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/src/sys/io/_Process/Stdin.cpp | amenoyoya/old-project | 640ec696af5d18267d86629098f41451857f8103 | [
"MIT"
] | 1 | 2019-07-07T09:52:20.000Z | 2019-07-07T09:52:20.000Z | c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/src/sys/io/_Process/Stdin.cpp | amenoyoya/old-project | 640ec696af5d18267d86629098f41451857f8103 | [
"MIT"
] | null | null | null | #include <hxcpp.h>
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_haxe_io_Output
#include <haxe/io/Output.h>
#endif
#ifndef INCLUDED_sys_io__Process_Stdin
#include <sys/io/_Process/Stdin.h>
#endif
namespace sys{
namespace io{
namespace _Process{
Void Stdin_obj::__construct(Dynamic p)
{
HX_STACK_FRAME("sys.io._Process.Stdin","new",0xd3131563,"sys.io._Process.Stdin.new","C:\\App\\Haxe-3.1.3\\haxe\\std/cpp/_std/sys/io/Process.hx",29,0x703fbaf1)
HX_STACK_THIS(this)
HX_STACK_ARG(p,"p")
{
HX_STACK_LINE(30)
this->p = p;
HX_STACK_LINE(31)
::haxe::io::Bytes _g = ::haxe::io::Bytes_obj::alloc((int)1); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(31)
this->buf = _g;
}
;
return null();
}
//Stdin_obj::~Stdin_obj() { }
Dynamic Stdin_obj::__CreateEmpty() { return new Stdin_obj; }
hx::ObjectPtr< Stdin_obj > Stdin_obj::__new(Dynamic p)
{ hx::ObjectPtr< Stdin_obj > result = new Stdin_obj();
result->__construct(p);
return result;}
Dynamic Stdin_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< Stdin_obj > result = new Stdin_obj();
result->__construct(inArgs[0]);
return result;}
Stdin_obj::Stdin_obj()
{
}
void Stdin_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(Stdin);
HX_MARK_MEMBER_NAME(p,"p");
HX_MARK_MEMBER_NAME(buf,"buf");
HX_MARK_END_CLASS();
}
void Stdin_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(p,"p");
HX_VISIT_MEMBER_NAME(buf,"buf");
}
Dynamic Stdin_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"p") ) { return p; }
break;
case 3:
if (HX_FIELD_EQ(inName,"buf") ) { return buf; }
}
return super::__Field(inName,inCallProp);
}
Dynamic Stdin_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"p") ) { p=inValue.Cast< Dynamic >(); return inValue; }
break;
case 3:
if (HX_FIELD_EQ(inName,"buf") ) { buf=inValue.Cast< ::haxe::io::Bytes >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void Stdin_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_CSTRING("p"));
outFields->push(HX_CSTRING("buf"));
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
String(null()) };
#if HXCPP_SCRIPTABLE
static hx::StorageInfo sMemberStorageInfo[] = {
{hx::fsObject /*Dynamic*/ ,(int)offsetof(Stdin_obj,p),HX_CSTRING("p")},
{hx::fsObject /*::haxe::io::Bytes*/ ,(int)offsetof(Stdin_obj,buf),HX_CSTRING("buf")},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String sMemberFields[] = {
HX_CSTRING("p"),
HX_CSTRING("buf"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(Stdin_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(Stdin_obj::__mClass,"__mClass");
};
#endif
Class Stdin_obj::__mClass;
void Stdin_obj::__register()
{
hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("sys.io._Process.Stdin"), hx::TCanCast< Stdin_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics
#ifdef HXCPP_VISIT_ALLOCS
, sVisitStatics
#endif
#ifdef HXCPP_SCRIPTABLE
, sMemberStorageInfo
#endif
);
}
void Stdin_obj::__boot()
{
}
} // end namespace sys
} // end namespace io
} // end namespace _Process
| 24.130137 | 159 | 0.688334 | amenoyoya |
4c8f76cf36d62c885082b9dcf6bfc294222323c3 | 3,367 | cpp | C++ | src/brylageo.cpp | KPO-2020-2021/zad5_3-KrystianCyga | e978ed7964bc863771d08a5dce2af491766249b4 | [
"Unlicense"
] | null | null | null | src/brylageo.cpp | KPO-2020-2021/zad5_3-KrystianCyga | e978ed7964bc863771d08a5dce2af491766249b4 | [
"Unlicense"
] | null | null | null | src/brylageo.cpp | KPO-2020-2021/zad5_3-KrystianCyga | e978ed7964bc863771d08a5dce2af491766249b4 | [
"Unlicense"
] | null | null | null | #include "../inc/brylageo.hh"
#define FOLDER_WLASCIWY "../BrylyWzorcowe/"
#define FOLDER_ROBOCZY "../datasets/"
#define WZORZEC_SZESCIAN "../BrylyWzorcowe/szescian.dat"
#define WZORZEC_ROTOR "../BrylyWzorcowe/graniastoslup6.dat"
#include <fstream>
brylageo::brylageo()
{
skala[0] = 1;
skala[1] = 1;
skala[2] = 2;
}
brylageo::brylageo(vector3d polozenie, double kat, const vector3d skala2)
{
skala = skala2;
trans = polozenie;
Orientacji_stopnie = kat;
}
void brylageo::pobierz_nazwe_wzorca(const std::string nazwa1){
NazwaWzorcowego=nazwa1;
}
void brylageo::pobierz_nazwe_final(const std::string nazwa2){
NazwaWyjsciowego=nazwa2;
}
void brylageo::skaluj(vector3d &skala2)
{
skala2[0] *= skala[0];
skala2[1] *= skala[1];
skala2[2] *= skala[2];
}
void brylageo::ObrocWzgledemOsiOZ(double kat, vector3d &Polozenie)
{
vector3d wynik;
double rad = kat * M_PI / 180;
wynik[0] = Polozenie[0] * cos(rad) - Polozenie[1] * sin(rad);
wynik[1] = Polozenie[0] * sin(rad) + Polozenie[1] * cos(rad);
Polozenie[0] = wynik[0];
Polozenie[1] = wynik[1];
}
void brylageo::TransformujWspolrzednePunktu(vector3d &Polozenie)
{
vector3d wynik;
ObrocWzgledemOsiOZ(Orientacji_stopnie, Polozenie);
skaluj(Polozenie);
wynik = Polozenie + trans;
Polozenie = wynik;
}
bool brylageo::wczytajbryle()
{
std::ifstream Plik_BrylaWzorcowa(NazwaWzorcowego);
if (!Plik_BrylaWzorcowa.is_open())
{
std::cerr << std::endl
<< " Blad otwarcia do odczytu pliku: " << NazwaWzorcowego << std::endl
<< std::endl;
return false;
}
vector3d PoTrans;
long unsigned int index = 0;
wierzcholki.reserve(17);
for (unsigned int nrWierz = 0; nrWierz < NumerWierzcholka;++nrWierz)
{
Plik_BrylaWzorcowa >> PoTrans;
TransformujWspolrzednePunktu(PoTrans);
++index;
if (wierzcholki.size() < index)
wierzcholki.push_back(PoTrans);
else
wierzcholki[index] = PoTrans;
}
index = 0;
return true;
}
void brylageo::ustaw_wielkosc(vector3d &tmp){
if (wierzcholki.size() == 0)
{
wielkosc[0][0] = 1000;
wielkosc[0][1] = 1000;
}
if (tmp[0] < wielkosc[0][0])
wielkosc[0][0] = tmp[0];
if (tmp[0] > wielkosc[1][0])
wielkosc[1][0] = tmp[0];
if (tmp[1] < wielkosc[0][1])
wielkosc[0][1] = tmp[1];
if (tmp[1] > wielkosc[1][1])
wielkosc[1][1] = tmp[1];
}
bool brylageo::zapiszbryle()
{
skala[0] = 1;
skala[1] = 1;
skala[2] = 1;
std::ofstream PLIK(NazwaWyjsciowego);
if (!PLIK.is_open())
{
std::cerr << std::endl
<< " Blad otwarcia do odczytu pliku: " << NazwaWyjsciowego << std::endl
<< std::endl;
return false;
}
vector3d PoTrans;
int index = 0;
{
for (unsigned int nrWierz = 0; nrWierz < NumerWierzcholka;
++nrWierz)
{
PoTrans = wierzcholki[nrWierz];
TransformujWspolrzednePunktu(PoTrans);
ustaw_wielkosc(PoTrans);
PLIK << std::fixed << PoTrans << std::endl;
++index;
if (index == 4)
{
index = 0;
PLIK << std::endl;
}
}
PLIK << std::endl;
}
return !PLIK.fail();
} | 23.711268 | 89 | 0.582418 | KPO-2020-2021 |
4c911c3b6a5398610177b6b451ce58955c448d14 | 2,659 | cpp | C++ | native/cocos/core/geometry/Distance.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/geometry/Distance.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/geometry/Distance.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "cocos/core/geometry/Distance.h"
#include "cocos/core/geometry/AABB.h"
#include "cocos/core/geometry/Obb.h"
#include "cocos/core/geometry/Plane.h"
#include "cocos/math/Mat4.h"
#include <algorithm>
#include "base/std/container/array.h"
#include "cocos/math/Utils.h"
#include "cocos/math/Vec3.h"
namespace cc {
namespace geometry {
float pointPlane(const Vec3 &point, const Plane &plane) {
return Vec3::dot(plane.n, point) - plane.d;
}
Vec3 *ptPointPlane(Vec3 *out, const Vec3 &point, const Plane &plane) {
auto t = pointPlane(point, plane);
*out = point - t * plane.n;
return out;
}
Vec3 *ptPointAabb(Vec3 *out, const Vec3 &point, const AABB &aabb) {
auto min = aabb.getCenter() - aabb.getHalfExtents();
auto max = aabb.getCenter() + aabb.getHalfExtents();
*out = {cc::mathutils::clamp(point.x, min.x, max.x),
cc::mathutils::clamp(point.y, min.y, max.y),
cc::mathutils::clamp(point.z, min.z, max.z)};
return out;
}
Vec3 *ptPointObb(Vec3 *out, const Vec3 &point, const OBB &obb) {
ccstd::array<Vec3, 3> u = {
Vec3{obb.orientation.m[0], obb.orientation.m[1], obb.orientation.m[2]},
Vec3{obb.orientation.m[3], obb.orientation.m[4], obb.orientation.m[5]},
Vec3{obb.orientation.m[6], obb.orientation.m[7], obb.orientation.m[8]},
};
ccstd::array<float, 3> e = {obb.halfExtents.x, obb.halfExtents.y, obb.halfExtents.z};
auto d = point - obb.center;
float dist = 0.0F;
// Start result at center of obb; make steps from there
*out = obb.center;
// For each OBB axis...
for (int i = 0; i < 3; i++) {
// ...project d onto that axis to get the distance
// along the axis of d from the obb center
dist = Vec3::dot(d, u[i]);
// if distance farther than the obb extents, clamp to the obb
dist = cc::mathutils::clamp(dist, -e[i], e[i]);
// Step that distance along the axis to get world coordinate
*out += (dist * u[i]);
}
return out;
}
Vec3 *ptPointLine(Vec3 *out, const Vec3 &point, const Vec3 &linePointA, const Vec3 &linePointB) {
auto dir = linePointA - linePointB;
auto dirSquared = dir.lengthSquared();
if (dirSquared == 0.0F) {
// The point is at the segment start.
*out = linePointA;
} else {
// Calculate the projection of the point onto the line extending through the segment.
auto ap = point - linePointA;
auto t = Vec3::dot(ap, dir) / dirSquared;
*out = linePointA + cc::mathutils::clamp(t, 0.0F, 1.0F) * dir;
}
return out;
}
} // namespace geometry
} // namespace cc | 33.2375 | 97 | 0.622038 | SteveLau-GameDeveloper |
4c91fcba34fa734d0b1a3dbd18f4299bc4fd87f4 | 42,011 | hpp | C++ | fem/fespace.hpp | Arthur-laurent312/mfem | 913361dd0db723d07e9c7492102f8b887acabc48 | [
"BSD-3-Clause"
] | null | null | null | fem/fespace.hpp | Arthur-laurent312/mfem | 913361dd0db723d07e9c7492102f8b887acabc48 | [
"BSD-3-Clause"
] | null | null | null | fem/fespace.hpp | Arthur-laurent312/mfem | 913361dd0db723d07e9c7492102f8b887acabc48 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_FESPACE
#define MFEM_FESPACE
#include "../config/config.hpp"
#include "../linalg/sparsemat.hpp"
#include "../mesh/mesh.hpp"
#include "fe_coll.hpp"
#include "restriction.hpp"
#include <iostream>
#include <unordered_map>
namespace mfem
{
/** @brief The ordering method used when the number of unknowns per mesh node
(vector dimension) is bigger than 1. */
class Ordering
{
public:
/// %Ordering methods:
enum Type
{
byNODES, /**< loop first over the nodes (inner loop) then over the vector
dimension (outer loop); symbolically it can be represented
as: XXX...,YYY...,ZZZ... */
byVDIM /**< loop first over the vector dimension (inner loop) then over
the nodes (outer loop); symbolically it can be represented
as: XYZ,XYZ,XYZ,... */
};
template <Type Ord>
static inline int Map(int ndofs, int vdim, int dof, int vd);
template <Type Ord>
static void DofsToVDofs(int ndofs, int vdim, Array<int> &dofs);
};
template <> inline int
Ordering::Map<Ordering::byNODES>(int ndofs, int vdim, int dof, int vd)
{
MFEM_ASSERT(dof < ndofs && -1-dof < ndofs && 0 <= vd && vd < vdim, "");
return (dof >= 0) ? dof+ndofs*vd : dof-ndofs*vd;
}
template <> inline int
Ordering::Map<Ordering::byVDIM>(int ndofs, int vdim, int dof, int vd)
{
MFEM_ASSERT(dof < ndofs && -1-dof < ndofs && 0 <= vd && vd < vdim, "");
return (dof >= 0) ? vd+vdim*dof : -1-(vd+vdim*(-1-dof));
}
/// Constants describing the possible orderings of the DOFs in one element.
enum class ElementDofOrdering
{
/// Native ordering as defined by the FiniteElement.
/** This ordering can be used by tensor-product elements when the
interpolation from the DOFs to quadrature points does not use the
tensor-product structure. */
NATIVE,
/// Lexicographic ordering for tensor-product FiniteElements.
/** This ordering can be used only with tensor-product elements. */
LEXICOGRAPHIC
};
// Forward declarations
class NURBSExtension;
class BilinearFormIntegrator;
class QuadratureSpace;
class QuadratureInterpolator;
class FaceQuadratureInterpolator;
/** @brief Class FiniteElementSpace - responsible for providing FEM view of the
mesh, mainly managing the set of degrees of freedom. */
class FiniteElementSpace
{
friend class InterpolationGridTransfer;
friend class PRefinementTransferOperator;
friend void Mesh::Swap(Mesh &, bool);
protected:
/// The mesh that FE space lives on (not owned).
Mesh *mesh;
/// Associated FE collection (not owned).
const FiniteElementCollection *fec;
/// %Vector dimension (number of unknowns per degree of freedom).
int vdim;
/** Type of ordering of the vector dofs when #vdim > 1.
- Ordering::byNODES - first nodes, then vector dimension,
- Ordering::byVDIM - first vector dimension, then nodes */
Ordering::Type ordering;
/// Number of degrees of freedom. Number of unknowns is #ndofs * #vdim.
int ndofs;
/** Polynomial order for each element. If empty, all elements are assumed
to be of the default order (fec->GetOrder()). */
Array<char> elem_order;
int nvdofs, nedofs, nfdofs, nbdofs;
int uni_fdof; ///< # of single face DOFs if all faces uniform; -1 otherwise
int *bdofs; ///< internal DOFs of elements if mixed/var-order; NULL otherwise
/** Variable order spaces only: DOF assignments for edges and faces, see
docs in MakeDofTable. For constant order spaces the tables are empty. */
Table var_edge_dofs;
Table var_face_dofs; ///< NOTE: also used for spaces with mixed faces
/** Additional data for the var_*_dofs tables: individual variant orders
(these are basically alternate J arrays for var_edge/face_dofs). */
Array<char> var_edge_orders, var_face_orders;
// precalculated DOFs for each element, boundary element, and face
mutable Table *elem_dof; // owned (except in NURBS FE space)
mutable Table *bdr_elem_dof; // owned (except in NURBS FE space)
mutable Table *face_dof; // owned; in var-order space contains variant 0 DOFs
Array<int> dof_elem_array, dof_ldof_array;
NURBSExtension *NURBSext;
int own_ext;
mutable Array<int> face_to_be; // NURBS FE space only
/** Matrix representing the prolongation from the global conforming dofs to
a set of intermediate partially conforming dofs, e.g. the dofs associated
with a "cut" space on a non-conforming mesh. */
mutable SparseMatrix *cP; // owned
/// Conforming restriction matrix such that cR.cP=I.
mutable SparseMatrix *cR; // owned
/// A version of the conforming restriction matrix for variable-order spaces.
mutable SparseMatrix *cR_hp; // owned
mutable bool cP_is_set;
/// Transformation to apply to GridFunctions after space Update().
OperatorHandle Th;
/// The element restriction operators, see GetElementRestriction().
mutable OperatorHandle L2E_nat, L2E_lex;
/// The face restriction operators, see GetFaceRestriction().
using key_face = std::tuple<bool, ElementDofOrdering, FaceType, L2FaceValues>;
struct key_hash
{
std::size_t operator()(const key_face& k) const
{
return std::get<0>(k)
+ 2 * (int)std::get<1>(k)
+ 4 * (int)std::get<2>(k)
+ 8 * (int)std::get<3>(k);
}
};
using map_L2F = std::unordered_map<const key_face,Operator*,key_hash>;
mutable map_L2F L2F;
mutable Array<QuadratureInterpolator*> E2Q_array;
mutable Array<FaceQuadratureInterpolator*> E2IFQ_array;
mutable Array<FaceQuadratureInterpolator*> E2BFQ_array;
/** Update counter, incremented every time the space is constructed/updated.
Used by GridFunctions to check if they are up to date with the space. */
long sequence;
/** Mesh sequence number last seen when constructing the space. The space
needs updating if Mesh::GetSequence() is larger than this. */
long mesh_sequence;
/// True if at least one element order changed (variable-order space only).
bool orders_changed;
bool relaxed_hp; // see SetRelaxedHpConformity()
void UpdateNURBS();
void Construct();
void Destroy();
void BuildElementToDofTable() const;
void BuildBdrElementToDofTable() const;
void BuildFaceToDofTable() const;
/** @brief Generates partial face_dof table for a NURBS space.
The table is only defined for exterior faces that coincide with a
boundary. */
void BuildNURBSFaceToDofTable() const;
/// Bit-mask representing a set of orders needed by an edge/face.
typedef std::uint64_t VarOrderBits;
static constexpr int MaxVarOrder = 8*sizeof(VarOrderBits) - 1;
/// Return the minimum order (least significant bit set) in the bit mask.
static int MinOrder(VarOrderBits bits);
/// Return element order: internal version of GetElementOrder without checks.
int GetElementOrderImpl(int i) const;
/** In a variable order space, calculate a bitmask of polynomial orders that
need to be represented on each edge and face. */
void CalcEdgeFaceVarOrders(Array<VarOrderBits> &edge_orders,
Array<VarOrderBits> &face_orders) const;
/** Build the table var_edge_dofs (or var_face_dofs) in a variable order
space; return total edge/face DOFs. */
int MakeDofTable(int ent_dim, const Array<int> &entity_orders,
Table &entity_dofs, Array<char> *var_ent_order);
/// Search row of a DOF table for a DOF set of size 'ndof', return first DOF.
int FindDofs(const Table &var_dof_table, int row, int ndof) const;
/** In a variable order space, return edge DOFs associated with a polynomial
order that has 'ndof' degrees of freedom. */
int FindEdgeDof(int edge, int ndof) const
{ return FindDofs(var_edge_dofs, edge, ndof); }
/// Similar to FindEdgeDof, but used for mixed meshes too.
int FindFaceDof(int face, int ndof) const
{ return FindDofs(var_face_dofs, face, ndof); }
int FirstFaceDof(int face, int variant = 0) const
{ return uni_fdof >= 0 ? face*uni_fdof : var_face_dofs.GetRow(face)[variant];}
/// Return number of possible DOF variants for edge/face (var. order spaces).
int GetNVariants(int entity, int index) const;
/// Helper to encode a sign flip into a DOF index (for Hcurl/Hdiv shapes).
static inline int EncodeDof(int entity_base, int idx)
{ return (idx >= 0) ? (entity_base + idx) : (-1-(entity_base + (-1-idx))); }
/// Helpers to remove encoded sign from a DOF
static inline int DecodeDof(int dof)
{ return (dof >= 0) ? dof : (-1 - dof); }
static inline int DecodeDof(int dof, double& sign)
{ return (dof >= 0) ? (sign = 1, dof) : (sign = -1, (-1 - dof)); }
/// Helper to get vertex, edge or face DOFs (entity=0,1,2 resp.).
int GetEntityDofs(int entity, int index, Array<int> &dofs,
Geometry::Type master_geom = Geometry::INVALID,
int variant = 0) const;
// Get degenerate face DOFs: see explanation in method implementation.
int GetDegenerateFaceDofs(int index, Array<int> &dofs,
Geometry::Type master_geom, int variant) const;
int GetNumBorderDofs(Geometry::Type geom, int order) const;
/// Calculate the cP and cR matrices for a nonconforming mesh.
void BuildConformingInterpolation() const;
static void AddDependencies(SparseMatrix& deps, Array<int>& master_dofs,
Array<int>& slave_dofs, DenseMatrix& I,
int skipfirst = 0);
static bool DofFinalizable(int dof, const Array<bool>& finalized,
const SparseMatrix& deps);
void AddEdgeFaceDependencies(SparseMatrix &deps, Array<int>& master_dofs,
const FiniteElement *master_fe,
Array<int> &slave_dofs, int slave_face,
const DenseMatrix *pm) const;
/// Replicate 'mat' in the vector dimension, according to vdim ordering mode.
void MakeVDimMatrix(SparseMatrix &mat) const;
/// GridFunction interpolation operator applicable after mesh refinement.
class RefinementOperator : public Operator
{
const FiniteElementSpace* fespace;
DenseTensor localP[Geometry::NumGeom];
Table* old_elem_dof; // Owned.
public:
/** Construct the operator based on the elem_dof table of the original
(coarse) space. The class takes ownership of the table. */
RefinementOperator(const FiniteElementSpace* fespace,
Table *old_elem_dof/*takes ownership*/, int old_ndofs);
RefinementOperator(const FiniteElementSpace *fespace,
const FiniteElementSpace *coarse_fes);
virtual void Mult(const Vector &x, Vector &y) const;
virtual void MultTranspose(const Vector &x, Vector &y) const;
virtual ~RefinementOperator();
};
/// Derefinement operator, used by the friend class InterpolationGridTransfer.
class DerefinementOperator : public Operator
{
const FiniteElementSpace *fine_fes; // Not owned.
DenseTensor localR[Geometry::NumGeom];
Table *coarse_elem_dof; // Owned.
Table coarse_to_fine;
Array<int> coarse_to_ref_type;
Array<Geometry::Type> ref_type_to_geom;
Array<int> ref_type_to_fine_elem_offset;
public:
DerefinementOperator(const FiniteElementSpace *f_fes,
const FiniteElementSpace *c_fes,
BilinearFormIntegrator *mass_integ);
virtual void Mult(const Vector &x, Vector &y) const;
virtual ~DerefinementOperator();
};
/** This method makes the same assumptions as the method:
void GetLocalRefinementMatrices(
const FiniteElementSpace &coarse_fes, Geometry::Type geom,
DenseTensor &localP) const
which is defined below. It also assumes that the coarse fes and this have
the same vector dimension, vdim. */
SparseMatrix *RefinementMatrix_main(const int coarse_ndofs,
const Table &coarse_elem_dof,
const DenseTensor localP[]) const;
void GetLocalRefinementMatrices(Geometry::Type geom,
DenseTensor &localP) const;
void GetLocalDerefinementMatrices(Geometry::Type geom,
DenseTensor &localR) const;
/** Calculate explicit GridFunction interpolation matrix (after mesh
refinement). NOTE: consider using the RefinementOperator class instead
of the fully assembled matrix, which can take a lot of memory. */
SparseMatrix* RefinementMatrix(int old_ndofs, const Table* old_elem_dof);
/// Calculate GridFunction restriction matrix after mesh derefinement.
SparseMatrix* DerefinementMatrix(int old_ndofs, const Table* old_elem_dof);
/** @brief Return in @a localP the local refinement matrices that map
between fespaces after mesh refinement. */
/** This method assumes that this->mesh is a refinement of coarse_fes->mesh
and that the CoarseFineTransformations of this->mesh are set accordingly.
Another assumption is that the FEs of this use the same MapType as the FEs
of coarse_fes. Finally, it assumes that the spaces this and coarse_fes are
NOT variable-order spaces. */
void GetLocalRefinementMatrices(const FiniteElementSpace &coarse_fes,
Geometry::Type geom,
DenseTensor &localP) const;
/// Help function for constructors + Load().
void Constructor(Mesh *mesh, NURBSExtension *ext,
const FiniteElementCollection *fec,
int vdim = 1, int ordering = Ordering::byNODES);
/// Updates the internal mesh pointer. @warning @a new_mesh must be
/// <b>topologically identical</b> to the existing mesh. Used if the address
/// of the Mesh object has changed, e.g. in @a Mesh::Swap.
virtual void UpdateMeshPointer(Mesh *new_mesh);
/// Resize the elem_order array on mesh change.
void UpdateElementOrders();
public:
/** @brief Default constructor: the object is invalid until initialized using
the method Load(). */
FiniteElementSpace();
/** @brief Copy constructor: deep copy all data from @a orig except the Mesh,
the FiniteElementCollection, ans some derived data. */
/** If the @a mesh or @a fec pointers are NULL (default), then the new
FiniteElementSpace will reuse the respective pointers from @a orig. If
any of these pointers is not NULL, the given pointer will be used instead
of the one used by @a orig.
@note The objects pointed to by the @a mesh and @a fec parameters must be
either the same objects as the ones used by @a orig, or copies of them.
Otherwise, the behavior is undefined.
@note Derived data objects, such as the conforming prolongation and
restriction matrices, and the update operator, will not be copied, even
if they are created in the @a orig object. */
FiniteElementSpace(const FiniteElementSpace &orig, Mesh *mesh = NULL,
const FiniteElementCollection *fec = NULL);
FiniteElementSpace(Mesh *mesh,
const FiniteElementCollection *fec,
int vdim = 1, int ordering = Ordering::byNODES)
{ Constructor(mesh, NULL, fec, vdim, ordering); }
/// Construct a NURBS FE space based on the given NURBSExtension, @a ext.
/** @note If the pointer @a ext is NULL, this constructor is equivalent to
the standard constructor with the same arguments minus the
NURBSExtension, @a ext. */
FiniteElementSpace(Mesh *mesh, NURBSExtension *ext,
const FiniteElementCollection *fec,
int vdim = 1, int ordering = Ordering::byNODES)
{ Constructor(mesh, ext, fec, vdim, ordering); }
/// Returns the mesh
inline Mesh *GetMesh() const { return mesh; }
const NURBSExtension *GetNURBSext() const { return NURBSext; }
NURBSExtension *GetNURBSext() { return NURBSext; }
NURBSExtension *StealNURBSext();
bool Conforming() const { return mesh->Conforming(); }
bool Nonconforming() const { return mesh->Nonconforming(); }
/// Sets the order of the i'th finite element.
/** By default, all elements are assumed to be of fec->GetOrder(). Once
SetElementOrder is called, the space becomes a variable order space. */
void SetElementOrder(int i, int p);
/// Returns the order of the i'th finite element.
int GetElementOrder(int i) const;
/// Return the maximum polynomial order.
int GetMaxElementOrder() const
{ return IsVariableOrder() ? elem_order.Max() : fec->GetOrder(); }
/// Returns true if the space contains elements of varying polynomial orders.
bool IsVariableOrder() const { return elem_order.Size(); }
/// The returned SparseMatrix is owned by the FiniteElementSpace.
const SparseMatrix *GetConformingProlongation() const;
/// The returned SparseMatrix is owned by the FiniteElementSpace.
const SparseMatrix *GetConformingRestriction() const;
/** Return a version of the conforming restriction matrix for variable-order
spaces with complex hp interfaces, where some true DOFs are not owned by
any elements and need to be interpolated from higher order edge/face
variants (see also @a SetRelaxedHpConformity()). */
/// The returned SparseMatrix is owned by the FiniteElementSpace.
const SparseMatrix *GetHpConformingRestriction() const;
/// The returned Operator is owned by the FiniteElementSpace.
virtual const Operator *GetProlongationMatrix() const
{ return GetConformingProlongation(); }
/// Return an operator that performs the transpose of GetRestrictionOperator
/** The returned operator is owned by the FiniteElementSpace. In serial this
is the same as GetProlongationMatrix() */
virtual const Operator *GetRestrictionTransposeOperator() const
{ return GetConformingProlongation(); }
/// An abstract operator that performs the same action as GetRestrictionMatrix
/** In some cases this is an optimized matrix-free implementation. The
returned operator is owned by the FiniteElementSpace. */
virtual const Operator *GetRestrictionOperator() const
{ return GetConformingRestriction(); }
/// The returned SparseMatrix is owned by the FiniteElementSpace.
virtual const SparseMatrix *GetRestrictionMatrix() const
{ return GetConformingRestriction(); }
/// The returned SparseMatrix is owned by the FiniteElementSpace.
virtual const SparseMatrix *GetHpRestrictionMatrix() const
{ return GetHpConformingRestriction(); }
/// Return an Operator that converts L-vectors to E-vectors.
/** An L-vector is a vector of size GetVSize() which is the same size as a
GridFunction. An E-vector represents the element-wise discontinuous
version of the FE space.
The layout of the E-vector is: ND x VDIM x NE, where ND is the number of
degrees of freedom, VDIM is the vector dimension of the FE space, and NE
is the number of the mesh elements.
The parameter @a e_ordering describes how the local DOFs in each element
should be ordered, see ElementDofOrdering.
For discontinuous spaces, the element restriction corresponds to a
permutation of the degrees of freedom, implemented by the
L2ElementRestriction class.
The returned Operator is owned by the FiniteElementSpace. */
const Operator *GetElementRestriction(ElementDofOrdering e_ordering) const;
/// Return an Operator that converts L-vectors to E-vectors on each face.
virtual const Operator *GetFaceRestriction(
ElementDofOrdering e_ordering, FaceType,
L2FaceValues mul = L2FaceValues::DoubleValued) const;
/** @brief Return a QuadratureInterpolator that interpolates E-vectors to
quadrature point values and/or derivatives (Q-vectors). */
/** An E-vector represents the element-wise discontinuous version of the FE
space and can be obtained, for example, from a GridFunction using the
Operator returned by GetElementRestriction().
All elements will use the same IntegrationRule, @a ir as the target
quadrature points. */
const QuadratureInterpolator *GetQuadratureInterpolator(
const IntegrationRule &ir) const;
/** @brief Return a QuadratureInterpolator that interpolates E-vectors to
quadrature point values and/or derivatives (Q-vectors). */
/** An E-vector represents the element-wise discontinuous version of the FE
space and can be obtained, for example, from a GridFunction using the
Operator returned by GetElementRestriction().
The target quadrature points in the elements are described by the given
QuadratureSpace, @a qs. */
const QuadratureInterpolator *GetQuadratureInterpolator(
const QuadratureSpace &qs) const;
/** @brief Return a FaceQuadratureInterpolator that interpolates E-vectors to
quadrature point values and/or derivatives (Q-vectors). */
const FaceQuadratureInterpolator *GetFaceQuadratureInterpolator(
const IntegrationRule &ir, FaceType type) const;
/// Returns the polynomial degree of the i'th finite element.
/** NOTE: it is recommended to use GetElementOrder in new code. */
int GetOrder(int i) const { return GetElementOrder(i); }
/** Return the order of an edge. In a variable order space, return the order
of a specific variant, or -1 if there are no more variants. */
int GetEdgeOrder(int edge, int variant = 0) const;
/// Returns the polynomial degree of the i'th face finite element
int GetFaceOrder(int face, int variant = 0) const;
/// Returns vector dimension.
inline int GetVDim() const { return vdim; }
/// Returns number of degrees of freedom.
inline int GetNDofs() const { return ndofs; }
/// Return the number of vector dofs, i.e. GetNDofs() x GetVDim().
inline int GetVSize() const { return vdim * ndofs; }
/// Return the number of vector true (conforming) dofs.
virtual int GetTrueVSize() const { return GetConformingVSize(); }
/// Returns the number of conforming ("true") degrees of freedom
/// (if the space is on a nonconforming mesh with hanging nodes).
int GetNConformingDofs() const;
int GetConformingVSize() const { return vdim * GetNConformingDofs(); }
/// Return the ordering method.
inline Ordering::Type GetOrdering() const { return ordering; }
const FiniteElementCollection *FEColl() const { return fec; }
/// Number of all scalar vertex dofs
int GetNVDofs() const { return nvdofs; }
/// Number of all scalar edge-interior dofs
int GetNEDofs() const { return nedofs; }
/// Number of all scalar face-interior dofs
int GetNFDofs() const { return nfdofs; }
/// Returns number of vertices in the mesh.
inline int GetNV() const { return mesh->GetNV(); }
/// Returns number of elements in the mesh.
inline int GetNE() const { return mesh->GetNE(); }
/// Returns number of faces (i.e. co-dimension 1 entities) in the mesh.
/** The co-dimension 1 entities are those that have dimension 1 less than the
mesh dimension, e.g. for a 2D mesh, the faces are the 1D entities, i.e.
the edges. */
inline int GetNF() const { return mesh->GetNumFaces(); }
/// Returns number of boundary elements in the mesh.
inline int GetNBE() const { return mesh->GetNBE(); }
/// Returns the number of faces according to the requested type.
/** If type==Boundary returns only the "true" number of boundary faces
contrary to GetNBE() that returns "fake" boundary faces associated to
visualization for GLVis.
Similarly, if type==Interior, the "fake" boundary faces associated to
visualization are counted as interior faces. */
inline int GetNFbyType(FaceType type) const
{ return mesh->GetNFbyType(type); }
/// Returns the type of element i.
inline int GetElementType(int i) const
{ return mesh->GetElementType(i); }
/// Returns the vertices of element i.
inline void GetElementVertices(int i, Array<int> &vertices) const
{ mesh->GetElementVertices(i, vertices); }
/// Returns the type of boundary element i.
inline int GetBdrElementType(int i) const
{ return mesh->GetBdrElementType(i); }
/// Returns ElementTransformation for the @a i-th element.
ElementTransformation *GetElementTransformation(int i) const
{ return mesh->GetElementTransformation(i); }
/** @brief Returns the transformation defining the @a i-th element in the
user-defined variable @a ElTr. */
void GetElementTransformation(int i, IsoparametricTransformation *ElTr)
{ mesh->GetElementTransformation(i, ElTr); }
/// Returns ElementTransformation for the @a i-th boundary element.
ElementTransformation *GetBdrElementTransformation(int i) const
{ return mesh->GetBdrElementTransformation(i); }
int GetAttribute(int i) const { return mesh->GetAttribute(i); }
int GetBdrAttribute(int i) const { return mesh->GetBdrAttribute(i); }
/// Returns indices of degrees of freedom of element 'elem'.
virtual void GetElementDofs(int elem, Array<int> &dofs) const;
/// Returns indices of degrees of freedom for boundary element 'bel'.
virtual void GetBdrElementDofs(int bel, Array<int> &dofs) const;
/** @brief Returns the indices of the degrees of freedom for the specified
face, including the DOFs for the edges and the vertices of the face. */
/** In variable order spaces, multiple variants of DOFs can be returned.
See @a GetEdgeDofs for more details.
@return Order of the selected variant, or -1 if there are no more
variants.*/
virtual int GetFaceDofs(int face, Array<int> &dofs, int variant = 0) const;
/** @brief Returns the indices of the degrees of freedom for the specified
edge, including the DOFs for the vertices of the edge. */
/** In variable order spaces, multiple sets of DOFs may exist on an edge,
corresponding to the different polynomial orders of incident elements.
The 'variant' parameter is the zero-based index of the desired DOF set.
The variants are ordered from lowest polynomial degree to the highest.
@return Order of the selected variant, or -1 if there are no more
variants. */
int GetEdgeDofs(int edge, Array<int> &dofs, int variant = 0) const;
void GetVertexDofs(int i, Array<int> &dofs) const;
void GetElementInteriorDofs(int i, Array<int> &dofs) const;
void GetFaceInteriorDofs(int i, Array<int> &dofs) const;
int GetNumElementInteriorDofs(int i) const;
void GetEdgeInteriorDofs(int i, Array<int> &dofs) const;
void DofsToVDofs(Array<int> &dofs, int ndofs = -1) const;
void DofsToVDofs(int vd, Array<int> &dofs, int ndofs = -1) const;
int DofToVDof(int dof, int vd, int ndofs = -1) const;
int VDofToDof(int vdof) const
{ return (ordering == Ordering::byNODES) ? (vdof%ndofs) : (vdof/vdim); }
static void AdjustVDofs(Array<int> &vdofs);
/// Returns indexes of degrees of freedom in array dofs for i'th element.
void GetElementVDofs(int i, Array<int> &vdofs) const;
/// Returns indexes of degrees of freedom for i'th boundary element.
void GetBdrElementVDofs(int i, Array<int> &vdofs) const;
/// Returns indexes of degrees of freedom for i'th face element (2D and 3D).
void GetFaceVDofs(int i, Array<int> &vdofs) const;
/// Returns indexes of degrees of freedom for i'th edge.
void GetEdgeVDofs(int i, Array<int> &vdofs) const;
void GetVertexVDofs(int i, Array<int> &vdofs) const;
void GetElementInteriorVDofs(int i, Array<int> &vdofs) const;
void GetEdgeInteriorVDofs(int i, Array<int> &vdofs) const;
/// (@deprecated) Use the Update() method if the space or mesh changed.
MFEM_DEPRECATED void RebuildElementToDofTable();
/** @brief Reorder the scalar DOFs based on the element ordering.
The new ordering is constructed as follows: 1) loop over all elements as
ordered in the Mesh; 2) for each element, assign new indices to all of
its current DOFs that are still unassigned; the new indices we assign are
simply the sequence `0,1,2,...`; if there are any signed DOFs their sign
is preserved. */
void ReorderElementToDofTable();
/** @brief Return a reference to the internal Table that stores the lists of
scalar dofs, for each mesh element, as returned by GetElementDofs(). */
const Table &GetElementToDofTable() const { return *elem_dof; }
/** @brief Return a reference to the internal Table that stores the lists of
scalar dofs, for each boundary mesh element, as returned by
GetBdrElementDofs(). */
const Table &GetBdrElementToDofTable() const
{ if (!bdr_elem_dof) { BuildBdrElementToDofTable(); } return *bdr_elem_dof; }
/** @brief Return a reference to the internal Table that stores the lists of
scalar dofs, for each face in the mesh, as returned by GetFaceDofs(). In
this context, "face" refers to a (dim-1)-dimensional mesh entity. */
/** @note In the case of a NURBS space, the rows corresponding to interior
faces will be empty. */
const Table &GetFaceToDofTable() const
{ if (!face_dof) { BuildFaceToDofTable(); } return *face_dof; }
/** @brief Initialize internal data that enables the use of the methods
GetElementForDof() and GetLocalDofForDof(). */
void BuildDofToArrays();
/// Return the index of the first element that contains dof @a i.
/** This method can be called only after setup is performed using the method
BuildDofToArrays(). */
int GetElementForDof(int i) const { return dof_elem_array[i]; }
/// Return the local dof index in the first element that contains dof @a i.
/** This method can be called only after setup is performed using the method
BuildDofToArrays(). */
int GetLocalDofForDof(int i) const { return dof_ldof_array[i]; }
/** @brief Returns pointer to the FiniteElement in the FiniteElementCollection
associated with i'th element in the mesh object. */
virtual const FiniteElement *GetFE(int i) const;
/** @brief Returns pointer to the FiniteElement in the FiniteElementCollection
associated with i'th boundary face in the mesh object. */
const FiniteElement *GetBE(int i) const;
/** @brief Returns pointer to the FiniteElement in the FiniteElementCollection
associated with i'th face in the mesh object. Faces in this case refer
to the MESHDIM-1 primitive so in 2D they are segments and in 1D they are
points.*/
const FiniteElement *GetFaceElement(int i) const;
/** @brief Returns pointer to the FiniteElement in the FiniteElementCollection
associated with i'th edge in the mesh object. */
const FiniteElement *GetEdgeElement(int i, int variant = 0) const;
/// Return the trace element from element 'i' to the given 'geom_type'
const FiniteElement *GetTraceElement(int i, Geometry::Type geom_type) const;
/** @brief Mark degrees of freedom associated with boundary elements with
the specified boundary attributes (marked in 'bdr_attr_is_ess').
For spaces with 'vdim' > 1, the 'component' parameter can be used
to restricts the marked vDOFs to the specified component. */
virtual void GetEssentialVDofs(const Array<int> &bdr_attr_is_ess,
Array<int> &ess_vdofs,
int component = -1) const;
/** @brief Get a list of essential true dofs, ess_tdof_list, corresponding to the
boundary attributes marked in the array bdr_attr_is_ess.
For spaces with 'vdim' > 1, the 'component' parameter can be used
to restricts the marked tDOFs to the specified component. */
virtual void GetEssentialTrueDofs(const Array<int> &bdr_attr_is_ess,
Array<int> &ess_tdof_list,
int component = -1);
/** @brief Get a list of all boundary true dofs, @a boundary_dofs. For spaces
with 'vdim' > 1, the 'component' parameter can be used to restricts the
marked tDOFs to the specified component. Equivalent to
FiniteElementSpace::GetEssentialTrueDofs with all boundary attributes
marked as essential. */
void GetBoundaryTrueDofs(Array<int> &boundary_dofs, int component = -1);
/// Convert a Boolean marker array to a list containing all marked indices.
static void MarkerToList(const Array<int> &marker, Array<int> &list);
/** @brief Convert an array of indices (list) to a Boolean marker array where all
indices in the list are marked with the given value and the rest are set
to zero. */
static void ListToMarker(const Array<int> &list, int marker_size,
Array<int> &marker, int mark_val = -1);
/** @brief For a partially conforming FE space, convert a marker array (nonzero
entries are true) on the partially conforming dofs to a marker array on
the conforming dofs. A conforming dofs is marked iff at least one of its
dependent dofs is marked. */
void ConvertToConformingVDofs(const Array<int> &dofs, Array<int> &cdofs);
/** @brief For a partially conforming FE space, convert a marker array (nonzero
entries are true) on the conforming dofs to a marker array on the
(partially conforming) dofs. A dof is marked iff it depends on a marked
conforming dofs, where dependency is defined by the ConformingRestriction
matrix; in other words, a dof is marked iff it corresponds to a marked
conforming dof. */
void ConvertFromConformingVDofs(const Array<int> &cdofs, Array<int> &dofs);
/** @brief Generate the global restriction matrix from a discontinuous
FE space to the continuous FE space of the same polynomial degree. */
SparseMatrix *D2C_GlobalRestrictionMatrix(FiniteElementSpace *cfes);
/** @brief Generate the global restriction matrix from a discontinuous
FE space to the piecewise constant FE space. */
SparseMatrix *D2Const_GlobalRestrictionMatrix(FiniteElementSpace *cfes);
/** @brief Construct the restriction matrix from the FE space given by
(*this) to the lower degree FE space given by (*lfes) which
is defined on the same mesh. */
SparseMatrix *H2L_GlobalRestrictionMatrix(FiniteElementSpace *lfes);
/** @brief Construct and return an Operator that can be used to transfer
GridFunction data from @a coarse_fes, defined on a coarse mesh, to @a
this FE space, defined on a refined mesh. */
/** It is assumed that the mesh of this FE space is a refinement of the mesh
of @a coarse_fes and the CoarseFineTransformations returned by the method
Mesh::GetRefinementTransforms() of the refined mesh are set accordingly.
The Operator::Type of @a T can be set to request an Operator of the set
type. Currently, only Operator::MFEM_SPARSEMAT and Operator::ANY_TYPE
(matrix-free) are supported. When Operator::ANY_TYPE is requested, the
choice of the particular Operator sub-class is left to the method. This
method also works in parallel because the transfer operator is local to
the MPI task when the input is a synchronized ParGridFunction. */
void GetTransferOperator(const FiniteElementSpace &coarse_fes,
OperatorHandle &T) const;
/** @brief Construct and return an Operator that can be used to transfer
true-dof data from @a coarse_fes, defined on a coarse mesh, to @a this FE
space, defined on a refined mesh.
This method calls GetTransferOperator() and multiplies the result by the
prolongation operator of @a coarse_fes on the right, and by the
restriction operator of this FE space on the left.
The Operator::Type of @a T can be set to request an Operator of the set
type. In serial, the supported types are: Operator::MFEM_SPARSEMAT and
Operator::ANY_TYPE (matrix-free). In parallel, the supported types are:
Operator::Hypre_ParCSR and Operator::ANY_TYPE. Any other type is treated
as Operator::ANY_TYPE: the operator representation choice is made by this
method. */
virtual void GetTrueTransferOperator(const FiniteElementSpace &coarse_fes,
OperatorHandle &T) const;
/** @brief Reflect changes in the mesh: update number of DOFs, etc. Also, calculate
GridFunction transformation operator (unless want_transform is false).
Safe to call multiple times, does nothing if space already up to date. */
virtual void Update(bool want_transform = true);
/// Get the GridFunction update operator.
const Operator* GetUpdateOperator() { Update(); return Th.Ptr(); }
/// Return the update operator in the given OperatorHandle, @a T.
void GetUpdateOperator(OperatorHandle &T) { T = Th; }
/** @brief Set the ownership of the update operator: if set to false, the
Operator returned by GetUpdateOperator() must be deleted outside the
FiniteElementSpace. */
/** The update operator ownership is automatically reset to true when a new
update operator is created by the Update() method. */
void SetUpdateOperatorOwner(bool own) { Th.SetOperatorOwner(own); }
/// Specify the Operator::Type to be used by the update operators.
/** The default type is Operator::ANY_TYPE which leaves the choice to this
class. The other currently supported option is Operator::MFEM_SPARSEMAT
which is only guaranteed to be honored for a refinement update operator.
Any other type will be treated as Operator::ANY_TYPE.
@note This operation destroys the current update operator (if owned). */
void SetUpdateOperatorType(Operator::Type tid) { Th.SetType(tid); }
/// Free the GridFunction update operator (if any), to save memory.
virtual void UpdatesFinished() { Th.Clear(); }
/** Return update counter, similar to Mesh::GetSequence(). Used by
GridFunction to check if it is up to date with the space. */
long GetSequence() const { return sequence; }
/// Return whether or not the space is discontinuous (L2)
bool IsDGSpace() const
{
return dynamic_cast<const L2_FECollection*>(fec) != NULL;
}
/** In variable order spaces on nonconforming (NC) meshes, this function
controls whether strict conformity is enforced in cases where coarse
edges/faces have higher polynomial order than their fine NC neighbors.
In the default (strict) case, the coarse side polynomial order is
reduced to that of the lowest order fine edge/face, so all fine
neighbors can interpolate the coarse side exactly. If relaxed == true,
some discontinuities in the solution in such cases are allowed and the
coarse side is not restricted. For an example, see
https://github.com/mfem/mfem/pull/1423#issuecomment-621340392 */
void SetRelaxedHpConformity(bool relaxed = true)
{
relaxed_hp = relaxed;
orders_changed = true; // force update
Update(false);
}
/// Save finite element space to output stream @a out.
void Save(std::ostream &out) const;
/** @brief Read a FiniteElementSpace from a stream. The returned
FiniteElementCollection is owned by the caller. */
FiniteElementCollection *Load(Mesh *m, std::istream &input);
virtual ~FiniteElementSpace();
};
/// Class representing the storage layout of a QuadratureFunction.
/** Multiple QuadratureFunction%s can share the same QuadratureSpace. */
class QuadratureSpace
{
protected:
friend class QuadratureFunction; // Uses the element_offsets.
Mesh *mesh;
int order;
int size;
const IntegrationRule *int_rule[Geometry::NumGeom];
int *element_offsets; // scalar offsets; size = number of elements + 1
// protected functions
// Assuming mesh and order are set, construct the members: int_rule,
// element_offsets, and size.
void Construct();
public:
/// Create a QuadratureSpace based on the global rules from #IntRules.
QuadratureSpace(Mesh *mesh_, int order_)
: mesh(mesh_), order(order_) { Construct(); }
/// Read a QuadratureSpace from the stream @a in.
QuadratureSpace(Mesh *mesh_, std::istream &in);
virtual ~QuadratureSpace() { delete [] element_offsets; }
/// Return the total number of quadrature points.
int GetSize() const { return size; }
/// Return the order of the quadrature rule(s) used by all elements.
int GetOrder() const { return order; }
/// Returns the mesh
inline Mesh *GetMesh() const { return mesh; }
/// Returns number of elements in the mesh.
inline int GetNE() const { return mesh->GetNE(); }
/// Get the IntegrationRule associated with mesh element @a idx.
const IntegrationRule &GetElementIntRule(int idx) const
{ return *int_rule[mesh->GetElementBaseGeometry(idx)]; }
/// Write the QuadratureSpace to the stream @a out.
void Save(std::ostream &out) const;
};
inline bool UsesTensorBasis(const FiniteElementSpace& fes)
{
return dynamic_cast<const mfem::TensorBasisElement *>(fes.GetFE(0))!=nullptr;
}
}
#endif
| 44.268704 | 86 | 0.696627 | Arthur-laurent312 |
4c94a7815ce8cc4d812f29577d9773c5fb983e8f | 2,454 | cpp | C++ | Leetcode Top Interview Questions/solutions/Intersection of Two Linked Lists.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | Leetcode Top Interview Questions/solutions/Intersection of Two Linked Lists.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | Leetcode Top Interview Questions/solutions/Intersection of Two Linked Lists.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
Intersection of Two Linked Lists
===============================
Write a program to find the node at which the intersection of two singly linked lists begins.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Reference of the node with value = 2
Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Each value on each linked list is in the range [1, 10^9].
Your code should preferably run in O(n) time and use only O(1) memory.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
ListNode *ans = NULL;
auto temp = headA;
while (temp)
{
temp->val *= (-1);
temp = temp->next;
}
temp = headB;
while (temp)
{
if (temp->val < 0)
{
ans = temp;
break;
}
temp = temp->next;
}
temp = headA;
while (temp)
{
temp->val *= (-1);
temp = temp->next;
}
return ans;
}
};
| 32.289474 | 307 | 0.649959 | Akshad7829 |
4c94ba2a61a762a86a6f0371a1ed98f2b64cc625 | 670 | hpp | C++ | shift/render.vk/private/shift/render/vk/memory_manager_livedebug.hpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | 2 | 2018-11-28T18:14:08.000Z | 2020-08-06T07:44:36.000Z | shift/render.vk/private/shift/render/vk/memory_manager_livedebug.hpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | 4 | 2018-11-06T21:01:05.000Z | 2019-02-19T07:52:52.000Z | shift/render.vk/private/shift/render/vk/memory_manager_livedebug.hpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | null | null | null | #ifndef SHIFT_RENDER_VK_MEMORY_MANAGER_LIVEDEBUG_HPP
#define SHIFT_RENDER_VK_MEMORY_MANAGER_LIVEDEBUG_HPP
#include <string>
#include <shift/livedebug/request_handler.hpp>
namespace shift::render::vk
{
///
class memory_manager_request_handler : public livedebug::request_handler
{
public:
/// Constructor.
memory_manager_request_handler(std::string&& target);
/// Destructor.
~memory_manager_request_handler() override = default;
/// @see request_handler::operator().
bool operator()(
const boost::beast::http::request<boost::beast::http::string_body>& request,
livedebug::session& session) override;
private:
std::string _target;
};
}
#endif
| 22.333333 | 80 | 0.762687 | cspanier |
4c9523051c686fa4adb84ee4cef34db2d4892c09 | 50,403 | cpp | C++ | bins/broker/storage/MessageStorage.cpp | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | null | null | null | bins/broker/storage/MessageStorage.cpp | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | null | null | null | bins/broker/storage/MessageStorage.cpp | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014-present IVK JSC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <Exchange.h>
#include <MessagePropertyInfo.h>
#include <Poco/File.h>
#include <Poco/Hash.h>
#include <Poco/StringTokenizer.h>
#include <Poco/Timezone.h>
#include <limits>
#include <sstream>
#include <fake_cpp14.h>
#include <NextBindParam.h>
#include "Broker.h"
#include "Connection.h"
#include "MappedDBMessage.h"
#include "MiscDefines.h"
#include "S2SProto.h"
#include "Defines.h"
#include "MessageStorage.h"
using upmq::broker::storage::DBMSConnectionPool;
namespace upmq {
namespace broker {
Storage::Storage(const std::string &messageTableID, size_t nonPersistentSize)
: _messageTableID("\"" + messageTableID + "\""),
_propertyTableID("\"" + messageTableID + "_property" + "\""),
_parent(nullptr),
_nonPersistent(nonPersistentSize) {
std::string mainTsql = generateSQLMainTable(messageTableID);
auto mainTXsqlIndexes = generateSQLMainTableIndexes(messageTableID);
TRY_POCO_DATA_EXCEPTION {
storage::DBMSConnectionPool::doNow(mainTsql);
for (const auto &index : mainTXsqlIndexes) {
storage::DBMSConnectionPool::doNow(index);
}
}
CATCH_POCO_DATA_EXCEPTION_PURE("can't init storage", mainTsql, ERROR_STORAGE)
std::string propTsql = generateSQLProperties();
TRY_POCO_DATA_EXCEPTION { storage::DBMSConnectionPool::doNow(propTsql); }
CATCH_POCO_DATA_EXCEPTION_PURE("can't init storage", mainTsql, ERROR_STORAGE)
}
Storage::~Storage() = default;
std::string Storage::generateSQLMainTable(const std::string &tableName) const {
std::stringstream sql;
std::string autoinc = "integer primary key autoincrement not null";
std::string currTimeType = "text";
std::string currTime = "(strftime('%Y-%m-%d %H:%M:%f', 'now'))";
switch (STORAGE_CONFIG.connection.props.dbmsType) {
case storage::Postgresql:
autoinc = "bigserial primary key";
currTimeType = "timestamp";
currTime = "clock_timestamp()";
break;
default:
break;
}
sql << " create table if not exists \"" << tableName << "\""
<< "("
<< " num " << autoinc << " ,message_id text not null unique"
<< " ,type text not null"
<< " ,body_type int not null default 0"
<< " ,priority int not null"
<< " ,persistent int not null"
<< " ,correlation_id text"
<< " ,reply_to text"
<< " ,client_timestamp bigint not null"
<< " ,expiration bigint not null default 0"
<< " ,ttl bigint not null default 0"
<< " ,created_time " << currTimeType << " not null default " << currTime << " ,delivery_count int not null default 0"
<< " ,delivery_status int not null default 0"
<< " ,client_id text not null"
<< " ,consumer_id text"
<< " ,group_id text"
<< " ,group_seq int not null default 0"
<< " ,last_in_group bool not null default 'false'"
<< " ,transaction_id text"
<< "); ";
return sql.str();
}
std::vector<std::string> Storage::generateSQLMainTableIndexes(const std::string &tableName) const {
std::stringstream sql;
std::vector<std::string> indexes;
sql << "create index if not exists \"" << tableName << "_msgs_delivery_status\" on " // if not exists
<< "\"" << tableName << "\""
<< "( delivery_status ); ";
indexes.emplace_back(sql.str());
sql.str("");
sql << "create index if not exists \"" << tableName << "_msgs_consumer_id\" on " // if not exists
<< "\"" << tableName << "\""
<< "( consumer_id ); ";
indexes.emplace_back(sql.str());
sql.str("");
sql << "create index if not exists \"" << tableName << "_msgs_transaction_id\" on " // if not exists
<< "\"" << tableName << "\""
<< "( transaction_id ); ";
indexes.emplace_back(sql.str());
sql.str("");
return indexes;
}
std::string Storage::generateSQLProperties() const {
std::stringstream sql;
std::string idx = _propertyTableID;
idx.replace(_propertyTableID.find_last_of('\"'), 1, "_");
idx.append("midpn\"");
std::string blob = "blob";
switch (STORAGE_CONFIG.connection.props.dbmsType) {
case storage::Postgresql:
blob = "bytea";
break;
default:
break;
}
sql << " create table if not exists " << _propertyTableID << "("
<< " value_char int"
<< " ,value_bool boolean"
<< " ,value_byte int"
<< " ,value_short int"
<< " ,value_int int"
<< " ,value_long bigint"
<< " ,value_float float"
<< " ,value_double double precision"
<< " ,value_string text"
<< " ,message_id text not null"
<< " ,property_name text not null"
<< " ,property_type int not null"
<< " ,value_bytes " << blob << " ,value_object " << blob << " ,is_null boolean not null default false"
<< " ,constraint " << idx << " unique (message_id, property_name)"
<< ");";
return sql.str();
}
void Storage::removeMessagesBySession(const upmq::broker::Session &session) {
std::stringstream sql;
sql << "select * from " << _messageTableID << " where consumer_id like \'%" << session.id() << "%\'";
if (session.isTransactAcknowledge()) {
sql << " and transaction_id = \'" << session.txName() << "\'";
}
sql << ";" << non_std_endl;
MessageInfo messageInfo;
TRY_POCO_DATA_EXCEPTION {
Poco::Data::Statement select((*session.currentDBSession)());
select << sql.str(), Poco::Data::Keywords::into(messageInfo.tuple), Poco::Data::Keywords::range(0, 1);
while (!select.done()) {
select.execute();
auto &fieldMessageId = messageInfo.tuple.get<message::field_message_id.position>();
if (!fieldMessageId.empty()) {
auto &fieldGroupId = messageInfo.tuple.get<message::field_group_id.position>();
if (!fieldGroupId.isNull() && !fieldGroupId.value().empty()) {
if (messageInfo.tuple.get<message::field_last_in_group.position>()) {
removeGroupMessage(fieldGroupId.value(), session);
}
} else {
removeMessage(fieldMessageId, *session.currentDBSession);
}
}
}
}
CATCH_POCO_DATA_EXCEPTION_PURE("can't remove all messages in session", sql.str(), ERROR_ON_SAVE_MESSAGE)
}
void Storage::resetMessagesBySession(const upmq::broker::Session &session) {
std::stringstream sql;
std::string transactionExclusion = std::string(" or delivery_status = ").append(std::to_string(message::WAS_SENT));
sql << "update " << _messageTableID << " set delivery_status = " << message::NOT_SENT << " , consumer_id = '' "
<< " where consumer_id like \'%" << session.id() << "%\'";
if (session.isTransactAcknowledge()) {
sql << " and transaction_id = \'" << session.txName() << "\'";
}
sql << " and (delivery_status = " << message::DELIVERED << transactionExclusion << ")"
<< ";" << non_std_endl;
*session.currentDBSession << sql.str(), Poco::Data::Keywords::now;
}
void Storage::removeGroupMessage(const std::string &groupID, const upmq::broker::Session &session) {
std::vector<std::string> result;
std::stringstream sql;
sql << "select message_id from " << _messageTableID << " where group_id = \'" << groupID << "\'"
<< ";";
bool externConnection = (session.currentDBSession != nullptr);
std::unique_ptr<storage::DBMSSession> tempDBMSSession;
if (!externConnection) {
tempDBMSSession = std::make_unique<storage::DBMSSession>(dbms::Instance().dbmsSession());
tempDBMSSession->beginTX(groupID);
}
storage::DBMSSession &dbSession = externConnection ? *session.currentDBSession : *tempDBMSSession;
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::into(result), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't get message group for ack", sql.str(), ERROR_ON_ACK_MESSAGE)
for (const auto &msgID : result) {
removeMessage(msgID, dbSession);
}
if (tempDBMSSession) {
tempDBMSSession->commitTX();
}
}
message::GroupStatus Storage::checkIsGroupClosed(const MessageDataContainer &sMessage, const Session &session) const {
int result = -1;
std::stringstream sql;
sql << "select count(last_in_group) from " << _messageTableID << " where last_in_group = \'TRUE\' and group_id in "
<< "(select group_id from " << _messageTableID << " where message_id = \'" << sMessage.ack().message_id() << "\'"
<< " and delivery_status <> " << message::DELIVERED << ")"
<< ";";
bool externConnection = (session.currentDBSession != nullptr);
std::unique_ptr<storage::DBMSSession> tempDBMSSession;
if (!externConnection) {
tempDBMSSession = std::make_unique<storage::DBMSSession>(dbms::Instance().dbmsSession());
}
storage::DBMSSession &dbSession = externConnection ? *session.currentDBSession : *tempDBMSSession;
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::into(result), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't check last in group for ack", sql.str(), ERROR_ON_ACK_MESSAGE)
switch (result) {
case 0:
return message::GroupStatus::ONE_OF_GROUP;
case 1:
return message::GroupStatus::LAST_IN_GROUP;
default:
return message::GroupStatus::NOT_IN_GROUP;
}
}
int Storage::deleteMessageHeader(storage::DBMSSession &dbSession, const std::string &messageID) {
std::stringstream sql;
int persistent = static_cast<int>(!_nonPersistent.contains(messageID));
sql << "delete from " << _messageTableID << " where message_id = \'" << messageID << "\'"
<< ";" << non_std_endl;
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't erase message", sql.str(), ERROR_UNKNOWN)
return persistent;
}
void Storage::deleteMessageProperties(storage::DBMSSession &dbSession, const std::string &messageID) {
std::stringstream sql;
sql << "delete from " << _propertyTableID << " where message_id = \'" << messageID << "\'"
<< ";" << non_std_endl;
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE_TROW_INVALID_SQL("can't erase message", sql.str(), ERROR_UNKNOWN)
}
int Storage::getSubscribersCount(storage::DBMSSession &dbSession, const std::string &messageID) {
int subscribersCount = 1;
std::stringstream sql;
sql << "select subscribers_count from " << STORAGE_CONFIG.messageJournal(_parent->name()) << " where message_id = \'" << messageID << "\';";
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::into(subscribersCount), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't get subscribers count", sql.str(), ERROR_UNKNOWN)
return (--subscribersCount);
}
void Storage::updateSubscribersCount(storage::DBMSSession &dbSession, const std::string &messageID) {
std::stringstream sql;
sql << "update " << STORAGE_CONFIG.messageJournal(_parent->name()) << " set subscribers_count = subscribers_count - 1 where message_id =\'"
<< messageID << "\';" << non_std_endl;
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't erase message", sql.str(), ERROR_UNKNOWN)
}
void Storage::deleteMessageInfoFromJournal(storage::DBMSSession &dbSession, const std::string &messageID) {
std::stringstream sql;
sql << "delete from " << STORAGE_CONFIG.messageJournal(_parent->name()) << " where message_id = \'" << messageID << "\';";
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't erase message", sql.str(), ERROR_UNKNOWN)
}
void Storage::deleteMessageDataIfExists(const std::string &messageID, int persistent) {
if (persistent == 1) {
std::string mID = Poco::replace(messageID, ":", "_");
Poco::Path msgFile = STORAGE_CONFIG.data.get();
msgFile.append(_parent->name());
msgFile.append(mID).makeFile();
::remove(msgFile.toString().c_str());
} else {
_nonPersistent.erase(messageID);
}
}
void Storage::removeMessage(const std::string &messageID, storage::DBMSSession &extDBSession) {
bool externConnection = extDBSession.isValid();
std::unique_ptr<storage::DBMSSession> tempDBMSSession;
if (!externConnection) {
tempDBMSSession = dbms::Instance().dbmsSessionPtr();
}
storage::DBMSSession &dbSession = externConnection ? extDBSession : *tempDBMSSession;
if (!externConnection) {
dbSession.beginTX(messageID);
}
const int wasPersistent = deleteMessageHeader(dbSession, messageID);
deleteMessageProperties(dbSession, messageID);
const int subscribersCount = getSubscribersCount(dbSession, messageID);
if (subscribersCount <= 0) {
deleteMessageInfoFromJournal(dbSession, messageID);
deleteMessageDataIfExists(messageID, wasPersistent);
} else {
updateSubscribersCount(dbSession, messageID);
}
if (!externConnection) {
dbSession.commitTX();
}
}
const std::string &Storage::messageTableID() const { return _messageTableID; }
const std::string &Storage::propertyTableID() const { return _propertyTableID; }
void Storage::saveMessageHeader(const upmq::broker::Session &session, const MessageDataContainer &sMessage) {
storage::DBMSSession &dbs = *session.currentDBSession;
const Proto::Message &message = sMessage.message();
int persistent = message.persistent() ? 1 : 0;
int bodyType = message.body_type();
int priority = message.priority();
Poco::Int64 timestamp = message.timestamp();
Poco::Int64 expiration = message.expiration();
Poco::Int64 ttl = message.timetolive();
int groupSeq = message.group_seq();
NextBindParam nextParam;
std::stringstream sql;
sql << "insert into " << saveTableName(session)
<< " (message_id, priority, persistent, correlation_id, reply_to, type, "
"client_timestamp, ttl, expiration, "
"body_type, client_id, group_id, group_seq)"
<< " values "
<< "(" << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam() << ");";
// Save header
Poco::Data::Statement insert(dbs());
insert.addBind(Poco::Data::Keywords::useRef(message.message_id()))
.addBind(Poco::Data::Keywords::use(priority))
.addBind(Poco::Data::Keywords::use(persistent))
.addBind(Poco::Data::Keywords::useRef(message.correlation_id()))
.addBind(Poco::Data::Keywords::useRef(message.reply_to()))
.addBind(Poco::Data::Keywords::useRef(message.type()))
.addBind(Poco::Data::Keywords::use(timestamp))
.addBind(Poco::Data::Keywords::use(ttl))
.addBind(Poco::Data::Keywords::use(expiration))
.addBind(Poco::Data::Keywords::use(bodyType))
.addBind(Poco::Data::Keywords::useRef(sMessage.clientID))
.addBind(Poco::Data::Keywords::useRef(message.group_id()))
.addBind(Poco::Data::Keywords::use(groupSeq));
insert << sql.str();
insert.execute();
}
void Storage::save(const upmq::broker::Session &session, const MessageDataContainer &sMessage) {
const Proto::Message &message = sMessage.message();
const std::string &messageID = message.message_id();
if (!message.persistent()) {
_nonPersistent.insert(std::make_pair(messageID, std::shared_ptr<MessageDataContainer>(sMessage.clone())));
}
try {
saveMessageProperties(session, message);
saveMessageHeader(session, sMessage);
} catch (PDSQLITE::InvalidSQLStatementException &ioex) {
_nonPersistent.erase(messageID);
if (ioex.message().find("no such table") != std::string::npos) {
throw EXCEPTION(ioex.message(), _messageTableID + " or " + _propertyTableID, ERROR_ON_SAVE_MESSAGE);
}
ioex.rethrow();
} catch (Poco::Exception &pex) {
_nonPersistent.erase(messageID);
pex.rethrow();
} catch (...) {
_nonPersistent.erase(messageID);
throw;
}
}
bool Storage::checkTTLIsOut(const std::string &stringMessageTime, Poco::Int64 ttl) {
if (ttl <= 0) {
return false;
}
Poco::DateTime currentDateTime;
int tzd = Poco::Timezone::tzd();
Poco::DateTime messageDateTime;
Poco::DateTimeParser::parse(DT_FORMAT, stringMessageTime, messageDateTime, tzd);
Poco::Timespan ttlTimespan(ttl * Poco::Timespan::MILLISECONDS);
return ((messageDateTime + ttlTimespan).timestamp() < currentDateTime.timestamp());
}
std::shared_ptr<MessageDataContainer> Storage::get(const Consumer &consumer, bool useFileLink) {
std::stringstream sql;
storage::DBMSSession dbSession = dbms::Instance().dbmsSession();
if (consumer.abort) {
consumer.select->clear();
consumer.abort = false;
}
bool needFiltered = false;
if (consumer.select->empty()) {
sql.str("");
sql << "select "
<< " msgs.num, "
<< " msgs.message_id,"
<< " msgs.priority, "
<< " msgs.persistent, "
<< " msgs.correlation_id, "
<< " msgs.reply_to, "
<< " msgs.type, "
<< " msgs.client_timestamp, "
<< " msgs.ttl, "
<< " msgs.expiration, "
<< " msgs.created_time, "
<< " msgs.body_type,"
<< " msgs.delivery_count, "
<< " msgs.group_id, "
<< " msgs.group_seq "
<< " FROM " << _messageTableID << " as msgs"
<< " where delivery_status = " << message::NOT_SENT;
if (consumer.noLocal) {
sql << " and msgs.client_id <> \'" << consumer.clientID << "\'";
}
sql << " order by msgs.priority desc, msgs.num";
if (consumer.selector && !consumer.browser) {
needFiltered = true;
sql << ";";
} else {
sql << " limit ";
sql << consumer.maxNotAckMsg << ";";
}
consumer::Msg tempMsg;
dbSession.beginTX(_extParentID);
TRY_POCO_DATA_EXCEPTION {
Poco::Data::Statement select(dbSession());
select << sql.str(), Poco::Data::Keywords::into(tempMsg.num), Poco::Data::Keywords::into(tempMsg.messageId),
Poco::Data::Keywords::into(tempMsg.priority), Poco::Data::Keywords::into(tempMsg.persistent),
Poco::Data::Keywords::into(tempMsg.correlationID), Poco::Data::Keywords::into(tempMsg.replyTo), Poco::Data::Keywords::into(tempMsg.type),
Poco::Data::Keywords::into(tempMsg.timestamp), Poco::Data::Keywords::into(tempMsg.ttl), Poco::Data::Keywords::into(tempMsg.expiration),
Poco::Data::Keywords::into(tempMsg.screated), Poco::Data::Keywords::into(tempMsg.bodyType),
Poco::Data::Keywords::into(tempMsg.deliveryCount), Poco::Data::Keywords::into(tempMsg.groupID),
Poco::Data::Keywords::into(tempMsg.groupSeq), Poco::Data::Keywords::range(0, 1);
while (!select.done()) {
tempMsg.reset();
select.execute();
if (!tempMsg.messageId.empty() && needFiltered) {
storage::MappedDBMessage mappedDBMessage(tempMsg.messageId, *this);
mappedDBMessage.dbmsConnection = dbSession.dbmsConnnectionRef();
if (consumer.selector->filter(mappedDBMessage)) {
auto sMessage = makeMessage(dbSession, tempMsg, consumer, useFileLink);
if (sMessage) {
consumer.select->push_back(std::move(sMessage));
}
}
} else if (!tempMsg.messageId.empty() && !needFiltered) {
auto sMessage = makeMessage(dbSession, tempMsg, consumer, useFileLink);
if (sMessage) {
consumer.select->push_back(std::move(sMessage));
}
}
}
setMessagesToWasSent(dbSession, consumer);
}
CATCH_POCO_DATA_EXCEPTION_PURE("get message", sql.str(), ERROR_ON_GET_MESSAGE)
dbSession.commitTX();
}
std::shared_ptr<MessageDataContainer> msgResult;
if (!consumer.select->empty()) {
msgResult = std::move(consumer.select->front());
consumer.select->pop_front();
}
return msgResult;
}
void Storage::setParent(const broker::Destination *parent) { _parent = parent; }
const std::string &Storage::uri() const { return _parent ? _parent->uri() : emptyString; }
void Storage::saveMessageProperties(const upmq::broker::Session &session, const Message &message) {
storage::DBMSSession &dbSession = *session.currentDBSession;
std::stringstream sql;
std::string upsert = "insert or replace";
std::string postfix;
if (STORAGE_CONFIG.connection.props.dbmsType == storage::Postgresql) {
upsert = "insert";
}
NextBindParam nextParam;
for (google::protobuf::Map<std::string, Proto::Property>::const_iterator it = message.property().begin(); it != message.property().end(); ++it) {
nextParam.reset();
sql.str("");
sql << upsert << " into " << _propertyTableID
<< " (message_id,"
" property_name,"
" property_type, "
" value_string,"
" value_char,"
" value_bool,"
" value_byte,"
" value_short,"
" value_int,"
" value_long,"
" value_float,"
" value_double,"
" value_bytes,"
" value_object,"
" is_null) values ("
<< "\'" << message.message_id() << "\'"
<< ","
<< "\'" << it->first << "\'"
<< "," << it->second.PropertyValue_case() << ",";
bool isNull = it->second.is_null();
switch (it->second.PropertyValue_case()) {
case Property::kValueString: {
sql << nextParam();
sql << ", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::useRef(it->second.value_string()), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueChar: {
sql << "NULL, " << it->second.value_char() << " , NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueBool: {
bool boolValue = it->second.value_bool();
sql << "NULL, NULL, " << nextParam();
sql << ", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(boolValue), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueByte: {
sql << "NULL, NULL, NULL, " << it->second.value_byte() << ", NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueShort: {
sql << "NULL, NULL, NULL, NULL, " << it->second.value_short() << ", NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueInt: {
sql << "NULL, NULL, NULL, NULL, NULL, " << it->second.value_int() << ", NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueLong: {
sql << "NULL, NULL, NULL, NULL, NULL, NULL, " << it->second.value_long() << ", NULL, NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueFloat: {
float fval = it->second.value_float();
sql << "NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ", NULL, NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(fval), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueDouble: {
double dval = it->second.value_double();
sql << "NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ", NULL, NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
dbSession << sql.str(), Poco::Data::Keywords::use(dval), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueBytes: {
sql << "NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ", NULL, " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
Poco::Data::BLOB blob((const unsigned char *)it->second.value_bytes().c_str(), it->second.value_bytes().size());
dbSession << sql.str(), Poco::Data::Keywords::use(blob), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
case Property::kValueObject: {
sql << "NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, " << nextParam();
sql << ", " << nextParam();
sql << ")" << postfix << ";" << non_std_endl;
Poco::Data::BLOB blob((const unsigned char *)it->second.value_object().c_str(), it->second.value_object().size());
dbSession << sql.str(), Poco::Data::Keywords::use(blob), Poco::Data::Keywords::use(isNull), Poco::Data::Keywords::now;
} break;
default:
sql.str("");
break;
}
}
}
void Storage::begin(const Session &session, const std::string &extParentId) {
{
upmq::ScopedWriteRWLock writeRWLock(_txSessionsLock);
if (_txSessions.find(session.id()) == _txSessions.end()) {
_txSessions.insert(session.id());
}
}
_extParentID = _parent->id() + extParentId;
std::string mainTXTable = std::to_string(Poco::hash(_extParentID + "_" + session.txName()));
std::string mainTXsql = generateSQLMainTable(mainTXTable);
auto mainTXsqlIndexes = generateSQLMainTableIndexes(mainTXTable);
TRY_POCO_DATA_EXCEPTION {
storage::DBMSConnectionPool::doNow(mainTXsql);
for (const auto &index : mainTXsqlIndexes) {
storage::DBMSConnectionPool::doNow(index);
}
}
CATCH_POCO_DATA_EXCEPTION_PURE("can't create tx_table", mainTXsql, ERROR_ON_BEGIN)
}
void Storage::commit(const Session &session) {
std::string mainTXTable = "\"" + std::to_string(Poco::hash(_extParentID + "_" + session.txName())) + "\"";
std::stringstream sql;
sql << "insert into " << _messageTableID
<< " (message_id, priority, persistent, correlation_id, reply_to, type, "
"client_timestamp, ttl, expiration, "
"body_type, client_id, consumer_id, group_id, group_seq)"
<< " select message_id, priority, persistent, correlation_id, reply_to, "
"type, client_timestamp, ttl, "
"expiration, body_type, client_id, consumer_id, group_id, group_seq from "
<< mainTXTable << " order by num asc;";
std::unique_ptr<storage::DBMSSession> dbSession = dbms::Instance().dbmsSessionPtr();
dbSession->beginTX(session.id());
TRY_POCO_DATA_EXCEPTION { *dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't commit", sql.str(), ERROR_ON_COMMIT)
TRY_POCO_DATA_EXCEPTION { dropTXTable(*dbSession, mainTXTable); }
CATCH_POCO_DATA_EXCEPTION_PURE("can't commit", mainTXTable, ERROR_ON_COMMIT)
TRY_POCO_DATA_EXCEPTION {
session.currentDBSession = std::move(dbSession);
removeMessagesBySession(session);
}
CATCH_POCO_DATA_EXCEPTION("can't commit (removeMessagesBySession)", session.id(), session.currentDBSession.reset(nullptr), ERROR_ON_COMMIT)
session.currentDBSession->commitTX();
session.currentDBSession.reset(nullptr);
_parent->postNewMessageEvent();
}
void Storage::abort(const Session &session) {
std::string mainTXTable = "\"" + std::to_string(Poco::hash(_extParentID + "_" + session.txName())) + "\"";
std::stringstream sql;
bool tbExist = false;
sql << "select 1 from " << mainTXTable << ";";
std::unique_ptr<storage::DBMSSession> dbSession = dbms::Instance().dbmsSessionPtr();
dbSession->beginTX(session.id());
TRY_POCO_DATA_EXCEPTION {
*dbSession << sql.str(), Poco::Data::Keywords::now;
tbExist = true;
}
catch (PDSQLITE::InvalidSQLStatementException &issex) {
UNUSED_VAR(issex);
tbExist = false;
}
CATCH_POCO_DATA_EXCEPTION_NO_INVALID_SQL("can't check table on existence", sql.str(), , ERROR_ON_ABORT)
if (tbExist) {
sql.str("");
sql << "delete from " << STORAGE_CONFIG.messageJournal(_parent->name()) << " where message_id in ("
<< " select message_id from " << mainTXTable << ");";
TRY_POCO_DATA_EXCEPTION { *dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't abort", sql.str(), ERROR_ON_ABORT)
sql.str("");
sql << "delete from " << _propertyTableID << " where message_id in ("
<< " select message_id from " << mainTXTable << ");";
TRY_POCO_DATA_EXCEPTION { *dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't abort", sql.str(), ERROR_ON_ABORT)
TRY_POCO_DATA_EXCEPTION { dropTXTable(*dbSession, mainTXTable); }
CATCH_POCO_DATA_EXCEPTION_PURE("can't abort", sql.str(), ERROR_ON_ABORT)
}
TRY_POCO_DATA_EXCEPTION {
session.currentDBSession = std::move(dbSession);
resetMessagesBySession(session);
}
CATCH_POCO_DATA_EXCEPTION("can't abort", sql.str(), session.currentDBSession.reset(nullptr), ERROR_ON_ABORT)
session.currentDBSession->commitTX();
session.currentDBSession.reset(nullptr);
_parent->postNewMessageEvent();
}
void Storage::dropTXTable(storage::DBMSSession &dbSession, const std::string &mainTXTable) const {
std::stringstream sql;
sql << "drop table if exists " << mainTXTable << ";";
dbSession << sql.str(), Poco::Data::Keywords::now;
}
std::vector<MessageInfo> Storage::getMessagesBelow(const Session &session, const std::string &messageID) const {
if (!session.isClientAcknowledge()) {
return std::vector<MessageInfo>{MessageInfo(messageID)};
}
std::vector<MessageInfo> result;
std::stringstream sql;
sql << "select * from " << _messageTableID << " where delivery_count > 0 "
<< " and consumer_id like \'%" << session.id() << "%'"
<< ";" << non_std_endl;
storage::DBMSSession &dbSession = session.currentDBSession.get();
TRY_POCO_DATA_EXCEPTION {
Poco::Data::Statement select(dbSession());
MessageInfo messageInfo;
select << sql.str(), Poco::Data::Keywords::into(messageInfo.tuple), Poco::Data::Keywords::range(0, 1);
while (!select.done()) {
select.execute();
if (!(messageInfo.tuple.get<message::field_message_id.position>()).empty()) {
result.push_back(messageInfo);
}
}
}
CATCH_POCO_DATA_EXCEPTION_PURE("can't get all messages below id", sql.str(), ERROR_ON_ACK_MESSAGE)
return result;
}
void Storage::setMessageToWasSent(const std::string &messageID, const Consumer &consumer) {
std::stringstream sql;
sql << "update " << _messageTableID << " set delivery_status = " << message::WAS_SENT << ", consumer_id = \'" << consumer.id << "\'"
<< ", delivery_count = delivery_count + 1";
if (consumer.session.type == SESSION_TRANSACTED) {
consumer.session.txName = BROKER::Instance().currentTransaction(consumer.clientID, consumer.session.id);
sql << ", transaction_id = \'" << consumer.session.txName << "\'";
}
sql << " where message_id = \'" << messageID << "\'"
<< ";";
TRY_POCO_DATA_EXCEPTION { storage::DBMSConnectionPool::doNow(sql.str()); }
CATCH_POCO_DATA_EXCEPTION_PURE("can't set message to was_sent ", sql.str(), ERROR_STORAGE)
}
void Storage::setMessagesToWasSent(storage::DBMSSession &dbSession, const Consumer &consumer) {
if (!consumer.select->empty()) {
std::stringstream sql;
sql << "update " << _messageTableID << " set delivery_status = " << message::WAS_SENT << ", consumer_id = \'" << consumer.id << "\'"
<< ", delivery_count = delivery_count + 1";
if (consumer.session.type == SESSION_TRANSACTED) {
consumer.session.txName = BROKER::Instance().currentTransaction(consumer.clientID, consumer.session.id);
sql << ", transaction_id = \'" << consumer.session.txName << "\'";
}
sql << " where ";
const std::deque<std::shared_ptr<MessageDataContainer>> &messages = *consumer.select;
for (size_t i = 0; i < messages.size(); ++i) {
if (i > 0) {
sql << " or ";
}
sql << "message_id = \'" << messages[i]->message().message_id() << "\'";
}
sql << ";";
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't set message to was_sent ", sql.str(), ERROR_STORAGE)
}
}
void Storage::setMessageToDelivered(const upmq::broker::Session &session, const std::string &messageID) {
std::stringstream sql;
sql << "update " << _messageTableID << " set delivery_status = " << message::DELIVERED << " where message_id = \'" << messageID << "\'"
<< ";";
storage::DBMSSession &dbSession = session.currentDBSession.get();
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't set message to delivered", sql.str(), ERROR_STORAGE)
}
void Storage::setMessageToLastInGroup(const Session &session, const std::string &messageID) {
std::stringstream sql;
bool externConnection = (session.currentDBSession != nullptr);
std::unique_ptr<storage::DBMSSession> tempDBMSSession;
if (!externConnection) {
tempDBMSSession = std::make_unique<storage::DBMSSession>(dbms::Instance().dbmsSession());
}
storage::DBMSSession &dbSession = (externConnection ? *session.currentDBSession : *tempDBMSSession);
sql << "update " << saveTableName(session) << " set last_in_group = \'TRUE\'"
<< " where message_id = \'" << messageID << "\'"
<< ";";
if (!externConnection) {
dbSession.beginTX(messageID);
}
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't set message to last_in_group", sql.str(), ERROR_ON_SAVE_MESSAGE)
if (!externConnection) {
dbSession.commitTX();
}
}
std::string Storage::saveTableName(const Session &session) const {
std::string messageTable = _messageTableID;
if (session.isTransactAcknowledge()) {
messageTable = "\"" + std::to_string(Poco::hash(_extParentID + "_" + session.txName())) + "\"";
}
return messageTable;
}
void Storage::setMessagesToNotSent(const Consumer &consumer) {
std::stringstream sql;
sql << "update " << _messageTableID << " set delivery_status = " << message::NOT_SENT << " where consumer_id like \'%" << consumer.id << "%\'";
if (consumer.session.type == SESSION_TRANSACTED) {
sql << " and transaction_id = \'" << consumer.session.txName << "\'";
}
sql << ";";
TRY_POCO_DATA_EXCEPTION { storage::DBMSConnectionPool::doNow(sql.str()); }
CATCH_POCO_DATA_EXCEPTION_PURE_NO_INVALIDEXCEPT_NO_EXCEPT("can't set messages to not-sent", sql.str(), ERROR_STORAGE)
}
void Storage::copyTo(Storage &storage, const Consumer &consumer) {
storage.resetNonPersistent(_nonPersistent);
bool withSelector = (consumer.selector && !consumer.selector->expression().empty());
std::stringstream sql;
storage::DBMSSession dbSession = dbms::Instance().dbmsSession();
sql.str("");
if (withSelector) {
sql << " select message_id, priority, persistent, correlation_id, "
"reply_to, type, client_timestamp, ttl, "
"expiration, body_type, client_id, group_id, group_seq from "
<< _messageTableID << " where delivery_status <> " << message::DELIVERED << " order by num asc;";
} else {
sql << "insert into " << storage.messageTableID()
<< " (message_id, priority, persistent, correlation_id, reply_to, "
"type, client_timestamp, ttl, expiration, "
"body_type, client_id, group_id, group_seq)"
<< " select message_id, priority, persistent, correlation_id, "
"reply_to, type, client_timestamp, ttl, "
"expiration, body_type, client_id, group_id, group_seq from "
<< _messageTableID << " where delivery_status <> " << message::DELIVERED << " order by num asc;";
}
dbSession.beginTX(consumer.objectID);
TRY_POCO_DATA_EXCEPTION {
if (withSelector) {
std::string messageID;
int priority;
int persistent;
Poco::Nullable<std::string> correlationID;
Poco::Nullable<std::string> replyTo;
std::string type;
std::string clientTimestamp;
Poco::Int64 ttl;
Poco::Int64 expiration;
int bodyType;
std::string clientID;
Poco::Nullable<std::string> groupID;
int groupSeq;
auto &session = dbSession();
Poco::Data::Statement select(session);
Poco::Data::Statement insert(session);
select << sql.str(), Poco::Data::Keywords::into(messageID), Poco::Data::Keywords::into(priority), Poco::Data::Keywords::into(persistent),
Poco::Data::Keywords::into(correlationID), Poco::Data::Keywords::into(replyTo), Poco::Data::Keywords::into(type),
Poco::Data::Keywords::into(clientTimestamp), Poco::Data::Keywords::into(ttl), Poco::Data::Keywords::into(expiration),
Poco::Data::Keywords::into(bodyType), Poco::Data::Keywords::into(clientID), Poco::Data::Keywords::into(groupID),
Poco::Data::Keywords::into(groupSeq), Poco::Data::Keywords::range(0, 1);
NextBindParam nextParam;
while (!select.done()) {
nextParam.reset();
select.execute();
if (!messageID.empty()) {
storage::MappedDBMessage mappedDBMessage(messageID, *this);
mappedDBMessage.dbmsConnection = dbSession.dbmsConnnectionRef();
if (consumer.selector->filter(mappedDBMessage)) {
sql.str("");
sql << " insert into " << storage.messageTableID() << " (message_id, priority, persistent, correlation_id, "
<< " reply_to, type, client_timestamp, "
<< " ttl, expiration, body_type, client_id, group_id, group_seq)"
<< " values "
<< " (" << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam();
sql << "," << nextParam() << ");";
insert << sql.str(), Poco::Data::Keywords::use(messageID), Poco::Data::Keywords::use(priority), Poco::Data::Keywords::use(persistent),
Poco::Data::Keywords::use(correlationID), Poco::Data::Keywords::use(replyTo), Poco::Data::Keywords::use(type),
Poco::Data::Keywords::use(clientTimestamp), Poco::Data::Keywords::use(ttl), Poco::Data::Keywords::use(expiration),
Poco::Data::Keywords::use(bodyType), Poco::Data::Keywords::use(clientID), Poco::Data::Keywords::use(groupID),
Poco::Data::Keywords::use(groupSeq), Poco::Data::Keywords::now;
}
}
}
} else {
dbSession << sql.str(), Poco::Data::Keywords::now;
}
}
CATCH_POCO_DATA_EXCEPTION_PURE("can't copy messages to the browser", sql.str(), ERROR_ON_BROWSER)
sql.str("");
sql << "update " << STORAGE_CONFIG.messageJournal(_parent->name()) << " set subscribers_count = subscribers_count + 1 where message_id in ("
<< "select message_id from " << storage.messageTableID() << ");";
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't copy messages to the browser", sql.str(), ERROR_ON_BROWSER)
sql.str("");
sql << "insert into " << storage.propertyTableID() << " select * from " << _propertyTableID << " where message_id in "
<< "("
<< " select message_id from " << storage.messageTableID() << ")"
<< ";";
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE("can't copy messages to the browser", sql.str(), ERROR_ON_BROWSER)
dbSession.commitTX();
}
void Storage::resetNonPersistent(const Storage::NonPersistentMessagesListType &nonPersistentMessagesList) {
_nonPersistent.clear();
_nonPersistent = nonPersistentMessagesList;
}
int64_t Storage::size() {
std::stringstream sql;
Poco::Int64 result = 0;
sql << "select count(*) from " << _messageTableID << " as msgs"
<< " where delivery_status <> " << message::DELIVERED;
sql << ";";
storage::DBMSSession dbSession = dbms::Instance().dbmsSession();
dbSession.beginTX(_messageTableID, storage::DBMSSession::TransactionMode::READ);
TRY_POCO_DATA_EXCEPTION { dbSession << sql.str(), Poco::Data::Keywords::into(result), Poco::Data::Keywords::now; }
CATCH_POCO_DATA_EXCEPTION_PURE_NO_INVALIDEXCEPT_NO_EXCEPT("can't get queue size", sql.str(), ERROR_STORAGE)
dbSession.commitTX();
return result;
}
std::shared_ptr<MessageDataContainer> Storage::makeMessage(storage::DBMSSession &dbSession,
const consumer::Msg &msgInfo,
const Consumer &consumer,
bool useFileLink) {
std::shared_ptr<MessageDataContainer> sMessage;
if (!msgInfo.messageId.empty()) {
bool ttlIsOut = checkTTLIsOut(msgInfo.screated, msgInfo.ttl);
if (ttlIsOut) {
removeMessage(msgInfo.messageId, dbSession);
return {};
}
bool needToFillProperties = true;
sMessage = std::make_shared<MessageDataContainer>(STORAGE_CONFIG.data.get().toString());
try {
Proto::Message &message = sMessage->createMessageHeader(consumer.objectID);
sMessage->clientID = Poco::replace(consumer.clientID, "-browser", "");
sMessage->handlerNum = consumer.tcpNum;
message.set_message_id(msgInfo.messageId);
message.set_destination_uri(_parent->uri());
message.set_priority(msgInfo.priority);
message.set_persistent(msgInfo.persistent == 1);
message.set_sender_id(BROKER::Instance().id());
sMessage->data.clear();
if (msgInfo.persistent == 1) {
std::string data = sMessage->message().message_id();
data[2] = '_';
data = Exchange::mainDestinationPath(sMessage->message().destination_uri()) + "/" + data;
auto &pmap = *message.mutable_property();
if (useFileLink) {
Poco::Path path = STORAGE_CONFIG.data.get();
path.append(data);
pmap[s2s::proto::upmq_data_link].set_value_string(path.toString());
pmap[s2s::proto::upmq_data_link].set_is_null(false);
pmap[s2s::proto::upmq_data_parts_number].set_value_int(0);
pmap[s2s::proto::upmq_data_parts_number].set_is_null(false);
pmap[s2s::proto::upmq_data_parts_count].set_value_int(0);
pmap[s2s::proto::upmq_data_parts_count].set_is_null(false);
pmap[s2s::proto::upmq_data_part_size].set_value_int(0);
pmap[s2s::proto::upmq_data_part_size].set_is_null(false);
} else {
pmap.erase(s2s::proto::upmq_data_link);
pmap.erase(s2s::proto::upmq_data_parts_number);
pmap.erase(s2s::proto::upmq_data_parts_count);
pmap.erase(s2s::proto::upmq_data_part_size);
sMessage->setWithFile(true);
sMessage->data = data;
}
} else {
auto item = _nonPersistent.find(msgInfo.messageId);
if (item.hasValue()) {
needToFillProperties = (*item)->message().property_size() > 0;
sMessage->data = (*item)->data;
} else {
removeMessage(msgInfo.messageId, dbSession);
return {};
}
}
if (!msgInfo.correlationID.isNull()) {
message.set_correlation_id(msgInfo.correlationID.value());
}
if (!msgInfo.replyTo.isNull()) {
message.set_reply_to(msgInfo.replyTo);
}
message.set_type(msgInfo.type);
message.set_timestamp(msgInfo.timestamp);
message.set_timetolive(msgInfo.ttl);
message.set_expiration(msgInfo.expiration);
if (sMessage) {
sMessage->setDeliveryCount(msgInfo.deliveryCount);
}
message.set_body_type(msgInfo.bodyType);
message.set_session_id(consumer.session.id);
if (!msgInfo.groupID.value().empty()) {
Poco::StringTokenizer groupIDAll(msgInfo.groupID, "+", Poco::StringTokenizer::TOK_TRIM);
message.set_group_id(groupIDAll[0]);
} else {
message.set_group_id(msgInfo.groupID.value());
}
message.set_group_seq(msgInfo.groupSeq);
if (needToFillProperties) {
fillProperties(dbSession, message);
}
} catch (Exception &ex) {
removeMessage(msgInfo.messageId, dbSession);
throw Exception(ex);
}
}
return sMessage;
}
void Storage::fillProperties(storage::DBMSSession &dbSession, Proto::Message &message) {
std::stringstream sql;
sql << "select "
" message_id,"
" property_name,"
" property_type, "
" value_string,"
" value_char,"
" value_bool,"
" value_byte,"
" value_short,"
" value_int,"
" value_long,"
" value_float,"
" value_double,"
" value_bytes,"
" value_object,"
" is_null"
" from "
<< _propertyTableID << " where message_id = \'" << message.message_id() << "\';";
MessagePropertyInfo messagePropertyInfo;
TRY_POCO_DATA_EXCEPTION {
Poco::Data::Statement select(dbSession());
select << sql.str(), Poco::Data::Keywords::into(messagePropertyInfo.tuple), Poco::Data::Keywords::range(0, 1);
while (!select.done()) {
select.execute();
if (!messagePropertyInfo.messageID().empty()) {
auto &pmap = *message.mutable_property();
const std::string &name = messagePropertyInfo.propertyName();
bool isNull = messagePropertyInfo.valueNull();
bool isNan = false;
if (messagePropertyInfo.isNull() && !isNull) {
isNan = true;
}
switch (static_cast<MessagePropertyInfo::Field>(messagePropertyInfo.propertyType())) {
case MessagePropertyInfo::Field::value_string:
pmap[name].set_value_string(messagePropertyInfo.valueString());
break;
case MessagePropertyInfo::Field::value_char:
pmap[name].set_value_char(messagePropertyInfo.valueChar());
break;
case MessagePropertyInfo::Field::value_bool:
pmap[name].set_value_bool(messagePropertyInfo.valueBool());
break;
case MessagePropertyInfo::Field::value_byte:
pmap[name].set_value_byte(messagePropertyInfo.valueByte());
break;
case MessagePropertyInfo::Field::value_short:
pmap[name].set_value_short(messagePropertyInfo.valueShort());
break;
case MessagePropertyInfo::Field::value_int:
pmap[name].set_value_int(messagePropertyInfo.valueInt());
break;
case MessagePropertyInfo::Field::value_long:
pmap[name].set_value_long(messagePropertyInfo.valueLong());
break;
case MessagePropertyInfo::Field::value_float:
if (isNan) {
pmap[name].set_value_float(std::numeric_limits<float>::quiet_NaN());
} else {
pmap[name].set_value_float(messagePropertyInfo.valueFloat());
}
break;
case MessagePropertyInfo::Field::value_double:
if (isNan) {
pmap[name].set_value_double(std::numeric_limits<double>::quiet_NaN());
} else {
pmap[name].set_value_double(messagePropertyInfo.valueDouble());
}
break;
case MessagePropertyInfo::Field::value_bytes:
pmap[name].set_value_bytes(messagePropertyInfo.valueBytes().rawContent(), messagePropertyInfo.valueBytes().size());
break;
case MessagePropertyInfo::Field::value_object:
pmap[name].set_value_object(reinterpret_cast<const char *>(messagePropertyInfo.valueObject().rawContent()),
messagePropertyInfo.valueObject().size());
break;
default:
pmap[name].set_is_null(true);
}
pmap[name].set_is_null(isNull);
}
}
}
CATCH_POCO_DATA_EXCEPTION_PURE_TROW_INVALID_SQL("can't fill properties", sql.str(), ERROR_ON_GET_MESSAGE)
}
void Storage::dropTables() {
std::stringstream sql;
sql << "drop table if exists " << _messageTableID << ";" << non_std_endl;
TRY_POCO_DATA_EXCEPTION { storage::DBMSConnectionPool::doNow(sql.str()); }
CATCH_POCO_DATA_EXCEPTION_PURE_NO_INVALIDEXCEPT_NO_EXCEPT("can't drop table", sql.str(), ERROR_ON_UNSUBSCRIPTION)
sql.str("");
sql << "drop table if exists " << _propertyTableID << ";";
TRY_POCO_DATA_EXCEPTION { storage::DBMSConnectionPool::doNow(sql.str()); }
CATCH_POCO_DATA_EXCEPTION_PURE_NO_INVALIDEXCEPT_NO_EXCEPT("can't drop table", sql.str(), ERROR_ON_UNSUBSCRIPTION)
}
bool Storage::hasTransaction(const Session &session) const {
upmq::ScopedReadRWLock readRWLock(_txSessionsLock);
return (_txSessions.find(session.id()) != _txSessions.end());
}
} // namespace broker
} // namespace upmq
| 44.135727 | 150 | 0.642839 | asvgit |
4c9533595ba35cc7690a50b3de4af4e1dfd59a31 | 5,126 | cpp | C++ | toolboxes/fatwater/bounded_field_map.cpp | roopchansinghv/gadgetron | fb6c56b643911152c27834a754a7b6ee2dd912da | [
"MIT"
] | 1 | 2022-02-22T21:06:36.000Z | 2022-02-22T21:06:36.000Z | toolboxes/fatwater/bounded_field_map.cpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | toolboxes/fatwater/bounded_field_map.cpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | //
// Created by dchansen on 9/4/18.
//
#include "bounded_field_map.h"
#include <boost/math/constants/constants.hpp>
#include <boost/math/tools/minima.hpp>
#include <numeric>
#include <GadgetronTimer.h>
constexpr float PI = boost::math::constants::pi<float>();
namespace Gadgetron {
namespace FatWater {
namespace {
template<unsigned int N>
struct FieldMapModel {
FieldMapModel(const Parameters ¶meters,
const std::array<complext<float>, N> &data) : TEs_(parameters.echo_times_s) {
std::transform(data.begin(), data.end(), angles.begin(), [](auto c) { return arg(c); });
auto data_norm = std::accumulate(data.begin(), data.end(), 0.0,
[](auto acc, auto c) { return acc + norm(c); });
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data.size(); j++) {
weights[j + i * N] = norm(data[i] * data[j]) / data_norm;
}
}
}
float operator()(float field_value) const {
float result = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
result += magnitude_internal(field_value, TEs_[i], TEs_[j], angles[i], angles[j],
weights[j + i * N]);
}
}
return result;
}
float magnitude_internal(float field_value, float time1, float time2, float angle1, float angle2,
float weight) const {
assert(weight >= 0);
return weight * (1.0f - std::cos(field_value * (time1 - time2) + angle1 - angle2));
}
const std::vector<float> TEs_;
std::array<float, N * N> weights;
std::array<float, N> angles;
};
template<unsigned int N>
void bounded_field_map_N(Gadgetron::hoNDArray<float> &field_map,
const Gadgetron::hoNDArray<std::complex<float>> &input_data,
const Gadgetron::FatWater::Parameters ¶meters,
float delta_field) {
const size_t X = input_data.get_size(0);
const size_t Y = input_data.get_size(1);
const size_t Z = input_data.get_size(2);
const size_t S = input_data.get_size(5);
#ifdef WIN32
#pragma omp parallel for
#else
#pragma omp parallel for collapse(2)
#endif
for (int ky = 0; ky < Y; ky++) {
for (size_t kx = 0; kx < X; kx++) {
std::array<complext<float>, N> signal;
for (int k3 = 0; k3 < S; k3++) {
signal[k3] = input_data(kx, ky, 0, 0, 0, k3, 0);
}
auto model = FieldMapModel<N>(parameters, signal);
auto result_pair = boost::math::tools::brent_find_minima(model, field_map(kx,ky)-delta_field,field_map(kx,ky)+delta_field, 24);
field_map(kx, ky) = result_pair.first;
}
}
}
}
void bounded_field_map(Gadgetron::hoNDArray<float> &field_map,
const Gadgetron::hoNDArray<std::complex<float>> &input_data,
const Gadgetron::FatWater::Parameters ¶meters,
float delta_field
) {
if (input_data.get_size(4) > 1) throw std::runtime_error("Only single repetition supported");
switch (input_data.get_size(5)) {
case 2:
bounded_field_map_N<2>(field_map, input_data, parameters, delta_field);
break;
case 3:
bounded_field_map_N<3>(field_map, input_data, parameters, delta_field);
break;
case 4:
bounded_field_map_N<4>(field_map, input_data, parameters, delta_field);
break;
case 5:
bounded_field_map_N<5>(field_map, input_data, parameters, delta_field);
break;
case 6:
bounded_field_map_N<6>(field_map, input_data, parameters, delta_field);
break;
case 7:
bounded_field_map_N<7>(field_map, input_data, parameters, delta_field);
break;
case 8:
bounded_field_map_N<8>(field_map, input_data, parameters, delta_field);
break;
default:
throw std::runtime_error("Unsupported number of echoes");
}
}
}
}
| 36.35461 | 151 | 0.464885 | roopchansinghv |
4c95eabae144be335da77ddf4d4002b5c8fbf95d | 4,955 | cpp | C++ | src/Particles/FlexiblePatchyRod.cpp | mtortora/chiralDFT | d5ea5e940d6bc72d96fd9728d042de1e09d3ef85 | [
"MIT"
] | 2 | 2018-01-03T09:33:09.000Z | 2019-06-14T13:29:37.000Z | src/Particles/FlexiblePatchyRod.cpp | mtortora/chiralDFT | d5ea5e940d6bc72d96fd9728d042de1e09d3ef85 | [
"MIT"
] | null | null | null | src/Particles/FlexiblePatchyRod.cpp | mtortora/chiralDFT | d5ea5e940d6bc72d96fd9728d042de1e09d3ef85 | [
"MIT"
] | null | null | null | // ===================================================================
/**
* Flexible patchy rod derived particle class.
* Particle model from http://dx.doi.org/10.1039/c7sm02077e
*/
// ===================================================================
/*
* FlexiblePatchyRod.cpp: Version 1.0
* Created 18/12/2017 by Maxime Tortora
*/
// ===================================================================
#include <fstream>
#include "Particles/FlexiblePatchyRod.hpp"
template<typename number>
FlexiblePatchyRod<number>::FlexiblePatchyRod()
{
this->N_DELTA_L = 2;
// WCA/LJ parameters
EPSILON_WCA_ = 1.;
E_CUT_ = 20.;
D_BACK_ = 1. * this->SIGMA_R;
R_BACK_ = pow(2., 1./6) * this->SIGMA_R;
D_PATCH_ = 0.1 * D_BACK_;
R_PATCH_ = 2.5 * this->SIGMA_R;
D_LB_ = (D_BACK_+D_PATCH_)/2.;
R_LB_ = (R_BACK_+R_PATCH_)/2.;
}
// ============================
/* Build particle model */
// ============================
template<typename number>
void FlexiblePatchyRod<number>::Build(int mpi_rank)
{
uint N_TOT;
// Load configurations from trajectory files on master thread
if ( mpi_rank == MPI_MASTER )
{
ArrayX<uint> Sizes_bck;
ArrayX<uint> Sizes_ptc;
ArrayX<uint> Types;
ArrayX<number> Charges;
std::string DATA_PATH = __DATA_PATH;
std::string file_bck = DATA_PATH + "/bck.in";
std::string file_ptc = DATA_PATH + "/ptc.in";
Utils<number>::Load(file_bck, &Backbones, &Charges, &Types, &Sizes_bck);
Utils<number>::Load(file_ptc, &Patches, &Charges, &Types, &Sizes_ptc);
if ( (Backbones.size() == 0) || (Patches.size() == 0) ) throw std::runtime_error("Unreadable input file(s)");
if ( (Sizes_bck != Sizes_ptc).all() ) throw std::runtime_error("Incompatible backbone/patch input files");
N_BCK = Sizes_bck(0);
N_TOT = Sizes_bck.sum();
N_CONF_ = Sizes_bck.size();
if ( (Sizes_bck != N_BCK).any() ) throw std::runtime_error("Found configurations of multiple sizes in backbone file");
}
// Broadcast data to slave threads
MPI_Bcast(&N_BCK, 1, Utils<uint>().MPI_type, MPI_MASTER, MPI_COMM_WORLD);
MPI_Bcast(&N_TOT, 1, Utils<uint>().MPI_type, MPI_MASTER, MPI_COMM_WORLD);
MPI_Bcast(&N_CONF_, 1, Utils<uint>().MPI_type, MPI_MASTER, MPI_COMM_WORLD);
if ( mpi_rank != MPI_MASTER )
{
Backbones.resize(3, N_TOT);
Patches .resize(3, N_TOT);
}
MPI_Bcast(Backbones.data(), Backbones.size(), Utils<number>().MPI_type, MPI_MASTER, MPI_COMM_WORLD);
MPI_Bcast(Patches .data(), Patches .size(), Utils<number>().MPI_type, MPI_MASTER, MPI_COMM_WORLD);
(this->BVH).Forest.resize(N_CONF_);
for ( uint idx_conf_ = 0; idx_conf_ < N_CONF_; ++idx_conf_ )
{
// Set center of masses to the origin and main axes to e_z
Matrix3X<number> Backbone = Matrix3X<number>::Map(Backbones.data() + 3 * idx_conf_*N_BCK, 3, N_BCK);
Matrix3X<number> Patch = Matrix3X<number>::Map(Patches .data() + 3 * idx_conf_*N_BCK, 3, N_BCK);
Vector3<number> Center_of_mass = Backbone.rowwise().mean();
Backbone = Backbone.colwise() - Center_of_mass;
Patch = Patch .colwise() - Center_of_mass;
Matrix33<number> Rot = Utils<number>::PCA(Backbone);
Backbone = Rot.transpose() * Backbone;
Patch = Rot.transpose() * Patch;
// Build root bounding volumes
number z_inf = Patch.row(2).minCoeff();
number z_sup = Patch.row(2).maxCoeff();
number r_max = Patch.block(0, 0, 2, N_BCK).colwise().norm().maxCoeff();
number z_max = fmax(std::abs(z_inf),std::abs(z_sup));
this->Hull = &(this->BVH).Forest[idx_conf_];
this->Hull->l_xh = r_max + R_PATCH_/2.;
this->Hull->l_yh = r_max + R_PATCH_/2.;
this->Hull->l_zh = z_max + R_PATCH_/2.;
this->Hull->l_cr = r_max + R_PATCH_/2.;
this->Hull->l_ch = z_max;
Backbones.block(0, N_BCK*idx_conf_, 3, N_BCK) = Backbone;
Patches .block(0, N_BCK*idx_conf_, 3, N_BCK) = Patch;
}
if ( this->id_ == 1 ) LogTxt("Loaded particle trajectory file: %d configurations, %d interaction sites", N_CONF_, 2*N_TOT);
this->R_INTEG = 2*Patches.colwise().norm().maxCoeff() + R_PATCH_;
this->V_INTEG = CUB(2.*this->R_INTEG) * 16.*pow(PI, 6);
this->V0 = 11.76167;
this->V_EFF = 11.76167;
}
template class FlexiblePatchyRod<float>;
template class FlexiblePatchyRod<double>;
| 36.433824 | 127 | 0.539859 | mtortora |
4c994842752b45e22246872205f35a3e2e111d41 | 10,896 | cpp | C++ | CloakEngine/DX12Device.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakEngine/DX12Device.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakEngine/DX12Device.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#if CHECK_OS(WINDOWS,10)
#include "Implementation/Rendering/DX12/Device.h"
#include "Implementation/Rendering/DX12/Casting.h"
#include "Implementation/Rendering/DX12/Resource.h"
#include "Implementation/Rendering/DX12/ColorBuffer.h"
#include "Implementation/Rendering/DX12/RootSignature.h"
namespace CloakEngine {
namespace Impl {
namespace Rendering {
namespace DX12 {
namespace Device_v1 {
CLOAK_CALL Device::Device(In const GraphicDevice& dev12)
{
DEBUG_NAME(Device);
m_dev12 = dev12;
}
CLOAK_CALL Device::~Device()
{
}
uint32_t CLOAK_CALL_THIS Device::GetDescriptorHandleIncrementSize(In HEAP_TYPE type) const
{
return static_cast<uint32_t>(m_dev12.V0->GetDescriptorHandleIncrementSize(Casting::CastForward(type)));
}
void CLOAK_CALL_THIS Device::CreateConstantBufferView(In const CBV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle) const
{
D3D12_CONSTANT_BUFFER_VIEW_DESC rd = Casting::CastForward(desc);
m_dev12.V0->CreateConstantBufferView(&rd, Casting::CastForward(cpuHandle));
}
void CLOAK_CALL_THIS Device::CreateShaderResourceView(In IResource* rsc, In const SRV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle)
{
Resource* res = nullptr;
if (rsc!=nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res))))
{
D3D12_SHADER_RESOURCE_VIEW_DESC rd = Casting::CastForward(desc);
m_dev12.V0->CreateShaderResourceView(res->m_data, &rd, Casting::CastForward(cpuHandle));
res->Release();
}
}
void CLOAK_CALL_THIS Device::CreateRenderTargetView(In IResource* rsc, In const RTV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle)
{
Resource* res = nullptr;
if (rsc != nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res))))
{
D3D12_RENDER_TARGET_VIEW_DESC rd = Casting::CastForward(desc);
m_dev12.V0->CreateRenderTargetView(res->m_data, &rd, Casting::CastForward(cpuHandle));
res->Release();
}
}
void CLOAK_CALL_THIS Device::CreateUnorderedAccessView(In IResource* rsc, In_opt IResource* byteAddress, In const UAV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle)
{
Resource* res = nullptr;
if (rsc != nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res))))
{
D3D12_UNORDERED_ACCESS_VIEW_DESC rd = Casting::CastForward(desc);
Resource* ba = nullptr;
if (byteAddress != nullptr && SUCCEEDED(byteAddress->QueryInterface(CE_QUERY_ARGS(&ba))))
{
m_dev12.V0->CreateUnorderedAccessView(res->m_data, ba->m_data, &rd, Casting::CastForward(cpuHandle));
ba->Release();
}
else
{
m_dev12.V0->CreateUnorderedAccessView(res->m_data, nullptr, &rd, Casting::CastForward(cpuHandle));
}
res->Release();
}
}
void CLOAK_CALL_THIS Device::CreateDepthStencilView(In IResource* rsc, In const DSV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle)
{
Resource* res = nullptr;
if (rsc != nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res))))
{
D3D12_DEPTH_STENCIL_VIEW_DESC rd = Casting::CastForward(desc);
m_dev12.V0->CreateDepthStencilView(res->m_data, &rd, Casting::CastForward(cpuHandle));
res->Release();
}
}
void CLOAK_CALL_THIS Device::CreateSampler(In const API::Rendering::SAMPLER_DESC& desc, In API::Rendering::CPU_DESCRIPTOR_HANDLE handle)
{
D3D12_SAMPLER_DESC d;
d.Filter = Casting::CastForward(desc.Filter);
d.AddressU = Casting::CastForward(desc.AddressU);
d.AddressV = Casting::CastForward(desc.AddressV);
d.AddressW = Casting::CastForward(desc.AddressW);
d.MipLODBias = desc.MipLODBias;
d.MaxAnisotropy = desc.MaxAnisotropy;
d.ComparisonFunc = Casting::CastForward(desc.CompareFunction);
for (size_t a = 0; a < 4; a++) { d.BorderColor[a] = desc.BorderColor[a]; }
d.MinLOD = desc.MinLOD;
d.MaxLOD = desc.MaxLOD;
m_dev12.V0->CreateSampler(&d, Casting::CastForward(handle));
}
void CLOAK_CALL_THIS Device::CopyDescriptorsSimple(In UINT numDescriptors, In const API::Rendering::CPU_DESCRIPTOR_HANDLE& dstStart, In const API::Rendering::CPU_DESCRIPTOR_HANDLE& srcStart, In HEAP_TYPE heap)
{
m_dev12.V0->CopyDescriptorsSimple(numDescriptors, Casting::CastForward(dstStart), Casting::CastForward(srcStart), Casting::CastForward(heap));
}
void CLOAK_CALL_THIS Device::CopyDescriptors(In UINT numDstRanges, In_reads(numDstRanges) const API::Rendering::CPU_DESCRIPTOR_HANDLE* dstRangeStarts, In_reads_opt(numDstRanges) const UINT* dstRangeSizes, In UINT numSrcRanges, In_reads(numSrcRanges) const API::Rendering::CPU_DESCRIPTOR_HANDLE* srcRangeStarts, In_reads_opt(numSrcRanges) const UINT* srcRangeSizes, In HEAP_TYPE heap)
{
D3D12_CPU_DESCRIPTOR_HANDLE* dstRange = NewArray(D3D12_CPU_DESCRIPTOR_HANDLE, numDstRanges);
D3D12_CPU_DESCRIPTOR_HANDLE* srcRange = NewArray(D3D12_CPU_DESCRIPTOR_HANDLE, numSrcRanges);
for (UINT a = 0; a < numDstRanges; a++) { dstRange[a] = Casting::CastForward(dstRangeStarts[a]); }
for (UINT a = 0; a < numSrcRanges; a++) { srcRange[a] = Casting::CastForward(srcRangeStarts[a]); }
m_dev12.V0->CopyDescriptors(numDstRanges, dstRange, dstRangeSizes, numSrcRanges, srcRange, srcRangeSizes, Casting::CastForward(heap));
DeleteArray(dstRange);
DeleteArray(srcRange);
}
HRESULT CLOAK_CALL_THIS Device::CreateRootSignature(In const void* data, In size_t dataSize, In REFIID riid, Out void** ppvObject)
{
const UINT nodeCount = m_dev12.V0->GetNodeCount();
return m_dev12.V0->CreateRootSignature(nodeCount == 1 ? 0 : ((1 << nodeCount) - 1), data, dataSize, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateCommandQueue(In const D3D12_COMMAND_QUEUE_DESC& desc, In REFIID riid, Out void** ppvObject)
{
CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1));
return m_dev12.V0->CreateCommandQueue(&desc, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateFence(In uint64_t value, In D3D12_FENCE_FLAGS flags, In REFIID riid, Out void** ppvObject)
{
return m_dev12.V0->CreateFence(value, flags, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateCommandList(In UINT node, In D3D12_COMMAND_LIST_TYPE type, In ID3D12CommandAllocator* alloc, In REFIID riid, Out void** ppvObject)
{
return m_dev12.V0->CreateCommandList(node, type, alloc, nullptr, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateCommandAllocator(In D3D12_COMMAND_LIST_TYPE type, In REFIID riid, Out void** ppvObject)
{
return m_dev12.V0->CreateCommandAllocator(type, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateCommittedResource(In const D3D12_HEAP_PROPERTIES& heap, In D3D12_HEAP_FLAGS heapFlags, In const D3D12_RESOURCE_DESC& desc, In D3D12_RESOURCE_STATES state, In_opt const D3D12_CLEAR_VALUE* clearValue, In REFIID riid, Out void** ppvObject)
{
CLOAK_ASSUME((heap.CreationNodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1) && heap.CreationNodeMask == heap.VisibleNodeMask);
return m_dev12.V0->CreateCommittedResource(&heap, heapFlags, &desc, state, clearValue, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateDescriptorHeap(In const D3D12_DESCRIPTOR_HEAP_DESC& desc, REFIID riid, void** ppvObject)
{
CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1));
return m_dev12.V0->CreateDescriptorHeap(&desc, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateComputePipelineState(In const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc, REFIID riid, void** ppvObject)
{
CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1));
return m_dev12.V0->CreateComputePipelineState(&desc, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreateGraphicsPipelineState(In const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, REFIID riid, void** ppvObject)
{
CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1));
return m_dev12.V0->CreateGraphicsPipelineState(&desc, riid, ppvObject);
}
HRESULT CLOAK_CALL_THIS Device::CreatePipelineState(In D3D12_PIPELINE_STATE_DESC& desc, REFIID riid, void** ppvObject)
{
if (m_dev12.V2 != nullptr)
{
D3D12_PIPELINE_STATE_STREAM_DESC d;
d.pPipelineStateSubobjectStream = &desc;
d.SizeInBytes = sizeof(desc);
return m_dev12.V2->CreatePipelineState(&d, riid, ppvObject);
}
else
{
//TODO
}
return E_FAIL;
}
HRESULT CLOAK_CALL_THIS Device::CreateQueryHeap(In const D3D12_QUERY_HEAP_DESC& desc, REFIID riid, void** ppvObject)
{
CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1));
return m_dev12.V0->CreateQueryHeap(&desc, riid, ppvObject);
}
void CLOAK_CALL_THIS Device::GetCopyableFootprints(In const D3D12_RESOURCE_DESC& resourceDesc, In UINT firstSubresource, In UINT numSubresources, In UINT64 baseOffset, Out_writes(numSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, Out_writes(numSubresources) UINT* numRows, Out_writes(numSubresources) UINT64* rowSizeInBytes, Out_opt UINT64* totalBytes)
{
m_dev12.V0->GetCopyableFootprints(&resourceDesc, firstSubresource, numSubresources, baseOffset, layouts, numRows, rowSizeInBytes, totalBytes);
}
Use_annotations HRESULT STDMETHODCALLTYPE Device::QueryInterface(REFIID riid, void** ppvObject)
{
if (ppvObject == nullptr) { return E_INVALIDARG; }
*ppvObject = nullptr;
bool got = false;
if (riid == __uuidof(ID3D12Device))
{
*ppvObject = static_cast<ID3D12Device*>(m_dev12.V0.Get());
m_dev12.V0->AddRef();
got = true;
}
else if (riid == __uuidof(Impl::Rendering::DX12::Device_v1::Device))
{
*ppvObject = static_cast<Impl::Rendering::DX12::Device_v1::Device*>(this);
AddRef();
got = true;
}
else if (riid == __uuidof(Impl::Rendering::Device_v1::IDevice))
{
*ppvObject = static_cast<Impl::Rendering::Device_v1::IDevice*>(this);
AddRef();
got = true;
}
else
{
got = SavePtr::iQueryInterface(riid, ppvObject);
if (got) { AddRef(); }
}
return got ? S_OK : E_NOINTERFACE;
}
}
}
}
}
}
#endif | 51.63981 | 389 | 0.687133 | Bizzarrus |
4c99c6f18b421a3a060af9c410e3c7df700aa39b | 1,079 | cpp | C++ | plugins/glib/src/application/models/CollectionData.cpp | winterdl/kinoko | 9cb040e2efcbe08377826c4bb7518cfd0ced0564 | [
"MIT"
] | 119 | 2020-09-22T07:40:55.000Z | 2022-03-28T18:28:02.000Z | plugins/glib/src/application/models/CollectionData.cpp | winterdl/kinoko | 9cb040e2efcbe08377826c4bb7518cfd0ced0564 | [
"MIT"
] | 32 | 2021-07-19T12:03:00.000Z | 2022-03-25T06:39:04.000Z | plugins/glib/src/application/models/CollectionData.cpp | winterdl/kinoko | 9cb040e2efcbe08377826c4bb7518cfd0ced0564 | [
"MIT"
] | 14 | 2021-07-16T14:38:35.000Z | 2022-03-06T00:25:37.000Z | //
// Created by gen on 7/24/20.
//
#include <nlohmann/json.hpp>
#include "CollectionData.h"
#include "../utils/JSON.h"
using namespace gs;
CollectionData::CollectionData() : flag(0) {
}
gc::Array CollectionData::all(const std::string &type) {
return CollectionData::query()->equal("type", type)->sortBy("identifier")->results();
}
gc::Array CollectionData::findBy(const std::string &type, const std::string &sort, int page, int page_count) {
return CollectionData::query()->equal("type", type)->sortBy(sort)->offset(page * page_count)->limit(page_count)->results();
}
gc::Ref<CollectionData> CollectionData::find(const std::string &type, const std::string &key) {
gc::Array arr = CollectionData::query()->equal("type", type)->andQ()->equal("key", key)->results();
if (arr->size())
return arr->get(0);
return gc::Ref<CollectionData>::null();
}
void CollectionData::setJSONData(const gc::Variant &data) {
if (data) {
nlohmann::json json = JSON::serialize(data);
setData(json.dump());
} else {
setData("");
}
} | 29.972222 | 127 | 0.652456 | winterdl |
4c9d053b22563ca5ceb2eeba5beb612158ee5331 | 625 | cpp | C++ | car_inher.cpp | ishansheth/ModernCpp-Exercises | c33d63ea9e6fe3115fbac51304a75292f32998cd | [
"MIT"
] | null | null | null | car_inher.cpp | ishansheth/ModernCpp-Exercises | c33d63ea9e6fe3115fbac51304a75292f32998cd | [
"MIT"
] | null | null | null | car_inher.cpp | ishansheth/ModernCpp-Exercises | c33d63ea9e6fe3115fbac51304a75292f32998cd | [
"MIT"
] | null | null | null | #include <iostream>
class car
{
public:
car(const std::string& name) : name(name)
{}
void all_info() const
{
std::cout<< "car name:"<<name<<std::endl;
}
protected:
std::string name;
};
class truck : public car
{
public:
truck(const std::String& name, double weight): car(name), weight(weight)
{}
void all_info()
{
std::cout<< "truck : My name is " << name <<std::endl;
std::cout<< "I can carry "<< weight<< std::endl;
}
protected:
double weight;
};
int main(int argc, char* arhv[])
{
truck robur("Robur L04",2.5);
robur.all_info();
} | 15.625 | 75 | 0.5584 | ishansheth |
4ca1ae89c3c0a8c805c8c2154f31bd65dc173363 | 4,566 | cpp | C++ | test/allocator/wary_ptr/test_wary_ptr_two_ptrs.cpp | bi-ts/dst | d68d4cfb7509a2f65c8120d88cbc198874343f30 | [
"BSL-1.0"
] | null | null | null | test/allocator/wary_ptr/test_wary_ptr_two_ptrs.cpp | bi-ts/dst | d68d4cfb7509a2f65c8120d88cbc198874343f30 | [
"BSL-1.0"
] | null | null | null | test/allocator/wary_ptr/test_wary_ptr_two_ptrs.cpp | bi-ts/dst | d68d4cfb7509a2f65c8120d88cbc198874343f30 | [
"BSL-1.0"
] | 1 | 2021-09-03T10:48:56.000Z | 2021-09-03T10:48:56.000Z |
// Copyright Maksym V. Bilinets 2015 - 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt )
#include <dst/allocator/wary_ptr.h>
#include <dst/allocator/detail/wary_ptr_factory.h>
#include "tester_wary_ptr.h"
#include <gtest/gtest.h>
#include <cstdint> // std::int64_t
using namespace dst;
namespace
{
class Test_wary_ptr_two_ptrs : public ::testing::Test,
public dst::test::Tester_wary_ptr
{
public:
Test_wary_ptr_two_ptrs()
: ptr_1(detail::wary_ptr_factory::create_associated_ptr(values, elements_num))
, ptr_2(ptr_1)
{
++++ptr_2; // shift by two
}
~Test_wary_ptr_two_ptrs() noexcept(true)
{
neutralize(ptr_2);
neutralize(ptr_1);
}
static const std::size_t elements_num = 3;
std::int64_t values[elements_num];
dst::wary_ptr<std::int64_t> ptr_1;
dst::wary_ptr<std::int64_t> ptr_2;
};
}
/// @fn wary_ptr<T>::operator==(const wary_ptr<U>& other) const
/// @test @b Test_wary_ptr_two_ptrs.equality_test <br>
/// Tests if:
/// * Two different pointers do not compare equal.
/// * Pointers compare equal to themselves.
/// * An associated and a loose pointer compare equal if they point to
/// the same memory location.
TEST_F(Test_wary_ptr_two_ptrs, equality_test)
{
wary_ptr<std::int64_t> loose_ptr =
wary_ptr<std::int64_t>::pointer_to(values[0]);
EXPECT_FALSE(ptr_1 == ptr_2);
EXPECT_FALSE(ptr_2 == ptr_1);
EXPECT_TRUE(ptr_1 == ptr_1);
EXPECT_TRUE(ptr_2 == ptr_2);
EXPECT_TRUE(ptr_1 == loose_ptr);
}
/// @fn wary_ptr<T>::operator!=(const wary_ptr<U>& other) const
/// @test @b Test_wary_ptr_two_ptrs.inequality_test <br>
/// Uses operator!=() to tests if:
/// * Two different pointers compare inequal.
/// * Pointers do not compare inequal to themselves.
TEST_F(Test_wary_ptr_two_ptrs, inequality_test)
{
EXPECT_TRUE(ptr_1 != ptr_2);
EXPECT_TRUE(ptr_2 != ptr_1);
EXPECT_FALSE(ptr_1 != ptr_1);
EXPECT_FALSE(ptr_2 != ptr_2);
}
/// @fn wary_ptr<T>::operator<(const wary_ptr<U>& other) const
/// @test @b Test_wary_ptr_two_ptrs.operator_less <br>
/// Tests operator<() comparing:
/// * Two different pointers.
/// * The same pointer with itself.
TEST_F(Test_wary_ptr_two_ptrs, operator_less)
{
EXPECT_TRUE(ptr_1 < ptr_2);
EXPECT_FALSE(ptr_2 < ptr_1);
EXPECT_FALSE(ptr_1 < ptr_1);
EXPECT_FALSE(ptr_2 < ptr_2);
}
/// @fn wary_ptr<T>::operator>(const wary_ptr<U>& other) const
/// @test @b Test_wary_ptr_two_ptrs.operator_greater <br>
/// Tests operator>() comparing:
/// * Two different pointers.
/// * The same pointer with itself.
TEST_F(Test_wary_ptr_two_ptrs, operator_greater)
{
EXPECT_FALSE(ptr_1 > ptr_2);
EXPECT_TRUE(ptr_2 > ptr_1);
EXPECT_FALSE(ptr_1 > ptr_1);
EXPECT_FALSE(ptr_2 > ptr_2);
}
/// @fn wary_ptr<T>::operator<=(const wary_ptr<U>& other) const
/// @test @b Test_wary_ptr_two_ptrs.operator_less_eq <br>
/// Tests operator<=() comparing:
/// * Two different pointers.
/// * The same pointer with itself.
TEST_F(Test_wary_ptr_two_ptrs, operator_less_eq)
{
EXPECT_TRUE(ptr_1 <= ptr_2);
EXPECT_FALSE(ptr_2 <= ptr_1);
EXPECT_TRUE(ptr_1 <= ptr_1);
EXPECT_TRUE(ptr_2 <= ptr_2);
}
/// @fn wary_ptr<T>::operator>=(const wary_ptr<U>& other) const
/// @test @b Test_wary_ptr_two_ptrs.operator_greater_eq <br>
/// Tests operator>=() comparing:
/// * Two different pointers.
/// * The same pointer with itself.
TEST_F(Test_wary_ptr_two_ptrs, operator_greater_eq)
{
EXPECT_FALSE(ptr_1 >= ptr_2);
EXPECT_TRUE(ptr_2 >= ptr_1);
EXPECT_TRUE(ptr_1 >= ptr_1);
EXPECT_TRUE(ptr_2 >= ptr_2);
}
/// @fn dst::wary_ptr::operator+()
/// @test @b Test_wary_ptr_two_ptrs.operator_plus <br>
/// Uses operator+() to shift pointer.
TEST_F(Test_wary_ptr_two_ptrs, operator_plus)
{
auto ptr = ptr_1 + 2;
EXPECT_EQ(ptr_2, ptr);
}
/// @fn dst::wary_ptr::operator-(std::ptrdiff_t) const
/// @test @b Test_wary_ptr_two_ptrs.operator_minus <br>
/// Uses operator-() to shift pointer.
TEST_F(Test_wary_ptr_two_ptrs, operator_minus)
{
auto ptr = ptr_2 - 2;
EXPECT_EQ(ptr_1, ptr);
}
/// @fn dst::wary_ptr::operator-(const wary_ptr<T>&) const
/// @test @b Test_wary_ptr_two_ptrs.difference <br>
/// Uses operator-() to calculate difference between pointers.
TEST_F(Test_wary_ptr_two_ptrs, difference)
{
EXPECT_EQ(2, ptr_2 - ptr_1);
EXPECT_EQ(-2, ptr_1 - ptr_2);
}
| 27.841463 | 80 | 0.681997 | bi-ts |
4ca769de97d0bfa30c935718b70d2c02387b0b0f | 6,811 | cpp | C++ | MLPP/LogReg/LogReg.cpp | KangLin/MLPP | abd2dba6076c98aa2e1c29fb3198b74a3f28f8fe | [
"MIT"
] | 927 | 2021-12-03T07:02:25.000Z | 2022-03-30T07:37:23.000Z | MLPP/LogReg/LogReg.cpp | DJofOUC/MLPP | 6940fc1fbcb1bc16fe910c90a32d9e4db52e264f | [
"MIT"
] | 7 | 2022-02-13T22:38:08.000Z | 2022-03-07T01:00:32.000Z | MLPP/LogReg/LogReg.cpp | DJofOUC/MLPP | 6940fc1fbcb1bc16fe910c90a32d9e4db52e264f | [
"MIT"
] | 132 | 2022-01-13T02:19:04.000Z | 2022-03-23T19:23:56.000Z | //
// LogReg.cpp
//
// Created by Marc Melikyan on 10/2/20.
//
#include "LogReg.hpp"
#include "Activation/Activation.hpp"
#include "LinAlg/LinAlg.hpp"
#include "Regularization/Reg.hpp"
#include "Utilities/Utilities.hpp"
#include "Cost/Cost.hpp"
#include <iostream>
#include <random>
namespace MLPP{
LogReg::LogReg(std::vector<std::vector<double>> inputSet, std::vector<double> outputSet, std::string reg, double lambda, double alpha)
: inputSet(inputSet), outputSet(outputSet), n(inputSet.size()), k(inputSet[0].size()), reg(reg), lambda(lambda), alpha(alpha)
{
y_hat.resize(n);
weights = Utilities::weightInitialization(k);
bias = Utilities::biasInitialization();
}
std::vector<double> LogReg::modelSetTest(std::vector<std::vector<double>> X){
return Evaluate(X);
}
double LogReg::modelTest(std::vector<double> x){
return Evaluate(x);
}
void LogReg::gradientDescent(double learning_rate, int max_epoch, bool UI){
LinAlg alg;
Reg regularization;
double cost_prev = 0;
int epoch = 1;
forwardPass();
while(true){
cost_prev = Cost(y_hat, outputSet);
std::vector<double> error = alg.subtraction(y_hat, outputSet);
// Calculating the weight gradients
weights = alg.subtraction(weights, alg.scalarMultiply(learning_rate/n, alg.mat_vec_mult(alg.transpose(inputSet), error)));
weights = regularization.regWeights(weights, lambda, alpha, reg);
// Calculating the bias gradients
bias -= learning_rate * alg.sum_elements(error) / n;
forwardPass();
if(UI) {
Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputSet));
Utilities::UI(weights, bias);
}
epoch++;
if(epoch > max_epoch) { break; }
}
}
void LogReg::MLE(double learning_rate, int max_epoch, bool UI){
LinAlg alg;
Reg regularization;
double cost_prev = 0;
int epoch = 1;
forwardPass();
while(true){
cost_prev = Cost(y_hat, outputSet);
std::vector<double> error = alg.subtraction(outputSet, y_hat);
// Calculating the weight gradients
weights = alg.addition(weights, alg.scalarMultiply(learning_rate/n, alg.mat_vec_mult(alg.transpose(inputSet), error)));
weights = regularization.regWeights(weights, lambda, alpha, reg);
// Calculating the bias gradients
bias += learning_rate * alg.sum_elements(error) / n;
forwardPass();
if(UI) {
Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputSet));
Utilities::UI(weights, bias);
}
epoch++;
if(epoch > max_epoch) { break; }
}
}
void LogReg::SGD(double learning_rate, int max_epoch, bool UI){
LinAlg alg;
Reg regularization;
double cost_prev = 0;
int epoch = 1;
while(true){
std::random_device rd;
std::default_random_engine generator(rd());
std::uniform_int_distribution<int> distribution(0, int(n - 1));
int outputIndex = distribution(generator);
double y_hat = Evaluate(inputSet[outputIndex]);
cost_prev = Cost({y_hat}, {outputSet[outputIndex]});
double error = y_hat - outputSet[outputIndex];
// Weight updation
weights = alg.subtraction(weights, alg.scalarMultiply(learning_rate * error, inputSet[outputIndex]));
weights = regularization.regWeights(weights, lambda, alpha, reg);
// Bias updation
bias -= learning_rate * error;
y_hat = Evaluate({inputSet[outputIndex]});
if(UI) {
Utilities::CostInfo(epoch, cost_prev, Cost({y_hat}, {outputSet[outputIndex]}));
Utilities::UI(weights, bias);
}
epoch++;
if(epoch > max_epoch) { break; }
}
forwardPass();
}
void LogReg::MBGD(double learning_rate, int max_epoch, int mini_batch_size, bool UI){
LinAlg alg;
Reg regularization;
double cost_prev = 0;
int epoch = 1;
// Creating the mini-batches
int n_mini_batch = n/mini_batch_size;
auto [inputMiniBatches, outputMiniBatches] = Utilities::createMiniBatches(inputSet, outputSet, n_mini_batch);
while(true){
for(int i = 0; i < n_mini_batch; i++){
std::vector<double> y_hat = Evaluate(inputMiniBatches[i]);
cost_prev = Cost(y_hat, outputMiniBatches[i]);
std::vector<double> error = alg.subtraction(y_hat, outputMiniBatches[i]);
// Calculating the weight gradients
weights = alg.subtraction(weights, alg.scalarMultiply(learning_rate/outputMiniBatches[i].size(), alg.mat_vec_mult(alg.transpose(inputMiniBatches[i]), error)));
weights = regularization.regWeights(weights, lambda, alpha, reg);
// Calculating the bias gradients
bias -= learning_rate * alg.sum_elements(error) / outputMiniBatches[i].size();
y_hat = Evaluate(inputMiniBatches[i]);
if(UI) {
Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputMiniBatches[i]));
Utilities::UI(weights, bias);
}
}
epoch++;
if(epoch > max_epoch) { break; }
}
forwardPass();
}
double LogReg::score(){
Utilities util;
return util.performance(y_hat, outputSet);
}
void LogReg::save(std::string fileName){
Utilities util;
util.saveParameters(fileName, weights, bias);
}
double LogReg::Cost(std::vector <double> y_hat, std::vector<double> y){
Reg regularization;
class Cost cost;
return cost.LogLoss(y_hat, y) + regularization.regTerm(weights, lambda, alpha, reg);
}
std::vector<double> LogReg::Evaluate(std::vector<std::vector<double>> X){
LinAlg alg;
Activation avn;
return avn.sigmoid(alg.scalarAdd(bias, alg.mat_vec_mult(X, weights)));
}
double LogReg::Evaluate(std::vector<double> x){
LinAlg alg;
Activation avn;
return avn.sigmoid(alg.dot(weights, x) + bias);
}
// sigmoid ( wTx + b )
void LogReg::forwardPass(){
y_hat = Evaluate(inputSet);
}
} | 34.055 | 175 | 0.569079 | KangLin |
4cac90491b78898f9afbb382b33aa3d32d6aae04 | 183 | cpp | C++ | 146/Square.cpp | shuowangphd/cpp400 | 6d764f4bf461c91d100a141875f39b8f56ec7c02 | [
"MIT"
] | null | null | null | 146/Square.cpp | shuowangphd/cpp400 | 6d764f4bf461c91d100a141875f39b8f56ec7c02 | [
"MIT"
] | null | null | null | 146/Square.cpp | shuowangphd/cpp400 | 6d764f4bf461c91d100a141875f39b8f56ec7c02 | [
"MIT"
] | null | null | null | #include "Square.h"
#include "Shape.h"
namespace ns{
Square::Square(double len) : Shape(len) {
}
double Square::getArea() const{
return getLen()*getLen();
}
} | 18.3 | 45 | 0.595628 | shuowangphd |
4cb197419c055cd421e7e84f866b09d3f0165c39 | 1,144 | cpp | C++ | data/test/cpp/4cb197419c055cd421e7e84f866b09d3f0165c39RepoPath.cpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/test/cpp/4cb197419c055cd421e7e84f866b09d3f0165c39RepoPath.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/test/cpp/4cb197419c055cd421e7e84f866b09d3f0165c39RepoPath.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | #include "stdafx.h"
namespace filerepo
{
RepoPath::RepoPath( const tstring &path )
: repo_dir_(path)
{
}
RepoPath::RepoPath( const RepoPath &rp )
{
*this = rp;
}
RepoPath::RepoPath()
{
}
tstring RepoPath::GetIndexFilePath()
{
return AppendPath(repo_dir_, _T("index"));
}
tstring RepoPath::GetTagsDirPath()
{
return AppendPath(repo_dir_, _T("tags\\"));
}
tstring RepoPath::GetVersionFilePath()
{
return AppendPath(repo_dir_, _T("version"));
}
tstring RepoPath::GetManifestFilePath()
{
return AppendPath(repo_dir_, _T("manifest"));
}
tstring RepoPath::GetTaggedIndexFilePath( int n )
{
char buf[8] = {0};
_itoa_s(n, buf, 10);
std::string index = "index_";
index += buf;
tstring windex = utf8_to_16(index.c_str());
return AppendPath(GetTagsDirPath(), windex);
}
RepoPath &RepoPath::operator=( const tstring &path )
{
repo_dir_ = path;
return *this;
}
RepoPath &RepoPath::operator=( const RepoPath &rp )
{
repo_dir_ = rp.repo_dir_;
return *this;
}
tstring RepoPath::Data() const
{
return repo_dir_;
}
RepoPath::operator tstring() const
{
return repo_dir_;
}
}
| 15.253333 | 52 | 0.666084 | harshp8l |
4cb1f38dc799ca637054f1aa5cfec434cfa9a1ba | 3,013 | cpp | C++ | velox/dwio/dwrf/common/Common.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | 672 | 2021-09-22T16:45:58.000Z | 2022-03-31T13:42:31.000Z | velox/dwio/dwrf/common/Common.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | 986 | 2021-09-22T17:02:52.000Z | 2022-03-31T23:57:25.000Z | velox/dwio/dwrf/common/Common.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | 178 | 2021-09-22T17:27:47.000Z | 2022-03-31T03:18:37.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 "velox/dwio/dwrf/common/Common.h"
#include <folly/Conv.h>
namespace facebook::velox::dwrf {
std::string compressionKindToString(CompressionKind kind) {
switch (static_cast<int32_t>(kind)) {
case CompressionKind_NONE:
return "none";
case CompressionKind_ZLIB:
return "zlib";
case CompressionKind_SNAPPY:
return "snappy";
case CompressionKind_LZO:
return "lzo";
case CompressionKind_ZSTD:
return "zstd";
case CompressionKind_LZ4:
return "lz4";
}
return folly::to<std::string>("unknown - ", kind);
}
std::string writerVersionToString(WriterVersion version) {
switch (static_cast<int32_t>(version)) {
case ORIGINAL:
return "original";
case DWRF_4_9:
return "dwrf-4.9";
case DWRF_5_0:
return "dwrf-5.0";
case DWRF_6_0:
return "dwrf-6.0";
case DWRF_7_0:
return "dwrf-7.0";
}
return folly::to<std::string>("future - ", version);
}
std::string streamKindToString(StreamKind kind) {
switch (static_cast<int32_t>(kind)) {
case StreamKind_PRESENT:
return "present";
case StreamKind_DATA:
return "data";
case StreamKind_LENGTH:
return "length";
case StreamKind_DICTIONARY_DATA:
return "dictionary";
case StreamKind_DICTIONARY_COUNT:
return "dictionary count";
case StreamKind_NANO_DATA:
return "nano data";
case StreamKind_ROW_INDEX:
return "index";
case StreamKind_IN_DICTIONARY:
return "in dictionary";
case StreamKind_STRIDE_DICTIONARY:
return "stride dictionary";
case StreamKind_STRIDE_DICTIONARY_LENGTH:
return "stride dictionary length";
case StreamKind_BLOOM_FILTER_UTF8:
return "bloom";
}
return folly::to<std::string>("unknown - ", kind);
}
std::string columnEncodingKindToString(ColumnEncodingKind kind) {
switch (static_cast<int32_t>(kind)) {
case ColumnEncodingKind_DIRECT:
return "direct";
case ColumnEncodingKind_DICTIONARY:
return "dictionary";
case ColumnEncodingKind_DIRECT_V2:
return "direct rle2";
case ColumnEncodingKind_DICTIONARY_V2:
return "dictionary rle2";
}
return folly::to<std::string>("unknown - ", kind);
}
StreamIdentifier EncodingKey::forKind(const proto::Stream_Kind kind) const {
return StreamIdentifier(node, sequence, 0, kind);
}
} // namespace facebook::velox::dwrf
| 28.971154 | 76 | 0.698307 | vancexu |
4cb6b6bf6ec32e29ff5e6f6a96db16f3be0a3cf4 | 3,614 | cc | C++ | archetype/Serialization.cc | gitosaurus/archetype | 849cd50e653adab6e5ca6f23d5350217a8a4d025 | [
"MIT"
] | 6 | 2015-05-04T17:18:54.000Z | 2021-01-24T16:23:56.000Z | archetype/Serialization.cc | gitosaurus/archetype | 849cd50e653adab6e5ca6f23d5350217a8a4d025 | [
"MIT"
] | null | null | null | archetype/Serialization.cc | gitosaurus/archetype | 849cd50e653adab6e5ca6f23d5350217a8a4d025 | [
"MIT"
] | null | null | null | //
// Serialization.cpp
// archetype
//
// Created by Derek Jones on 6/15/14.
// Copyright (c) 2014 Derek Jones. All rights reserved.
//
// For Windows
#define _SCL_SECURE_NO_WARNINGS
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include "Serialization.hh"
using namespace std;
namespace archetype {
const Storage::Byte SignBit = 0x01;
const Storage::Byte MoreBit = 0x80;
const Storage::Byte PayloadBits = 0x7F;
const Storage::Byte FirstBytePayloadBits = 0x3F;
int Storage::readInteger() {
int bytes_left = remaining();
if (not bytes_left) {
throw invalid_argument("No more bytes remaining; cannot read an integer");
}
Byte byte;
read(&byte, sizeof(byte));
bool more = static_cast<bool>(byte & MoreBit);
byte &= ~MoreBit;
// The sign bit is the very first bit deserialized.
// Note it for this number and shift it off.
bool negative = (byte & SignBit);
byte >>= 1;
int bits = 6;
int result = byte;
while (more) {
if (not read(&byte, sizeof(byte))) {
throw invalid_argument("End of storage in the middle of a continued integer");
}
int next_part = (byte & PayloadBits);
next_part <<= bits;
result |= next_part;
more = static_cast<bool>(byte & MoreBit);
bits += 7;
}
return negative ? -result : result;
}
void Storage::writeInteger(int value) {
bool negative = value < 0;
if (negative) {
value = -value;
}
int bits = 6;
Byte byte = (value & FirstBytePayloadBits);
byte <<= 1;
if (negative) {
byte |= SignBit;
} else {
byte &= ~SignBit;
}
do {
value >>= bits;
if (value) {
byte |= MoreBit;
}
write(&byte, sizeof(byte));
bits = 7;
byte = (value & PayloadBits);
} while (value);
}
Storage& operator<<(Storage& out, int value) {
out.writeInteger(value);
return out;
}
Storage& operator>>(Storage& in, int& value) {
value = in.readInteger();
return in;
}
Storage& operator<<(Storage& out, std::string value) {
int size = static_cast<int>(value.size());
out << size;
out.write(reinterpret_cast<const Storage::Byte*>(value.data()), size);
return out;
}
Storage& operator>>(Storage& in, std::string& value) {
int size;
in >> size;
value.resize(size);
int bytes_read = in.read(reinterpret_cast<Storage::Byte*>(&value[0]), size);
if (bytes_read != size) {
ostringstream out;
out << "Could not fully read string declared as " << size << " bytes; "
<< "only read " << bytes_read;
throw invalid_argument(out.str());
}
return in;
}
MemoryStorage::MemoryStorage():
seekIndex_{0}
{ }
int MemoryStorage::remaining() const {
return int(bytes_.size() - seekIndex_);
}
int MemoryStorage::read(Byte *buf, int nbytes) {
int bytes_read = min(nbytes, remaining());
auto cursor = bytes_.begin() + seekIndex_;
copy(cursor, cursor + bytes_read, buf);
seekIndex_ += bytes_read;
return bytes_read;
}
void MemoryStorage::write(const Byte *buf, int nbytes) {
copy(buf, buf + nbytes, back_inserter(bytes_));
}
}
| 27.587786 | 94 | 0.546486 | gitosaurus |
4cb9f755ecff148bd0501ffe24efe666f03d10c5 | 1,213 | hpp | C++ | graph/chromatic-number.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 69 | 2020-11-06T05:21:42.000Z | 2022-03-29T03:38:35.000Z | graph/chromatic-number.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 21 | 2020-07-25T04:47:12.000Z | 2022-02-01T14:39:29.000Z | graph/chromatic-number.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 9 | 2020-11-06T11:55:10.000Z | 2022-03-20T04:45:31.000Z | #pragma once
#include <cstdint>
#include <utility>
#include <vector>
using namespace std;
namespace ChromaticNumberImpl {
using i64 = int64_t;
template <uint32_t mod>
int calc(int n, vector<pair<int, int>> hist) {
for (int c = 1; c <= n; c++) {
i64 sm = 0;
for (auto& [i, x] : hist) sm += (x = i64(x) * i % mod);
if (sm % mod != 0) return c;
}
return n;
}
} // namespace ChromaticNumberImpl
template <typename G>
__attribute__((target("avx2"))) int ChromaticNumber(G& g) {
int n = g.size();
vector<int> adj(n), dp(1 << n);
for (int i = 0; i < n; i++)
for (auto& j : g[i]) adj[i] |= 1 << j, adj[j] |= 1 << i;
dp[0] = 1;
for (int i = 1; i < (1 << n); i++) {
int j = __builtin_ctz(i);
int k = i & (i - 1);
dp[i] = dp[k] + dp[k & ~adj[j]];
}
vector<int> memo((1 << n) + 1);
for (int i = 0; i < (1 << n); i++)
memo[dp[i]] += __builtin_parity(i) ? -1 : 1;
vector<pair<int, int>> hist;
for (int i = 1; i <= (1 << n); i++)
if (memo[i]) hist.emplace_back(i, memo[i]);
return min(ChromaticNumberImpl::calc<1000000021>(n, hist),
ChromaticNumberImpl::calc<1000000033>(n, hist));
}
/**
* @brief 彩色数
* @docs docs/graph/chromatic-number.md
*/
| 25.808511 | 61 | 0.546579 | NachiaVivias |
4cbb2b3efc81a9b50ba7e07e5013cbd99199e4da | 4,983 | cpp | C++ | TestTravelingSalesman.cpp | sormo/geneticAlgorithm | c69eafa757bfead611663afb6403394e65cbb616 | [
"MIT"
] | null | null | null | TestTravelingSalesman.cpp | sormo/geneticAlgorithm | c69eafa757bfead611663afb6403394e65cbb616 | [
"MIT"
] | null | null | null | TestTravelingSalesman.cpp | sormo/geneticAlgorithm | c69eafa757bfead611663afb6403394e65cbb616 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <cmath>
#include <map>
#include <chrono>
#include "json.hpp"
#include "BinaryGASolver.h"
#include "Common.h"
using json = nlohmann::json;
#define POPULATION_SIZE 300
#define MUTATION_PROBABILITY 0.01
#define CROSSOVER_FACTOR 0.75
#define MAX_NUMBER_OF_GENERATIONS 15000
using DistancesMap = std::map<std::pair<size_t, size_t>, double>;
double ComputeDistance(const std::vector<uint8_t> & chromosome, const DistancesMap & distances)
{
double totalDistance = 0.0;
for (size_t i = 1; i < chromosome.size(); ++i)
totalDistance += distances.at({ chromosome[i - 1], chromosome[i] });
totalDistance += distances.at({ chromosome.back(), chromosome[0] });
return totalDistance;
}
struct EvaluateTravelingSalesman
{
BinaryGA::EvaluationResult operator()(uint32_t generation, const std::vector<uint8_t> & chromosome)
{
if (generation != currentGeneration)
{
std::cout << "\rGeneration " << std::fixed << generation;
std::cout << " current minimum: " << std::fixed << std::setprecision(2) << currentDistance;
std::cout << " optimal minimum: " << std::fixed << std::setprecision(2) << optimalDistance;
//currentDistance = std::numeric_limits<double>::max();
currentGeneration = generation;
}
double distance = ComputeDistance(chromosome, distances);
if (distance < currentDistance)
{
currentDistance = distance;
currentSolution = chromosome;
}
return fabs(currentDistance - optimalDistance) < 0.1 ?
BinaryGA::EvaluationResult::ObjectiveReached : BinaryGA::EvaluationResult::ContinueProcessing;
}
std::map<std::pair<size_t, size_t>, double> & distances;
double optimalDistance;
uint32_t currentGeneration = 0;
double currentDistance = std::numeric_limits<double>::max();
std::vector<uint8_t> currentSolution;
};
std::string ConvertSolutionToString(const std::vector<uint8_t> & solution, const DistancesMap & distances)
{
std::stringstream str;
for (size_t i = 0; i < solution.size(); ++i)
str << (size_t)solution[i] << " -> ";
str << (size_t)solution[0];
str << " = " << std::fixed << std::setprecision(3) << ComputeDistance(solution, distances);
return str.str();
}
void TestTravelingSalesman()
{
std::cout << "Traveling salesman" << std::endl;
std::ifstream file("data\\travelingSalesman.json");
json jsonProblems;
file >> jsonProblems;
BinaryGA::Definition<uint8_t> definition;
definition.parentSelection = BinaryGA::ParentSelectionType::Ranked;
definition.mutation = BinaryGA::MutationType::Swap;
definition.crossover = BinaryGA::CrossoverType::Ordered;
definition.populationSize = POPULATION_SIZE;
definition.mutationProbability = MUTATION_PROBABILITY;
definition.crossoverFactor = CROSSOVER_FACTOR;
definition.maxNumberOfGenerations = MAX_NUMBER_OF_GENERATIONS;
for (size_t i = 0; i < jsonProblems["problems"].size(); ++i)
{
std::cout << "Problem: " << i << std::endl;
std::cout << "Generation 0";
// read problem
double optimalDistance = jsonProblems["problems"][i]["optimal"];
std::vector<Common::Point> points;
for (auto point : jsonProblems["problems"][i]["points"])
points.push_back({ point["x"], point["y"] });
// precompute distances
std::map<std::pair<size_t, size_t>, double> distances;
for (size_t i = 0; i < points.size(); ++i)
{
for (size_t j = i + 1; j < points.size(); ++j)
{
double distance = Common::Distance(points[i], points[j]);
distances[{i, j}] = distance;
distances[{j, i}] = distance;
}
}
// prepare seed
std::vector<uint8_t> seed;
for (uint8_t i = 0; i < points.size(); ++i)
seed.push_back(i);
definition.initializationCustomCallback = [&seed](size_t) -> std::vector<uint8_t>
{
std::random_shuffle(std::begin(seed), std::end(seed));
return seed;
};
definition.numberOfGenes = seed.size();
// solve
definition.computeFitness = [&distances](const std::vector<uint8_t> & chromosome) -> double
{
return 1.0 / ComputeDistance(chromosome, distances);
};
EvaluateTravelingSalesman evaluate{ distances, optimalDistance };
definition.evaluate = std::ref(evaluate);
auto startTime = std::chrono::high_resolution_clock::now();
auto solution = BinaryGA::Solve(definition);
std::chrono::duration<double, std::milli> solveDuration = std::chrono::high_resolution_clock::now() - startTime;
std::cout << std::endl << "Generation " << evaluate.currentGeneration << " (" << solveDuration.count() << "ms)" << std::endl;
if (!solution.empty())
{
std::cout << "Optimal solution found: " << std::endl;
std::cout << ConvertSolutionToString(solution, distances) << std::endl;
}
else
{
std::cout << "Best found solution: " << std::endl;
std::cout << ConvertSolutionToString(evaluate.currentSolution, distances) << " ";
std::cout << std::fixed << std::setprecision(2);
std::cout << (optimalDistance / (double)ComputeDistance(evaluate.currentSolution, distances)) * 100.0 << "%" << std::endl;
}
}
std::cout << std::endl;
}
| 32.357143 | 127 | 0.693157 | sormo |
4cbc6a6435fb02e95017c88dcce968fd9614a896 | 731 | cpp | C++ | 配套代码/L059/REV_059/REV_059.cpp | zmrbak/ReverseAnalysis | 994fdc61c8af2eecc2a065a6f5ee0aacf371e836 | [
"MIT"
] | 35 | 2019-11-19T03:12:09.000Z | 2022-02-18T08:38:53.000Z | 配套代码/L059/REV_059/REV_059.cpp | zmrbak/ReverseAnalysis | 994fdc61c8af2eecc2a065a6f5ee0aacf371e836 | [
"MIT"
] | null | null | null | 配套代码/L059/REV_059/REV_059.cpp | zmrbak/ReverseAnalysis | 994fdc61c8af2eecc2a065a6f5ee0aacf371e836 | [
"MIT"
] | 22 | 2019-08-03T17:07:17.000Z | 2022-02-18T08:38:55.000Z | // REV_059.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
uint64_t f()
{
return 0x1234567890ABCDEF;
}
uint64_t f_add(uint64_t a, uint64_t b)
{
return a + b;
}
uint64_t f_sub(uint64_t a, uint64_t b)
{
return a - b;
}
uint64_t f_multi(uint64_t a, uint64_t b)
{
return a * b;
}
uint64_t f_div(uint64_t a, uint64_t b)
{
return a / b;
}
uint64_t f_left(uint64_t a, uint64_t b)
{
return a << b;
}
uint64_t f_right(uint64_t a, uint64_t b)
{
return a >> b;
}
int main()
{
printf("Hello World!\n");
uint64_t a = f();
printf("%lld\n",a);
printf("%I64d\n", a);
printf("Hello World 1!\n");
a = f_add(0x11111111FFFFFFFF,0x22222222EEEEEEEE);
printf("%lld\n", a);
}
| 14.057692 | 53 | 0.614227 | zmrbak |
4cc093252fc67a14c5155b461029119f5beb30c9 | 1,386 | cpp | C++ | engine/src/Util/Logger.cpp | kyle-piddington/MoonEngine | 243cce7988ee089d0fc51d817e2736501e019702 | [
"MIT",
"BSD-3-Clause"
] | 5 | 2017-01-20T00:23:23.000Z | 2018-07-17T07:48:04.000Z | engine/src/Util/Logger.cpp | kyle-piddington/MoonEngine | 243cce7988ee089d0fc51d817e2736501e019702 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | engine/src/Util/Logger.cpp | kyle-piddington/MoonEngine | 243cce7988ee089d0fc51d817e2736501e019702 | [
"MIT",
"BSD-3-Clause"
] | 2 | 2017-01-24T05:09:37.000Z | 2021-02-18T14:42:00.000Z | #include "Logger.h"
#include <iostream>
#include <string>
using namespace MoonEngine;
std::ostream * Logger::_logStream;
LogLevel Logger::_logLevel = ERROR;
void Logger::ProvideErrorStream(std::ostream * str)
{
_logStream = str;
}
void Logger::SetLogLevel(LogLevel level)
{
_logLevel = level;
}
void Logger::Log(LogLevel lv, std::string log, std::string file, int line)
{
if (lv <= _logLevel)
{
std::ostream * stream = &std::cerr;
if (_logStream != nullptr)
{
stream = _logStream;
}
switch (lv)
{
case FATAL_ERROR:
(*stream) << "[!FATAL ERROR!]: ";
break;
case ERROR:
(*stream) << "[ERROR]: ";
break;
case WARN:
(*stream) << "[WARN]: ";
break;
case GAME:
(*stream) << "[GAME]: ";
break;
case INFO:
(*stream) << "[INFO]: ";
break;
default:
(*stream) << "[Log]: ";
break;
}
if (file != "") {
file = file.substr(file.find_last_of("\\/") + 1, file.length());
file = " @" + file;
}
if(line == -1)
(*stream) << log << file << std::endl;
else
(*stream) << log << file << "[" << line << "]" << std::endl;
}
} | 22.721311 | 74 | 0.445166 | kyle-piddington |
4cc1853c9c123c7dac466c8c05cb8c9a68f42780 | 318 | hpp | C++ | include/vm/vm.hpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 14 | 2020-04-14T17:00:56.000Z | 2021-08-30T08:29:26.000Z | include/vm/vm.hpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 27 | 2020-12-27T16:00:44.000Z | 2021-08-01T13:12:14.000Z | include/vm/vm.hpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 1 | 2020-05-29T18:33:37.000Z | 2020-05-29T18:33:37.000Z | #pragma once
#include "novasm/executable.hpp"
#include "vm/exec_state.hpp"
#include "vm/platform_interface.hpp"
namespace vm {
// Execute the given program. Will block until the execution is complete.
auto run(const novasm::Executable* executable, PlatformInterface* iface) noexcept -> ExecState;
} // namespace vm
| 26.5 | 95 | 0.77044 | BastianBlokland |
4cc1c75ffb236182b3e61f008634bd0a329b9242 | 14,737 | cpp | C++ | src/textures.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | 3 | 2019-12-07T23:57:47.000Z | 2019-12-31T19:46:41.000Z | src/textures.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | null | null | null | src/textures.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | null | null | null | #include "textures.h"
#include "control.h"
#include "render.h"
#include "zone.h"
#include "lodepng.h"
#include "flog.h"
#include <math.h>
/* {
GVAR: logical_device -> startup.cpp
GVAR: max2DTex_size -> startup.cpp
GVAR: descriptor_pool -> control.cpp
GVAR: command_buffer -> control.cpp
GVAR: staging_buffers - > control.cpp
GVAR: current_staging_buffer -> control.cpp
GVAR: tex_dsl -> control.cpp
GVAR: number_of_swapchain_images -> swapchain.cpp
} */
VkDescriptorSet tex_descriptor_sets[20];
static VkImage v_image[20];
static int current_tex_ds_index = 0;
static unsigned char palette[768];
static unsigned int data[256];
static VkSampler point_sampler = VK_NULL_HANDLE;
namespace textures
{
static unsigned* TexMgr8to32(unsigned char *in, int pixels, unsigned int *usepal)
{
int i;
unsigned *out, *data;
out = data = (unsigned *) zone::Hunk_Alloc(pixels*4);
for (i = 0; i < pixels; i++)
*out++ = usepal[*in++];
return data;
}
unsigned char* Tex8to32(unsigned char* image, int l)
{
unsigned int *usepal = data;
image = (unsigned char*)TexMgr8to32(image, l, usepal);
return image;
}
void InitSamplers()
{
trace("Initializing samplers");
VkResult err;
if (point_sampler == VK_NULL_HANDLE)
{
VkSamplerCreateInfo sampler_create_info;
memset(&sampler_create_info, 0, sizeof(sampler_create_info));
sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
sampler_create_info.magFilter = VK_FILTER_NEAREST;
sampler_create_info.minFilter = VK_FILTER_NEAREST;
sampler_create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
sampler_create_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_create_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_create_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_create_info.mipLodBias = 0.0f;
sampler_create_info.maxAnisotropy = 1.0f;
sampler_create_info.minLod = 0;
sampler_create_info.maxLod = 0.25f;
err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &point_sampler);
if (err != VK_SUCCESS)
fatal("vkCreateSampler failed");
/* sampler_create_info.anisotropyEnable = VK_TRUE;
sampler_create_info.maxAnisotropy = logical_device_properties.limits.maxSamplerAnisotropy;
err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &vulkan_globals.point_aniso_sampler);
if (err != VK_SUCCESS)
printf("vkCreateSampler failed");
GL_SetObjectName((uint64_t)vulkan_globals.point_aniso_sampler, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT, "point_aniso");
sampler_create_info.magFilter = VK_FILTER_LINEAR;
sampler_create_info.minFilter = VK_FILTER_LINEAR;
sampler_create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
sampler_create_info.anisotropyEnable = VK_FALSE;
sampler_create_info.maxAnisotropy = 1.0f;
err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &vulkan_globals.linear_sampler);
if (err != VK_SUCCESS)
printf("vkCreateSampler failed");
sampler_create_info.anisotropyEnable = VK_TRUE;
sampler_create_info.maxAnisotropy = logical_device_properties.limits.maxSamplerAnisotropy;
err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &vulkan_globals.linear_aniso_sampler);
if (err != VK_SUCCESS)
printf("vkCreateSampler failed"); */
}
}
void TexDeinit()
{
vkDestroySampler(logical_device, point_sampler, nullptr);
for(int i = 0; i<current_tex_ds_index; i++)
{
vkDestroyImage(logical_device, v_image[i], nullptr);
//vkDestroyImageView(logical_device, imageViews[number_of_swapchain_images+i+1], nullptr);
}
}
void SetFilterModes(int tex_index, VkImageView *imgView)
{
VkDescriptorImageInfo image_info;
memset(&image_info, 0, sizeof(image_info));
image_info.imageView = *imgView;
image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_info.sampler = point_sampler;
VkWriteDescriptorSet texture_write;
memset(&texture_write, 0, sizeof(texture_write));
texture_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
texture_write.dstSet = tex_descriptor_sets[tex_index];
texture_write.dstBinding = 0;
texture_write.dstArrayElement = 0;
texture_write.descriptorCount = 1;
texture_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
texture_write.pImageInfo = &image_info;
vkUpdateDescriptorSets(logical_device, 1, &texture_write, 0, nullptr);
}
void GenerateColorPalette()
{
unsigned char* dst = palette;
for(int i = 0; i < 256; i++)
{
unsigned char r = 127 * (1 + sin(5 * i * 6.28318531 / 16));
unsigned char g = 127 * (1 + sin(2 * i * 6.28318531 / 16));
unsigned char b = 127 * (1 + sin(3 * i * 6.28318531 / 16));
// unsigned char a = 63 * (1 + std::sin(8 * i * 6.28318531 / 16)) + 128; /*alpha channel of the palette (tRNS chunk)*/
*dst++ = r;
*dst++ = g;
*dst++ = b;
//*dst++ = a;
}
dst = (unsigned char*)data;
unsigned char* src = palette;
for (int i = 0; i < 256; i++)
{
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = 255;
}
}
void UpdateTexture(unsigned char* image, int w, int h, int index)
{
//SetFilterModes(index, &imageViews[imageViewCount-1]);
unsigned char* staging_memory = control::StagingBufferDigress((w*h*4), 4);
zone::Q_memcpy(staging_memory, image, (w * h * 4));
VkBufferImageCopy regions = {};
regions.bufferOffset = staging_buffers[current_staging_buffer].current_offset;
regions.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
regions.imageSubresource.layerCount = 1;
regions.imageSubresource.mipLevel = 0;
regions.imageOffset = {0, 0, 0};
regions.imageExtent.width = w;
regions.imageExtent.height = h;
regions.imageExtent.depth = 1;
control::SetCommandBuffer(current_staging_buffer);
VkImageMemoryBarrier image_memory_barrier;
memset(&image_memory_barrier, 0, sizeof(image_memory_barrier));
image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
image_memory_barrier.image = v_image[index];
image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
image_memory_barrier.subresourceRange.baseMipLevel = 0;
image_memory_barrier.subresourceRange.levelCount = 1;
image_memory_barrier.subresourceRange.baseArrayLayer = 0;
image_memory_barrier.subresourceRange.layerCount = 1;
image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
image_memory_barrier.srcAccessMask = 0;
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
vkCmdCopyBufferToImage(command_buffer, staging_buffers[current_staging_buffer].buffer, v_image[index], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ions);
image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
control::SetCommandBuffer(0);
control::SubmitStagingBuffer();
}
void UploadTexture(unsigned char* image, int w, int h, VkFormat format)
{
VkDescriptorSetAllocateInfo dsai;
memset(&dsai, 0, sizeof(dsai));
dsai.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
dsai.descriptorPool = descriptor_pool;
dsai.descriptorSetCount = 1;
dsai.pSetLayouts = &tex_dsl;
vkAllocateDescriptorSets(logical_device, &dsai, &tex_descriptor_sets[current_tex_ds_index]);
v_image[current_tex_ds_index] = render::Create2DImage(format, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, w, h);
VkMemoryRequirements memory_requirements;
vkGetImageMemoryRequirements(logical_device, v_image[current_tex_ds_index], &memory_requirements);
int mem_type = control::MemoryTypeFromProperties(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0);
try_again:
;
VkDeviceSize aligned_offset;
vram_heap* heap = control::VramHeapDigress(memory_requirements.size, memory_requirements.alignment, &aligned_offset);
if(!heap)
{
if(current_tex_ds_index > 0)
{
//1st allocation - OK. Do not warn.
warn("Failed to align the memory");
}
control::VramHeapAllocate((VkDeviceSize)1073741824, mem_type);
goto try_again;
}
VK_CHECK(vkBindImageMemory(logical_device, v_image[current_tex_ds_index], heap->memory, aligned_offset));
//render::CreateImageViews(1, &v_image[current_tex_ds_index], VK_FORMAT_R8G8B8A8_UNORM, 0, 1);
VkImageViewCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = format;
createInfo.components.r = VK_COMPONENT_SWIZZLE_R;
createInfo.components.g = VK_COMPONENT_SWIZZLE_G;
createInfo.components.b = VK_COMPONENT_SWIZZLE_B;
createInfo.components.a = VK_COMPONENT_SWIZZLE_A;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.layerCount = 1;
createInfo.image = v_image[current_tex_ds_index];
VK_CHECK(vkCreateImageView(logical_device, &createInfo, 0, &imageViews[imageViewCount++]));
SetFilterModes(current_tex_ds_index, &imageViews[imageViewCount-1]);
// p("%d", current_staging_buffer);
unsigned char* staging_memory = control::StagingBufferDigress((w*h*4), 4);
zone::Q_memcpy(staging_memory, image, (w * h * 4));
VkBufferImageCopy regions = {};
regions.bufferOffset = staging_buffers[current_staging_buffer].current_offset;
regions.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
regions.imageSubresource.layerCount = 1;
regions.imageSubresource.mipLevel = 0;
regions.imageOffset = {0, 0, 0};
regions.imageExtent.width = w;
regions.imageExtent.height = h;
regions.imageExtent.depth = 1;
control::SetCommandBuffer(current_staging_buffer);
VkImageMemoryBarrier image_memory_barrier;
memset(&image_memory_barrier, 0, sizeof(image_memory_barrier));
image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
image_memory_barrier.image = v_image[current_tex_ds_index];
image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
image_memory_barrier.subresourceRange.baseMipLevel = 0;
image_memory_barrier.subresourceRange.levelCount = 1;
image_memory_barrier.subresourceRange.baseArrayLayer = 0;
image_memory_barrier.subresourceRange.layerCount = 1;
image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
image_memory_barrier.srcAccessMask = 0;
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
vkCmdCopyBufferToImage(command_buffer, staging_buffers[current_staging_buffer].buffer, v_image[current_tex_ds_index], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ions);
image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
control::SetCommandBuffer(0);
control::SubmitStagingBuffer();
current_tex_ds_index++;
}
void FsLoadPngTexture(const char* filename)
{
ASSERT(filename, "Null pointer passed into FsLoadPngTexture");
// Load file and decode image.
unsigned char mem[sizeof(std::vector<unsigned char>)];
std::vector<unsigned char>* image = new (mem) std::vector<unsigned char>;
unsigned width, height;
unsigned error = lodepng::decode(*image, width, height, filename);
if(error != 0)
{
fatal("Error %s : %s",error,lodepng_error_text(error));
startup::debug_pause();
}
unsigned int* usepal = data;
unsigned char* img = (unsigned char*)TexMgr8to32(image->data(), (width * height), usepal);
UploadTexture(img, width, height, VK_FORMAT_R8G8B8A8_UNORM);
}
bool SampleTexture()
{
int mark = zone::Hunk_LowMark();
//generate some image
const unsigned w = 511;
const unsigned h = 511;
unsigned char* image = reinterpret_cast<unsigned char*>(zone::Hunk_Alloc(w * h));
for(unsigned y = 0; y < h; y++)
for(unsigned x = 0; x < w; x++)
{
size_t byte_index = (y * w + x);
// printf("%d ", byte_index);
// bool byte_half = (y * w + x) % 2 == 1;
int color = (int)(4 * ((1 + sin(2.0 * 6.28318531 * x / (double)w))
+ (1 + sin(2.0 * 6.28318531 * y / (double)h))) );
image[byte_index] |= (unsigned char)(color << (0));
}
unsigned int *usepal = data;
image = (unsigned char*)TexMgr8to32(image, (w * h), usepal);
UploadTexture(image, w, h, VK_FORMAT_R8G8B8A8_UNORM);
zone::Hunk_FreeToLowMark(mark);
return true;
}
bool SampleTextureUpdate()
{
int mark = zone::Hunk_LowMark();
//generate some image
const unsigned w = 511;
const unsigned h = 511;
unsigned char* image = reinterpret_cast<unsigned char*>(zone::Hunk_Alloc(w * h));
for(unsigned y = 0; y < h; y++)
for(unsigned x = 0; x < w; x++)
{
size_t byte_index = (y * w + x);
// printf("%d ", byte_index);
// bool byte_half = (y * w + x) % 2 == 1;
int color = (int)(4 * ((1 + sin(frametime * 6.28318531 * x / (double)w))
+ (1 + sin(time1 * 6.28318531 * y / (double)h))) );
image[byte_index] |= (unsigned char)(color << (0));
}
unsigned int *usepal = data;
image = (unsigned char*)TexMgr8to32(image, (w * h), usepal);
UpdateTexture(image, w, h, 0);
zone::Hunk_FreeToLowMark(mark);
return true;
}
} //namespace tex
| 37.214646 | 171 | 0.749406 | FAETHER |
4cc2ee85567c9588b00ba02803f9f87bb9e99f8a | 201 | hpp | C++ | src/main.hpp | Dyndrilliac/shell | 7f2e858502cf98d5df190d94dd557f1005e74ca5 | [
"MIT"
] | null | null | null | src/main.hpp | Dyndrilliac/shell | 7f2e858502cf98d5df190d94dd557f1005e74ca5 | [
"MIT"
] | null | null | null | src/main.hpp | Dyndrilliac/shell | 7f2e858502cf98d5df190d94dd557f1005e74ca5 | [
"MIT"
] | null | null | null | /*
Main Header File
Project: Shell-CPP
Author: Matthew Boyette (N00868808)
Date: 9/27/2017
*/
#pragma once
#include "stringSplitter.hpp"
#include "shell.hpp"
using namespace std; | 15.461538 | 40 | 0.671642 | Dyndrilliac |
4cc5ba098e996643ef66ad4eee7ec3c262ac765f | 3,281 | cpp | C++ | source/LibFgWin/FgGuiWinSelect.cpp | maamountki/FaceGenBaseLibrary | 0c647920e913354028ed09fff3293555e84d2b94 | [
"MIT"
] | null | null | null | source/LibFgWin/FgGuiWinSelect.cpp | maamountki/FaceGenBaseLibrary | 0c647920e913354028ed09fff3293555e84d2b94 | [
"MIT"
] | null | null | null | source/LibFgWin/FgGuiWinSelect.cpp | maamountki/FaceGenBaseLibrary | 0c647920e913354028ed09fff3293555e84d2b94 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2015 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
// Authors: Andrew Beatty
// Created: Oct 14, 2011
//
#include "stdafx.h"
#include "FgGuiApiSelect.hpp"
#include "FgGuiWin.hpp"
#include "FgThrowWindows.hpp"
#include "FgBounds.hpp"
#include "FgDefaultVal.hpp"
#include "FgMetaFormat.hpp"
#include "FgAlgs.hpp"
using namespace std;
struct FgGuiWinSelect : public FgGuiOsBase
{
FgGuiApiSelect m_api;
vector<FgPtr<FgGuiOsBase> > m_panes;
size_t m_currPane; // Which one is Windows currently displaying ?
FgVect2I m_lo,m_sz;
FgString m_store;
FgGuiWinSelect(const FgGuiApiSelect & api)
: m_api(api)
{
FGASSERT(api.wins.size() > 0);
m_panes.resize(api.wins.size());
for (size_t ii=0; ii<m_panes.size(); ++ii)
m_panes[ii] = api.wins[ii]->getInstance();
}
virtual void
create(HWND parentHwnd,int,const FgString & store,DWORD extStyle,bool visible)
{
m_store = store;
for (size_t ii=0; ii<m_panes.size(); ++ii)
m_panes[ii]->create(parentHwnd,int(ii),m_store+"_"+fgToStr(ii),extStyle,false);
m_currPane = g_gg.getVal(m_api.selection);
if (visible)
m_panes[m_currPane]->showWindow(true);
}
virtual void
destroy()
{
for (size_t ii=0; ii<m_panes.size(); ++ii)
m_panes[ii]->destroy();
}
virtual FgVect2UI
getMinSize() const
{
FgVect2UI max(0);
for (size_t ii=0; ii<m_panes.size(); ++ii)
max = fgMax(max,m_panes[ii]->getMinSize());
return max;
}
virtual FgVect2B
wantStretch() const
{
FgVect2B ret(false,false);
for (size_t ii=0; ii<m_panes.size(); ++ii)
ret = fgOr(ret,m_panes[ii]->wantStretch());
return ret;
}
virtual void
updateIfChanged()
{
if (g_gg.dg.update(m_api.updateNodeIdx)) {
size_t currPane = g_gg.getVal(m_api.selection);
if (currPane != m_currPane) {
m_panes[m_currPane]->showWindow(false);
m_currPane = currPane;
m_panes[m_currPane]->showWindow(true);
// Only previously current pane was last updated for size, plus the
// MoveWindow call will refresh the screen (ShowWindow doesn't):
m_panes[m_currPane]->moveWindow(m_lo,m_sz);
}
}
m_panes[m_currPane]->updateIfChanged();
}
virtual void
moveWindow(FgVect2I lo,FgVect2I sz)
{
if (sz[0] * sz[1] > 0) {
m_lo = lo;
m_sz = sz;
m_panes[m_currPane]->moveWindow(lo,sz);
}
}
virtual void
showWindow(bool s)
{m_panes[m_currPane]->showWindow(s); }
virtual void
saveState()
{
for (size_t ii=0; ii<m_panes.size(); ++ii)
m_panes[ii]->saveState();
}
};
FgPtr<FgGuiOsBase>
fgGuiGetOsInstance(const FgGuiApiSelect & api)
{return FgPtr<FgGuiOsBase>(new FgGuiWinSelect(api)); }
| 28.042735 | 98 | 0.579092 | maamountki |
4ccd4e11ae9b2217c0e9e3a5eaa295f9239cd36b | 1,862 | cc | C++ | tests/tools/tflite_run/src/tensor_dumper.cc | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | tests/tools/tflite_run/src/tensor_dumper.cc | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | tests/tools/tflite_run/src/tensor_dumper.cc | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tensor_dumper.h"
#include <fstream>
#include <iostream>
#include <cstring>
#include "tensorflow/lite/interpreter.h"
namespace TFLiteRun
{
TensorDumper::TensorDumper()
{
// DO NOTHING
}
void TensorDumper::addTensors(tflite::Interpreter &interpreter, const std::vector<int> &indices)
{
for (const auto &o : indices)
{
const TfLiteTensor *tensor = interpreter.tensor(o);
int size = tensor->bytes;
std::vector<char> buffer;
buffer.resize(size);
memcpy(buffer.data(), tensor->data.raw, size);
_tensors.emplace_back(o, std::move(buffer));
}
}
void TensorDumper::dump(const std::string &filename) const
{
// TODO Handle file open/write error
std::ofstream file(filename, std::ios::out | std::ios::binary);
// Write number of tensors
uint32_t num_tensors = static_cast<uint32_t>(_tensors.size());
file.write(reinterpret_cast<const char *>(&num_tensors), sizeof(num_tensors));
// Write tensor indices
for (const auto &t : _tensors)
{
file.write(reinterpret_cast<const char *>(&t._index), sizeof(int));
}
// Write data
for (const auto &t : _tensors)
{
file.write(t._data.data(), t._data.size());
}
file.close();
}
} // end of namespace TFLiteRun
| 26.225352 | 96 | 0.70247 | periannath |
4cd1c222366e766aa2107c486dcac887e2fb07a1 | 7,660 | cc | C++ | mindspore/lite/test/ut/src/runtime/kernel/opencl/depthwise_conv2d_tests.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | 55 | 2020-12-17T10:26:06.000Z | 2022-03-28T07:18:26.000Z | mindspore/lite/test/ut/src/runtime/kernel/opencl/depthwise_conv2d_tests.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | null | null | null | mindspore/lite/test/ut/src/runtime/kernel/opencl/depthwise_conv2d_tests.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | 14 | 2021-01-29T02:39:47.000Z | 2022-03-23T05:00:26.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ut/src/runtime/kernel/opencl/common.h"
#include "nnacl/conv_parameter.h"
namespace mindspore::lite::opencl::test {
class TestOpenCL_DepthwiseConv2d : public CommonTest {};
namespace {
// PrimitiveType_DepthwiseConv2D: src/ops/populate/depthwise_conv2d_populate.cc
OpParameter *CreateParameter(int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_u, int pad_d, int pad_l,
int pad_r, int dilation_h, int dilation_w, ActType act_type, int input_channel) {
auto *param = test::CreateParameter<ConvParameter>(schema::PrimitiveType_DepthwiseConv2D);
param->kernel_h_ = kernel_h;
param->kernel_w_ = kernel_w;
param->stride_h_ = stride_h;
param->stride_w_ = stride_w;
param->pad_u_ = pad_u;
param->pad_d_ = pad_d;
param->pad_l_ = pad_l;
param->pad_r_ = pad_r;
param->input_channel_ = input_channel;
param->dilation_h_ = dilation_h;
param->dilation_w_ = dilation_w;
param->act_type_ = act_type;
return reinterpret_cast<OpParameter *>(param);
}
} // namespace
TEST_F(TestOpenCL_DepthwiseConv2d, NoPad) {
int kernel_h = 3;
int kernel_w = 3;
int stride_h = 1;
int stride_w = 1;
int pad_u = 0;
int pad_d = 0;
int pad_l = 0;
int pad_r = 0;
int dilation_h = 1;
int dilation_w = 1;
ActType act_type = ActType_No;
std::vector<int> input_shape = {1, 4, 4, 4};
std::vector<int> output_shape = {1, 2, 2, 4};
std::vector<int> weight_shape = {1, kernel_h, kernel_w, output_shape.back()};
std::vector<int> bias_shape = {output_shape.back()};
float input_data[] = {0.5488135, 0.0202184, 0.45615032, 0.31542835, 0.71518934, 0.83261985, 0.56843394, 0.36371076,
0.60276335, 0.77815676, 0.0187898, 0.57019675, 0.5448832, 0.87001216, 0.6176355, 0.43860152,
0.4236548, 0.9786183, 0.6120957, 0.9883738, 0.6458941, 0.7991586, 0.616934, 0.10204481,
0.4375872, 0.46147937, 0.94374806, 0.20887676, 0.891773, 0.7805292, 0.6818203, 0.16130951,
0.96366274, 0.11827443, 0.3595079, 0.6531083, 0.3834415, 0.639921, 0.43703195, 0.2532916,
0.79172504, 0.14335328, 0.6976312, 0.46631077, 0.5288949, 0.9446689, 0.06022547, 0.2444256,
0.56804454, 0.5218483, 0.6667667, 0.15896958, 0.92559665, 0.41466194, 0.67063785, 0.11037514,
0.07103606, 0.2645556, 0.21038257, 0.6563296, 0.0871293, 0.7742337, 0.12892629, 0.13818295};
float bias_data[] = {0, 0, 0, 0};
float weight_data[] = {0.19658236, 0.36872518, 0.82099324, 0.09710128, 0.8379449, 0.09609841, 0.97645944, 0.4686512,
0.9767611, 0.6048455, 0.7392636, 0.03918779, 0.28280696, 0.12019656, 0.2961402, 0.11872772,
0.31798318, 0.41426298, 0.06414749, 0.6924721, 0.56660146, 0.2653895, 0.5232481, 0.09394051,
0.5759465, 0.9292962, 0.31856894, 0.6674104, 0.13179787, 0.7163272, 0.2894061, 0.18319136,
0.5865129, 0.02010755, 0.82894003, 0.00469548};
float output_data[] = {3.3848767, 1.4446403, 1.8428744, 1.3194335, 2.5873442, 2.1384869, 2.04022, 1.1872686,
2.2294958, 1.6570128, 2.465089, 1.4294086, 2.7941442, 1.7871612, 2.188921, 1.0601988};
for (auto fp16_enable : {false, true}) {
auto *param = CreateParameter(kernel_h, kernel_w, stride_h, stride_w, pad_u, pad_d, pad_l, pad_r, dilation_h,
dilation_w, act_type, input_shape.back());
TestMain({{input_shape, input_data, VAR},
{weight_shape, weight_data, CONST_TENSOR},
{bias_shape, bias_data, CONST_TENSOR}},
{output_shape, output_data}, param, fp16_enable, fp16_enable ? 1e-2 : 1e-5);
}
}
TEST_F(TestOpenCL_DepthwiseConv2d, Pad) {
int kernel_h = 3;
int kernel_w = 3;
int stride_h = 1;
int stride_w = 1;
int pad_u = 1;
int pad_d = 1;
int pad_l = 1;
int pad_r = 1;
int dilation_h = 1;
int dilation_w = 1;
ActType act_type = ActType_No;
std::vector<int> input_shape = {1, 3, 3, 5};
std::vector<int> output_shape = {1, 3, 3, 5};
std::vector<int> weight_shape = {1, kernel_h, kernel_w, output_shape.back()};
std::vector<int> bias_shape = {output_shape.back()};
float input_data[] = {0.5488135, 0.3834415, 0.77815676, 0.9446689, 0.6120957, 0.71518934, 0.79172504, 0.87001216,
0.5218483, 0.616934, 0.60276335, 0.5288949, 0.9786183, 0.41466194, 0.94374806, 0.5448832,
0.56804454, 0.7991586, 0.2645556, 0.6818203, 0.4236548, 0.92559665, 0.46147937, 0.7742337,
0.3595079, 0.6458941, 0.07103606, 0.7805292, 0.45615032, 0.43703195, 0.4375872, 0.0871293,
0.11827443, 0.56843394, 0.6976312, 0.891773, 0.0202184, 0.639921, 0.0187898, 0.06022547,
0.96366274, 0.83261985, 0.14335328, 0.6176355, 0.6667667};
float weight_data[] = {0.67063785, 0.21038257, 0.12892629, 0.31542835, 0.36371076, 0.57019675, 0.43860152, 0.9883738,
0.10204481, 0.20887676, 0.16130951, 0.6531083, 0.2532916, 0.46631077, 0.2444256, 0.15896958,
0.11037514, 0.6563296, 0.13818295, 0.19658236, 0.36872518, 0.82099324, 0.09710128, 0.8379449,
0.09609841, 0.97645944, 0.4686512, 0.9767611, 0.6048455, 0.7392636, 0.03918779, 0.28280696,
0.12019656, 0.2961402, 0.11872772, 0.31798318, 0.41426298, 0.06414749, 0.6924721, 0.56660146,
0.2653895, 0.5232481, 0.09394051, 0.5759465, 0.9292962};
float bias_data[] = {0, 0, 0, 0, 0};
float output_data[] = {1.189188, 1.0425153, 1.8012011, 0.6074867, 1.2120346, 1.5005531, 0.8346756, 2.4365785,
0.54975945, 1.6815965, 1.2690231, 0.60214907, 1.6158017, 0.42115876, 0.8854959, 1.1709145,
1.0929465, 1.3534508, 1.1985044, 1.2932993, 2.4621446, 1.7086457, 2.6977584, 2.1960166,
2.3769147, 2.3185873, 0.6133741, 0.9687358, 0.9987654, 1.0254729, 0.8368954, 0.74171704,
0.8749627, 0.8953936, 0.5093431, 1.5496738, 0.54936385, 0.7683113, 1.165742, 1.3682933,
1.0517888, 0.59817517, 0.75649744, 1.2075498, 0.38804203};
for (auto fp16_enable : {false, true}) {
auto *param = CreateParameter(kernel_h, kernel_w, stride_h, stride_w, pad_u, pad_d, pad_l, pad_r, dilation_h,
dilation_w, act_type, input_shape.back());
TestMain({{input_shape, input_data, VAR},
{weight_shape, weight_data, CONST_TENSOR},
{bias_shape, bias_data, CONST_TENSOR}},
{output_shape, output_data}, param, fp16_enable, fp16_enable ? 1e-2 : 1e-5);
}
}
} // namespace mindspore::lite::opencl::test
| 56.323529 | 121 | 0.617493 | taroxd |
4cd2aaef96e5d2b5b7b3ecaf267bdfb15bbbe044 | 372 | hpp | C++ | Source/Maths/Matrices/Matrix3x4.hpp | KingKiller100/kLibrary | 37971acd3c54f9ea0decdf78b13e47c935d4bbf0 | [
"Apache-2.0"
] | null | null | null | Source/Maths/Matrices/Matrix3x4.hpp | KingKiller100/kLibrary | 37971acd3c54f9ea0decdf78b13e47c935d4bbf0 | [
"Apache-2.0"
] | null | null | null | Source/Maths/Matrices/Matrix3x4.hpp | KingKiller100/kLibrary | 37971acd3c54f9ea0decdf78b13e47c935d4bbf0 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Matrix.hpp"
namespace kmaths
{
template<class T>
using Matrix3x4 = Matrix<T, 3, 4>;
using Matrix3x4s = Matrix3x4 < int >; // 3 rows - 4 columns - signed integer
using Matrix3x4f = Matrix3x4 < float >; // 3 rows - 4 columns - floating point
using Matrix3x4d = Matrix3x4 < double >; // 3 rows - 4 columns - double floating point
}
| 26.571429 | 89 | 0.666667 | KingKiller100 |
4cd5c85f1aa53aa82449174f646a9b0428af3cf0 | 795 | cpp | C++ | source/random.cpp | in1tiate/OoT3D_Randomizer | baa1f4a0f4a2e1aadec9547120b29d1617211f45 | [
"MIT"
] | 133 | 2020-08-25T20:27:08.000Z | 2022-03-28T04:38:44.000Z | source/random.cpp | in1tiate/OoT3D_Randomizer | baa1f4a0f4a2e1aadec9547120b29d1617211f45 | [
"MIT"
] | 112 | 2020-11-27T18:51:33.000Z | 2022-03-28T21:58:21.000Z | source/random.cpp | in1tiate/OoT3D_Randomizer | baa1f4a0f4a2e1aadec9547120b29d1617211f45 | [
"MIT"
] | 57 | 2020-08-24T08:54:39.000Z | 2022-03-27T18:08:51.000Z | #include "random.hpp"
#include <random>
static bool init = false;
static std::mt19937_64 generator;
//Initialize with seed specified
void Random_Init(uint32_t seed) {
init = true;
generator = std::mt19937_64{seed};
}
//Returns a random integer in range [min, max-1]
uint32_t Random(int min, int max) {
if (!init) {
//No seed given, get a random number from device to seed
const auto seed = static_cast<uint32_t>(std::random_device{}());
Random_Init(seed);
}
std::uniform_int_distribution<uint32_t> distribution(min, max-1);
return distribution(generator);
}
//Returns a random floating point number in [0.0, 1.0]
double RandomDouble() {
std::uniform_real_distribution<double> distribution(0.0, 1.0);
return distribution(generator);
}
| 26.5 | 72 | 0.69434 | in1tiate |
4cd8d8b7eef22d3bb218a925ec6800d1a496803d | 3,944 | cpp | C++ | Abzynt/Abzynt/sdk/config/config.cpp | patrykkolodziej/Abzynt-Cheat | 862c72514f868fe24728ae83278647bcc3092180 | [
"MIT"
] | 14 | 2019-04-11T19:09:26.000Z | 2021-03-27T06:18:02.000Z | Abzynt/Abzynt/sdk/config/config.cpp | patrykkolodziej/Abzynt-Cheat | 862c72514f868fe24728ae83278647bcc3092180 | [
"MIT"
] | 2 | 2019-05-01T09:19:31.000Z | 2019-08-23T01:20:20.000Z | Abzynt/Abzynt/sdk/config/config.cpp | patrykkolodziej/Abzynt-Cheat | 862c72514f868fe24728ae83278647bcc3092180 | [
"MIT"
] | 7 | 2019-04-16T12:49:30.000Z | 2020-09-27T01:53:49.000Z | #include "config.hpp"
c_config g_config("config.json");
c_config::c_config(const std::string config_path)
{
char current_path[MAX_PATH] = "";
GetModuleFileNameA(NULL, current_path, MAX_PATH);
PathRemoveFileSpecA(current_path);
PathAddBackslashA(current_path);
path += config_path;
}
void c_config::save()
{
std::ofstream out(path);
if (!out.is_open())
{
return;
}
Json::Value save;
save["Abzynt - Config"]["Triggerbot"] = settings.triggerbot;
save["Abzynt - Config"]["GlowESP"] = settings.glowesp;
save["Abzynt - Config"]["ClrRender"] = settings.clrrender;
save["Abzynt - Config"]["Glow Enemy Colors"][0] = settings.glow_enemy_colors[0];
save["Abzynt - Config"]["Glow Enemy Colors"][1] = settings.glow_enemy_colors[1];
save["Abzynt - Config"]["Glow Enemy Colors"][2] = settings.glow_enemy_colors[2];
save["Abzynt - Config"]["Glow Team Colors"][0] = settings.glow_team_colors[0];
save["Abzynt - Config"]["Glow Team Colors"][1] = settings.glow_team_colors[1];
save["Abzynt - Config"]["Glow Team Colors"][2] = settings.glow_team_colors[2];
save["Abzynt - Config"]["Clr Enemy Colors"][0] = settings.clr_enemy_colors[0];
save["Abzynt - Config"]["Clr Enemy Colors"][1] = settings.clr_enemy_colors[1];
save["Abzynt - Config"]["Clr Enemy Colors"][2] = settings.clr_enemy_colors[2];
save["Abzynt - Config"]["Clr Team Colors"][0] = settings.clr_team_colors[0];
save["Abzynt - Config"]["Clr Team Colors"][1] = settings.clr_team_colors[1];
save["Abzynt - Config"]["Clr Team Colors"][2] = settings.clr_team_colors[2];
save["Abzynt - Config"]["Triggerbot Key"] = settings.triggerbot_key;
save["Abzynt - Config"]["Autopistol"] = settings.autopistol;
save["Abzynt - Config"]["Noflash"] = settings.noflash;
save["Abzynt - Config"]["Fovchanger"] = settings.fovchanger;
save["Abzynt - Config"]["Fovchanger Amount"] = settings.fovchanger_amount;
save["Abzynt - Config"]["Radarhack"] = settings.radarhack;
out << save;
out.close();
}
void c_config::load()
{
std::ifstream in(path);
if (!in.good())
{
save();
}
if (!in.is_open())
{
return;
}
Json::Value load;
in >> load;
settings.triggerbot = load["Abzynt - Config"]["Triggerbot"].asBool();
settings.glowesp = load["Abzynt - Config"]["GlowESP"].asBool();
settings.clrrender = load["Abzynt - Config"]["ClrRender"].asBool();
settings.glow_enemy_colors[0] = load["Abzynt - Config"]["Glow Enemy Colors"][0].asFloat();
settings.glow_enemy_colors[1] = load["Abzynt - Config"]["Glow Enemy Colors"][1].asFloat();
settings.glow_enemy_colors[2] = load["Abzynt - Config"]["Glow Enemy Colors"][2].asFloat();
settings.glow_team_colors[0] = load["Abzynt - Config"]["Glow Team Colors"][0].asFloat();
settings.glow_team_colors[1] = load["Abzynt - Config"]["Glow Team Colors"][1].asFloat();
settings.glow_team_colors[2] = load["Abzynt - Config"]["Glow Team Colors"][2].asFloat();
settings.clr_enemy_colors[0] = load["Abzynt - Config"]["Clr Enemy Colors"][0].asFloat();
settings.clr_enemy_colors[1] = load["Abzynt - Config"]["Clr Enemy Colors"][1].asFloat();
settings.clr_enemy_colors[2] = load["Abzynt - Config"]["Clr Enemy Colors"][2].asFloat();
settings.clr_team_colors[0] = load["Abzynt - Config"]["Clr Team Colors"][0].asFloat();
settings.clr_team_colors[1] = load["Abzynt - Config"]["Clr Team Colors"][1].asFloat();
settings.clr_team_colors[2] = load["Abzynt - Config"]["Clr Team Colors"][2].asFloat();
settings.triggerbot_key = load["Abzynt - Config"]["Triggerbot Key"].asInt();
settings.autopistol = load["Abzynt - Config"]["Autopistol"].asBool();
settings.fovchanger = load["Abzynt - Config"]["Fovchanger"].asBool();
settings.noflash = load["Abzynt - Config"]["Noflash"].asBool();
settings.fovchanger_amount = load["Abzynt - Config"]["Fovchanger Amount"].asInt();
settings.radarhack = load["Abzynt - Config"]["Radarhack"].asBool();
in.close();
}
| 41.957447 | 92 | 0.677485 | patrykkolodziej |
4cdfe1d286d6b6ce88b3dabe4b1aa97096b91d33 | 9,033 | cpp | C++ | cpp/lib/graph/functional_graph.cpp | KATO-Hiro/atcoder-1 | c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2 | [
"MIT"
] | null | null | null | cpp/lib/graph/functional_graph.cpp | KATO-Hiro/atcoder-1 | c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2 | [
"MIT"
] | null | null | null | cpp/lib/graph/functional_graph.cpp | KATO-Hiro/atcoder-1 | c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
// --------------------------------------------------------
#define FOR(i,l,r) for (ll i = (l); i < (r); ++i)
#define REP(i,n) FOR(i,0,n)
#define BIT(b,i) (((b)>>(i)) & 1)
// --------------------------------------------------------
// References:
// <https://usaco.guide/CPH.pdf#page=164>
// <https://usaco.guide/problems/cses-1160-planets-queries-ii/solution>
struct FunctionalGraph {
int N, K;
vector<pair<int,ll>> f; // 頂点 u から出る有向辺
vector<vector<pair<int,ll>>> Gr; // 逆辺グラフ
vector<int> comp; // 頂点 u が属する連結成分の番号
vector<int> root; // 頂点 u が属する木の根(サイクルに属する頂点は自身が根)
int cc_id = 0; // 連携成分の番号用
// サイクル
vector<int> cycle_length; // i 番目の連結成分に含まれるサイクル長
vector<int> cycle_weight; // i 番目の連結成分に含まれるサイクル総距離
vector<int> cycle_dist_e; // サイクル上の頂点 u における辺数の累積和
vector<ll> cycle_dist_w; // サイクル上の頂点 u における距離の累積和
// 木(複数存在することに注意)
vector<vector<int>> parent; // parent[k][u]: 頂点 u から 2^k 回親を辿って到達する頂点 (根を越えたら -1)
vector<int> depth; // depth[u] := 頂点 u の根からの深さ
vector<ll> dist; // dist[u] := 頂点 u の根からの距離 (パス上の重みの総和)
FunctionalGraph(int n) : N(n) {
f.resize(N);
Gr.resize(N);
comp.resize(N,-1);
root.resize(N,-1);
cycle_dist_e.resize(N,0);
cycle_dist_w.resize(N,0);
K = 1; while ((1<<K) <= N) { K++; }
parent.resize(K, vector<int>(N));
depth.resize(N);
dist.resize(N,0);
}
void add_edge(int u, int v, ll w) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
f[u] = {v, w};
Gr[v].push_back({u, w});
}
// Functional Graph におけるサイクル検出 (Floyd's cycle-finding algorithm)
// (サイクルに属する頂点の一つ, サイクル長) のペアを返す
pair<int,int> _cycle_detection(int x) {
int a = f[x].first;
int b = f[f[x].first].first;
while (a != b) {
a = f[a].first;
b = f[f[b].first].first;
}
b = f[a].first;
int length = 1;
while (a != b) {
b = f[b].first;
length++;
}
return make_pair(a, length);
}
void build() {
// 連結成分分解とサイクル検出
for (int s = 0; s < N; s++) if (root[s] == -1) {
// サイクル検出
auto [x, length] = _cycle_detection(s);
cycle_length.push_back(length);
// サイクル上の頂点をチェック
int r = x;
for (int i = 0; i < length; i++) {
root[r] = r; r = f[r].first;
}
// 木上の頂点をチェック
r = x; ll sum_w = 0;
for (int i = 0; i < length; i++) {
auto dfs = [&](auto self, int u) -> void {
root[u] = r; comp[u] = cc_id;
for (auto [v, _] : Gr[u]) if (root[v] == -1) {
self(self, v);
}
};
dfs(dfs, r);
sum_w += f[r].second;
r = f[r].first;
cycle_dist_w[r] = sum_w;
cycle_dist_e[r] = i + 1;
}
cc_id++;
cycle_weight.push_back(sum_w);
}
// 木の初期化
for (int r = 0; r < N; r++) if (root[r] == r) {
auto dfs = [&](auto self, int u, int p, int d, ll sum_w) -> void {
parent[0][u] = p;
depth[u] = d;
dist[u] = sum_w;
for (auto [v, w] : Gr[u]) if (u != v && root[v] == r) {
self(self, v, u, d+1, sum_w + w);
}
};
dfs(dfs, r, -1, 0, 0);
}
// ダブリング (木に属する頂点のみ対象)
for (int k = 1; k < K; k++) {
for (int u = 0; u < N; u++) {
if (parent[k-1][u] < 0) {
parent[k][u] = -1;
} else {
parent[k][u] = parent[k-1][parent[k-1][u]];
}
}
}
}
// 連結成分ごとの頂点リストを返す
vector<vector<int>> groups() {
vector<vector<int>> g(cc_id);
for (int u = 0; u < N; u++) {
g[comp[u]].push_back(u);
}
return g;
}
// 頂点 u がサイクルに属しているか判定(木の根もサイクルに属するとみなされる)
bool on_cycle(int u) {
assert(0 <= u && u < N);
return (root[u] == u);
}
// 頂点 u, v が同じ連結成分に属しているか判定
bool same_comp(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
return (comp[u] == comp[v]);
}
// 頂点 u, v が同じ木に属しているか判定
bool same_tree(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
return (root[u] == root[v]);
}
// 頂点 u, v が同じサイクルに属しているか判定
bool same_cycle(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
return (same_comp(u, v) && on_cycle(u) && on_cycle(v));
}
// 頂点 u から深さ d だけ親を辿る (level-ancestor)
// 辿った先が木上にあることを想定している
// - d <= depth[u]
int la(int u, int d) {
assert(0 <= u && u < N);
for (int k = K-1; 0 <= k; k--) if (BIT(d, k)) {
u = parent[k][u];
}
return u;
}
// 頂点 u, v の LCA
// 同じ木に属することを想定している
// - same_tree(u, v) == true
int lca(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
if (depth[u] < depth[v]) swap(u, v);
// depth[u] >= depth[v]
u = la(u, depth[u] - depth[v]); // (u, v) の深さを揃える
if (u == v) return u;
for (int k = K-1; 0 <= k; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
// (u -> v) パス間の辺数
// パスが存在しない場合は -1 を返す
int distance_e(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
if (!same_comp(u, v)) return -1; // 連結成分が異なる場合は到達不可能
int res = 0;
if (same_tree(u, v)) { // 同じ木に属する
res = (lca(u, v) == v ? _distance_e_tree(u, v) : -1);
} else if (on_cycle(u) && on_cycle(v)) { // 同じサイクルに属する
res = _distance_e_cycle(u, v);
} else if (!on_cycle(u) && on_cycle(v)) { // 木からサイクルへ
res = _distance_e_tree(u, root[u]) + _distance_e_cycle(root[u], v);
} else if (on_cycle(u) && !on_cycle(v)) { // サイクルから木へ
res = -1;
} else if (!on_cycle(u) && !on_cycle(v)) { // 別々の木に属する
res = -1;
} else {
assert(false);
}
return res;
}
// (u -> v) パス間の距離
// パスが存在しない場合は -1 を返す
ll distance_w(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
if (!same_comp(u, v)) return -1; // 連結成分が異なる場合は到達不可能
ll res = 0;
if (same_tree(u, v)) { // 同じ木に属する
res = (lca(u, v) == v ? _distance_w_tree(u, v) : -1);
} else if (on_cycle(u) && on_cycle(v)) { // 同じサイクルに属する
res = _distance_w_cycle(u, v);
} else if (!on_cycle(u) && on_cycle(v)) { // 木からサイクルへ
res = _distance_w_tree(u, root[u]) + _distance_w_cycle(root[u], v);
} else if (on_cycle(u) && !on_cycle(v)) { // サイクルから木へ
res = -1;
} else if (!on_cycle(u) && !on_cycle(v)) { // 別々の木に属する
res = -1;
} else {
assert(false);
}
return res;
}
// 木における (u -> v) パス間の辺数
// パスが存在することを想定している
// - same_tree(u, v) == true
// - lca(u, v) == v
int _distance_e_tree(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
return depth[u] - depth[v];
}
// サイクルにおける (u -> v) パス間の辺数
// パスが存在することを想定している
// - same_cycle(u, v) == true
int _distance_e_cycle(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
int length = cycle_length[comp[u]];
return (cycle_dist_e[v] - cycle_dist_e[u] + length) % length;
}
// 木における (u -> v) パス間の距離
// パスが存在することを想定している
// - same_tree(u, v) == true
// - lca(u, v) == v
ll _distance_w_tree(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
return dist[u] - dist[v];
}
// サイクルにおける (u -> v) パス間の距離
// パスが存在することを想定している
// - same_cycle(u, v) == true
ll _distance_w_cycle(int u, int v) {
assert(0 <= u && u < N);
assert(0 <= v && v < N);
ll weight = cycle_weight[comp[u]];
return (cycle_dist_w[v] - cycle_dist_w[u] + weight) % weight;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout << fixed << setprecision(15);
ll N, Q; cin >> N >> Q;
FunctionalGraph fg(N);
REP(u,N) {
ll v; cin >> v;
v--;
fg.add_edge(u, v, 1);
}
fg.build();
while (Q--) {
ll a, b; cin >> a >> b;
a--; b--;
ll ans = fg.distance_e(a, b);
cout << ans << '\n';
}
return 0;
}
// Verify: https://cses.fi/problemset/task/1160
| 28.951923 | 86 | 0.435736 | KATO-Hiro |
4ce2aac2db35d7c362099463fc83d8e3ab73049c | 52,453 | cpp | C++ | syn/core/grm_parser.cpp | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | 1 | 2019-02-08T02:23:56.000Z | 2019-02-08T02:23:56.000Z | syn/core/grm_parser.cpp | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | null | null | null | syn/core/grm_parser.cpp | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | 1 | 2020-12-02T02:37:40.000Z | 2020-12-02T02:37:40.000Z | /*
* Copyright 2014 Anton Karmanov
*
* 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.
*/
//Grammar Parser implementation.
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include "bnf.h"
#include "commons.h"
#include "syn.h"
#include "ebnf__imp.h"
#include "grm_parser.h"
#include "grm_parser_impl.h"
#include "lrtables.h"
#include "raw_bnf.h"
#include "util.h"
#include "util_mptr.h"
namespace ns = synbin;
namespace ebnf = ns::ebnf;
namespace prs = ns::grm_parser;
namespace raw = ns::raw_bnf;
namespace util = ns::util;
using std::unique_ptr;
using util::MPtr;
using util::MContainer;
using util::MHeap;
using util::MRoot;
using syn::ProductionStack;
//
//GrammarParsingResult
//
ns::GrammarParsingResult::GrammarParsingResult(
unique_ptr<MRoot<ebnf::Grammar>> grammar_root,
unique_ptr<MHeap> const_heap)
: m_grammar_root(std::move(grammar_root)),
m_const_heap(std::move(const_heap))
{}
MPtr<ebnf::Grammar> ns::GrammarParsingResult::get_grammar() const {
return m_grammar_root->ptr();
}
MHeap* ns::GrammarParsingResult::get_const_heap() const {
return m_const_heap.get();
}
//
//(Parser code)
//
namespace {
using syn::Shift;
using syn::Goto;
using syn::Reduce;
using syn::State;
class ActionContext;
//typedef ActionResult (ActionContext::*SyntaxAction)(ProductionResult& pr);
enum class SyntaxRule;
//A derived class is used instead of typedef to avoid "decorated name length exceeded..." warning.
class RawTraits : public ns::BnfTraits<raw::NullType, prs::Tokens::E, SyntaxRule>{};
typedef ns::LRTables<RawTraits> LRTbl;
typedef LRTbl::State LRState;
typedef LRTbl::Shift LRShift;
typedef LRTbl::Goto LRGoto;
typedef raw::RawBnfParser<RawTraits> RawPrs;
typedef RawPrs::RawTr RawTr;
typedef RawPrs::RawRule RawRule;
typedef ns::BnfGrammar<RawTraits> BnfGrm;
//
//SyntaxRule
//
enum class SyntaxRule {
NONE,
Grammar__DeclarationList,
DeclarationList__Declaration,
DeclarationList__DeclarationList_Declaration,
Declaration__TypeDeclaration,
Declaration__TerminalDeclaration,
Declaration__NonterminalDeclaration,
Declaration__CustomTerminalTypeDeclaration,
TypeDeclaration__KWTYPE_NAME_CHSEMICOLON,
TerminalDeclaration__KWTOKEN_NAME_TypeOpt_CHSEMICOLON,
NonterminalDeclaration__AtOpt_NAME_TypeOpt_CHCOLON_SyntaxOrExpression_CHSEMICOLON,
CustomTerminalTypeDeclaration__KWTOKEN_STRING_Type_CHSEMICOLON,
AtOpt__CHAT,
AtOpt__,
TypeOpt__Type,
TypeOpt__,
Type__CHOBRACE_NAME_CHCBRACE,
SyntaxOrExpression__SyntaxAndExpressionList,
SyntaxAndExpressionList__SyntaxAndExpression,
SyntaxAndExpressionList__SyntaxAndExpressionList_CHOR_SyntaxAndExpression,
SyntaxAndExpression__SyntaxElementListOpt_TypeOpt,
SyntaxElementListOpt__SyntaxElementList,
SyntaxElementListOpt__,
SyntaxElementList__SyntaxElement,
SyntaxElementList__SyntaxElementList_SyntaxElement,
SyntaxElement__NameSyntaxElement,
SyntaxElement__ThisSyntaxElement,
NameSyntaxElement__NAME_CHEQ_SyntaxTerm,
NameSyntaxElement__SyntaxTerm,
ThisSyntaxElement__KWTHIS_CHEQ_SyntaxTerm,
SyntaxTerm__PrimarySyntaxTerm,
SyntaxTerm__AdvanvedSyntaxTerm,
PrimarySyntaxTerm__NameSyntaxTerm,
PrimarySyntaxTerm__StringSyntaxTerm,
PrimarySyntaxTerm__NestedSyntaxTerm,
NameSyntaxTerm__NAME,
StringSyntaxTerm__STRING,
NestedSyntaxTerm__TypeOpt_CHOPAREN_SyntaxOrExpression_CHCPAREN,
AdvanvedSyntaxTerm__ZeroOneSyntaxTerm,
AdvanvedSyntaxTerm__ZeroManySyntaxTerm,
AdvanvedSyntaxTerm__OneManySyntaxTerm,
AdvanvedSyntaxTerm__ConstSyntaxTerm,
ZeroOneSyntaxTerm__PrimarySyntaxTerm_CHQUESTION,
ZeroManySyntaxTerm__LoopBody_CHASTERISK,
OneManySyntaxTerm__LoopBody_CHPLUS,
LoopBody__SimpleLoopBody,
LoopBody__AdvancedLoopBody,
SimpleLoopBody__PrimarySyntaxTerm,
AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCOLON_SyntaxOrExpression_CHCPAREN,
AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCPAREN,
ConstSyntaxTerm__CHLT_ConstExpression_CHGT,
ConstExpression__IntegerConstExpression,
ConstExpression__StringConstExpression,
ConstExpression__BooleanConstExpression,
ConstExpression__NativeConstExpression,
IntegerConstExpression__NUMBER,
StringConstExpression__STRING,
BooleanConstExpression__KWFALSE,
BooleanConstExpression__KWTRUE,
NativeConstExpression__NativeQualificationOpt_NativeName_NativeReferencesOpt,
NativeQualificationOpt__NativeQualification,
NativeQualificationOpt__,
NativeQualification__NAME_CHCOLONCOLON,
NativeQualification__NativeQualification_NAME_CHCOLONCOLON,
NativeReferencesOpt__NativeReferences,
NativeReferencesOpt__,
NativeReferences__NativeReference,
NativeReferences__NativeReferences_NativeReference,
NativeName__NativeVariableName,
NativeName__NativeFunctionName,
NativeVariableName__NAME,
NativeFunctionName__NAME_CHOPAREN_ConstExpressionListOpt_CHCPAREN,
ConstExpressionListOpt__ConstExpressionList,
ConstExpressionListOpt__,
ConstExpressionList__ConstExpression,
ConstExpressionList__ConstExpressionList_CHCOMMA_ConstExpression,
NativeReference__CHDOT_NativeName,
NativeReference__CHMINUSGT_NativeName,
LAST
};
const syn::InternalAction ACTION_FIRST = static_cast<syn::InternalAction>(SyntaxRule::NONE);
const syn::InternalAction ACTION_LAST = static_cast<syn::InternalAction>(SyntaxRule::LAST);
//
//ActionContext
//
class ActionContext {
NONCOPYABLE(ActionContext);
MHeap* const m_managed_heap;
const MPtr<MContainer<ebnf::Object>> m_managed_container;
MHeap* const m_const_managed_heap;
const MPtr<MContainer<ebnf::Object>> m_const_managed_container;
std::vector<const syn::StackElement*> m_stack_vector;
template<class T>
MPtr<T> manage(T* object) {
return m_managed_container->add(object);
}
template<class T>
MPtr<T> manage_spec(T* value) {
return m_managed_heap->add_object(value);
}
template<class T>
MPtr<T> manage_const(T* value) {
return m_const_managed_container->add(value);
}
template<class T>
MPtr<T> manage_const_spec(T* value) {
return m_const_managed_heap->add_object(value);
}
private:
static SyntaxRule syntax_rule(const syn::StackElement_Nt* nt) {
syn::InternalAction action = nt->action();
if (action <= ACTION_FIRST || action >= ACTION_LAST) {
throw std::logic_error("syntax_rule(): Illegal state");
}
return static_cast<SyntaxRule>(action);
}
static std::exception illegal_state() {
throw std::logic_error("illegal state");
}
static bool is_rule(const ProductionStack& stack, SyntaxRule rule, std::size_t len) {
if (rule != syntax_rule(stack.get_nt())) return false;
if (len != stack.size()) throw illegal_state();
return true;
}
static void check_rule(const ProductionStack& stack, SyntaxRule rule, std::size_t len) {
if (!is_rule(stack, rule, len)) throw illegal_state();
}
static ns::FilePos tk_pos(const syn::StackElement* node) {
const syn::StackElement_Value* val = node->as_value();
return *static_cast<const ns::FilePos*>(val->value());
}
static ns::syntax_number tk_number(const syn::StackElement* node) {
const syn::StackElement_Value* val = node->as_value();
return *static_cast<const ns::syntax_number*>(val->value());
}
static ns::syntax_string tk_string(const syn::StackElement* node) {
const syn::StackElement_Value* val = node->as_value();
return *static_cast<const ns::syntax_string*>(val->value());
}
public:
ActionContext(MHeap* managed_heap, MHeap* const_managed_heap)
: m_managed_heap(managed_heap),
m_managed_container(managed_heap->create_container<ebnf::Object>()),
m_const_managed_heap(const_managed_heap),
m_const_managed_container(const_managed_heap->create_container<ebnf::Object>())
{}
private:
typedef std::vector<MPtr<ebnf::Declaration>> DeclVector;
typedef std::vector<MPtr<ebnf::SyntaxExpression>> SyntaxExprVector;
typedef std::vector<MPtr<const ebnf::ConstExpression>> ConstExprVector;
typedef std::vector<MPtr<const ebnf::NativeReference>> NativeRefVector;
typedef std::vector<ns::syntax_string> StrVector;
MPtr<ebnf::RawType> nt_Type(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::Type__CHOBRACE_NAME_CHCBRACE, 3);
ns::syntax_string name = tk_string(stack[1]);
return manage(new ebnf::RawType(name));
}
MPtr<ebnf::RawType> nt_TypeOpt(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::TypeOpt__Type == rule) {
assert(1 == stack.size());
return nt_Type(stack[0]);
} else if (SyntaxRule::TypeOpt__ == rule) {
assert(0 == stack.size());
return MPtr<ebnf::RawType>();
} else {
throw illegal_state();
}
}
MPtr<ebnf::IntegerConstExpression> nt_IntegerConstExpression(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::IntegerConstExpression__NUMBER, 1);
const ns::syntax_number number = tk_number(stack[0]);
return manage_const(new ebnf::IntegerConstExpression(number));
}
MPtr<ebnf::StringConstExpression> nt_StringConstExpression(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::StringConstExpression__STRING, 1);
ns::syntax_string string = tk_string(stack[0]);
return manage_const(new ebnf::StringConstExpression(string));
}
MPtr<ebnf::BooleanConstExpression> nt_BooleanConstExpression(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
bool value;
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::BooleanConstExpression__KWTRUE == rule) {
value = true;
} else if (SyntaxRule::BooleanConstExpression__KWFALSE == rule) {
value = false;
} else {
throw illegal_state();
}
return manage_const(new ebnf::BooleanConstExpression(value));
}
void nt_NativeQualification(const syn::StackElement* node, MPtr<StrVector> lst) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::NativeQualification__NAME_CHCOLONCOLON == rule) {
assert(2 == stack.size());
lst->push_back(tk_string(stack[0]));
} else if (SyntaxRule::NativeQualification__NativeQualification_NAME_CHCOLONCOLON == rule) {
assert(3 == stack.size());
nt_NativeQualification(stack[0], lst);
lst->push_back(tk_string(stack[1]));
} else {
throw illegal_state();
}
}
MPtr<const StrVector> nt_NativeQualificationOpt(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
MPtr<StrVector> lst = manage_const_spec(new StrVector());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::NativeQualificationOpt__NativeQualification == rule) {
assert(1 == stack.size());
nt_NativeQualification(stack[0], lst);
} else if (SyntaxRule::NativeQualificationOpt__ == rule) {
assert(0 == stack.size());
} else {
throw illegal_state();
}
return lst;
}
MPtr<ebnf::NativeReference> nt_NativeReference(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::NativeReference__CHDOT_NativeName == rule) {
assert(2 == stack.size());
MPtr<const ebnf::NativeName> name = nt_NativeName(stack[1]);
return manage_const(new ebnf::NativeReferenceReference(name));
} else if (SyntaxRule::NativeReference__CHMINUSGT_NativeName == rule) {
assert(2 == stack.size());
MPtr<const ebnf::NativeName> name = nt_NativeName(stack[1]);
return manage_const(new ebnf::NativePointerReference(name));
} else {
throw illegal_state();
}
}
void nt_NativeReferences(const syn::StackElement* node, MPtr<NativeRefVector> lst) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::NativeReferences__NativeReference == rule) {
assert(1 == stack.size());
lst->push_back(nt_NativeReference(stack[0]));
} else if (SyntaxRule::NativeReferences__NativeReferences_NativeReference == rule) {
assert(3 == stack.size());
nt_NativeReferences(stack[0], lst);
lst->push_back(nt_NativeReference(stack[2]));
} else {
throw illegal_state();
}
}
MPtr<const NativeRefVector> nt_NativeReferencesOpt(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
MPtr<NativeRefVector> lst = manage_const_spec(new NativeRefVector());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::NativeReferencesOpt__NativeReferences == rule) {
assert(1 == stack.size());
nt_NativeReferences(stack[0], lst);
} else if (SyntaxRule::NativeReferencesOpt__ == rule) {
assert(0 == stack.size());
} else {
throw illegal_state();
}
return lst;
}
MPtr<ebnf::NativeVariableName> nt_NativeVariableName(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::NativeVariableName__NAME, 1);
const ns::syntax_string name = tk_string(stack[0]);
return manage_const(new ebnf::NativeVariableName(name));
}
MPtr<ebnf::NativeFunctionName> nt_NativeFunctionName(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::NativeFunctionName__NAME_CHOPAREN_ConstExpressionListOpt_CHCPAREN, 4);
const ns::syntax_string name = tk_string(stack[0]);
MPtr<const ConstExprVector> expressions = nt_ConstExpressionListOpt(stack[2]);
return manage_const(new ebnf::NativeFunctionName(name, expressions));
}
MPtr<ebnf::NativeName> nt_NativeName(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::NativeName__NativeVariableName == rule) {
return nt_NativeVariableName(stack[0]);
} else if (SyntaxRule::NativeName__NativeFunctionName == rule) {
return nt_NativeFunctionName(stack[0]);
} else {
throw illegal_state();
}
}
void nt_ConstExpressionList(const syn::StackElement* node, MPtr<ConstExprVector> lst) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::ConstExpressionList__ConstExpression == rule) {
assert(1 == stack.size());
lst->push_back(nt_ConstExpression(stack[0]));
} else if (SyntaxRule::ConstExpressionList__ConstExpressionList_CHCOMMA_ConstExpression == rule) {
assert(3 == stack.size());
nt_ConstExpressionList(stack[0], lst);
lst->push_back(nt_ConstExpression(stack[2]));
} else {
throw illegal_state();
}
}
MPtr<const ConstExprVector> nt_ConstExpressionListOpt(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
MPtr<ConstExprVector> lst = manage_const_spec(new ConstExprVector());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::ConstExpressionListOpt__ConstExpressionList == rule) {
assert(1 == stack.size());
nt_ConstExpressionList(stack[0], lst);
} else if (SyntaxRule::ConstExpressionListOpt__ == rule) {
assert(0 == stack.size());
} else {
throw illegal_state();
}
return lst;
}
MPtr<ebnf::NativeConstExpression> nt_NativeConstExpression(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::NativeConstExpression__NativeQualificationOpt_NativeName_NativeReferencesOpt, 3);
MPtr<const StrVector> qualifications = nt_NativeQualificationOpt(stack[0]);
MPtr<const ebnf::NativeName> name = nt_NativeName(stack[1]);
MPtr<const NativeRefVector> references = nt_NativeReferencesOpt(stack[2]);
return manage_const(new ebnf::NativeConstExpression(qualifications, name, references));
}
MPtr<ebnf::ConstExpression> nt_ConstExpression(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::ConstExpression__IntegerConstExpression == rule) {
return nt_IntegerConstExpression(stack[0]);
} else if (SyntaxRule::ConstExpression__StringConstExpression == rule) {
return nt_StringConstExpression(stack[0]);
} else if (SyntaxRule::ConstExpression__BooleanConstExpression == rule) {
return nt_BooleanConstExpression(stack[0]);
} else if (SyntaxRule::ConstExpression__NativeConstExpression == rule) {
return nt_NativeConstExpression(stack[0]);
} else {
throw illegal_state();
}
}
MPtr<ebnf::NameSyntaxExpression> nt_NameSyntaxTerm(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::NameSyntaxTerm__NAME, 1);
ns::syntax_string name = tk_string(stack[0]);
return manage(new ebnf::NameSyntaxExpression(name));
}
MPtr<ebnf::StringSyntaxExpression> nt_StringSyntaxTerm(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::StringSyntaxTerm__STRING, 1);
ns::syntax_string name = tk_string(stack[0]);
return manage(new ebnf::StringSyntaxExpression(name));
}
MPtr<ebnf::SyntaxExpression> nt_NestedSyntaxTerm(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::NestedSyntaxTerm__TypeOpt_CHOPAREN_SyntaxOrExpression_CHCPAREN, 4);
MPtr<const ebnf::RawType> type = nt_TypeOpt(stack[0]);
MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[2]);
if (type.get()) expression = manage(new ebnf::CastSyntaxExpression(type, expression));
return expression;
}
MPtr<ebnf::SyntaxExpression> nt_PrimarySyntaxTerm(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::PrimarySyntaxTerm__NameSyntaxTerm == rule) {
return nt_NameSyntaxTerm(stack[0]);
} else if (SyntaxRule::PrimarySyntaxTerm__StringSyntaxTerm == rule) {
return nt_StringSyntaxTerm(stack[0]);
} else if (SyntaxRule::PrimarySyntaxTerm__NestedSyntaxTerm == rule) {
return nt_NestedSyntaxTerm(stack[0]);
} else {
throw illegal_state();
}
}
MPtr<ebnf::SyntaxExpression> nt_ZeroOneSyntaxTerm(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::ZeroOneSyntaxTerm__PrimarySyntaxTerm_CHQUESTION, 2);
MPtr<ebnf::SyntaxExpression> sub_expression = nt_PrimarySyntaxTerm(stack[0]);
return manage(new ebnf::ZeroOneSyntaxExpression(sub_expression));
}
MPtr<ebnf::LoopBody> nt_SimpleLoopBody(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::SimpleLoopBody__PrimarySyntaxTerm, 1);
MPtr<ebnf::SyntaxExpression> expression = nt_PrimarySyntaxTerm(stack[0]);
return manage(new ebnf::LoopBody(expression, MPtr<ebnf::SyntaxExpression>(), ns::FilePos()));
}
MPtr<ebnf::LoopBody> nt_AdvancedLoopBody(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCOLON_SyntaxOrExpression_CHCPAREN == rule) {
assert(5 == stack.size());
MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[1]);
ns::FilePos separator_pos = tk_pos(stack[2]);
MPtr<ebnf::SyntaxExpression> separator = nt_SyntaxOrExpression(stack[3]);
return manage(new ebnf::LoopBody(expression, separator, separator_pos));
} else if (SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCPAREN == rule) {
assert(3 == stack.size());
MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[1]);
return manage(new ebnf::LoopBody(expression, MPtr<ebnf::SyntaxExpression>(), ns::FilePos()));
} else {
throw illegal_state();
}
}
MPtr<ebnf::LoopBody> nt_LoopBody(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::LoopBody__SimpleLoopBody == rule) {
return nt_SimpleLoopBody(stack[0]);
} else if (SyntaxRule::LoopBody__AdvancedLoopBody == rule) {
return nt_AdvancedLoopBody(stack[0]);
} else {
throw illegal_state();
}
}
MPtr<ebnf::ZeroManySyntaxExpression> nt_ZeroManySyntaxTerm(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::ZeroManySyntaxTerm__LoopBody_CHASTERISK, 2);
MPtr<ebnf::LoopBody> body = nt_LoopBody(stack[0]);
return manage(new ebnf::ZeroManySyntaxExpression(body));
}
MPtr<ebnf::OneManySyntaxExpression> nt_OneManySyntaxTerm(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::OneManySyntaxTerm__LoopBody_CHPLUS, 2);
MPtr<ebnf::LoopBody> body = nt_LoopBody(stack[0]);
return manage(new ebnf::OneManySyntaxExpression(body));
}
MPtr<ebnf::ConstSyntaxExpression> nt_ConstSyntaxTerm(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::ConstSyntaxTerm__CHLT_ConstExpression_CHGT, 3);
MPtr<const ebnf::ConstExpression> const_expression = nt_ConstExpression(stack[1]);
return manage(new ebnf::ConstSyntaxExpression(const_expression));
}
MPtr<ebnf::SyntaxExpression> nt_AdvanvedSyntaxTerm(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::AdvanvedSyntaxTerm__ZeroOneSyntaxTerm == rule) {
return nt_ZeroOneSyntaxTerm(stack[0]);
} else if (SyntaxRule::AdvanvedSyntaxTerm__ZeroManySyntaxTerm == rule) {
return nt_ZeroManySyntaxTerm(stack[0]);
} else if (SyntaxRule::AdvanvedSyntaxTerm__OneManySyntaxTerm == rule) {
return nt_OneManySyntaxTerm(stack[0]);
} else if (SyntaxRule::AdvanvedSyntaxTerm__ConstSyntaxTerm == rule) {
return nt_ConstSyntaxTerm(stack[0]);
} else {
throw illegal_state();
}
}
MPtr<ebnf::SyntaxExpression> nt_SyntaxTerm(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::SyntaxTerm__PrimarySyntaxTerm == rule) {
return nt_PrimarySyntaxTerm(stack[0]);
} else if (SyntaxRule::SyntaxTerm__AdvanvedSyntaxTerm == rule) {
return nt_AdvanvedSyntaxTerm(stack[0]);
} else {
throw illegal_state();
}
}
MPtr<ebnf::SyntaxExpression> nt_NameSyntaxElement(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::NameSyntaxElement__NAME_CHEQ_SyntaxTerm == rule) {
assert(3 == stack.size());
const ns::syntax_string name = tk_string(stack[0]);
MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxTerm(stack[2]);
return manage(new ebnf::NameSyntaxElement(expression, name));
} else if (SyntaxRule::NameSyntaxElement__SyntaxTerm == rule) {
assert(1 == stack.size());
return nt_SyntaxTerm(stack[0]);
} else {
throw illegal_state();
}
}
MPtr<ebnf::ThisSyntaxElement> nt_ThisSyntaxElement(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::ThisSyntaxElement__KWTHIS_CHEQ_SyntaxTerm, 3);
ns::FilePos pos = tk_pos(stack[0]);
MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxTerm(stack[2]);
return manage(new ebnf::ThisSyntaxElement(pos, expression));
}
MPtr<ebnf::SyntaxExpression> nt_SyntaxElement(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::SyntaxElement__NameSyntaxElement == rule) {
return nt_NameSyntaxElement(stack[0]);
} else if (SyntaxRule::SyntaxElement__ThisSyntaxElement == rule) {
return nt_ThisSyntaxElement(stack[0]);
} else {
throw illegal_state();
}
}
void nt_SyntaxElementList(const syn::StackElement* node, MPtr<SyntaxExprVector> lst) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::SyntaxElementList__SyntaxElement == rule) {
assert(1 == stack.size());
lst->push_back(nt_SyntaxElement(stack[0]));
} else if (SyntaxRule::SyntaxElementList__SyntaxElementList_SyntaxElement == rule) {
assert(2 == stack.size());
nt_SyntaxElementList(stack[0], lst);
lst->push_back(nt_SyntaxElement(stack[1]));
} else {
throw illegal_state();
}
}
MPtr<SyntaxExprVector> nt_SyntaxElementListOpt(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
MPtr<SyntaxExprVector> lst = manage_const_spec(new SyntaxExprVector());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::SyntaxElementListOpt__SyntaxElementList == rule) {
assert(1 == stack.size());
nt_SyntaxElementList(stack[0], lst);
} else if (SyntaxRule::SyntaxElementListOpt__ == rule) {
assert(0 == stack.size());
} else {
throw illegal_state();
}
return lst;
}
MPtr<ebnf::SyntaxExpression> nt_SyntaxAndExpression(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::SyntaxAndExpression__SyntaxElementListOpt_TypeOpt, 2);
MPtr<SyntaxExprVector> expressions = nt_SyntaxElementListOpt(stack[0]);
MPtr<const ebnf::RawType> type = nt_TypeOpt(stack[1]);
MPtr<ebnf::SyntaxExpression> expression;
if (expressions->empty() && !type.get()) {
expression = manage(new ebnf::EmptySyntaxExpression());
} else if (1 == expressions->size() && !type.get()) {
SyntaxExprVector& vector = *expressions;
MPtr<ebnf::SyntaxExpression> expr = (*expressions)[0];
expression = (*expressions)[0];
expressions->clear();
} else {
expression = manage(new ebnf::SyntaxAndExpression(expressions, type));
}
return expression;
}
void nt_SyntaxAndExpressionList(const syn::StackElement* node, MPtr<SyntaxExprVector> lst) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpression == rule) {
assert(1 == stack.size());
lst->push_back(nt_SyntaxAndExpression(stack[0]));
} else if (SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpressionList_CHOR_SyntaxAndExpression == rule) {
assert(3 == stack.size());
nt_SyntaxAndExpressionList(stack[0], lst);
lst->push_back(nt_SyntaxAndExpression(stack[2]));
} else {
throw illegal_state();
}
}
MPtr<ebnf::SyntaxExpression> nt_SyntaxOrExpression(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::SyntaxOrExpression__SyntaxAndExpressionList, 1);
MPtr<SyntaxExprVector> expressions = manage_const_spec(new SyntaxExprVector());
nt_SyntaxAndExpressionList(stack[0], expressions);
MPtr<ebnf::SyntaxExpression> expression;
if (expressions->empty()) {
expression = manage(new ebnf::EmptySyntaxExpression());
} else if (1 == expressions->size()) {
expression = (*expressions)[0];
expressions->clear();
} else {
expression = manage(new ebnf::SyntaxOrExpression(expressions));
}
return expression;
}
MPtr<ebnf::TypeDeclaration> nt_TypeDeclaration(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::TypeDeclaration__KWTYPE_NAME_CHSEMICOLON, 3);
const ns::syntax_string name = tk_string(stack[1]);
return manage(new ebnf::TypeDeclaration(name));
}
MPtr<ebnf::TerminalDeclaration> nt_TerminalDeclaration(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::TerminalDeclaration__KWTOKEN_NAME_TypeOpt_CHSEMICOLON, 4);
const ns::syntax_string name = tk_string(stack[1]);
MPtr<ebnf::RawType> raw_type = nt_TypeOpt(stack[2]);
return manage(new ebnf::TerminalDeclaration(name, raw_type));
}
bool nt_AtOpt(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::AtOpt__CHAT == rule) {
assert(1 == stack.size());
return true;
} else if (SyntaxRule::AtOpt__ == rule) {
assert(0 == stack.size());
return false;
} else {
throw illegal_state();
}
}
MPtr<ebnf::NonterminalDeclaration> nt_NonterminalDeclaration(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::NonterminalDeclaration__AtOpt_NAME_TypeOpt_CHCOLON_SyntaxOrExpression_CHSEMICOLON, 6);
bool start = nt_AtOpt(stack[0]);
const ns::syntax_string name = tk_string(stack[1]);
MPtr<const ebnf::RawType> type = nt_TypeOpt(stack[2]);
MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[4]);
return manage(new ebnf::NonterminalDeclaration(start, name, expression, type));
}
MPtr<ebnf::Declaration> nt_CustomTerminalTypeDeclaration(const syn::StackElement* node) {
ProductionStack stack(m_stack_vector, node);
check_rule(stack, SyntaxRule::CustomTerminalTypeDeclaration__KWTOKEN_STRING_Type_CHSEMICOLON, 4);
const ns::syntax_string str = tk_string(stack[1]);
MPtr<ebnf::RawType> raw_type = nt_Type(stack[2]);
if (str.get_string().str() != "") {
throw prs::ParserException("Empty string literal is expected", str.pos());
}
return manage(new ebnf::CustomTerminalTypeDeclaration(raw_type));
}
MPtr<ebnf::Declaration> nt_Declaration(const syn::StackElement* node) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
assert(1 == stack.size());
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::Declaration__TypeDeclaration == rule) {
return nt_TypeDeclaration(stack[0]);
} else if (SyntaxRule::Declaration__TerminalDeclaration == rule) {
return nt_TerminalDeclaration(stack[0]);
} else if (SyntaxRule::Declaration__NonterminalDeclaration == rule) {
return nt_NonterminalDeclaration(stack[0]);
} else if (SyntaxRule::Declaration__CustomTerminalTypeDeclaration == rule) {
return nt_CustomTerminalTypeDeclaration(stack[0]);
} else {
throw illegal_state();
}
}
void nt_DeclarationList(const syn::StackElement* node, MPtr<DeclVector> lst) {
const syn::StackElement_Nt* nt = node->as_nt();
ProductionStack stack(m_stack_vector, nt);
const SyntaxRule rule = syntax_rule(nt);
if (SyntaxRule::DeclarationList__Declaration == rule) {
assert(1 == stack.size());
lst->push_back(nt_Declaration(stack[0]));
} else if (SyntaxRule::DeclarationList__DeclarationList_Declaration == rule) {
assert(2 == stack.size());
nt_DeclarationList(stack[0], lst);
lst->push_back(nt_Declaration(stack[1]));
} else {
throw illegal_state();
}
}
public:
MPtr<ebnf::Grammar> nt_Grammar(const syn::StackElement_Nt* nt) {
ProductionStack stack(m_stack_vector, nt);
check_rule(stack, SyntaxRule::Grammar__DeclarationList, 1);
MPtr<DeclVector> declarations = manage_const_spec(new DeclVector());
nt_DeclarationList(stack[0], declarations);
return manage(new ebnf::Grammar(declarations));
}
};
const RawTr g_raw_tokens[] = {
{ "NAME", prs::Tokens::NAME },
{ "NUMBER", prs::Tokens::NUMBER },
{ "STRING", prs::Tokens::STRING },
{ "KW_CLASS", prs::Tokens::KW_CLASS },
{ "KW_THIS", prs::Tokens::KW_THIS },
{ "KW_TOKEN", prs::Tokens::KW_TOKEN },
{ "KW_TYPE", prs::Tokens::KW_TYPE },
{ "KW_FALSE", prs::Tokens::KW_FALSE },
{ "KW_TRUE", prs::Tokens::KW_TRUE },
{ "CH_SEMICOLON", prs::Tokens::CH_SEMICOLON },
{ "CH_AT", prs::Tokens::CH_AT },
{ "CH_COLON", prs::Tokens::CH_COLON },
{ "CH_OBRACE", prs::Tokens::CH_OBRACE },
{ "CH_CBRACE", prs::Tokens::CH_CBRACE },
{ "CH_OR", prs::Tokens::CH_OR },
{ "CH_EQ", prs::Tokens::CH_EQ },
{ "CH_OPAREN", prs::Tokens::CH_OPAREN },
{ "CH_CPAREN", prs::Tokens::CH_CPAREN },
{ "CH_QUESTION", prs::Tokens::CH_QUESTION },
{ "CH_ASTERISK", prs::Tokens::CH_ASTERISK },
{ "CH_PLUS", prs::Tokens::CH_PLUS },
{ "CH_LT", prs::Tokens::CH_LT },
{ "CH_GT", prs::Tokens::CH_GT },
{ "CH_COLON_COLON", prs::Tokens::CH_COLON_COLON },
{ "CH_COMMA", prs::Tokens::CH_COMMA },
{ "CH_DOT", prs::Tokens::CH_DOT },
{ "CH_MINUS_GT", prs::Tokens::CH_MINUS_GT },
{ 0, prs::Tokens::E(0) }
};
const RawRule g_raw_rules[] =
{
{ "Grammar", SyntaxRule::NONE },
{ "DeclarationList", SyntaxRule::Grammar__DeclarationList },
{ "DeclarationList", SyntaxRule::NONE },
{ "Declaration", SyntaxRule::DeclarationList__Declaration },
{ "DeclarationList Declaration", SyntaxRule::DeclarationList__DeclarationList_Declaration },
{ "Declaration", SyntaxRule::NONE },
{ "TypeDeclaration", SyntaxRule::Declaration__TypeDeclaration },
{ "TerminalDeclaration", SyntaxRule::Declaration__TerminalDeclaration },
{ "NonterminalDeclaration", SyntaxRule::Declaration__NonterminalDeclaration },
{ "CustomTerminalTypeDeclaration", SyntaxRule::Declaration__CustomTerminalTypeDeclaration },
{ "TypeDeclaration", SyntaxRule::NONE },
{ "KW_TYPE NAME CH_SEMICOLON", SyntaxRule::TypeDeclaration__KWTYPE_NAME_CHSEMICOLON },
{ "TerminalDeclaration", SyntaxRule::NONE },
{ "KW_TOKEN NAME TypeOpt CH_SEMICOLON", SyntaxRule::TerminalDeclaration__KWTOKEN_NAME_TypeOpt_CHSEMICOLON },
{ "NonterminalDeclaration", SyntaxRule::NONE },
{ "AtOpt NAME TypeOpt CH_COLON SyntaxOrExpression CH_SEMICOLON",
SyntaxRule::NonterminalDeclaration__AtOpt_NAME_TypeOpt_CHCOLON_SyntaxOrExpression_CHSEMICOLON },
{ "CustomTerminalTypeDeclaration", SyntaxRule::NONE },
{ "KW_TOKEN STRING Type CH_SEMICOLON", SyntaxRule::CustomTerminalTypeDeclaration__KWTOKEN_STRING_Type_CHSEMICOLON },
{ "AtOpt", SyntaxRule::NONE },
{ "CH_AT", SyntaxRule::AtOpt__CHAT },
{ "", SyntaxRule::AtOpt__ },
{ "TypeOpt", SyntaxRule::NONE },
{ "Type", SyntaxRule::TypeOpt__Type },
{ "", SyntaxRule::TypeOpt__ },
{ "Type", SyntaxRule::NONE },
{ "CH_OBRACE NAME CH_CBRACE", SyntaxRule::Type__CHOBRACE_NAME_CHCBRACE },
{ "SyntaxOrExpression", SyntaxRule::NONE },
{ "SyntaxAndExpressionList", SyntaxRule::SyntaxOrExpression__SyntaxAndExpressionList },
{ "SyntaxAndExpressionList", SyntaxRule::NONE },
{ "SyntaxAndExpression", SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpression },
{ "SyntaxAndExpressionList CH_OR SyntaxAndExpression",
SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpressionList_CHOR_SyntaxAndExpression },
{ "SyntaxAndExpression", SyntaxRule::NONE },
{ "SyntaxElementListOpt TypeOpt", SyntaxRule::SyntaxAndExpression__SyntaxElementListOpt_TypeOpt },
{ "SyntaxElementListOpt", SyntaxRule::NONE },
{ "SyntaxElementList", SyntaxRule::SyntaxElementListOpt__SyntaxElementList },
{ "", SyntaxRule::SyntaxElementListOpt__ },
{ "SyntaxElementList", SyntaxRule::NONE },
{ "SyntaxElement", SyntaxRule::SyntaxElementList__SyntaxElement },
{ "SyntaxElementList SyntaxElement", SyntaxRule::SyntaxElementList__SyntaxElementList_SyntaxElement },
{ "SyntaxElement", SyntaxRule::NONE },
{ "NameSyntaxElement", SyntaxRule::SyntaxElement__NameSyntaxElement },
{ "ThisSyntaxElement", SyntaxRule::SyntaxElement__ThisSyntaxElement },
{ "NameSyntaxElement", SyntaxRule::NONE },
{ "NAME CH_EQ SyntaxTerm", SyntaxRule::NameSyntaxElement__NAME_CHEQ_SyntaxTerm },
{ "SyntaxTerm", SyntaxRule::NameSyntaxElement__SyntaxTerm },
{ "ThisSyntaxElement", SyntaxRule::NONE },
{ "KW_THIS CH_EQ SyntaxTerm", SyntaxRule::ThisSyntaxElement__KWTHIS_CHEQ_SyntaxTerm },
{ "SyntaxTerm", SyntaxRule::NONE },
{ "PrimarySyntaxTerm", SyntaxRule::SyntaxTerm__PrimarySyntaxTerm },
{ "AdvanvedSyntaxTerm", SyntaxRule::SyntaxTerm__AdvanvedSyntaxTerm },
{ "PrimarySyntaxTerm", SyntaxRule::NONE },
{ "NameSyntaxTerm", SyntaxRule::PrimarySyntaxTerm__NameSyntaxTerm },
{ "StringSyntaxTerm", SyntaxRule::PrimarySyntaxTerm__StringSyntaxTerm },
{ "NestedSyntaxTerm", SyntaxRule::PrimarySyntaxTerm__NestedSyntaxTerm },
{ "NameSyntaxTerm", SyntaxRule::NONE },
{ "NAME", SyntaxRule::NameSyntaxTerm__NAME },
{ "StringSyntaxTerm", SyntaxRule::NONE },
{ "STRING", SyntaxRule::StringSyntaxTerm__STRING },
{ "NestedSyntaxTerm", SyntaxRule::NONE },
{ "TypeOpt CH_OPAREN SyntaxOrExpression CH_CPAREN",
SyntaxRule::NestedSyntaxTerm__TypeOpt_CHOPAREN_SyntaxOrExpression_CHCPAREN },
{ "AdvanvedSyntaxTerm", SyntaxRule::NONE },
{ "ZeroOneSyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__ZeroOneSyntaxTerm },
{ "ZeroManySyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__ZeroManySyntaxTerm },
{ "OneManySyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__OneManySyntaxTerm },
{ "ConstSyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__ConstSyntaxTerm },
{ "ZeroOneSyntaxTerm", SyntaxRule::NONE },
{ "PrimarySyntaxTerm CH_QUESTION", SyntaxRule::ZeroOneSyntaxTerm__PrimarySyntaxTerm_CHQUESTION },
{ "ZeroManySyntaxTerm", SyntaxRule::NONE },
{ "LoopBody CH_ASTERISK", SyntaxRule::ZeroManySyntaxTerm__LoopBody_CHASTERISK },
{ "OneManySyntaxTerm", SyntaxRule::NONE },
{ "LoopBody CH_PLUS", SyntaxRule::OneManySyntaxTerm__LoopBody_CHPLUS },
{ "LoopBody", SyntaxRule::NONE },
{ "SimpleLoopBody", SyntaxRule::LoopBody__SimpleLoopBody },
{ "AdvancedLoopBody", SyntaxRule::LoopBody__AdvancedLoopBody },
{ "SimpleLoopBody", SyntaxRule::NONE },
{ "PrimarySyntaxTerm", SyntaxRule::SimpleLoopBody__PrimarySyntaxTerm },
{ "AdvancedLoopBody", SyntaxRule::NONE },
{ "CH_OPAREN SyntaxOrExpression CH_COLON SyntaxOrExpression CH_CPAREN",
SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCOLON_SyntaxOrExpression_CHCPAREN },
{ "CH_OPAREN SyntaxOrExpression CH_CPAREN", SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCPAREN },
{ "ConstSyntaxTerm", SyntaxRule::NONE },
{ "CH_LT ConstExpression CH_GT", SyntaxRule::ConstSyntaxTerm__CHLT_ConstExpression_CHGT },
{ "ConstExpression", SyntaxRule::NONE },
{ "IntegerConstExpression", SyntaxRule::ConstExpression__IntegerConstExpression },
{ "StringConstExpression", SyntaxRule::ConstExpression__StringConstExpression },
{ "BooleanConstExpression", SyntaxRule::ConstExpression__BooleanConstExpression },
{ "NativeConstExpression", SyntaxRule::ConstExpression__NativeConstExpression },
{ "IntegerConstExpression", SyntaxRule::NONE },
{ "NUMBER", SyntaxRule::IntegerConstExpression__NUMBER },
{ "StringConstExpression", SyntaxRule::NONE },
{ "STRING", SyntaxRule::StringConstExpression__STRING },
{ "BooleanConstExpression", SyntaxRule::NONE },
{ "KW_FALSE", SyntaxRule::BooleanConstExpression__KWFALSE },
{ "KW_TRUE", SyntaxRule::BooleanConstExpression__KWTRUE },
{ "NativeConstExpression", SyntaxRule::NONE },
{ "NativeQualificationOpt NativeName NativeReferencesOpt",
SyntaxRule::NativeConstExpression__NativeQualificationOpt_NativeName_NativeReferencesOpt },
{ "NativeQualificationOpt", SyntaxRule::NONE },
{ "NativeQualification", SyntaxRule::NativeQualificationOpt__NativeQualification },
{ "", SyntaxRule::NativeQualificationOpt__ },
{ "NativeQualification", SyntaxRule::NONE },
{ "NAME CH_COLON_COLON", SyntaxRule::NativeQualification__NAME_CHCOLONCOLON },
{ "NativeQualification NAME CH_COLON_COLON",
SyntaxRule::NativeQualification__NativeQualification_NAME_CHCOLONCOLON },
{ "NativeReferencesOpt", SyntaxRule::NONE },
{ "NativeReferences", SyntaxRule::NativeReferencesOpt__NativeReferences },
{ "", SyntaxRule::NativeReferencesOpt__ },
{ "NativeReferences", SyntaxRule::NONE },
{ "NativeReference", SyntaxRule::NativeReferences__NativeReference },
{ "NativeReferences NativeReference", SyntaxRule::NativeReferences__NativeReferences_NativeReference },
{ "NativeName", SyntaxRule::NONE },
{ "NativeVariableName", SyntaxRule::NativeName__NativeVariableName },
{ "NativeFunctionName", SyntaxRule::NativeName__NativeFunctionName },
{ "NativeVariableName", SyntaxRule::NONE },
{ "NAME", SyntaxRule::NativeVariableName__NAME },
{ "NativeFunctionName", SyntaxRule::NONE },
{ "NAME CH_OPAREN ConstExpressionListOpt CH_CPAREN",
SyntaxRule::NativeFunctionName__NAME_CHOPAREN_ConstExpressionListOpt_CHCPAREN },
{ "ConstExpressionListOpt", SyntaxRule::NONE },
{ "ConstExpressionList", SyntaxRule::ConstExpressionListOpt__ConstExpressionList },
{ "", SyntaxRule::ConstExpressionListOpt__ },
{ "ConstExpressionList", SyntaxRule::NONE },
{ "ConstExpression", SyntaxRule::ConstExpressionList__ConstExpression },
{ "ConstExpressionList CH_COMMA ConstExpression",
SyntaxRule::ConstExpressionList__ConstExpressionList_CHCOMMA_ConstExpression },
{ "NativeReference", SyntaxRule::NONE },
{ "CH_DOT NativeName", SyntaxRule::NativeReference__CHDOT_NativeName },
{ "CH_MINUS_GT NativeName", SyntaxRule::NativeReference__CHMINUSGT_NativeName },
{ nullptr, SyntaxRule::NONE }
};
//
//CoreTables
//
class CoreTables {
NONCOPYABLE(CoreTables);
std::vector<State> m_states;
std::vector<Shift> m_shifts;
std::vector<Goto> m_gotos;
std::vector<Reduce> m_reduces;
State* m_start_state;
MHeap m_managed_heap;
public:
CoreTables(
std::vector<State>::size_type state_count,
std::vector<Shift>::size_type shift_count,
std::vector<Goto>::size_type goto_count,
std::vector<Reduce>::size_type reduce_count,
const LRState* lr_start_state)
: m_states(state_count),
m_shifts(shift_count),
m_gotos(goto_count),
m_reduces(reduce_count)
{
m_start_state = &m_states[lr_start_state->get_index()];
}
std::vector<State>::iterator get_states_begin() {
return m_states.begin();
}
std::vector<Shift>::iterator get_shifts_begin() {
return m_shifts.begin();
}
std::vector<Goto>::iterator get_gotos_begin() {
return m_gotos.begin();
}
std::vector<Reduce>::iterator get_reduces_begin() {
return m_reduces.begin();
}
const std::vector<State>& get_states() const {
return m_states;
}
const std::vector<Reduce>& get_reduces() const {
return m_reduces;
}
const State* get_start_state() const {
return m_start_state;
}
MHeap& get_managed_heap() {
return m_managed_heap;
}
};
//
//TransformShift
//
class TransformShift : public std::unary_function<const LRShift, Shift> {
const std::vector<State>& m_states;
public:
explicit TransformShift(const std::vector<State>& states)
: m_states(states)
{}
Shift operator()(const LRShift lr_shift) const {
Shift core_shift;
core_shift.assign(&m_states[lr_shift.get_state()->get_index()], lr_shift.get_tr()->get_tr_obj());
return core_shift;
}
};
//
//TransformGoto
//
class TransformGoto : public std::unary_function<const LRGoto, Goto> {
const std::vector<State>& m_states;
public:
explicit TransformGoto(const std::vector<State>& states)
: m_states(states)
{}
Goto operator()(const LRGoto lr_goto) const {
Goto core_goto;
core_goto.assign(&m_states[lr_goto.get_state()->get_index()], lr_goto.get_nt()->get_nt_index());
return core_goto;
}
};
//
//TransformReduce
//
class TransformReduce : public std::unary_function<const BnfGrm::Pr*, Reduce> {
public:
TransformReduce(){}
Reduce operator()(const BnfGrm::Pr* pr) {
Reduce core_reduce;
if (pr) {
syn::InternalAction action = static_cast<syn::InternalAction>(pr->get_pr_obj());
core_reduce.assign(pr->get_elements().size(), pr->get_nt()->get_nt_index(), action);
} else {
core_reduce.assign(0, 0, syn::ACCEPT_ACTION);
}
return core_reduce;
}
};
//
//TransformState
//
//This class is implemented not like a standard functor, because it has to be used by pointer, not by value.
class TransformState {
const TransformShift m_transform_shift;
const TransformGoto m_transform_goto;
const TransformReduce m_transform_reduce;
Shift m_null_shift;
Goto m_null_goto;
Reduce m_null_reduce;
std::vector<Shift>::iterator m_shift_it;
std::vector<Goto>::iterator m_goto_it;
std::vector<Reduce>::iterator m_reduce_it;
public:
explicit TransformState(CoreTables* core_tables)
: m_transform_shift(core_tables->get_states()),
m_transform_goto(core_tables->get_states())
{
m_null_shift.assign(nullptr, 0);
m_null_goto.assign(nullptr, 0);
m_null_reduce.assign(0, 0, syn::NULL_ACTION);
m_shift_it = core_tables->get_shifts_begin();
m_goto_it = core_tables->get_gotos_begin();
m_reduce_it = core_tables->get_reduces_begin();
}
State::SymType get_sym_type(const BnfGrm::Sym* sym) {
//If the symbol is NULL, the type does not matter, because this is either a start state,
//or a final one (goto by the extended nonterminal),
if (!sym) return State::sym_none;
if (const BnfGrm::Tr* tr = sym->as_tr()) {
prs::Tokens::E token = tr->get_tr_obj();
if (prs::Tokens::NAME == token || prs::Tokens::STRING == token || prs::Tokens::NUMBER == token) {
//This set of tokens must correspond to the set of tokens for which a value is created
//in InternalScanner.
return State::sym_tk_value;
} else {
return State::sym_none;
}
} else {
//Assuming that if the symbol is not a nonterminal, then it is a terminal.
return State::sym_nt;
}
}
State transform(const LRState* lrstate) {
State core_state;
const BnfGrm::Sym* sym = lrstate->get_sym();
State::SymType sym_type = get_sym_type(sym);
bool is_nt = sym && sym->as_nt();
core_state.assign(lrstate->get_index(), &*m_shift_it, &*m_goto_it, &*m_reduce_it, sym_type);
m_shift_it = std::transform(
lrstate->get_shifts().begin(),
lrstate->get_shifts().end(),
m_shift_it,
m_transform_shift);
*m_shift_it++ = m_null_shift;
m_goto_it = std::transform(
lrstate->get_gotos().begin(),
lrstate->get_gotos().end(),
m_goto_it,
m_transform_goto);
*m_goto_it++ = m_null_goto;
m_reduce_it = std::transform(
lrstate->get_reduces().begin(),
lrstate->get_reduces().end(),
m_reduce_it,
m_transform_reduce);
*m_reduce_it++ = m_null_reduce;
return core_state;
}
};
unique_ptr<CoreTables> create_core_tables(const BnfGrm* bnf_grammar, const LRTbl* lrtables) {
const std::vector<const LRState*>& lrstates = lrtables->get_states();
//Calculate counts.
std::vector<Shift>::size_type shift_count = 0;
std::vector<Goto>::size_type goto_count = 0;
std::vector<Goto>::size_type reduce_count = 0;
for (const LRState* lrstate : lrstates) {
shift_count += lrstate->get_shifts().size() + 1;
goto_count += lrstate->get_gotos().size() + 1;
reduce_count += lrstate->get_reduces().size() + 1;
}
//Determine start state.
//There must be one and only one start state.
const LRState* lr_start_state = lrtables->get_start_states()[0].second;
//Create empty tables.
unique_ptr<CoreTables> core_tables(new CoreTables(
lrstates.size(),
shift_count,
goto_count,
reduce_count,
lr_start_state));
//Transform states.
//Here the function object is not passed directly to std::transform(), because the object must be
//used by pointer, not by value (because the object has a state).
TransformState transform_state(core_tables.get());
std::transform(
lrtables->get_states().begin(),
lrtables->get_states().end(),
core_tables->get_states_begin(),
std::bind1st(std::mem_fun(&TransformState::transform), &transform_state));
return core_tables;
}
//
//InternalScanner
//
class InternalScanner : public syn::ScannerInterface {
NONCOPYABLE(InternalScanner);
syn::Pool<ns::FilePos> m_pos_pool;
syn::Pool<ns::syntax_number> m_number_pool;
syn::Pool<ns::syntax_string> m_string_pool;
prs::Scanner& m_scanner;
prs::TokenRecord m_token_record;
public:
InternalScanner(
prs::Scanner& scanner)
: m_scanner(scanner),
m_number_pool(200),
m_string_pool(100)
{}
std::pair<syn::InternalTk, const void*> scan() override {
m_scanner.scan_token(&m_token_record);
const void* value = nullptr;
if (prs::Tokens::NAME == m_token_record.token || prs::Tokens::STRING == m_token_record.token) {
value = m_string_pool.allocate(m_token_record.v_string);
} else if (prs::Tokens::NUMBER == m_token_record.token) {
value = m_number_pool.allocate(m_token_record.v_number);
} else {
value = m_pos_pool.allocate(ns::FilePos(m_scanner.file_name(), m_token_record.pos));
}
return std::make_pair(m_token_record.token, value);
}
bool fire_syntax_error(const char* message) {
throw prs::ParserException(message, ns::FilePos(m_scanner.file_name(), m_token_record.pos));
}
};
}
//
//parse_grammar()
//
unique_ptr<ns::GrammarParsingResult> prs::parse_grammar(std::istream& in, const util::String& file_name) {
//Create BNF grammar.
unique_ptr<const BnfGrm> bnf_grammar = RawPrs::raw_grammar_to_bnf(g_raw_tokens, g_raw_rules, SyntaxRule::NONE);
//Create LR tables.
std::vector<const BnfGrm::Nt*> start_nts;
start_nts.push_back(bnf_grammar->get_nonterminals()[0]);
unique_ptr<const LRTbl> lrtables = ns::create_LR_tables(*bnf_grammar.get(), start_nts, false);
//Create managed heap.
unique_ptr<MHeap> managed_heap(new MHeap());
unique_ptr<MHeap> const_managed_heap(new MHeap());
//Create core tables.
unique_ptr<const CoreTables> core_tables(create_core_tables(bnf_grammar.get(), lrtables.get()));
//Parse.
prs::Scanner scanner(in, file_name);
InternalScanner internal_scanner(scanner);
MPtr<ebnf::Grammar> grammar_mptr;
try {
std::unique_ptr<syn::ParserInterface> parser = syn::ParserInterface::create();
syn::StackElement_Nt* root_element = parser->parse(
core_tables->get_start_state(),
internal_scanner,
static_cast<syn::InternalTk>(Tokens::END_OF_FILE)
);
ActionContext action_context(managed_heap.get(), const_managed_heap.get());
grammar_mptr = action_context.nt_Grammar(root_element);
} catch (const syn::SynSyntaxError&) {
throw internal_scanner.fire_syntax_error("Syntax error");
} catch (const syn::SynLexicalError&) {
throw internal_scanner.fire_syntax_error("Lexical error");
} catch (const syn::SynError&) {
throw std::runtime_error("Unable to parse grammar");
}
//Return result.
std::unique_ptr<util::MRoot<ebnf::Grammar>> grammar_root(new util::MRoot<ebnf::Grammar>(grammar_mptr));
grammar_root->add_heap(std::move(managed_heap));
return make_unique1<GrammarParsingResult>(std::move(grammar_root), std::move(const_managed_heap));
}
| 35.779673 | 119 | 0.739138 | asmwarrior |
4ce4b03fc07e7bd088be5cb5037af11bab8a3cb2 | 2,146 | hh | C++ | neb/inc/com/centreon/broker/neb/downtime_map.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 40 | 2015-03-10T07:55:39.000Z | 2021-06-11T10:13:56.000Z | neb/inc/com/centreon/broker/neb/downtime_map.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 297 | 2015-04-30T10:02:04.000Z | 2022-03-09T13:31:54.000Z | neb/inc/com/centreon/broker/neb/downtime_map.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 29 | 2015-08-03T10:04:15.000Z | 2021-11-25T12:21:00.000Z | /*
** Copyright 2009-2013 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#ifndef CCB_NEB_DOWNTIME_MAP_HH
#define CCB_NEB_DOWNTIME_MAP_HH
#include <unordered_map>
#include "com/centreon/broker/misc/pair.hh"
#include "com/centreon/broker/namespace.hh"
#include "com/centreon/broker/neb/downtime.hh"
#include "com/centreon/broker/neb/node_id.hh"
CCB_BEGIN()
namespace neb {
/**
* @class downtime_map downtime_map.hh
* "com/centreon/broker/neb/downtime_map.hh"
* @brief Map of downtimes.
*/
class downtime_map {
public:
downtime_map();
downtime_map(downtime_map const& other);
downtime_map& operator=(downtime_map const& other);
virtual ~downtime_map();
uint32_t get_new_downtime_id();
std::list<downtime> get_all_downtimes_of_node(node_id id) const;
std::list<downtime> get_all_recurring_downtimes_of_node(node_id id) const;
void delete_downtime(downtime const& dwn);
void add_downtime(downtime const& dwn);
downtime* get_downtime(uint32_t internal_id);
bool is_recurring(uint32_t internal_id) const;
std::list<downtime> get_all_recurring_downtimes() const;
std::list<downtime> get_all_downtimes() const;
bool spawned_downtime_exist(uint32_t parent_id) const;
private:
uint32_t _actual_downtime_id;
std::unordered_map<uint32_t, downtime> _downtimes;
std::unordered_multimap<node_id, uint32_t> _downtime_id_by_nodes;
std::unordered_map<uint32_t, downtime> _recurring_downtimes;
std::unordered_multimap<node_id, uint32_t> _recurring_downtime_id_by_nodes;
};
} // namespace neb
CCB_END()
#endif // !CCB_NEB_DOWNTIME_MAP_HH
| 32.515152 | 77 | 0.770736 | centreon-lab |